[^<]+<\/a><\/h2>([^<]+)<\/p>/)?.[1] ?? "";
+ assertIncludes(listing, langSuffix === "zh" ? "记录分数" : "reported EdgeBench", "Blog catalog describes the recorded score pair scope");
+ for (const observedText of [snapshotSection, snapshotSvg, JSON.stringify(snapshot), listing]) {
+ if (/controlled|fixed Explore|holding Explore|同构|受控|固定 Explore|four.arm|四臂/i.test(observedText)) {
+ throw new Error("Reported score snapshot restored a controlled or mixed-arm claim: " + locale);
+ }
+ }
+ for (const publicText of [article, snapshotSvg, JSON.stringify(audit)]) {
+ if (/sforge/i.test(publicText)) {
+ throw new Error(`Internal benchmark name leaked into public context-delivery blog artifact (${locale})`);
+ }
+ }
if (/7,479,469|33\.4%|69\.9 KB|57\.1ms/.test(article))
throw new Error("Unreconciled totals or unsupported C1 attribution reappeared");
}
@@ -420,6 +594,37 @@ async function assertClockLabelRejected(blogDir, { figure, declared, regressed }
}
}
+async function assertScoreMismatchRejected(blogDir) {
+ const temporaryRoot = await mkdtemp(join(tmpdir(), "loopx-blog-score-parity-"));
+ const fixtureBlog = join(temporaryRoot, "blog");
+ try {
+ await cp(blogDir, fixtureBlog, { recursive: true });
+ // Each mutation changes just one published representation (or its source provenance).
+ const data = "data/long-horizon-audit.json";
+ const en = "context-delivery/index.html";
+ const zh = "zh/context-delivery/index.html";
+ const svg = "images/context-delivery/stride-context-on-vs-off-en.svg";
+ for (const [path, before, after, expected] of [
+ [data, '"context_on_native": 80,', '"context_on_native": 5,', /snapshot direction or winner/],
+ [data, '"context_on_native": 80,', '"context_on_native": 81,', /table row differs.*Borden/],
+ [svg, "7,159 / 3,746", "7,159 / 3,747", /chart native example differs/],
+ [en, "33,090,430 (62.99", "13,090,430 (62.99", /table row differs.*OpenTTD/],
+ [zh, "(27.18 · 17h57m · 10 次)", "(27.18 · 17h57m · 1 次)", /table row differs.*Rust/],
+ [data, '"prior_public_ann_url": "https://github.com/', '"prior_public_ann_url": "https://example.invalid/', /immutable public sources/],
+ [data, '"direction": "lower",\n "metric_label_en": "Total cost"', '"direction": "higher",\n "metric_label_en": "Total cost"', /snapshot direction or winner/],
+ ]) {
+ const file = resolve(fixtureBlog, path);
+ const source = await readFile(file, "utf8");
+ assertIncludes(source, before, "Negative fixture must contain the original value: " + path);
+ await writeFile(file, source.replace(before, after));
+ await rejects(() => validateBilingualBlog(fixtureBlog), expected);
+ await writeFile(file, source);
+ }
+ } finally {
+ await rm(temporaryRoot, { recursive: true, force: true });
+ }
+}
+
const modulePath = fileURLToPath(import.meta.url);
if (process.argv[1] && resolve(process.argv[1]) === modulePath) {
const articleUrl = "https://loopx-project.github.io/loopx/blog/example/";
@@ -506,5 +711,6 @@ if (process.argv[1] && resolve(process.argv[1]) === modulePath) {
},
"中文主图恢复反馈口径也必须被配对标签检查拦下",
);
+ await assertScoreMismatchRejected(blogDir);
console.log(`blog-bilingual-index-smoke: ok (${articleSlugs.length} paired articles)`);
}
diff --git a/examples/bootstrap-command-pack-smoke.py b/examples/bootstrap-command-pack-smoke.py
index 10916a206d..d5303b3b3d 100644
--- a/examples/bootstrap-command-pack-smoke.py
+++ b/examples/bootstrap-command-pack-smoke.py
@@ -43,6 +43,7 @@ def assert_packet_summary_refs(
*,
packet_kind: str,
compact_projection_default: bool = False,
+ legacy_fields_retained: bool | None = None,
) -> dict[str, object]:
summary = payload["packet_summary"]
assert isinstance(summary, dict)
@@ -50,8 +51,10 @@ def assert_packet_summary_refs(
assert summary["packet_kind"] == packet_kind
compatibility = summary["compatibility"]
assert isinstance(compatibility, dict)
+ if legacy_fields_retained is None:
+ legacy_fields_retained = not compact_projection_default
assert compatibility == {
- "legacy_fields_retained": not compact_projection_default,
+ "legacy_fields_retained": legacy_fields_retained,
"compact_projection_default": compact_projection_default,
"removal_gate": "explicit_host_shadow_parity",
}
@@ -357,6 +360,8 @@ def test_start_goal_guided_previews_transaction_without_mutation() -> None:
selection_summary = assert_packet_summary_refs(
selection,
packet_kind="guided_start_host_surface_selection",
+ compact_projection_default=True,
+ legacy_fields_retained=True,
)
assert selection_summary["next_step_kind"] == "select_host_surface"
assert selection["guided_transaction"]["blocked_by"] == "host_surface_selection"
diff --git a/examples/canary/catalog-planner-smoke.py b/examples/canary/catalog-planner-smoke.py
index f27dc612cf..a3c1e19ff3 100644
--- a/examples/canary/catalog-planner-smoke.py
+++ b/examples/canary/catalog-planner-smoke.py
@@ -708,7 +708,7 @@ def assert_pr_release_and_refactor_profiles_select() -> None:
]
assert "python3 examples/control_plane/heartbeat-prompt-smoke.py" in runtime_connector_commands
assert (
- "python3 examples/codex-cli-tui-bootstrap-smoke-bundle-smoke.py"
+ "python3 examples/codex-cli-bootstrap-message-smoke.py"
in runtime_connector_commands
)
assert "python3 examples/claude-goalmode-lifecycle-smoke.py" in runtime_connector_commands
diff --git a/examples/cli-benchmark-boundary-command-modularization-smoke.py b/examples/cli-benchmark-boundary-command-modularization-smoke.py
deleted file mode 100644
index 18e984b3dc..0000000000
--- a/examples/cli-benchmark-boundary-command-modularization-smoke.py
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def assert_contains(text: str, needle: str) -> None:
- if needle not in text:
- raise AssertionError(f"expected to find {needle!r} in output:\n{text}")
-
-
-def main() -> int:
- cli_source = (ROOT / "loopx" / "cli.py").read_text(encoding="utf-8")
- init_source = (ROOT / "loopx" / "cli_commands" / "__init__.py").read_text(
- encoding="utf-8"
- )
- dispatch_source = (
- ROOT / "loopx" / "cli_commands" / "benchmark_dispatch.py"
- ).read_text(encoding="utf-8")
- boundary_source = (
- ROOT / "loopx" / "cli_commands" / "benchmark_boundary.py"
- ).read_text(encoding="utf-8")
-
- leaked_markers = [
- "benchmark_artifact_filter_parser = benchmark_sub.add_parser",
- "benchmark_candidate_source_parser = benchmark_sub.add_parser",
- "def render_benchmark_artifact_path_filter_markdown",
- ]
- for marker in leaked_markers:
- if marker in cli_source:
- raise AssertionError(f"{marker} leaked back into loopx/cli.py")
- assert_contains(dispatch_source, "register_benchmark_boundary_commands(benchmark_sub, add_subcommand_format)")
- assert_contains(dispatch_source, "handle_benchmark_boundary_command(")
- assert_contains(init_source, "register_benchmark_boundary_commands")
- assert_contains(init_source, "handle_benchmark_boundary_command")
- assert_contains(boundary_source, "BENCHMARK_TOOLKIT_COMMANDS")
- if "split-control-execution-seam" in boundary_source:
- raise AssertionError("legacy split-control code leaked into the active toolkit CLI")
-
- help_result = run_cli("benchmark", "classify-artifacts", "--help")
- if help_result.returncode != 0:
- raise AssertionError(help_result.stderr or help_result.stdout)
- assert_contains(help_result.stdout, "--allow-public-filename")
-
- classify_result = run_cli(
- "benchmark",
- "classify-artifacts",
- "benchmark_run.compact.json",
- "--format",
- "json",
- )
- if classify_result.returncode != 0:
- raise AssertionError(classify_result.stderr or classify_result.stdout)
- classify_payload = json.loads(classify_result.stdout)
- if classify_payload.get("path_recorded") is not False:
- raise AssertionError(classify_payload)
-
- print("cli-benchmark-boundary-command-modularization-smoke: ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/cli-bootstrap-rollout-helper-command-modularization-smoke.py b/examples/cli-bootstrap-rollout-helper-command-modularization-smoke.py
deleted file mode 100644
index fbf9a43c60..0000000000
--- a/examples/cli-bootstrap-rollout-helper-command-modularization-smoke.py
+++ /dev/null
@@ -1,148 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-CLI = ROOT / "loopx" / "cli.py"
-BOOTSTRAP_MODULE = ROOT / "loopx" / "cli_commands" / "bootstrap_connect.py"
-ROLLOUT_MODULE = ROOT / "loopx" / "cli_rollout.py"
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- stdout = require_success(result)
- payload = json.loads(stdout)
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def assert_source_shape() -> None:
- cli_source = CLI.read_text(encoding="utf-8")
- bootstrap_source = BOOTSTRAP_MODULE.read_text(encoding="utf-8")
- rollout_source = ROLLOUT_MODULE.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
-
- forbidden_cli_markers = [
- "bootstrap_parser = sub.add_parser",
- "bootstrap_project(",
- "render_bootstrap_markdown",
- "DEFAULT_OBJECTIVE",
- "DEFAULT_DOMAIN",
- 'if args.command in {"bootstrap", "connect"}:',
- "def append_cli_rollout_event(",
- "def append_benchmark_run_rollout_event(",
- "def append_benchmark_result_rollout_event(",
- "def _benchmark_rollout_",
- "build_rollout_event(",
- "append_rollout_event(",
- ]
- for marker in forbidden_cli_markers:
- require(marker not in cli_source, f"bootstrap/rollout marker leaked into cli.py: {marker}")
-
- for marker in (
- "register_bootstrap_connect_command",
- "handle_bootstrap_connect_command",
- "bootstrap",
- "connect",
- "bootstrap_project(",
- ):
- require(marker in bootstrap_source, f"bootstrap module missing {marker}")
- for marker in (
- "append_cli_rollout_event",
- "build_rollout_event(",
- ):
- require(marker in rollout_source, f"rollout module missing {marker}")
- require("register_bootstrap_connect_command" in cli_source, "cli.py did not register bootstrap/connect")
- require("handle_bootstrap_connect_command" in cli_source, "cli.py did not dispatch bootstrap/connect")
- require("register_bootstrap_connect_command" in init_source, "__init__ omitted bootstrap registration")
- require("handle_bootstrap_connect_command" in init_source, "__init__ omitted bootstrap handler")
-
-
-def assert_help_surfaces() -> None:
- for command in ("bootstrap", "connect"):
- help_text = require_success(run_cli(command, "--help"))
- for option in (
- "--fork-goal",
- "--execution-minimum-scale",
- "--replace-state",
- "--no-global-sync",
- ):
- require(option in help_text, f"{command} help omitted {option}")
-
-
-def assert_bootstrap_dry_run() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-bootstrap-modular-smoke-") as tmp:
- root = Path(tmp)
- project = root / "project"
- project.mkdir()
- (project / "README.md").write_text("# Bootstrap Smoke\n", encoding="utf-8")
- registry = project / ".loopx" / "registry.json"
- payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "--registry",
- str(registry),
- "--runtime-root",
- str(root / "runtime"),
- "connect",
- "--project",
- str(project),
- "--goal-id",
- "bootstrap-modular-smoke",
- "--objective",
- "Validate bootstrap/connect command modularization.",
- "--domain",
- "smoke",
- "--adapter-kind",
- "read_only_project_map_v0",
- "--adapter-status",
- "connected-read-only",
- "--dry-run",
- "--no-global-sync",
- )
- )
- require(payload.get("dry_run") is True, payload)
- require(payload.get("goal_id") == "bootstrap-modular-smoke", payload)
- require(not registry.exists(), "bootstrap dry-run wrote the registry")
-
-
-def main() -> None:
- assert_source_shape()
- assert_help_surfaces()
- assert_bootstrap_dry_run()
- print("cli-bootstrap-rollout-helper-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-command-module-size-ownership-command-modularization-smoke.py b/examples/cli-command-module-size-ownership-command-modularization-smoke.py
index 8cefe282a2..8492f6e2e0 100644
--- a/examples/cli-command-module-size-ownership-command-modularization-smoke.py
+++ b/examples/cli-command-module-size-ownership-command-modularization-smoke.py
@@ -12,16 +12,9 @@
STARTER_MODULE_LIMITS = {
# Legacy command owners are frozen at their current baseline while each
# cohesive extraction lands; the default budget still catches new growth.
- "todo.py": 1098,
"starter.py": 180,
"starter_bootstrap.py": 220,
"starter_bootstrap_registration.py": 240,
- "starter_runtime_idle.py": 160,
- "starter_scheduler.py": 240,
- "starter_session_runtime.py": 220,
- "starter_visible_common.py": 120,
- "starter_visible_driver.py": 220,
- "starter_visible_pilot.py": 340,
}
STARTER_COMMAND_OWNERS = {
"start-goal": "start_goal.py",
@@ -29,21 +22,6 @@
"deliver-operation": "goal_channel_operation.py",
"new-project-prompt": "starter_bootstrap_registration.py",
"codex-cli-bootstrap-message": "starter_bootstrap_registration.py",
- "codex-cli-tui-bootstrap-smoke-bundle": "starter_bootstrap_registration.py",
- "codex-cli-exec-handoff": "starter_bootstrap_registration.py",
- "codex-cli-one-message-loop-pilot": "starter_visible_pilot.py",
- "codex-cli-visible-local-driver-pilot": "starter_visible_pilot.py",
- "codex-cli-bounded-visible-pilot-adapter": "starter_visible_pilot.py",
- "codex-cli-visible-first-response-capture-plan": "starter_visible_pilot.py",
- "codex-cli-visible-attach-acceptance": "starter_visible_pilot.py",
- "codex-cli-visible-driver-plan": "starter_visible_driver.py",
- "codex-cli-local-driver-plan": "starter_visible_driver.py",
- "codex-cli-visible-driver-run": "starter_visible_driver.py",
- "codex-cli-session-probe": "starter_session_runtime.py",
- "codex-cli-visible-session-proof": "starter_session_runtime.py",
- "codex-cli-runtime-idle-detector": "starter_session_runtime.py",
- "codex-cli-local-scheduler-tick": "starter_scheduler.py",
- "codex-cli-local-scheduler-exec": "starter_scheduler.py",
}
ADD_PARSER_RE = re.compile(
diff --git a/examples/cli-help-manpage-smoke.py b/examples/cli-help-manpage-smoke.py
index 218781f737..cdc8d506e6 100644
--- a/examples/cli-help-manpage-smoke.py
+++ b/examples/cli-help-manpage-smoke.py
@@ -30,7 +30,7 @@
)
-LONG_TAIL_COMMAND = "codex-cli-visible-first-response-capture-plan"
+LONG_TAIL_COMMAND = "configuration-backup"
def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
diff --git a/examples/cli-history-command-modularization-smoke.py b/examples/cli-history-command-modularization-smoke.py
deleted file mode 100644
index f9ef9bba02..0000000000
--- a/examples/cli-history-command-modularization-smoke.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def assert_contains(text: str, needle: str) -> None:
- if needle not in text:
- raise AssertionError(f"expected to find {needle!r} in output:\n{text}")
-
-
-def assert_not_contains(text: str, needle: str) -> None:
- if needle in text:
- raise AssertionError(f"did not expect to find {needle!r} in output:\n{text}")
-
-
-def main() -> int:
- cli_source = (ROOT / "loopx" / "cli.py").read_text(encoding="utf-8")
- init_source = (ROOT / "loopx" / "cli_commands" / "__init__.py").read_text(
- encoding="utf-8"
- )
- history_source = (ROOT / "loopx" / "cli_commands" / "history.py").read_text(
- encoding="utf-8"
- )
-
- if "history_parser = sub.add_parser" in cli_source:
- raise AssertionError("history parser registration leaked back into loopx/cli.py")
- assert_contains(cli_source, "register_history_command(sub)")
- assert_contains(cli_source, "handle_history_command(")
- assert_contains(init_source, "register_history_command")
- assert_contains(init_source, "handle_history_command")
- assert_not_contains(history_source, "append_active_user_assisted_pilot")
- assert_contains(history_source, "render_index_duplicate_repair_markdown")
-
- help_result = run_cli("history", "--help")
- if help_result.returncode != 0:
- raise AssertionError(help_result.stderr or help_result.stdout)
- assert_not_contains(help_result.stdout, "append-active-user-assisted-pilot")
- assert_contains(help_result.stdout, "repair-index-duplicates")
- assert_contains(help_result.stdout, "rebuild-index-collisions")
- assert_not_contains(help_result.stdout, "--active-user-pilot-json")
-
- print("cli-history-command-modularization-smoke: ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/cli-project-lifecycle-command-modularization-smoke.py b/examples/cli-project-lifecycle-command-modularization-smoke.py
deleted file mode 100644
index b07af56074..0000000000
--- a/examples/cli-project-lifecycle-command-modularization-smoke.py
+++ /dev/null
@@ -1,442 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-import tempfile
-from contextlib import ExitStack
-from pathlib import Path
-
-from pytest import MonkeyPatch
-
-from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection
-from loopx.control_plane.effect_runtime import restart_effect_runtime
-from loopx.control_plane.todos.active_state_todo_parser import parse_todo_source
-from loopx.control_plane.todos.todo_summary import canonical_todo_read_record, structured_todo_item
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT / "tests" / "control_plane"))
-CLI = ROOT / "loopx" / "cli.py"
-MODULE = ROOT / "loopx" / "cli_commands" / "project_lifecycle.py"
-PROJECT_SKILL = ROOT / "skills" / "loopx-project" / "SKILL.md"
-# The `refresh-state` command owns its own module since #4521, so the markers
-# that belong to that command are required there instead of in the dispatcher.
-REFRESH_MODULE = ROOT / "loopx" / "cli_commands" / "project_lifecycle_refresh_state.py"
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-GOAL_ID = "project-lifecycle-smoke"
-
-
-def run_cli(*args: str, cwd: Path = ROOT) -> subprocess.CompletedProcess[str]:
- env = {**os.environ, "PYTHONPATH": str(ROOT)}
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=cwd,
- env=env,
- text=True,
- encoding="utf-8",
- errors="replace",
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- stdout = require_success(result)
- try:
- payload = json.loads(stdout)
- except json.JSONDecodeError as exc:
- raise AssertionError(f"expected JSON output, got:\n{stdout}") from exc
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def write_fixture(project: Path) -> tuple[Path, Path, Path]:
- from canonical_authority_fixture import initialize_canonical_authority
-
- runtime_root = project / "runtime"
- registry_path = project / ".loopx" / "registry.json"
- state_file = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md"
- runs_dir = runtime_root / "goals" / GOAL_ID / "runs"
- run_json = runs_dir / "2026-06-22T00-00-00-smoke.json"
- run_md = runs_dir / "2026-06-22T00-00-00-smoke.md"
- index_path = runs_dir / "index.jsonl"
-
- registry_path.parent.mkdir(parents=True, exist_ok=True)
- state_file.parent.mkdir(parents=True, exist_ok=True)
- runs_dir.mkdir(parents=True, exist_ok=True)
- (project / "README.md").write_text("# Project Lifecycle Smoke\n", encoding="utf-8")
- state_file.write_text(
- "\n".join(
- [
- "---",
- f"goal_id: {GOAL_ID}",
- "updated_at: 2026-06-22T00:00:00+00:00",
- "---",
- "",
- "## Authority Sources",
- "",
- "- public fixture registry",
- "",
- "## Operating Contract",
- "",
- "- keep lifecycle command previews dry-run only",
- "",
- "## Work Clusters",
- "",
- "- CLI modularization smoke",
- "",
- "## Validation Surfaces",
- "",
- "- project lifecycle command smoke",
- "",
- "## Private/Public Boundary",
- "",
- "- fixture contains only public-safe synthetic values",
- "",
- "## Next Action",
- "",
- "- Continue project lifecycle command modularization smoke.",
- "",
- "## Agent Todo",
- "",
- "- [ ] [P1] Continue project lifecycle command modularization smoke.",
- " ",
- "",
- "## Progress Ledger",
- "",
- "- 2026-06-22T00:00:00+00:00: Fixture initialized.",
- "",
- ]
- ),
- encoding="utf-8",
- )
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": "0.1",
- "registry_role": "project-local",
- "common_runtime_root": str(runtime_root),
- "goals": [
- {
- "id": GOAL_ID,
- "objective": "Validate project lifecycle CLI command modularization.",
- "domain": "smoke",
- "repo": str(project),
- "state_file": ".codex/goals/project-lifecycle-smoke/ACTIVE_GOAL_STATE.md",
- "status": "connected-read-only",
- "adapter": {
- "kind": "read_only_project_map_v0",
- "status": "connected-read-only",
- },
- "coordination": {
- "agent_model": "peer_v1",
- "registered_agents": ["codex-product-capability"],
- },
- "guards": ["dry-run smoke fixture only"],
- }
- ],
- },
- ensure_ascii=False,
- indent=2,
- )
- + "\n",
- encoding="utf-8",
- )
- run_record = {
- "generated_at": "2026-06-22T00:00:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "state_refreshed",
- "recommended_action": "Continue project lifecycle command modularization smoke.",
- "health_check": "fixture run",
- "json_path": str(run_json),
- "markdown_path": str(run_md),
- }
- run_json.write_text(json.dumps(run_record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- run_md.write_text("# Fixture Run\n", encoding="utf-8")
- index_path.write_text(json.dumps(run_record, ensure_ascii=False) + "\n", encoding="utf-8")
- groups, _, _ = parse_todo_source(state_file.read_text(encoding="utf-8"))
- records = [canonical_todo_read_record(structured_todo_item(item, role=role,
- source_section=item["source_section"])) for role, rows in groups.items() for item in rows]
- initialize_canonical_authority(runtime_root, GOAL_ID, build_todo_runtime_shadow_projection(
- goal_id=GOAL_ID, todos=records, handoff_mode="soft_claim"), state_path=state_file, provider="sqlite")
- return registry_path, runtime_root, index_path
-
-
-def main() -> None:
- from canonical_authority_fixture import isolate_sqlite_runtime
-
- cli_source = CLI.read_text(encoding="utf-8")
- module_source = MODULE.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
- project_skill = PROJECT_SKILL.read_text(encoding="utf-8")
- require("references/handoff-and-feedback.md" in project_skill, "reward procedure must be routed from skill")
- handoff = PROJECT_SKILL.parent / "references/handoff-and-feedback.md"
- reward_skill = handoff.read_text(encoding="utf-8").split("## Record Human Reward", 1)[1].split(
- "## Capability Context And Child Models", 1
- )[0]
-
- for marker in (
- "--dry-run",
- "--actor-kind owner",
- "--actor-kind controller",
- "Never infer",
- ):
- require(marker in reward_skill, f"project skill reward flow omitted {marker}")
-
- forbidden_cli_markers = [
- "refresh_state_parser = sub.add_parser",
- "read_only_map_parser = sub.add_parser",
- "reward_parser = sub.add_parser",
- 'gate_parser = sub.add_parser(\n "operator-gate"',
- "refresh_state_run(",
- "read_only_project_map_run(",
- "append_human_reward(",
- "record_operator_gate(",
- 'if args.command == "refresh-state":',
- 'if args.command == "read-only-map":',
- 'if args.command == "reward":',
- 'if args.command == "operator-gate":',
- ]
- for marker in forbidden_cli_markers:
- require(marker not in cli_source, f"project lifecycle marker leaked into cli.py: {marker}")
-
- for marker in (
- "PROJECT_LIFECYCLE_COMMANDS",
- "register_project_lifecycle_commands",
- "handle_project_lifecycle_command",
- "read-only-map",
- "reward",
- "operator-gate",
- ):
- require(marker in module_source, f"project lifecycle module missing {marker}")
- refresh_source = REFRESH_MODULE.read_text(encoding="utf-8")
- for marker in (
- "retry it before delivery",
- "refresh-state",
- ):
- require(marker in refresh_source, f"refresh-state module missing {marker}")
- sink_source = (MODULE.parent / "project_lifecycle_sinks.py").read_text(encoding="utf-8")
- for marker in (
- "apply_external_sink_postcondition",
- "delivery_postcondition",
- "blocks_delivery",
- ):
- require(marker in sink_source, f"project lifecycle sink module missing {marker}")
- require("register_project_lifecycle_commands" in cli_source, "cli.py did not register project lifecycle commands")
- runtime_source = (CLI.parent / "cli_runtime.py").read_text(encoding="utf-8")
- require("dispatch_common_command" in cli_source and "handle_project_lifecycle_command" in runtime_source,
- "CLI entrypoints did not share project lifecycle dispatch")
- require("register_project_lifecycle_commands" in init_source, "__init__ did not export project lifecycle registration")
- require("handle_project_lifecycle_command" in init_source, "__init__ did not export project lifecycle handler")
-
- for command, options in {
- "refresh-state": (
- "--delivery-outcome",
- "--agent-id",
- "--suppress-external-sinks",
- "--dry-run",
- ),
- "read-only-map": ("--recommended-action", "--dry-run"),
- "reward": ("--actor-kind", "--write-active-state-summary", "--lesson-kind", "--lesson-avoid", "--dry-run"),
- "operator-gate": ("--agent-command", "--no-global-sync"),
- }.items():
- help_text = require_success(run_cli(command, "--help"))
- for option in options:
- require(option in help_text, f"{command} help omitted {option}")
-
- with (tempfile.TemporaryDirectory(prefix="loopx-project-lifecycle-cli-") as tmp,
- MonkeyPatch.context() as patch, ExitStack() as cleanup):
- project = Path(tmp)
- isolate_sqlite_runtime(project, patch)
- patch.setenv("LOOPX_USAGE_PING", "0")
- cleanup.callback(restart_effect_runtime, wait_for_exit=True)
- registry_path, runtime_root, index_path = write_fixture(project)
- before_index = index_path.read_text(encoding="utf-8")
- command_prefix = (
- "--registry",
- str(registry_path),
- "--runtime-root",
- str(runtime_root),
- )
-
- refresh_payload = require_json_success(
- run_cli(
- *command_prefix,
- "refresh-state",
- "--goal-id",
- GOAL_ID,
- "--dry-run",
- "--no-global-sync",
- "--suppress-external-sinks",
- "--delivery-batch-scale",
- "implementation",
- "--delivery-outcome",
- "outcome_progress",
- "--format",
- "json",
- )
- )
- require(refresh_payload.get("dry_run") is True, "refresh-state should stay dry-run")
- require(refresh_payload.get("appended") is False, "refresh-state dry-run should not append")
- require(refresh_payload.get("delivery_outcome") == "outcome_progress", "refresh-state outcome changed")
- require(
- refresh_payload.get("external_sink_delivery_authorized") is False,
- "refresh-state did not project the external sink suppression boundary",
- )
-
- map_payload = require_json_success(
- run_cli(
- *command_prefix,
- "read-only-map",
- "--goal-id",
- GOAL_ID,
- "--dry-run",
- "--no-global-sync",
- "--format",
- "json",
- )
- )
- require(map_payload.get("dry_run") is True, "read-only-map should stay dry-run")
- require(map_payload.get("appended") is False, "read-only-map dry-run should not append")
- require(
- (map_payload.get("project_map") or {}).get("adapter_kind") == "read_only_project_map_v0",
- "read-only-map compact payload changed",
- )
-
- reward_payload = require_json_success(
- run_cli(
- *command_prefix,
- "reward",
- "--goal-id",
- GOAL_ID,
- "--decision",
- "continue_route",
- "--reward",
- "positive",
- "--reason-summary",
- "synthetic dry-run reward",
- "--follow-up",
- "continue modularization smoke",
- "--lesson-kind",
- "route",
- "--lesson-summary",
- "Keep modularization dry-run checks ahead of broad lifecycle rewrites.",
- "--lesson-avoid",
- "broad lifecycle rewrite before dry-run check",
- "--lesson-prefer",
- "modularization dry-run check",
- "--dry-run",
- "--format",
- "json",
- )
- )
- require(reward_payload.get("dry_run") is True, "reward should stay dry-run")
- require(reward_payload.get("appended") is False, "reward dry-run should not append")
- require(
- (reward_payload.get("human_reward") or {}).get("reward") == "positive",
- "reward payload polarity changed",
- )
- reward_lesson = (reward_payload.get("human_reward") or {}).get("lesson") or {}
- require(reward_lesson.get("kind") == "route", "reward lesson kind changed")
- require(
- reward_lesson.get("avoid") == ["broad lifecycle rewrite before dry-run check"],
- "reward lesson avoid changed",
- )
-
- rejected_reward = run_cli(
- *command_prefix,
- "reward",
- "--goal-id",
- GOAL_ID,
- "--decision",
- "continue_route",
- "--reward",
- "positive",
- "--reason-summary",
- "synthetic durable reward",
- "--format",
- "json",
- )
- require(rejected_reward.returncode == 1, "anonymous durable reward should fail")
- rejected_payload = json.loads(rejected_reward.stdout)
- require(
- "actor kind is required" in str(rejected_payload.get("error") or ""),
- f"anonymous durable reward returned the wrong error: {rejected_payload}",
- )
- require(index_path.read_text(encoding="utf-8") == before_index, "rejected reward mutated run index")
-
- durable_reward = require_json_success(
- run_cli(
- *command_prefix,
- "reward",
- "--goal-id",
- GOAL_ID,
- "--actor-kind",
- "owner",
- "--decision",
- "continue_route",
- "--reward",
- "positive",
- "--reason-summary",
- "synthetic durable reward",
- "--format",
- "json",
- )
- )
- require(durable_reward.get("actor_kind") == "owner", "durable reward lost its actor")
- persisted_reward = json.loads(index_path.read_text(encoding="utf-8").splitlines()[-1])
- require(
- (persisted_reward.get("human_reward") or {}).get("actor_kind") == "owner",
- "durable reward index row lost its actor",
- )
-
- gate_payload = require_json_success(
- run_cli(
- *command_prefix,
- "operator-gate",
- "--goal-id",
- GOAL_ID,
- "--decision",
- "defer",
- "--reason-summary",
- "synthetic dry-run gate",
- "--follow-up",
- "collect more smoke evidence",
- "--dry-run",
- "--no-global-sync",
- "--format",
- "json",
- )
- )
- require(gate_payload.get("dry_run") is True, "operator-gate should stay dry-run")
- require(gate_payload.get("appended") is False, "operator-gate dry-run should not append")
- require(
- (gate_payload.get("operator_gate") or {}).get("decision") == "defer",
- "operator-gate decision changed",
- )
- require(
- len(index_path.read_text(encoding="utf-8").splitlines()) == 2,
- "project lifecycle smoke wrote an unexpected number of run rows",
- )
-
- print("cli-project-lifecycle-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-registry-admin-command-modularization-smoke.py b/examples/cli-registry-admin-command-modularization-smoke.py
deleted file mode 100644
index 896161f6c0..0000000000
--- a/examples/cli-registry-admin-command-modularization-smoke.py
+++ /dev/null
@@ -1,389 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-CLI = ROOT / "loopx" / "cli.py"
-MODULE = ROOT / "loopx" / "cli_commands" / "registry_admin.py"
-CONFIGURE_MODULE = ROOT / "loopx" / "cli_commands" / "registry_admin_configure.py"
-AUTHORITY_MODULE = ROOT / "loopx" / "cli_commands" / "registry_authority.py"
-LIFECYCLE_MODULE = ROOT / "loopx" / "cli_commands" / "registry_admin_lifecycle.py"
-THREAD_RESOLUTION_MODULE = (
- ROOT / "loopx" / "cli_commands" / "registry_admin_thread_resolution.py"
-)
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-GOAL_ID = "registry-admin-smoke"
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- env = {**os.environ, "PYTHONPATH": str(ROOT)}
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- env=env,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- stdout = require_success(result)
- try:
- payload = json.loads(stdout)
- except json.JSONDecodeError as exc:
- raise AssertionError(f"expected JSON output, got:\n{stdout}") from exc
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def run_json(command_prefix: tuple[str, ...], command: str, *args: str) -> dict[str, object]:
- return require_json_success(run_cli(*command_prefix, command, *args))
-
-def write_json(path: Path, payload: dict[str, object]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
-
-
-def write_fixture(project: Path) -> tuple[Path, Path, Path, Path]:
- runtime_root = project / "runtime"
- registry_path = project / ".loopx" / "registry.json"
- legacy_registry_path = project / "legacy" / "registry.global.json"
- doc_registry_path = project / "DOC_REGISTRY.yaml"
- obsolete_runtime = runtime_root / "goals" / "obsolete-runtime-goal" / "runs"
- obsolete_runtime.mkdir(parents=True, exist_ok=True)
- state_file = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md"
- state_file.parent.mkdir(parents=True, exist_ok=True)
- state_file.write_text("# Registry Admin Smoke State\n", encoding="utf-8")
- (project / "README.md").write_text("# Registry Admin Smoke\n", encoding="utf-8")
-
- goal = {
- "id": GOAL_ID,
- "objective": "Validate registry admin command modularization.",
- "domain": "smoke",
- "repo": str(project),
- "state_file": ".codex/goals/registry-admin-smoke/ACTIVE_GOAL_STATE.md",
- "status": "connected-read-only",
- "adapter": {"kind": "read_only_project_map_v0", "status": "connected-read-only"},
- "coordination": {
- "registered_agents": [{"id": "codex-main-control", "role": "primary"}],
- "agent_model": "peer_v1",
- },
- "guards": ["dry-run registry admin smoke fixture only"],
- }
- registry_payload = {
- "schema_version": "0.1",
- "registry_role": "project-local",
- "common_runtime_root": str(runtime_root),
- "goals": [goal],
- }
- write_json(registry_path, registry_payload)
- write_json(
- runtime_root / "registry.global.json",
- {
- "schema_version": "0.1",
- "registry_role": "global-local",
- "common_runtime_root": str(runtime_root),
- "goals": [{**goal, "source_registry": str(registry_path)}],
- },
- )
- write_json(
- legacy_registry_path,
- {
- "schema_version": "0.1",
- "common_runtime_root": str(project / "legacy-runtime"),
- "goals": [
- {
- "id": "legacy-smoke-goal",
- "objective": "Legacy smoke goal.",
- "repo": str(project / "legacy-repo"),
- "state_file": ".codex/goals/legacy-smoke-goal/ACTIVE_GOAL_STATE.md",
- "status": "legacy",
- }
- ],
- },
- )
- doc_registry_path.write_text(
- "version: doc_registry_v0\n"
- "updated_at: 2026-06-22T00:00:00+00:00\n"
- "default_entry_docs:\n"
- " - README.md\n"
- "topic_authority:\n"
- " issue_fix: README.md\n"
- "status_definitions:\n"
- " current: usable\n",
- encoding="utf-8",
- )
- return registry_path, runtime_root, legacy_registry_path, doc_registry_path
-
-
-def main() -> None:
- cli_source = CLI.read_text(encoding="utf-8")
- module_source = MODULE.read_text(encoding="utf-8")
- configure_source = CONFIGURE_MODULE.read_text(encoding="utf-8")
- authority_source = AUTHORITY_MODULE.read_text(encoding="utf-8")
- lifecycle_source = LIFECYCLE_MODULE.read_text(encoding="utf-8")
- thread_resolution_source = THREAD_RESOLUTION_MODULE.read_text(encoding="utf-8")
- registry_admin_family_source = (
- module_source
- + "\n"
- + configure_source
- + "\n"
- + authority_source
- + "\n"
- + lifecycle_source
- + "\n"
- + thread_resolution_source
- )
- init_source = INIT.read_text(encoding="utf-8")
-
- forbidden_cli_markers = [
- "configure_goal_parser = sub.add_parser",
- "register_agent_parser = sub.add_parser",
- "archive_runtime_parser = sub.add_parser",
- "retire_global_goal_parser = sub.add_parser",
- "sync_global_parser = sub.add_parser",
- "migrate_state_parser = sub.add_parser",
- "authority_parser = sub.add_parser",
- "doc_registry_authority_parser = sub.add_parser",
- "register_agent_via_source_registry(",
- "configure_goal(",
- "archive_runtime_goal(",
- "retire_global_registry_goals(",
- "migrate_legacy_state(",
- "register_authority_source(",
- "import_doc_registry_authority(",
- 'if args.command == "configure-goal":',
- 'if args.command == "register-agent":',
- 'if args.command == "archive-runtime":',
- 'if args.command == "retire-global-goal":',
- 'if args.command == "uninstall-project":',
- 'if args.command == "sync-global":',
- 'if args.command == "migrate-state":',
- 'if args.command == "register-authority-source":',
- 'if args.command == "import-doc-registry-authority":',
- ]
- for marker in forbidden_cli_markers:
- require(marker not in cli_source, f"registry admin marker leaked into cli.py: {marker}")
-
- for marker in (
- "REGISTRY_ADMIN_COMMANDS",
- "register_registry_admin_commands",
- "handle_registry_admin_command",
- "configure-goal",
- "register-agent",
- "archive-runtime",
- "retire-global-goal",
- "uninstall-project",
- "sync-global",
- "migrate-state",
- "register-authority-source",
- "import-doc-registry-authority",
- ):
- require(marker in registry_admin_family_source, f"registry admin command family missing {marker}")
- for marker in (
- "REGISTRY_AUTHORITY_COMMANDS",
- "register_registry_authority_commands",
- "handle_registry_authority_command",
- 'if args.command == "register-authority-source":',
- 'if args.command != "import-doc-registry-authority":',
- "register_authority_source(",
- "import_doc_registry_authority(",
- ):
- require(marker in authority_source, f"registry authority module missing {marker}")
- for marker in (
- "REGISTRY_LIFECYCLE_COMMANDS",
- "register_registry_lifecycle_commands",
- "handle_registry_lifecycle_command",
- 'if args.command == "archive-runtime":',
- 'if args.command == "retire-global-goal":',
- 'if args.command == "uninstall-project":',
- 'if args.command == "sync-global":',
- 'if args.command == "migrate-state":',
- "archive_runtime_goal(",
- "retire_global_registry_goals(",
- "uninstall_project(",
- "migrate_legacy_state(",
- ):
- require(marker in lifecycle_source, f"registry lifecycle module missing {marker}")
- for marker in ("register_registry_authority_commands", "handle_registry_authority_command"):
- require(marker in module_source, f"registry admin module should delegate authority commands through {marker}")
- for marker in (
- "register_registry_lifecycle_commands",
- "handle_registry_lifecycle_command",
- ):
- require(
- marker in module_source,
- f"registry admin module should delegate lifecycle commands through {marker}",
- )
- for marker in (
- "register_registry_thread_resolution_command",
- "handle_registry_thread_resolution_command",
- ):
- require(
- marker in module_source,
- f"registry admin module should delegate thread resolution through {marker}",
- )
- for marker in (
- "register_configure_goal_command",
- 'subparsers.add_parser(\n "configure-goal"',
- ):
- require(marker in configure_source, f"configure-goal command owner missing {marker}")
- require(
- "register_configure_goal_command(subparsers)" in module_source,
- "registry admin module should delegate configure-goal registration",
- )
- require("register_registry_admin_commands" in cli_source, "cli.py did not register registry admin commands")
- require("handle_registry_admin_command" in cli_source, "cli.py did not dispatch registry admin commands")
- require("register_registry_admin_commands" in init_source, "__init__ did not export registry admin registration")
- require("handle_registry_admin_command" in init_source, "__init__ did not export registry admin handler")
-
- for command, options in {
- "configure-goal": ("--quota-compute", "--registered-agent", "--execute"),
- "register-agent": ("--agent-id", "--require-new", "--execute"),
- "archive-runtime": ("--archive-root", "--allow-registered", "--execute"),
- "retire-global-goal": ("--goal-id", "--execute"),
- "uninstall-project": ("--goal-id", "--archive-state", "--remove-empty-registry", "--execute"),
- "sync-global": ("--replace-state", "--dry-run"),
- "migrate-state": ("--legacy-registry", "--goal-id-map", "--copy-runtime"),
- "register-authority-source": ("--source-ref", "--boundary", "--no-global-sync"),
- "import-doc-registry-authority": ("--doc-registry-path", "--import-topic-prefix", "--max-imported-topics"),
- }.items():
- help_text = require_success(run_cli(command, "--help"))
- for option in options:
- require(option in help_text, f"{command} help omitted {option}")
-
- with tempfile.TemporaryDirectory(prefix="loopx-registry-admin-cli-") as tmp:
- project = Path(tmp)
- registry_path, runtime_root, legacy_registry_path, doc_registry_path = write_fixture(project)
- command_prefix = ("--format", "json", "--registry", str(registry_path), "--runtime-root", str(runtime_root))
- registry_before = registry_path.read_text(encoding="utf-8")
-
- configure_payload = run_json(
- command_prefix,
- "configure-goal",
- "--goal-id",
- GOAL_ID,
- "--quota-compute",
- "2",
- "--registered-agent",
- "codex-product-capability",
- )
- require(configure_payload.get("dry_run") is True, "configure-goal should preview by default")
- require(configure_payload.get("written") is False, "configure-goal preview should not write")
-
- register_payload = run_json(
- command_prefix,
- "register-agent",
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- "codex-product-capability",
- )
- require(register_payload.get("dry_run") is True, "register-agent should preview by default")
- require("codex-product-capability" in (register_payload.get("registered_agents") or []), register_payload)
-
- archive_payload = run_json(command_prefix, "archive-runtime", "--goal-id", "obsolete-runtime-goal")
- require(archive_payload.get("dry_run") is True, "archive-runtime should dry-run by default")
- require(archive_payload.get("archived") is False, "archive-runtime preview should not move")
- require((runtime_root / "goals" / "obsolete-runtime-goal").exists(), "archive-runtime preview moved source")
-
- uninstall_payload = run_json(command_prefix, "uninstall-project", "--goal-id", GOAL_ID, "--archive-state")
- require(uninstall_payload.get("dry_run") is True, "uninstall-project should dry-run by default")
- require(uninstall_payload.get("wrote_local_registry") is False, "uninstall-project preview should not write local registry")
- require(uninstall_payload.get("wrote_global_registry") is False, "uninstall-project preview should not write global registry")
- require(registry_path.read_text(encoding="utf-8") == registry_before, "uninstall-project preview changed registry")
-
- sync_payload = run_json(command_prefix, "sync-global", "--goal-id", GOAL_ID, "--dry-run")
- require(sync_payload.get("dry_run") is True, "sync-global should honor --dry-run")
- require(sync_payload.get("wrote") is False, "sync-global dry-run should not write")
-
- migrate_payload = run_json(
- command_prefix,
- "migrate-state",
- "--legacy-registry",
- str(legacy_registry_path),
- "--legacy-runtime-root",
- str(project / "legacy-runtime"),
- "--target-runtime-root",
- str(runtime_root),
- "--goal-id",
- "legacy-smoke-goal",
- "--goal-id-map",
- "legacy-smoke-goal=migrated-smoke-goal",
- "--no-global-sync",
- )
- require(migrate_payload.get("dry_run") is True, "migrate-state should dry-run by default")
- require(migrate_payload.get("wrote_project_registry") is False, "migrate-state preview should not write")
- require("migrated-smoke-goal" in (migrate_payload.get("migrated_goal_ids") or []), migrate_payload)
-
- authority_payload = run_json(
- command_prefix,
- "register-authority-source",
- "--goal-id",
- GOAL_ID,
- "--source-id",
- "source-smoke",
- "--source-ref",
- "https://example.com/public-smoke",
- "--source-kind",
- "doc",
- "--role",
- "smoke_authority",
- "--freshness",
- "current",
- "--topic",
- "issue_fix",
- "--dry-run",
- "--no-global-sync",
- )
- require(authority_payload.get("dry_run") is True, "authority registration should honor --dry-run")
- require(authority_payload.get("written") is False, "authority dry-run should not write")
- require(authority_payload.get("raw_source_ref_stored") is False, "authority source ref must stay redacted")
-
- doc_payload = run_json(
- command_prefix,
- "import-doc-registry-authority",
- "--goal-id",
- GOAL_ID,
- "--source-id",
- "doc-registry-smoke",
- "--doc-registry-path",
- str(doc_registry_path),
- "--topic",
- "content_ops",
- "--import-topic-prefix",
- "smoke:",
- "--dry-run",
- "--no-global-sync",
- )
- require(doc_payload.get("dry_run") is True, "doc registry import should honor --dry-run")
- require(doc_payload.get("written") is False, "doc registry import dry-run should not write")
- require(doc_payload.get("raw_doc_registry_path_stored") is False, "doc registry path must stay redacted")
- require(registry_path.read_text(encoding="utf-8") == registry_before, "dry-run commands mutated registry")
-
- print("cli-registry-admin-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-starter-bootstrap-family-command-modularization-smoke.py b/examples/cli-starter-bootstrap-family-command-modularization-smoke.py
deleted file mode 100644
index 68002f731f..0000000000
--- a/examples/cli-starter-bootstrap-family-command-modularization-smoke.py
+++ /dev/null
@@ -1,190 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-STARTER = ROOT / "loopx" / "cli_commands" / "starter.py"
-BOOTSTRAP = ROOT / "loopx" / "cli_commands" / "starter_bootstrap.py"
-BOOTSTRAP_REGISTRATION = ROOT / "loopx" / "cli_commands" / "starter_bootstrap_registration.py"
-START_GOAL = ROOT / "loopx" / "cli_commands" / "start_goal.py"
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- payload = json.loads(require_success(result))
- require(isinstance(payload, dict), "expected JSON object payload")
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def assert_source_shape() -> None:
- starter_source = STARTER.read_text(encoding="utf-8")
- bootstrap_source = BOOTSTRAP.read_text(encoding="utf-8")
- registration_source = BOOTSTRAP_REGISTRATION.read_text(encoding="utf-8")
- start_goal_source = START_GOAL.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
-
- forbidden_starter_markers = [
- "DEFAULT_HANDOFF_ADAPTER_KIND",
- "build_new_project_prompt(",
- "render_new_project_prompt_markdown",
- "build_codex_cli_bootstrap_message(",
- "render_codex_cli_bootstrap_message_markdown",
- "build_codex_cli_tui_bootstrap_smoke_bundle(",
- "build_codex_cli_exec_handoff(",
- "def handle_new_project_prompt_command(",
- "def handle_codex_cli_bootstrap_message_command(",
- "def handle_codex_cli_tui_bootstrap_smoke_bundle_command(",
- "def handle_codex_cli_exec_handoff_command(",
- ]
- for marker in forbidden_starter_markers:
- require(marker not in starter_source, f"bootstrap/message marker leaked into starter.py: {marker}")
-
- for marker in (
- "register_starter_bootstrap_commands(subparsers)",
- "handle_starter_bootstrap_command(args, print_payload)",
- ):
- require(marker in starter_source, f"starter.py missing bootstrap delegation marker: {marker}")
-
- for marker in (
- "def handle_starter_bootstrap_command(",
- "def handle_new_project_prompt_command(",
- "def handle_codex_cli_bootstrap_message_command(",
- "def handle_codex_cli_tui_bootstrap_smoke_bundle_command(",
- "def handle_codex_cli_exec_handoff_command(",
- "build_new_project_prompt(",
- "build_codex_cli_exec_handoff(",
- ):
- require(marker in bootstrap_source, f"starter_bootstrap.py missing marker: {marker}")
-
- for marker in (
- "def register_starter_bootstrap_commands(",
- 'subparsers.add_parser(\n "agent-onboard"',
- 'subparsers.add_parser(\n "bootstrap-command-pack"',
- 'subparsers.add_parser(\n "new-project-prompt"',
- ):
- require(
- marker in registration_source,
- f"starter_bootstrap_registration.py missing marker: {marker}",
- )
-
- for marker in (
- "def register_start_goal_command(",
- 'subparsers.add_parser(\n "start-goal"',
- ):
- require(
- marker in start_goal_source,
- f"start_goal.py missing marker: {marker}",
- )
-
- for marker in (
- "handle_starter_bootstrap_command",
- "register_starter_bootstrap_commands",
- "handle_new_project_prompt_command",
- "handle_codex_cli_exec_handoff_command",
- ):
- require(marker in init_source, f"__init__ omitted bootstrap export: {marker}")
-
-
-def assert_cli_surfaces() -> None:
- for command, needles in {
- "new-project-prompt": ["--goal-doc", "--adapter-status", "--write-scope"],
- "codex-cli-bootstrap-message": ["--agent-id", "--message-only"],
- "codex-cli-tui-bootstrap-smoke-bundle": ["--agent-id", "--cli-bin"],
- "codex-cli-exec-handoff": ["--codex-bin", "--cli-bin"],
- }.items():
- help_text = require_success(run_cli(command, "--help"))
- for needle in needles:
- require(needle in help_text, f"{command} help omitted {needle}")
-
- prompt_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "new-project-prompt",
- "--project",
- ".",
- "--goal-doc",
- "README.md",
- "--goal-id",
- "starter-bootstrap-smoke",
- )
- )
- require(prompt_payload.get("goal_id") == "starter-bootstrap-smoke", prompt_payload)
-
- bootstrap_text = require_success(
- run_cli(
- "codex-cli-bootstrap-message",
- "--project",
- ".",
- "--goal-id",
- "starter-bootstrap-smoke",
- "--message-only",
- )
- )
- require("loopx" in bootstrap_text, "bootstrap message lost LoopX text")
-
- bundle_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-tui-bootstrap-smoke-bundle",
- "--project",
- ".",
- "--goal-id",
- "starter-bootstrap-smoke",
- )
- )
- require(bundle_payload.get("goal_id") == "starter-bootstrap-smoke", bundle_payload)
-
- handoff_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-exec-handoff",
- "--project",
- ".",
- "--goal-id",
- "starter-bootstrap-smoke",
- )
- )
- require(handoff_payload.get("goal_id") == "starter-bootstrap-smoke", handoff_payload)
-
-
-def main() -> None:
- assert_source_shape()
- assert_cli_surfaces()
- print("cli-starter-bootstrap-family-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-starter-dispatch-command-modularization-smoke.py b/examples/cli-starter-dispatch-command-modularization-smoke.py
deleted file mode 100644
index ecf68c69ae..0000000000
--- a/examples/cli-starter-dispatch-command-modularization-smoke.py
+++ /dev/null
@@ -1,209 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-CLI = ROOT / "loopx" / "cli.py"
-STARTER_MODULE = ROOT / "loopx" / "cli_commands" / "starter.py"
-VISIBLE_DRIVER_MODULE = ROOT / "loopx" / "cli_commands" / "starter_visible_driver.py"
-SCHEDULER_MODULE = ROOT / "loopx" / "cli_commands" / "starter_scheduler.py"
-SESSION_RUNTIME_MODULE = ROOT / "loopx" / "cli_commands" / "starter_session_runtime.py"
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- payload = json.loads(require_success(result))
- require(isinstance(payload, dict), "expected JSON object payload")
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def assert_source_shape() -> None:
- cli_source = CLI.read_text(encoding="utf-8")
- starter_source = STARTER_MODULE.read_text(encoding="utf-8")
- visible_driver_source = VISIBLE_DRIVER_MODULE.read_text(encoding="utf-8")
- scheduler_source = SCHEDULER_MODULE.read_text(encoding="utf-8")
- session_runtime_source = SESSION_RUNTIME_MODULE.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
-
- starter_commands = [
- "new-project-prompt",
- "codex-cli-bootstrap-message",
- "codex-cli-tui-bootstrap-smoke-bundle",
- "codex-cli-one-message-loop-pilot",
- "codex-cli-visible-local-driver-pilot",
- "codex-cli-bounded-visible-pilot-adapter",
- "codex-cli-visible-first-response-capture-plan",
- "codex-cli-visible-attach-acceptance",
- "codex-cli-exec-handoff",
- "codex-cli-session-probe",
- "codex-cli-visible-driver-plan",
- "codex-cli-local-driver-plan",
- "codex-cli-visible-driver-run",
- "codex-cli-local-scheduler-tick",
- "codex-cli-local-scheduler-exec",
- "codex-cli-visible-session-proof",
- "codex-cli-runtime-idle-detector",
- "demo",
- ]
- for command in starter_commands:
- marker = f'if args.command == "{command}":'
- require(marker not in cli_source, f"starter dispatch branch leaked into cli.py: {marker}")
-
- forbidden_handler_markers = [
- "handle_new_project_prompt_command(",
- "handle_codex_cli_bootstrap_message_command(",
- "handle_codex_cli_visible_driver_run_command(",
- "handle_codex_cli_local_scheduler_exec_command(",
- "handle_demo_command(",
- ]
- for marker in forbidden_handler_markers:
- require(marker not in cli_source, f"starter handler marker leaked into cli.py: {marker}")
-
- require("register_starter_commands(sub)" in cli_source, "cli.py did not register starter commands")
- require("handle_starter_command(args, print_payload)" in cli_source, "cli.py did not call starter dispatcher")
- require("def handle_starter_command(" in starter_source, "starter module omitted dispatcher")
- require(
- "register_starter_visible_driver_commands(subparsers)" in starter_source,
- "starter module omitted visible-driver registration delegation",
- )
- require(
- "handle_starter_visible_driver_command(args, print_payload)" in starter_source,
- "starter module omitted visible-driver dispatch delegation",
- )
- require(
- "register_starter_session_runtime_commands(subparsers)" in starter_source,
- "starter module omitted session-runtime registration delegation",
- )
- require(
- "handle_starter_session_runtime_command(args, print_payload)" in starter_source,
- "starter module omitted session-runtime dispatch delegation",
- )
- require(
- "register_starter_scheduler_commands(subparsers)" in starter_source,
- "starter module omitted scheduler registration delegation",
- )
- require(
- "handle_starter_scheduler_command(args, print_payload)" in starter_source,
- "starter module omitted scheduler dispatch delegation",
- )
- require(
- '"codex-cli-visible-driver-run": handle_codex_cli_visible_driver_run_command' in visible_driver_source,
- "visible-driver module omitted visible driver run dispatch",
- )
- require(
- '"codex-cli-local-scheduler-exec": handle_codex_cli_local_scheduler_exec_command' in scheduler_source,
- "scheduler module omitted local scheduler exec dispatch",
- )
- require(
- '"codex-cli-runtime-idle-detector": handle_codex_cli_runtime_idle_detector_command' in session_runtime_source,
- "session-runtime module omitted runtime idle dispatch",
- )
- require('str(getattr(args, "command", "")) == "demo"' in starter_source, "starter dispatcher omitted demo")
- require("handle_starter_command" in init_source, "__init__ omitted starter dispatcher export")
-
-
-def assert_cli_surfaces() -> None:
- help_expectations = {
- "new-project-prompt": ["--goal-doc", "--write-scope"],
- "codex-cli-bootstrap-message": ["--agent-id", "--message-only"],
- "codex-cli-visible-driver-run": ["--proof-fixture", "--allow-headless-fallback"],
- "codex-cli-local-scheduler-exec": ["--guard-checked", "--candidate-command-prefix", "--quota-fixture"],
- "demo": ["--user-todo", "--agent-todo"],
- }
- for command, needles in help_expectations.items():
- help_text = require_success(run_cli(command, "--help"))
- for needle in needles:
- require(needle in help_text, f"{command} help omitted {needle}")
-
- prompt_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "new-project-prompt",
- "--project",
- ".",
- "--goal-doc",
- "README.md",
- "--goal-id",
- "starter-dispatch-smoke",
- )
- )
- require(prompt_payload.get("goal_id") == "starter-dispatch-smoke", prompt_payload)
-
- bootstrap_text = require_success(
- run_cli(
- "codex-cli-bootstrap-message",
- "--project",
- ".",
- "--goal-id",
- "starter-dispatch-smoke",
- "--message-only",
- )
- )
- require("loopx" in bootstrap_text, "message-only bootstrap output lost LoopX command text")
-
- capture_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-first-response-capture-plan",
- "--project",
- ".",
- "--goal-id",
- "starter-dispatch-smoke",
- )
- )
- require(capture_payload.get("goal_id") == "starter-dispatch-smoke", capture_payload)
-
- handoff_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-exec-handoff",
- "--project",
- ".",
- "--goal-id",
- "starter-dispatch-smoke",
- )
- )
- require(handoff_payload.get("goal_id") == "starter-dispatch-smoke", handoff_payload)
-
-
-def main() -> None:
- assert_source_shape()
- assert_cli_surfaces()
- print("cli-starter-dispatch-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-starter-runtime-family-command-modularization-smoke.py b/examples/cli-starter-runtime-family-command-modularization-smoke.py
deleted file mode 100644
index 64c9bd9530..0000000000
--- a/examples/cli-starter-runtime-family-command-modularization-smoke.py
+++ /dev/null
@@ -1,221 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-STARTER = ROOT / "loopx" / "cli_commands" / "starter.py"
-SCHEDULER = ROOT / "loopx" / "cli_commands" / "starter_scheduler.py"
-SESSION_RUNTIME = ROOT / "loopx" / "cli_commands" / "starter_session_runtime.py"
-RUNTIME_IDLE = ROOT / "loopx" / "cli_commands" / "starter_runtime_idle.py"
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-VISIBLE_HELP_FIXTURE = (
- ROOT / "examples" / "fixtures" / "codex-cli-visible-proof" / "codex-visible-resume-help.public.json"
-)
-VISIBLE_PROOF_FIXTURE = (
- ROOT / "examples" / "fixtures" / "codex-cli-visible-proof" / "visible-resume-proof.public.json"
-)
-RUNTIME_IDLE_FIXTURE = (
- ROOT / "examples" / "fixtures" / "codex-cli-visible-proof" / "runtime-idle-visible-resume.public.json"
-)
-
-
-SESSION_RUNTIME_COMMANDS = {
- "codex-cli-session-probe": ["--fixture", "--codex-bin"],
- "codex-cli-visible-session-proof": ["--proof-fixture", "--cli-bin"],
- "codex-cli-runtime-idle-detector": ["--idle-fixture", "--observe-local-runtime"],
-}
-SCHEDULER_COMMANDS = {
- "codex-cli-local-scheduler-tick": ["--proof-fixture", "--idle-fixture", "--quota-fixture", "--allow-headless-fallback"],
- "codex-cli-local-scheduler-exec": ["--guard-checked", "--candidate-command-prefix", "--quota-fixture", "--executor-timeout-seconds"],
-}
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- payload = json.loads(require_success(result))
- require(isinstance(payload, dict), "expected JSON object payload")
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def assert_source_shape() -> None:
- starter_source = STARTER.read_text(encoding="utf-8")
- scheduler_source = SCHEDULER.read_text(encoding="utf-8")
- session_runtime_source = SESSION_RUNTIME.read_text(encoding="utf-8")
- runtime_idle_source = RUNTIME_IDLE.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
-
- forbidden_starter_markers = [
- "codex-cli-session-probe",
- "codex-cli-local-scheduler-tick",
- "codex-cli-local-scheduler-exec",
- "codex-cli-visible-session-proof",
- "codex-cli-runtime-idle-detector",
- "def handle_codex_cli_session_probe_command(",
- "def handle_codex_cli_local_scheduler_tick_command(",
- "def handle_codex_cli_local_scheduler_exec_command(",
- "def handle_codex_cli_visible_session_proof_command(",
- "def handle_codex_cli_runtime_idle_detector_command(",
- "build_codex_cli_local_scheduler_tick(",
- "build_codex_cli_local_scheduler_executor(",
- "build_codex_cli_visible_session_proof(",
- "build_codex_cli_runtime_idle_detector(",
- ]
- for marker in forbidden_starter_markers:
- require(marker not in starter_source, f"runtime/scheduler marker leaked into starter.py: {marker}")
-
- for marker in (
- "register_starter_session_runtime_commands(subparsers)",
- "handle_starter_session_runtime_command(args, print_payload)",
- "register_starter_scheduler_commands(subparsers)",
- "handle_starter_scheduler_command(args, print_payload)",
- ):
- require(marker in starter_source, f"starter.py missing delegation marker: {marker}")
-
- for command in SESSION_RUNTIME_COMMANDS:
- require(command in session_runtime_source, f"starter_session_runtime.py missing command: {command}")
- for marker in (
- "def register_starter_session_runtime_commands(",
- "def handle_starter_session_runtime_command(",
- "_SESSION_RUNTIME_HANDLERS",
- "build_codex_cli_visible_session_proof(",
- "build_codex_cli_runtime_idle_detector(",
- ):
- require(marker in session_runtime_source, f"starter_session_runtime.py missing marker: {marker}")
-
- for command in SCHEDULER_COMMANDS:
- require(command in scheduler_source, f"starter_scheduler.py missing command: {command}")
- for marker in (
- "def register_starter_scheduler_commands(",
- "def handle_starter_scheduler_command(",
- "_SCHEDULER_HANDLERS",
- "build_codex_cli_local_scheduler_tick(",
- "build_codex_cli_local_scheduler_executor(",
- ):
- require(marker in scheduler_source, f"starter_scheduler.py missing marker: {marker}")
-
- for marker in (
- "def _add_runtime_idle_observation_arguments(",
- "def _load_codex_cli_runtime_idle_payload(",
- ):
- require(marker in runtime_idle_source, f"starter_runtime_idle.py missing marker: {marker}")
-
- for marker in (
- "handle_starter_scheduler_command",
- "register_starter_scheduler_commands",
- "handle_starter_session_runtime_command",
- "register_starter_session_runtime_commands",
- "handle_codex_cli_runtime_idle_detector_command",
- "handle_codex_cli_local_scheduler_exec_command",
- ):
- require(marker in init_source, f"__init__ omitted runtime/scheduler export: {marker}")
-
-
-def assert_cli_surfaces() -> None:
- for command, needles in {**SESSION_RUNTIME_COMMANDS, **SCHEDULER_COMMANDS}.items():
- help_text = require_success(run_cli(command, "--help"))
- for needle in needles:
- require(needle in help_text, f"{command} help omitted {needle}")
-
- probe_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-session-probe",
- "--fixture",
- str(VISIBLE_HELP_FIXTURE),
- )
- )
- require(probe_payload.get("recommended_mode") == "visible_resume_or_remote_control_spike", probe_payload)
-
- proof_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-session-proof",
- "--project",
- ".",
- "--goal-id",
- "starter-runtime-family-smoke",
- "--proof-fixture",
- str(VISIBLE_PROOF_FIXTURE),
- )
- )
- require(proof_payload.get("decision") == "visible_session_proof_passed", proof_payload)
-
- idle_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-runtime-idle-detector",
- "--project",
- ".",
- "--goal-id",
- "starter-runtime-family-smoke",
- "--idle-fixture",
- str(RUNTIME_IDLE_FIXTURE),
- )
- )
- require(idle_payload.get("decision") == "runtime_idle_detector_passed", idle_payload)
-
- scheduler_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-local-scheduler-exec",
- "--project",
- ".",
- "--goal-id",
- "starter-runtime-family-smoke",
- "--fixture",
- str(VISIBLE_HELP_FIXTURE),
- "--proof-fixture",
- str(VISIBLE_PROOF_FIXTURE),
- "--idle-fixture",
- str(RUNTIME_IDLE_FIXTURE),
- )
- )
- require(scheduler_payload.get("decision") == "visible_session_turn_candidate", scheduler_payload)
- boundary = scheduler_payload.get("boundary")
- require(isinstance(boundary, dict), scheduler_payload)
- require(boundary.get("runs_external_candidate") is False, scheduler_payload)
- require(boundary.get("runs_codex_candidate_possible") is False, scheduler_payload)
- require(boundary.get("requires_fresh_quota_guard_confirmation") is True, scheduler_payload)
-
-
-def main() -> None:
- assert_source_shape()
- assert_cli_surfaces()
- print("cli-starter-runtime-family-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-starter-visible-driver-family-command-modularization-smoke.py b/examples/cli-starter-visible-driver-family-command-modularization-smoke.py
deleted file mode 100644
index 250dda24a7..0000000000
--- a/examples/cli-starter-visible-driver-family-command-modularization-smoke.py
+++ /dev/null
@@ -1,223 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-STARTER = ROOT / "loopx" / "cli_commands" / "starter.py"
-VISIBLE_COMMON = ROOT / "loopx" / "cli_commands" / "starter_visible_common.py"
-VISIBLE_DRIVER = ROOT / "loopx" / "cli_commands" / "starter_visible_driver.py"
-VISIBLE_PILOT = ROOT / "loopx" / "cli_commands" / "starter_visible_pilot.py"
-RUNTIME_IDLE = ROOT / "loopx" / "cli_commands" / "starter_runtime_idle.py"
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-VISIBLE_HELP_FIXTURE = (
- ROOT / "examples" / "fixtures" / "codex-cli-visible-proof" / "codex-visible-resume-help.public.json"
-)
-VISIBLE_PROOF_FIXTURE = (
- ROOT / "examples" / "fixtures" / "codex-cli-visible-proof" / "visible-resume-proof.public.json"
-)
-
-
-VISIBLE_PILOT_COMMANDS = {
- "codex-cli-one-message-loop-pilot": ["--proof-fixture", "--allow-headless-fallback"],
- "codex-cli-visible-local-driver-pilot": ["--idle-fixture", "--allow-headless-fallback"],
- "codex-cli-bounded-visible-pilot-adapter": ["--first-response-fixture", "--idle-fixture"],
- "codex-cli-visible-first-response-capture-plan": ["--first-response-path", "--idle-path"],
- "codex-cli-visible-attach-acceptance": ["--proof-fixture", "--idle-fixture"],
-}
-VISIBLE_DRIVER_COMMANDS = {
- "codex-cli-visible-driver-plan": ["--fixture", "--codex-bin"],
- "codex-cli-local-driver-plan": ["--fixture", "--codex-bin"],
- "codex-cli-visible-driver-run": ["--proof-fixture", "--allow-headless-fallback"],
-}
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def require_json_success(result: subprocess.CompletedProcess[str]) -> dict[str, object]:
- payload = json.loads(require_success(result))
- require(isinstance(payload, dict), "expected JSON object payload")
- require(payload.get("ok") is True, f"payload was not ok: {payload}")
- return payload
-
-
-def assert_source_shape() -> None:
- starter_source = STARTER.read_text(encoding="utf-8")
- visible_common_source = VISIBLE_COMMON.read_text(encoding="utf-8")
- visible_driver_source = VISIBLE_DRIVER.read_text(encoding="utf-8")
- visible_pilot_source = VISIBLE_PILOT.read_text(encoding="utf-8")
- runtime_idle_source = RUNTIME_IDLE.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
-
- forbidden_starter_markers = [
- "build_codex_cli_one_message_loop_pilot(",
- "build_codex_cli_visible_local_driver_pilot(",
- "build_codex_cli_bounded_visible_pilot_adapter(",
- "build_codex_cli_visible_first_response_capture_plan(",
- "build_codex_cli_visible_attach_acceptance(",
- "build_codex_cli_visible_driver_plan(",
- "build_codex_cli_local_driver_plan(",
- "build_codex_cli_visible_driver_run_packet(",
- "def handle_codex_cli_one_message_loop_pilot_command(",
- "def handle_codex_cli_visible_local_driver_pilot_command(",
- "def handle_codex_cli_bounded_visible_pilot_adapter_command(",
- "def handle_codex_cli_visible_first_response_capture_plan_command(",
- "def handle_codex_cli_visible_attach_acceptance_command(",
- "def handle_codex_cli_visible_driver_plan_command(",
- "def handle_codex_cli_local_driver_plan_command(",
- "def handle_codex_cli_visible_driver_run_command(",
- ]
- for marker in forbidden_starter_markers:
- require(marker not in starter_source, f"visible-driver marker leaked into starter.py: {marker}")
-
- for marker in (
- "register_starter_visible_driver_commands(subparsers)",
- "handle_starter_visible_driver_command(args, print_payload)",
- ):
- require(marker in starter_source, f"starter.py missing visible-driver delegation marker: {marker}")
-
- for command in VISIBLE_PILOT_COMMANDS:
- require(command in visible_pilot_source, f"starter_visible_pilot.py missing command: {command}")
- require(command not in visible_driver_source, f"pilot command leaked into starter_visible_driver.py: {command}")
- for command in VISIBLE_DRIVER_COMMANDS:
- require(command in visible_driver_source, f"starter_visible_driver.py missing command: {command}")
-
- for marker in (
- "def register_starter_visible_driver_commands(",
- "def handle_starter_visible_driver_command(",
- "def handle_codex_cli_visible_driver_run_command(",
- "_VISIBLE_DRIVER_HANDLERS",
- ):
- require(marker in visible_driver_source, f"starter_visible_driver.py missing marker: {marker}")
- for marker in (
- "register_starter_visible_pilot_commands(subparsers)",
- "handle_starter_visible_pilot_command(args, print_payload)",
- ):
- require(marker in visible_driver_source, f"starter_visible_driver.py missing pilot delegation marker: {marker}")
- for marker in (
- "def register_starter_visible_pilot_commands(",
- "def handle_starter_visible_pilot_command(",
- "def handle_codex_cli_one_message_loop_pilot_command(",
- "def handle_codex_cli_visible_attach_acceptance_command(",
- "_VISIBLE_PILOT_HANDLERS",
- ):
- require(marker in visible_pilot_source, f"starter_visible_pilot.py missing marker: {marker}")
-
- for marker in (
- "def _add_project_arguments(",
- "def _add_codex_probe_arguments(",
- "def _add_optional_proof_fixture(",
- "def _add_headless_fallback_argument(",
- ):
- require(marker in visible_common_source, f"starter_visible_common.py missing marker: {marker}")
-
- for marker in (
- "def _add_runtime_idle_observation_arguments(",
- "def _load_codex_cli_runtime_idle_payload(",
- "build_codex_cli_runtime_idle_observation_payload(",
- ):
- require(marker in runtime_idle_source, f"starter_runtime_idle.py missing marker: {marker}")
-
- for marker in (
- "handle_starter_visible_driver_command",
- "handle_starter_visible_pilot_command",
- "register_starter_visible_driver_commands",
- "register_starter_visible_pilot_commands",
- "handle_codex_cli_visible_driver_run_command",
- ):
- require(marker in init_source, f"__init__ omitted visible-driver export: {marker}")
-
- require(len(visible_driver_source.splitlines()) <= 220, "starter_visible_driver.py exceeded size guard")
- require(len(visible_pilot_source.splitlines()) <= 340, "starter_visible_pilot.py exceeded size guard")
-
-
-def assert_cli_surfaces() -> None:
- for command, needles in {**VISIBLE_PILOT_COMMANDS, **VISIBLE_DRIVER_COMMANDS}.items():
- help_text = require_success(run_cli(command, "--help"))
- for needle in needles:
- require(needle in help_text, f"{command} help omitted {needle}")
-
- capture_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-first-response-capture-plan",
- "--project",
- ".",
- "--goal-id",
- "starter-visible-driver-smoke",
- )
- )
- require(capture_payload.get("goal_id") == "starter-visible-driver-smoke", capture_payload)
-
- plan_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-driver-plan",
- "--project",
- ".",
- "--goal-id",
- "starter-visible-driver-smoke",
- "--fixture",
- str(VISIBLE_HELP_FIXTURE),
- )
- )
- require(plan_payload.get("driver_mode") == "visible_resume_or_remote_control_spike", plan_payload)
-
- run_payload = require_json_success(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-driver-run",
- "--project",
- ".",
- "--goal-id",
- "starter-visible-driver-smoke",
- "--fixture",
- str(VISIBLE_HELP_FIXTURE),
- "--proof-fixture",
- str(VISIBLE_PROOF_FIXTURE),
- )
- )
- require(run_payload.get("decision") == "visible_session_turn_candidate", run_payload)
- boundary = run_payload.get("boundary")
- require(isinstance(boundary, dict), run_payload)
- require(boundary.get("runs_codex") is False, run_payload)
- require(boundary.get("mutates_codex_session") is False, run_payload)
-
-
-def main() -> None:
- assert_source_shape()
- assert_cli_surfaces()
- print("cli-starter-visible-driver-family-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cli-support-control-command-modularization-smoke.py b/examples/cli-support-control-command-modularization-smoke.py
deleted file mode 100644
index 8866d63072..0000000000
--- a/examples/cli-support-control-command-modularization-smoke.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import subprocess
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-CLI = ROOT / "loopx" / "cli.py"
-MODULE = ROOT / "loopx" / "cli_commands" / "support_control.py"
-HEARTBEAT = MODULE.with_name("support_control_heartbeat.py")
-INIT = ROOT / "loopx" / "cli_commands" / "__init__.py"
-
-
-def run_cli(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.entrypoint", *args],
- cwd=ROOT,
- text=True,
- capture_output=True,
- check=False,
- )
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def require_success(result: subprocess.CompletedProcess[str]) -> str:
- if result.returncode != 0:
- raise AssertionError(
- f"expected success, got {result.returncode}\n"
- f"stdout:\n{result.stdout}\n\nstderr:\n{result.stderr}"
- )
- return result.stdout
-
-
-def main() -> None:
- cli_source = CLI.read_text(encoding="utf-8")
- module_source = MODULE.read_text(encoding="utf-8")
- init_source = INIT.read_text(encoding="utf-8")
-
- forbidden_cli_markers = [
- "backup_state_parser = sub.add_parser",
- "heartbeat_prompt_parser = sub.add_parser",
- "promotion_gate_parser = sub.add_parser",
- "upgrade_plan_parser = sub.add_parser",
- "update_parser = sub.add_parser",
- "registry_boundary_parser = sub.add_parser",
- "serve_status_parser = sub.add_parser",
- "chat_parser = sub.add_parser",
- "resolve_heartbeat_active_state(",
- "build_heartbeat_prompt(",
- "build_promotion_gate(",
- "build_upgrade_plan(",
- "build_update_plan(",
- "build_state_backup_plan(",
- "inspect_registry(",
- "inspect_registry_boundary(",
- "serve_status(",
- "serve_chat(",
- 'if args.command == "backup-state":',
- 'if args.command == "heartbeat-prompt":',
- 'if args.command == "promotion-gate":',
- 'if args.command == "upgrade-plan":',
- 'if args.command == "update":',
- 'if args.command == "registry":',
- 'if args.command == "registry-boundary":',
- 'if args.command == "serve-status":',
- 'if args.command == "chat":',
- ]
- for marker in forbidden_cli_markers:
- require(marker not in cli_source, f"support/control marker leaked into cli.py: {marker}")
-
- for marker in (
- "SUPPORT_CONTROL_COMMANDS",
- "register_support_control_commands",
- "handle_support_control_command",
- "backup-state",
- "chat",
- "promotion-gate",
- "upgrade-plan",
- "update",
- "registry-boundary",
- "serve-status",
- ):
- require(marker in module_source, f"support/control module missing {marker}")
- require("register_support_control_commands" in cli_source, "cli.py did not register support/control commands")
- require("handle_support_control_command" in cli_source, "cli.py did not dispatch support/control commands")
- require("register_support_control_commands" in init_source, "__init__ omitted support/control registration")
- require("handle_support_control_command" in init_source, "__init__ omitted support/control handler")
- heartbeat_source = HEARTBEAT.read_text(encoding="utf-8")
- require("build_heartbeat_prompt(" not in module_source, "support/control retained duplicate heartbeat dispatch")
- for marker in ("handle_heartbeat_prompt_command", "resolve_heartbeat_active_state", "build_heartbeat_prompt("):
- require(marker in heartbeat_source, f"heartbeat handler missing {marker}")
-
- for command, options in {
- "backup-state": (
- "--project",
- "--output-dir",
- "--backup-id",
- "--current-project-only",
- "--execute",
- ),
- "heartbeat-prompt": ("--goal-id", "--agent-id", "--thin"),
- "promotion-gate": ("--format",),
- "upgrade-plan": ("--installed-manifest", "--cli-bin", "--mode"),
- "update": ("--check", "--dry-run", "--execute"),
- "registry": (),
- "registry-boundary": ("--path", "--require-not-tracked", "--require-gitignored"),
- "serve-status": ("--global-registry", "--enable-reward-write-api", "--enable-control-plane-write-api"),
- "chat": ("--goal-id", "--codex-bin", "--no-open", "--global-registry"),
- }.items():
- help_text = require_success(run_cli(command, "--help"))
- for option in options:
- require(option in help_text, f"{command} help omitted {option}")
-
- print("cli-support-control-command-modularization-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/codex-app-control-plane-hook-cache-smoke.py b/examples/codex-app-control-plane-hook-cache-smoke.py
deleted file mode 100644
index 266007e261..0000000000
--- a/examples/codex-app-control-plane-hook-cache-smoke.py
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex App control-plane hook/cache experiment contract."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-DOC = REPO_ROOT / "docs/product/runtimes/codex-app/codex-app-control-plane-hook-cache.md"
-RUNTIME_INDEX = REPO_ROOT / "docs/product/runtimes/codex-app/README.md"
-
-
-def main() -> int:
- doc = DOC.read_text(encoding="utf-8")
- index = RUNTIME_INDEX.read_text(encoding="utf-8")
- normalized_doc = " ".join(doc.split())
-
- required_phrases = [
- "Status: experimental design note, default off.",
- "enabled_by_default: false",
- "mode: advisory_hint",
- "host-runtime hint",
- "LoopX remains authoritative",
- "Missing, stale, or mismatched hints fall back to the CLI.",
- "quiet_wait_cache_lab",
- "guard_projection_lab",
- "default_candidate",
- "Evidence Gates",
- "zero false run and zero false quiet-skip decisions",
- "public/private scans",
- "Fallback CLI Path",
- "Keep all delivery, writeback, publication, and quota spend decisions on the existing CLI guard.",
- ]
- for phrase in required_phrases:
- assert phrase in doc or phrase in normalized_doc, phrase
-
- forbidden_default_claims = [
- "enabled_by_default: true",
- "default enabled",
- "enable automatically",
- "replace quota should-run",
- ]
- lowered = doc.lower()
- for phrase in forbidden_default_claims:
- assert phrase not in lowered, phrase
-
- assert "codex-app-control-plane-hook-cache.md" in index, "runtime index link"
-
- print("codex-app-control-plane-hook-cache-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-bootstrap-message-smoke.py b/examples/codex-cli-bootstrap-message-smoke.py
index 1a69c41e14..3791217ccc 100644
--- a/examples/codex-cli-bootstrap-message-smoke.py
+++ b/examples/codex-cli-bootstrap-message-smoke.py
@@ -193,13 +193,12 @@ def assert_docs_surface_codex_cli_quickstart() -> None:
assert "Codex App gets a heartbeat automation body that starts at 3 minutes" in normalized_getting_started, getting_started
assert "transcript-free validation checklist" in normalized_getting_started, getting_started
assert "installs the generated LoopX goal/heartbeat loader immediately" in normalized_product_contract, product_contract
- assert "optional automation checks after the setup path works" in normalized_getting_started, getting_started
assert "first useful TUI response should be a control-plane snapshot" in normalized_product_contract, product_contract
assert "setup-only work" in normalized_product_contract, product_contract
- assert "loopx codex-cli-session-probe" in getting_started, getting_started
- assert "loopx codex-cli-exec-handoff --project . --goal-id " in getting_started, getting_started
+ assert "loopx turn plan" in getting_started, getting_started
+ assert "loopx turn run-once" in getting_started, getting_started
assert "headless-disabled boundary" in normalized_getting_started, getting_started
- assert "This command no longer prints a runnable `codex exec` handoff script" in product_contract, product_contract
+ assert "default Codex CLI LoopX setup-then-`/goal` path does not expose a headless fallback" in normalized_product_contract, product_contract
def main() -> int:
diff --git a/examples/codex-cli-bounded-visible-pilot-adapter-smoke.py b/examples/codex-cli-bounded-visible-pilot-adapter-smoke.py
deleted file mode 100644
index 8bb28ddf51..0000000000
--- a/examples/codex-cli-bounded-visible-pilot-adapter-smoke.py
+++ /dev/null
@@ -1,225 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI bounded visible pilot adapter packet."""
-
-from __future__ import annotations
-
-import copy
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_bounded_visible_pilot_adapter,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-LIVE_PILOT_DOC = REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "codex-cli-live-tui-first-message-pilot.md"
-PRODUCT_README = (
- REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "README.md"
-)
-
-
-PASSING_FIRST_RESPONSE_FIXTURE = {
- "observed_surface": "codex_cli_tui_visible_window",
- "prompt_delivery": {
- "manual_or_visible_delivery": True,
- "prompt_public_safe": True,
- "argv_prompt_used": False,
- },
- "first_response": {
- "goal_id_visible": True,
- "user_gate_or_none_visible": True,
- "top_user_todo_or_none_visible": True,
- "top_agent_todo_visible": True,
- "next_safe_action_visible": True,
- "bounded_segment_started_or_blocker_written": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "writeback": {
- "compact_evidence_planned": True,
- "quota_spend_after_writeback_only": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
-}
-
-
-PASSING_IDLE_FIXTURE = {
- "observed_surface": "codex_cli_tui_visible_window",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-def build_adapter(
- *,
- first_response: dict[str, object] | None = None,
- idle: dict[str, object] | None = None,
-) -> dict[str, object]:
- return build_codex_cli_bounded_visible_pilot_adapter(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- first_response_payload=first_response,
- idle_payload=idle,
- )
-
-
-def assert_boundary(payload: dict[str, object]) -> None:
- boundary = payload["boundary"]
- assert boundary["adapter_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["reads_stdout_stderr"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["writes_loopx_state"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["requires_visible_delivery"] is True, payload
- assert boundary["argv_prompt_rejected"] is True, payload
- assert boundary["success_claim_requires_first_response_and_idle"] is True, payload
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_docs() -> None:
- live_pilot = LIVE_PILOT_DOC.read_text(encoding="utf-8")
- product_readme = PRODUCT_README.read_text(encoding="utf-8")
- assert "codex-cli-bounded-visible-pilot-adapter" in live_pilot, live_pilot
- assert "public-first-response.json" in live_pilot, live_pilot
- assert "argv prompt" in live_pilot, live_pilot
- assert "Codex CLI bounded visible pilot adapter" in product_readme, product_readme
- assert "codex-cli-bounded-visible-pilot-adapter-smoke.py" in product_readme, product_readme
-
-
-def main() -> int:
- missing = build_adapter()
- assert missing["ok"] is True, missing
- assert missing["schema_version"] == "codex_cli_bounded_visible_pilot_adapter_v0", missing
- assert missing["decision"] == "bounded_visible_completion_evidence_required", missing
- assert missing["approved_for_live_tui_success_claim"] is False, missing
- assert "missing_first_response_evidence" in missing["blockers"], missing
- assert "missing_runtime_idle_evidence" in missing["blockers"], missing
- assert "codex-cli-bootstrap-message" in missing["commands"]["bootstrap_message"], missing
- assert "codex-cli-bounded-visible-pilot-adapter" in missing["commands"]["bounded_visible_pilot_adapter"], missing
- assert_boundary(missing)
-
- argv_leaking = copy.deepcopy(PASSING_FIRST_RESPONSE_FIXTURE)
- argv_leaking["prompt_delivery"]["argv_prompt_used"] = True
- rejected = build_adapter(first_response=argv_leaking, idle=PASSING_IDLE_FIXTURE)
- assert rejected["decision"] == "bounded_visible_first_response_incomplete", rejected
- assert rejected["approved_for_live_tui_success_claim"] is False, rejected
- assert "no_argv_prompt" in rejected["blockers"], rejected
- assert "argv_prompt_leakage_risk" in rejected["blockers"], rejected
- assert rejected["runtime_idle_detector"]["approved"] is True, rejected
- assert_boundary(rejected)
-
- passing = build_adapter(
- first_response=PASSING_FIRST_RESPONSE_FIXTURE,
- idle=PASSING_IDLE_FIXTURE,
- )
- assert passing["decision"] == "bounded_visible_pilot_ready_for_success_claim", passing
- assert passing["approved_for_live_tui_success_claim"] is True, passing
- assert passing["first_response"]["approved"] is True, passing
- assert passing["runtime_idle_detector"]["approved"] is True, passing
- assert passing["blockers"] == [], passing
- assert "--delivery-outcome outcome_progress" in passing["commands"]["success_writeback"], passing
- assert_boundary(passing)
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-bounded-visible-") as tmp:
- tmp_path = Path(tmp)
- first_response_fixture = tmp_path / "public-first-response.json"
- first_response_fixture.write_text(json.dumps(PASSING_FIRST_RESPONSE_FIXTURE))
- idle_fixture = tmp_path / "public-runtime-idle.json"
- idle_fixture.write_text(json.dumps(PASSING_IDLE_FIXTURE))
-
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-bounded-visible-pilot-adapter",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--first-response-fixture",
- str(first_response_fixture),
- "--idle-fixture",
- str(idle_fixture),
- )
- )
- assert cli_json["decision"] == "bounded_visible_pilot_ready_for_success_claim", cli_json
- assert cli_json["approved_for_live_tui_success_claim"] is True, cli_json
- assert_boundary(cli_json)
-
- markdown = run_cli(
- "codex-cli-bounded-visible-pilot-adapter",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--first-response-fixture",
- str(first_response_fixture),
- "--idle-fixture",
- str(idle_fixture),
- )
- assert "# Codex CLI Bounded Visible Pilot Adapter" in markdown, markdown
- assert "approved_for_live_tui_success_claim" in markdown, markdown
- assert "argv_prompt_rejected" in markdown, markdown
-
- assert_docs()
- print("codex-cli-bounded-visible-pilot-adapter-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-exec-handoff-smoke.py b/examples/codex-cli-exec-handoff-smoke.py
deleted file mode 100644
index 4b717064a2..0000000000
--- a/examples/codex-cli-exec-handoff-smoke.py
+++ /dev/null
@@ -1,104 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the disabled Codex CLI exec handoff boundary."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.project_prompt import build_codex_cli_exec_handoff # noqa: E402
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_handoff_contract(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_exec_handoff_v0", payload
- assert payload["mode"] == "headless_fallback_disabled_for_goal_mode_bootstrap", payload
- assert payload["primary_experience"] == "codex_cli_tui_goal_bootstrap", payload
- assert payload["goal_id"] == GOAL_ID, payload
- assert payload["agent_id"] == AGENT_ID, payload
- command = str(payload["handoff_command"])
- message_only = str(payload["message_only_command"])
- assert command == "", payload
- assert "codex exec" not in command, payload
- assert "codex-cli-bootstrap-message" in message_only, payload
- assert "--message-only" in message_only, payload
- assert "disabled" in str(payload["disabled_reason"]).lower(), payload
- boundary = payload["boundary"]
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["headless_execution_disabled"] is True, payload
- assert boundary["provides_executable_headless_command"] is False, payload
-
-
-def main() -> int:
- payload = build_codex_cli_exec_handoff(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- )
- assert_handoff_contract(payload)
-
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-exec-handoff",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- )
- )
- assert_handoff_contract(cli_json)
-
- cli_markdown = run_cli(
- "codex-cli-exec-handoff",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- )
- assert "# Codex CLI Exec Handoff Disabled" in cli_markdown, cli_markdown
- assert "Headless `codex exec` handoff is disabled" in cli_markdown, cli_markdown
- assert "codex-cli-bootstrap-message" in cli_markdown, cli_markdown
- assert "cat <<'LOOPX_CODEX_PROMPT' | codex exec" not in cli_markdown, cli_markdown
-
- print("codex-cli-exec-handoff-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-first-run-rehearsal-smoke.py b/examples/codex-cli-first-run-rehearsal-smoke.py
index ac64e15fb8..f94bb87d6d 100644
--- a/examples/codex-cli-first-run-rehearsal-smoke.py
+++ b/examples/codex-cli-first-run-rehearsal-smoke.py
@@ -43,15 +43,12 @@ def assert_doc() -> None:
"Codex CLI First-Run Rehearsal",
"PyPI install/update with packaged workflow skills and an archive fallback",
"one-message Codex CLI TUI bootstrap",
- "proof-capture fixtures for later visible automation",
+ "bounded isolated-headless turns via `loopx turn`",
"Start LoopX for this repo",
"python3 -m pip install --upgrade loopx",
"loopx workflow-skills --install",
"loopx codex-cli-bootstrap-message --project . --goal-id --message-only",
- "loopx codex-cli-tui-bootstrap-smoke-bundle",
- "loopx --format json codex-cli-visible-attach-acceptance",
- "does not prove same-open-TUI automation",
- "Same-TUI automation stays optional until the proof path passes",
+ "Same-TUI automation stays optional until a safe attach primitive is proven",
"must not:",
"require cloning the LoopX repo",
"read raw Codex transcripts, session files, stdout, stderr, credentials, or private paths",
@@ -77,7 +74,7 @@ def assert_indexes() -> None:
assert f"../product/runtimes/codex-cli/{link}" in getting_started, getting_started
assert "PyPI" in product, product
assert "one-message TUI bootstrap" in product, product
- assert "proof-capture fixtures" in getting_started, getting_started
+ assert "explicit `loopx turn` boundaries" in getting_started, getting_started
def assert_cli_surfaces_align() -> None:
@@ -111,20 +108,6 @@ def assert_cli_surfaces_align() -> None:
assert "settlement_plan.ordered_steps" in normalized, message
assert "raw Codex transcripts" in normalized, message
- bundle = run_cli(
- "codex-cli-tui-bootstrap-smoke-bundle",
- "--project",
- "/tmp/public-codex-cli-project",
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- )
- normalized_bundle = normalize(bundle)
- assert "Codex CLI TUI Bootstrap Smoke Bundle" in normalized_bundle, bundle
- assert "runs_codex: `False`" in normalized_bundle, bundle
- assert "requires_loopx_repo_clone: `False`" in normalized_bundle, bundle
-
def main() -> int:
assert_doc()
diff --git a/examples/codex-cli-live-tui-first-message-pilot-smoke.py b/examples/codex-cli-live-tui-first-message-pilot-smoke.py
deleted file mode 100644
index 02a159041f..0000000000
--- a/examples/codex-cli-live-tui-first-message-pilot-smoke.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/env python3
-"""Validate the Codex CLI live TUI first-message pilot record."""
-
-from __future__ import annotations
-
-import subprocess
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-DOC = REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "codex-cli-live-tui-first-message-pilot.md"
-FIRST_RUN = REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "codex-cli-first-run-rehearsal.md"
-PRODUCT_README = (
- REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "README.md"
-)
-GOAL_ID = "public-live-tui-pilot-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-def normalize(text: str) -> str:
- return " ".join(text.split())
-
-
-def run_cli(*args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *args],
- cwd=REPO_ROOT,
- check=True,
- text=True,
- capture_output=True,
- )
- return result.stdout
-
-
-def assert_doc() -> None:
- text = DOC.read_text(encoding="utf-8")
- normalized = normalize(text)
-
- must_have = (
- "Codex CLI Live TUI First-Message Pilot",
- "Status: blocker recorded; manual TUI bootstrap remains primary.",
- "Recorded: 2026-06-21.",
- "disposable public-safe repo",
- "codex [OPTIONS] [PROMPT]",
- "--no-alt-screen",
- "--cd ",
- "resume",
- "remote-control",
- "codex doctor",
- "did not produce bounded output before manual interrupt",
- "no bounded first-response or completion signal",
- "capture output exceeded the automation budget",
- "process remained active",
- "process command line",
- "live_tui_first_message_blocked_by_bounded_visible_completion_missing",
- "manual TUI bootstrap remains primary",
- "the user pastes one LoopX start message",
- "without leaking project-specific prompt text through process arguments",
- "raw transcript or session-file reads",
- "Codex CLI bounded visible pilot adapter",
- )
- for phrase in must_have:
- assert phrase in normalized, phrase
-
- assert "LoopX should not advertise automated `codex [PROMPT]` launch" in text
- assert "raw TUI output, Codex transcripts, session files" in normalized, text
- assert "without raw transcript or session-file reads" in normalized, text
-
-
-def assert_indexes() -> None:
- product = PRODUCT_README.read_text(encoding="utf-8")
- first_run = FIRST_RUN.read_text(encoding="utf-8")
- assert "codex-cli-live-tui-first-message-pilot.md" in product, product
- assert "Codex CLI live TUI first-message pilot" in product, product
- assert "Live TUI Pilot Note" in first_run, first_run
- assert (
- "Automated live launch needs a bounded visible completion proof first." in first_run
- ), first_run
-
-
-def assert_bootstrap_message_still_copy_first() -> None:
- message = run_cli(
- "codex-cli-bootstrap-message",
- "--project",
- "/tmp/loopx-live-tui-pilot.public",
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--message-only",
- )
- normalized = normalize(message)
- assert message.startswith("Install and connect LoopX for this repo"), message
- assert not message.startswith("/goal "), message
- assert "Codex CLI TUI" in normalized, message
- assert "setup/bootstrap instruction" in normalized, message
- assert "/goal " in normalized, message
- assert "raw Codex transcripts" in normalized, message
- assert "watch, steer, review, and take over" in normalized, message
-
-
-def main() -> int:
- assert_doc()
- assert_indexes()
- assert_bootstrap_message_still_copy_first()
- print("codex-cli-live-tui-first-message-pilot-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-local-driver-plan-smoke.py b/examples/codex-cli-local-driver-plan-smoke.py
deleted file mode 100644
index 14d57c5171..0000000000
--- a/examples/codex-cli-local-driver-plan-smoke.py
+++ /dev/null
@@ -1,183 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the dry-run-first Codex CLI local driver plan."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_local_driver_plan,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec Run Codex non-interactively
- resume Resume a previous conversation
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-ATTACH_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- resume
- attach-session Send prompt to session after checking the idle TUI
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_common_contract(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_local_driver_plan_v0", payload
- assert payload["driver_phase"] == "dry_run_plan", payload
- assert payload["goal_id"] == GOAL_ID, payload
- assert payload["agent_id"] == AGENT_ID, payload
- commands = payload["commands"]
- assert "quota should-run --goal-id public-codex-cli-goal --agent-id codex-side-bypass" in commands["quota_guard"], payload
- assert "codex-cli-visible-driver-plan" in commands["visible_driver_plan"], payload
- assert "codex-cli-bootstrap-message" in commands["tui_bootstrap_message"], payload
- assert commands["explicit_headless_fallback"] is None, payload
- assert "headless codex exec is disabled" in commands["headless_fallback_disabled"], payload
- assert payload["idle_guard"]["required"] is True, payload
- assert payload["idle_guard"]["implemented"] is False, payload
- policy = payload["execution_policy"]
- assert policy["tui_bootstrap_primary"] is True, payload
- assert policy["headless_execution_disabled"] is True, payload
- assert policy["same_session_attachment_requires_visible_proof"] is True, payload
- boundary = payload["boundary"]
- assert boundary["dry_run_plan_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
-
-
-def build_plan(command_outputs: dict[str, str]) -> dict[str, object]:
- return build_codex_cli_local_driver_plan(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=command_outputs),
- )
-
-
-def main() -> int:
- fallback_plan = build_plan(HELP_FIXTURE)
- assert_common_contract(fallback_plan)
- assert fallback_plan["driver_mode"] == "tui_bootstrap_only", fallback_plan
- assert fallback_plan["decision"] == "ask_user_to_start_from_tui", fallback_plan
-
- remote_plan = build_plan(REMOTE_RESUME_HELP_FIXTURE)
- assert_common_contract(remote_plan)
- assert remote_plan["driver_mode"] == "visible_resume_or_remote_control_spike", remote_plan
- assert remote_plan["decision"] == "run_visible_resume_or_remote_control_proof", remote_plan
-
- attach_plan = build_plan(ATTACH_HELP_FIXTURE)
- assert_common_contract(attach_plan)
- assert attach_plan["driver_mode"] == "session_attached_visible_turn", attach_plan
- assert attach_plan["decision"] == "attempt_visible_session_attach_after_idle_guard", attach_plan
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-local-driver-") as tmp:
- fixture = Path(tmp) / "codex-remote-help.json"
- fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-local-driver-plan",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(fixture),
- )
- )
- assert_common_contract(cli_json)
- assert cli_json["driver_mode"] == "visible_resume_or_remote_control_spike", cli_json
-
- cli_markdown = run_cli(
- "codex-cli-local-driver-plan",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(fixture),
- )
- assert "# Codex CLI Local Driver Plan" in cli_markdown, cli_markdown
- assert "driver_phase: `dry_run_plan`" in cli_markdown, cli_markdown
- assert "headless_execution_disabled: `True`" in cli_markdown, cli_markdown
-
- print("codex-cli-local-driver-plan-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-local-scheduler-exec-smoke.py b/examples/codex-cli-local-scheduler-exec-smoke.py
deleted file mode 100644
index cbbe19e8ea..0000000000
--- a/examples/codex-cli-local-scheduler-exec-smoke.py
+++ /dev/null
@@ -1,359 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI local scheduler executor wrapper."""
-
-from __future__ import annotations
-
-import json
-import shlex
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_local_scheduler_executor,
- classify_codex_cli_session_surface,
- execute_codex_cli_local_scheduler_tick_result,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-VISIBLE_PROOF_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "recommended_command": f"{shlex.quote(sys.executable)} -c 'pass'",
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
-}
-
-
-RUNTIME_IDLE_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-def fake_runner_calls() -> tuple[list[dict[str, object]], object]:
- calls: list[dict[str, object]] = []
-
- def runner(command: str, *, timeout_seconds: float, capture_output: bool = False) -> dict[str, object]:
- calls.append(
- {
- "command": command,
- "timeout_seconds": timeout_seconds,
- "capture_output": capture_output,
- }
- )
- return {
- "attempted": True,
- "returncode": 0,
- "timed_out": False,
- "output_captured": capture_output,
- }
-
- return calls, runner
-
-
-def build_exec(
- *,
- proof_payload: dict[str, object] | None = VISIBLE_PROOF_FIXTURE,
- idle_payload: dict[str, object] | None = RUNTIME_IDLE_FIXTURE,
- execute_candidate: bool = False,
- execute_blocker_writeback: bool = False,
- guard_checked: bool = False,
- prefixes: list[str] | None = None,
- runner=None,
-) -> dict[str, object]:
- return build_codex_cli_local_scheduler_executor(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=REMOTE_RESUME_HELP_FIXTURE),
- proof_payload=proof_payload,
- idle_payload=idle_payload,
- execute_candidate=execute_candidate,
- execute_blocker_writeback=execute_blocker_writeback,
- guard_checked=guard_checked,
- candidate_command_prefixes=prefixes or [],
- runner=runner,
- )
-
-
-def assert_executor_boundary(payload: dict[str, object]) -> None:
- assert payload["schema_version"] == "codex_cli_local_scheduler_executor_v0", payload
- boundary = payload["boundary"]
- assert boundary["executor_wrapper"] is True, payload
- assert boundary["requires_explicit_execute_flag"] is True, payload
- assert boundary["requires_fresh_quota_guard_confirmation"] is True, payload
- assert boundary["candidate_prefix_required"] is True, payload
- assert boundary["runtime_idle_detector_required_for_visible_candidate"] is True, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["candidate_output_captured"] is False, payload
- assert boundary["blocker_output_captured"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def main() -> int:
- calls, runner = fake_runner_calls()
-
- no_execute = build_exec(runner=runner)
- assert no_execute["ok"] is True, no_execute
- assert_executor_boundary(no_execute)
- assert no_execute["execution"]["executed"] is False, no_execute
- assert no_execute["execution"]["reason"] == "no_execute_flag", no_execute
- assert calls == [], calls
-
- guard_missing = build_exec(
- execute_candidate=True,
- prefixes=[sys.executable],
- runner=runner,
- )
- assert guard_missing["execution"]["reason"] == "fresh_quota_guard_confirmation_required", guard_missing
- assert calls == [], calls
-
- idle_missing = build_exec(
- idle_payload=None,
- execute_candidate=True,
- guard_checked=True,
- prefixes=[sys.executable],
- runner=runner,
- )
- assert idle_missing["scheduler_action"] == "write_precise_blocker", idle_missing
- assert idle_missing["scheduler_tick"]["precise_blocker"]["reason"] == "runtime_idle_evidence_missing", idle_missing
- assert idle_missing["execution"]["reason"] == "scheduler_action_not_candidate", idle_missing
- assert calls == [], calls
-
- tampered_tick = {
- "schema_version": "codex_cli_local_scheduler_tick_v0",
- "project": str(PROJECT),
- "goal_id": GOAL_ID,
- "agent_id": AGENT_ID,
- "cli_bin": "loopx",
- "codex_bin": "codex",
- "scheduler_phase": "tick_packet_no_execution",
- "scheduler_action": "external_visible_command_candidate",
- "decision": "visible_session_turn_candidate",
- "next_safe_step": "tampered visible candidate",
- "candidate_command": f"{shlex.quote(sys.executable)} -c 'pass'",
- "commands": {"scheduler_tick": "loopx codex-cli-local-scheduler-tick"},
- "visible_driver_run_packet": {
- "visible_session_proof": {"supplied": True, "approved": True}
- },
- "runtime_idle_detector": {"supplied": False, "approved": False},
- }
- tampered_reject = execute_codex_cli_local_scheduler_tick_result(
- tampered_tick,
- execute_candidate=True,
- guard_checked=True,
- candidate_command_prefixes=[sys.executable],
- runner=runner,
- )
- assert tampered_reject["execution"]["reason"] == "runtime_idle_detector_required", tampered_reject
- assert calls == [], calls
-
- prefix_missing = build_exec(
- execute_candidate=True,
- guard_checked=True,
- runner=runner,
- )
- assert prefix_missing["execution"]["reason"] == "candidate_command_prefix_required", prefix_missing
- assert calls == [], calls
-
- prefix_mismatch = build_exec(
- execute_candidate=True,
- guard_checked=True,
- prefixes=["definitely-not-python"],
- runner=runner,
- )
- assert prefix_mismatch["execution"]["reason"] == "candidate_command_prefix_mismatch", prefix_mismatch
- assert calls == [], calls
-
- candidate = build_exec(
- execute_candidate=True,
- guard_checked=True,
- prefixes=[sys.executable],
- runner=runner,
- )
- assert candidate["ok"] is True, candidate
- assert candidate["execution"]["executed"] is True, candidate
- assert candidate["execution"]["kind"] == "candidate_command", candidate
- assert candidate["execution"]["reason"] == "candidate_command_executed", candidate
- assert candidate["boundary"]["runs_external_candidate"] is True, candidate
- assert calls[-1]["capture_output"] is False, calls
-
- blocker = build_exec(
- proof_payload=None,
- execute_blocker_writeback=True,
- guard_checked=True,
- runner=runner,
- )
- assert blocker["ok"] is True, blocker
- assert blocker["execution"]["kind"] == "blocker_writeback", blocker
- assert "refresh-state" in calls[-1]["command"], calls
- assert blocker["boundary"]["writes_loopx_state"] is True, blocker
- assert blocker["boundary"]["spends_loopx_quota"] is False, blocker
- assert calls[-1]["capture_output"] is False, calls
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-scheduler-exec-") as tmp:
- tmp_path = Path(tmp)
- help_fixture = tmp_path / "codex-remote-help.json"
- help_fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- proof_fixture = tmp_path / "visible-proof.json"
- proof_fixture.write_text(json.dumps(VISIBLE_PROOF_FIXTURE))
- idle_fixture = tmp_path / "runtime-idle.json"
- idle_fixture.write_text(json.dumps(RUNTIME_IDLE_FIXTURE))
- missing_registry = tmp_path / "missing-registry.json"
- runtime_root = tmp_path / "runtime"
-
- cli_json = json.loads(
- run_cli(
- "--registry",
- str(missing_registry),
- "--runtime-root",
- str(runtime_root),
- "--format",
- "json",
- "codex-cli-local-scheduler-exec",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- )
- assert_executor_boundary(cli_json)
- assert cli_json["execution"]["reason"] == "no_execute_flag", cli_json
-
- cli_prefix_reject = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-local-scheduler-exec",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- "--idle-fixture",
- str(idle_fixture),
- "--execute-candidate",
- "--guard-checked",
- "--candidate-command-prefix",
- "definitely-not-python",
- )
- )
- assert cli_prefix_reject["ok"] is True, cli_prefix_reject
- assert cli_prefix_reject["execution"]["executed"] is False, cli_prefix_reject
- assert cli_prefix_reject["execution"]["reason"] == "candidate_command_prefix_mismatch", cli_prefix_reject
-
- cli_markdown = run_cli(
- "codex-cli-local-scheduler-exec",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- assert "# Codex CLI Local Scheduler Executor" in cli_markdown, cli_markdown
- assert "reason: `no_execute_flag`" in cli_markdown, cli_markdown
- assert "candidate_output_captured: `False`" in cli_markdown, cli_markdown
-
- print("codex-cli-local-scheduler-exec-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-local-scheduler-tick-smoke.py b/examples/codex-cli-local-scheduler-tick-smoke.py
deleted file mode 100644
index 0df0ccf48c..0000000000
--- a/examples/codex-cli-local-scheduler-tick-smoke.py
+++ /dev/null
@@ -1,353 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI local scheduler tick packet."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_local_scheduler_tick,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-FALLBACK_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec Run Codex non-interactively
- resume Resume a previous conversation
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-VISIBLE_PROOF_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "recommended_command": "codex resume public-session-id 'LoopX visible steering turn'",
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
-}
-
-
-RUNTIME_IDLE_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-QUOTA_HINT_FIXTURE = {
- "scheduler_hint": {
- "schema_version": "scheduler_hint_v0",
- "action": "backoff_until_reassigned",
- "cadence_class": "agent_scope_wait",
- "codex_app": {
- "recommended_interval_minutes": 10,
- "max_interval_minutes": 60,
- "unchanged_poll_backoff_multiplier": 2,
- "example_progression_minutes": [10, 20, 30, 60],
- },
- "unchanged_poll": {
- "limits": {
- "local_scheduler": 3,
- "codex_cli_tui": 3,
- "claude_code_loop": 3,
- },
- "after_limits": {
- "local_scheduler": "stop_tick_loop",
- "codex_cli_tui": "update_goal_blocked_keep_loopx_active",
- "claude_code_loop": "stop_loop",
- },
- "final_quota_replan_check_enabled": True,
- "final_quota_replan_check_action": "rerun_quota_should_run_once",
- },
- "reset_policy": {
- "schema_version": "scheduler_reset_policy_v0",
- "reset_token": "fixture-reset-001",
- "local_scheduler_initial_interval_minutes": 10,
- "codex_app_initial_rrule": "FREQ=MINUTELY;INTERVAL=10",
- },
- }
-}
-
-
-def assert_boundary(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_local_scheduler_tick_v0", payload
- assert payload["scheduler_phase"] == "tick_packet_no_execution", payload
- boundary = payload["boundary"]
- assert boundary["tick_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["writes_loopx_state"] is False, payload
- assert boundary["visible_candidate_requires_runtime_idle_detector"] is True, payload
- assert boundary["headless_execution_disabled"] is True, payload
-
-
-def build_tick(
- command_outputs: dict[str, str],
- *,
- proof_payload: dict[str, object] | None = None,
- idle_payload: dict[str, object] | None = None,
- quota_payload: dict[str, object] | None = None,
- allow_headless_fallback: bool = False,
-) -> dict[str, object]:
- return build_codex_cli_local_scheduler_tick(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=command_outputs),
- quota_payload=quota_payload,
- proof_payload=proof_payload,
- idle_payload=idle_payload,
- allow_headless_fallback=allow_headless_fallback,
- )
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def main() -> int:
- proof_missing = build_tick(REMOTE_RESUME_HELP_FIXTURE)
- assert_boundary(proof_missing)
- assert proof_missing["scheduler_action"] == "write_precise_blocker", proof_missing
- assert proof_missing["precise_blocker"]["reason"] == "visible_session_proof_missing", proof_missing
- assert "refresh-state" in proof_missing["blocker_writeback_command"], proof_missing
- assert proof_missing["candidate_command"] is None, proof_missing
-
- tui_only = build_tick(FALLBACK_HELP_FIXTURE)
- assert_boundary(tui_only)
- assert tui_only["scheduler_action"] == "surface_tui_bootstrap", tui_only
- assert tui_only["candidate_command"] is None, tui_only
- assert tui_only["blocker_writeback_command"] is None, tui_only
-
- fallback_ignored = build_tick(FALLBACK_HELP_FIXTURE, allow_headless_fallback=True)
- assert_boundary(fallback_ignored)
- assert fallback_ignored["scheduler_action"] == "surface_tui_bootstrap", fallback_ignored
- assert fallback_ignored["candidate_command"] is None, fallback_ignored
- assert fallback_ignored["blocker_writeback_command"] is None, fallback_ignored
- assert any("allow_headless_fallback was ignored" in warning for warning in fallback_ignored["warnings"]), fallback_ignored
-
- visible_idle_missing = build_tick(REMOTE_RESUME_HELP_FIXTURE, proof_payload=VISIBLE_PROOF_FIXTURE)
- assert_boundary(visible_idle_missing)
- assert visible_idle_missing["scheduler_action"] == "write_precise_blocker", visible_idle_missing
- assert visible_idle_missing["precise_blocker"]["reason"] == "runtime_idle_evidence_missing", visible_idle_missing
- assert visible_idle_missing["runtime_idle_detector"]["approved"] is False, visible_idle_missing
- assert visible_idle_missing["candidate_command"] is None, visible_idle_missing
-
- visible_candidate = build_tick(
- REMOTE_RESUME_HELP_FIXTURE,
- proof_payload=VISIBLE_PROOF_FIXTURE,
- idle_payload=RUNTIME_IDLE_FIXTURE,
- )
- assert_boundary(visible_candidate)
- assert visible_candidate["scheduler_action"] == "external_visible_command_candidate", visible_candidate
- assert "codex resume public-session-id" in visible_candidate["candidate_command"], visible_candidate
- assert visible_candidate["runtime_idle_detector"]["approved"] is True, visible_candidate
-
- hinted_tick = build_tick(FALLBACK_HELP_FIXTURE, quota_payload=QUOTA_HINT_FIXTURE)
- assert hinted_tick["scheduler_hint"]["action"] == "backoff_until_reassigned", hinted_tick
- assert hinted_tick["launchd"]["recommended_interval_seconds"] == 600, hinted_tick
- assert hinted_tick["launchd"]["reset_token"] == "fixture-reset-001", hinted_tick
- assert hinted_tick["launchd"]["reset_interval_seconds"] == 600, hinted_tick
- assert hinted_tick["launchd"]["reset_policy"]["codex_app_initial_rrule"] == "FREQ=MINUTELY;INTERVAL=10", hinted_tick
- assert hinted_tick["scheduler_hint"]["codex_app"]["example_progression_minutes"] == [10, 20, 30, 60], hinted_tick
- assert hinted_tick["scheduler_hint"]["unchanged_poll"]["final_quota_replan_check_enabled"] is True, hinted_tick
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-scheduler-tick-") as tmp:
- tmp_path = Path(tmp)
- help_fixture = tmp_path / "codex-remote-help.json"
- help_fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- proof_fixture = tmp_path / "visible-proof.json"
- proof_fixture.write_text(json.dumps(VISIBLE_PROOF_FIXTURE))
- idle_fixture = tmp_path / "runtime-idle.json"
- idle_fixture.write_text(json.dumps(RUNTIME_IDLE_FIXTURE))
- quota_fixture = tmp_path / "quota.json"
- quota_fixture.write_text(json.dumps(QUOTA_HINT_FIXTURE))
- missing_registry = tmp_path / "missing-registry.json"
- runtime_root = tmp_path / "runtime"
-
- cli_json = json.loads(
- run_cli(
- "--registry",
- str(missing_registry),
- "--runtime-root",
- str(runtime_root),
- "--format",
- "json",
- "codex-cli-local-scheduler-tick",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--quota-fixture",
- str(quota_fixture),
- )
- )
- assert_boundary(cli_json)
- assert cli_json["scheduler_action"] == "write_precise_blocker", cli_json
- assert cli_json["scheduler_hint"]["action"] == "backoff_until_reassigned", cli_json
- assert cli_json["launchd"]["recommended_interval_seconds"] == 600, cli_json
-
- cli_proof_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-local-scheduler-tick",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- )
- )
- assert_boundary(cli_proof_json)
- assert cli_proof_json["scheduler_action"] == "write_precise_blocker", cli_proof_json
- assert cli_proof_json["precise_blocker"]["reason"] == "runtime_idle_evidence_missing", cli_proof_json
-
- cli_proof_idle_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-local-scheduler-tick",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- "--idle-fixture",
- str(idle_fixture),
- )
- )
- assert_boundary(cli_proof_idle_json)
- assert cli_proof_idle_json["scheduler_action"] == "external_visible_command_candidate", cli_proof_idle_json
- assert cli_proof_idle_json["runtime_idle_detector"]["approved"] is True, cli_proof_idle_json
-
- cli_markdown = run_cli(
- "codex-cli-local-scheduler-tick",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--quota-fixture",
- str(quota_fixture),
- )
- assert "# Codex CLI Local Scheduler Tick" in cli_markdown, cli_markdown
- assert "scheduler_action: `write_precise_blocker`" in cli_markdown, cli_markdown
- assert "local_progression_minutes: `[10, 20, 30, 60]`" in cli_markdown, cli_markdown
- assert "local_unchanged_poll_limit: `3`" in cli_markdown, cli_markdown
- assert "final_quota_replan_check:" in cli_markdown, cli_markdown
- assert "runs_codex: `False`" in cli_markdown, cli_markdown
-
- print("codex-cli-local-scheduler-tick-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-one-message-loop-pilot-smoke.py b/examples/codex-cli-one-message-loop-pilot-smoke.py
deleted file mode 100644
index 9be5cafa6a..0000000000
--- a/examples/codex-cli-one-message-loop-pilot-smoke.py
+++ /dev/null
@@ -1,277 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI one-message loop pilot packet."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_one_message_loop_pilot,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-VISIBLE_PROOF_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "recommended_command": "codex resume public-session-id 'LoopX visible steering turn'",
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
-}
-
-
-RUNTIME_IDLE_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-def build_pilot(
- proof_payload: dict[str, object] | None = None,
- idle_payload: dict[str, object] | None = None,
-) -> dict[str, object]:
- return build_codex_cli_one_message_loop_pilot(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=REMOTE_RESUME_HELP_FIXTURE),
- proof_payload=proof_payload,
- idle_payload=idle_payload,
- )
-
-
-def assert_pilot_boundary(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_one_message_loop_pilot_v0", payload
- boundary = payload["boundary"]
- assert boundary["pilot_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["runs_scheduler_result"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["requires_user_visible_start"] is True, payload
- assert boundary["headless_execution_disabled"] is True, payload
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def main() -> int:
- no_proof = build_pilot()
- assert_pilot_boundary(no_proof)
- assert no_proof["start_surface"] == "codex_cli_tui_one_message", no_proof
- assert no_proof["pilot_decision"] == "first_message_then_visible_blocker_writeback", no_proof
- assert no_proof["first_turn"]["autostarts_loopx_loop"] is True, no_proof
- assert no_proof["first_turn"]["setup_then_loop_activation"] is True, no_proof
- assert no_proof["first_turn"]["loop_activation"]["codex_cli"] == "/goal ", no_proof
- assert no_proof["first_turn"]["loop_activation"]["codex_app"] == " heartbeat automation", no_proof
- assert no_proof["first_turn"]["preserve_tui"] is True, no_proof
- assert "workspace_guard" in no_proof["first_turn"]["stop_only_for"], no_proof
- assert no_proof["first_turn"]["message"].startswith("Install and connect LoopX for this repo"), no_proof
- assert not no_proof["first_turn"]["message"].startswith("/goal "), no_proof
- assert "Codex CLI TUI" in no_proof["first_turn"]["message"], no_proof
- assert "headless `codex exec`" in no_proof["first_turn"]["message"], no_proof
- assert "runtime_idle_evidence" in no_proof["later_turn_contract"]["visible_steering_requires"], no_proof
- assert no_proof["bootstrap_message"]["invocation_mode"] == "codex_cli_setup_then_goal_mode", no_proof
- assert "heartbeat-prompt --thin" in no_proof["bootstrap_message"]["heartbeat_prompt_json_command"], no_proof
- assert no_proof["later_turn_contract"]["default_without_proof"] == "write_blocker_or_keep_tui_bootstrap_primary", no_proof
- assert no_proof["automation_bridge"]["command"] == "codex-cli-local-scheduler-exec", no_proof
- assert no_proof["automation_bridge"]["default_executes"] is False, no_proof
- assert no_proof["automation_bridge"]["scheduler_action"] == "write_precise_blocker", no_proof
- assert no_proof["automation_bridge"]["executor_reason"] == "no_execute_flag", no_proof
- assert "codex-cli-bootstrap-message" in no_proof["commands"]["bootstrap_message"], no_proof
- assert "codex-cli-local-scheduler-exec" in no_proof["commands"]["scheduler_exec_dry_run"], no_proof
- assert "--execute-blocker-writeback" in no_proof["commands"]["scheduler_exec_blocker_template"], no_proof
-
- with_proof = build_pilot(VISIBLE_PROOF_FIXTURE)
- assert_pilot_boundary(with_proof)
- assert with_proof["pilot_decision"] == "first_message_then_runtime_idle_required", with_proof
- assert with_proof["automation_bridge"]["scheduler_action"] == "write_precise_blocker", with_proof
- assert with_proof["scheduler_executor"]["execution"]["executed"] is False, with_proof
-
- with_proof_and_idle = build_pilot(VISIBLE_PROOF_FIXTURE, RUNTIME_IDLE_FIXTURE)
- assert_pilot_boundary(with_proof_and_idle)
- assert with_proof_and_idle["pilot_decision"] == "first_message_then_candidate_available", with_proof_and_idle
- assert with_proof_and_idle["automation_bridge"]["scheduler_action"] == "external_visible_command_candidate", with_proof_and_idle
- assert with_proof_and_idle["scheduler_executor"]["scheduler_tick"]["runtime_idle_detector"]["approved"] is True, with_proof_and_idle
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-one-message-") as tmp:
- tmp_path = Path(tmp)
- help_fixture = tmp_path / "codex-remote-help.json"
- help_fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- proof_fixture = tmp_path / "visible-proof.json"
- proof_fixture.write_text(json.dumps(VISIBLE_PROOF_FIXTURE))
- idle_fixture = tmp_path / "runtime-idle.json"
- idle_fixture.write_text(json.dumps(RUNTIME_IDLE_FIXTURE))
- missing_registry = tmp_path / "missing-registry.json"
- runtime_root = tmp_path / "runtime"
-
- cli_json = json.loads(
- run_cli(
- "--registry",
- str(missing_registry),
- "--runtime-root",
- str(runtime_root),
- "--format",
- "json",
- "codex-cli-one-message-loop-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- )
- assert_pilot_boundary(cli_json)
- assert cli_json["pilot_decision"] == "first_message_then_visible_blocker_writeback", cli_json
-
- cli_proof_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-one-message-loop-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- )
- )
- assert_pilot_boundary(cli_proof_json)
- assert cli_proof_json["pilot_decision"] == "first_message_then_runtime_idle_required", cli_proof_json
-
- cli_proof_idle_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-one-message-loop-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- "--idle-fixture",
- str(idle_fixture),
- )
- )
- assert_pilot_boundary(cli_proof_idle_json)
- assert cli_proof_idle_json["pilot_decision"] == "first_message_then_candidate_available", cli_proof_idle_json
-
- cli_markdown = run_cli(
- "codex-cli-one-message-loop-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- assert "# Codex CLI One-Message Loop Pilot" in cli_markdown, cli_markdown
- assert "requires_user_visible_start: `True`" in cli_markdown, cli_markdown
- assert "candidate_execution_requires_guard_and_prefix: `True`" in cli_markdown, cli_markdown
-
- print("codex-cli-one-message-loop-pilot-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-proof-capture-demo-fixtures-smoke.py b/examples/codex-cli-proof-capture-demo-fixtures-smoke.py
deleted file mode 100644
index c71b589f51..0000000000
--- a/examples/codex-cli-proof-capture-demo-fixtures-smoke.py
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/usr/bin/env python3
-"""Validate the public Codex CLI proof-capture demo fixtures."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_visible_attach_acceptance,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-FIXTURE_DIR = REPO_ROOT / "examples" / "fixtures" / "codex-cli-visible-proof"
-
-
-def load_fixture(name: str) -> dict[str, object]:
- path = FIXTURE_DIR / name
- return json.loads(path.read_text())
-
-
-def command_outputs(name: str) -> dict[str, str]:
- payload = load_fixture(name)
- outputs = payload["command_outputs"]
- assert isinstance(outputs, dict), payload
- return {str(key): str(value) for key, value in outputs.items()}
-
-
-def build_acceptance(
- help_fixture: str,
- proof_fixture: str,
- idle_fixture: str,
-) -> dict[str, object]:
- return build_codex_cli_visible_attach_acceptance(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(
- command_outputs=command_outputs(help_fixture)
- ),
- proof_payload=load_fixture(proof_fixture),
- idle_payload=load_fixture(idle_fixture),
- )
-
-
-def run_cli_acceptance(
- help_fixture: str,
- proof_fixture: str,
- idle_fixture: str,
-) -> dict[str, object]:
- result = subprocess.run(
- [
- sys.executable,
- "-m",
- "loopx.cli",
- "--format",
- "json",
- "codex-cli-visible-attach-acceptance",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(FIXTURE_DIR / help_fixture),
- "--proof-fixture",
- str(FIXTURE_DIR / proof_fixture),
- "--idle-fixture",
- str(FIXTURE_DIR / idle_fixture),
- ],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return json.loads(result.stdout)
-
-
-def assert_public_safe_boundary(payload: dict[str, object]) -> None:
- boundary = payload["boundary"]
- assert boundary["acceptance_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["reads_stdout_stderr"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["writes_loopx_state"] is False, payload
-
-
-def assert_visible_resume_spike(payload: dict[str, object]) -> None:
- assert payload["decision"] == "visible_surface_spike_passed_not_same_tui", payload
- assert payload["accepted_for_visible_later_turn"] is True, payload
- assert payload["accepted_for_same_tui_automation"] is False, payload
- assert payload["observed_surface"] == "visible_resume_prompt", payload
- assert "same_tui_visible_attach_not_proven" in payload["blockers"], payload
- assert_public_safe_boundary(payload)
-
-
-def assert_same_tui_accepted(payload: dict[str, object]) -> None:
- assert payload["decision"] == "same_tui_visible_attach_accepted", payload
- assert payload["accepted_for_visible_later_turn"] is True, payload
- assert payload["accepted_for_same_tui_automation"] is True, payload
- assert payload["observed_surface"] == "same_tui_visible_attach", payload
- assert payload["blockers"] == [], payload
- assert_public_safe_boundary(payload)
-
-
-def main() -> int:
- visible_resume = build_acceptance(
- "codex-visible-resume-help.public.json",
- "visible-resume-proof.public.json",
- "runtime-idle-visible-resume.public.json",
- )
- assert_visible_resume_spike(visible_resume)
-
- visible_resume_cli = run_cli_acceptance(
- "codex-visible-resume-help.public.json",
- "visible-resume-proof.public.json",
- "runtime-idle-visible-resume.public.json",
- )
- assert_visible_resume_spike(visible_resume_cli)
-
- same_tui = build_acceptance(
- "codex-same-tui-help.public.json",
- "same-tui-proof.public.json",
- "runtime-idle-same-tui.public.json",
- )
- assert_same_tui_accepted(same_tui)
-
- same_tui_cli = run_cli_acceptance(
- "codex-same-tui-help.public.json",
- "same-tui-proof.public.json",
- "runtime-idle-same-tui.public.json",
- )
- assert_same_tui_accepted(same_tui_cli)
-
- print("codex-cli-proof-capture-demo-fixtures-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-runtime-idle-detector-smoke.py b/examples/codex-cli-runtime-idle-detector-smoke.py
deleted file mode 100644
index 458ada76c9..0000000000
--- a/examples/codex-cli-runtime-idle-detector-smoke.py
+++ /dev/null
@@ -1,246 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI runtime idle detector packet."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_runtime_idle_detector,
- build_codex_cli_runtime_idle_observation_payload,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-PASSING_IDLE_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-def build_idle(payload: dict[str, object] | None) -> dict[str, object]:
- return build_codex_cli_runtime_idle_detector(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- idle_payload=payload,
- )
-
-
-def assert_boundary(payload: dict[str, object]) -> None:
- boundary = payload["boundary"]
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["reads_stdout_stderr"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def run_cli_fail_closed(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=False,
- capture_output=True,
- text=True,
- )
- assert result.returncode != 0, result.stdout
- return result.stdout
-
-
-def main() -> int:
- missing = build_idle(None)
- assert missing["ok"] is False, missing
- assert missing["schema_version"] == "codex_cli_runtime_idle_detector_v0", missing
- assert missing["decision"] == "runtime_idle_evidence_required", missing
- assert missing["approved_for_visible_later_turn"] is False, missing
- assert "missing_runtime_idle_evidence" in missing["failures"], missing
- assert_boundary(missing)
-
- failing_fixture = dict(PASSING_IDLE_FIXTURE)
- failing_fixture["idle_guard"] = dict(PASSING_IDLE_FIXTURE["idle_guard"])
- failing_fixture["idle_guard"]["no_running_turn"] = False
- incomplete = build_idle(failing_fixture)
- assert incomplete["ok"] is True, incomplete
- assert incomplete["decision"] == "runtime_idle_detector_incomplete", incomplete
- assert incomplete["approved_for_visible_later_turn"] is False, incomplete
- assert "idle_no_running_turn" in incomplete["failures"], incomplete
- assert_boundary(incomplete)
-
- passing = build_idle(PASSING_IDLE_FIXTURE)
- assert passing["ok"] is True, passing
- assert passing["decision"] == "runtime_idle_detector_passed", passing
- assert passing["approved_for_visible_later_turn"] is True, passing
- assert passing["observed_surface"] == "visible_resume_prompt", passing
- assert not passing["failures"], passing
- assert passing["source"] == "idle_fixture", passing
- assert passing["boundary"]["fixture_only"] is True, passing
- assert_boundary(passing)
-
- local_observation = build_codex_cli_runtime_idle_observation_payload(
- observed_surface="visible_resume_prompt",
- turn_state="idle",
- human_input_idle_seconds=12.0,
- min_human_input_idle_seconds=5.0,
- checked_before_prompt=True,
- visible_to_user=True,
- user_can_interrupt=True,
- manual_takeover_available=True,
- probe_result={"ok": True, "source": "test_idle_counter"},
- )
- local_passing = build_idle(local_observation)
- assert local_passing["ok"] is True, local_passing
- assert local_passing["decision"] == "runtime_idle_detector_passed", local_passing
- assert local_passing["approved_for_visible_later_turn"] is True, local_passing
- assert local_passing["source"] == "local_runtime_observation", local_passing
- assert local_passing["boundary"]["fixture_only"] is False, local_passing
- assert local_passing["boundary"]["local_observation_adapter_supported"] is True, local_passing
- runtime_observation = local_passing["runtime_observation"]
- assert runtime_observation["human_input_idle_seconds"] == 12.0, local_passing
- assert runtime_observation["turn_state"] == "idle", local_passing
- assert_boundary(local_passing)
-
- local_unknown_turn = build_idle(
- build_codex_cli_runtime_idle_observation_payload(
- observed_surface="visible_resume_prompt",
- turn_state="unknown",
- human_input_idle_seconds=12.0,
- min_human_input_idle_seconds=5.0,
- checked_before_prompt=True,
- visible_to_user=True,
- user_can_interrupt=True,
- manual_takeover_available=True,
- )
- )
- assert local_unknown_turn["decision"] == "runtime_idle_detector_incomplete", local_unknown_turn
- assert "idle_no_running_turn" in local_unknown_turn["failures"], local_unknown_turn
-
- local_recent_input = build_idle(
- build_codex_cli_runtime_idle_observation_payload(
- observed_surface="visible_resume_prompt",
- turn_state="idle",
- human_input_idle_seconds=1.0,
- min_human_input_idle_seconds=5.0,
- checked_before_prompt=True,
- visible_to_user=True,
- user_can_interrupt=True,
- manual_takeover_available=True,
- )
- )
- assert local_recent_input["decision"] == "runtime_idle_detector_incomplete", local_recent_input
- assert "idle_no_human_typing" in local_recent_input["failures"], local_recent_input
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-runtime-idle-") as tmp:
- fixture = Path(tmp) / "runtime-idle.json"
- fixture.write_text(json.dumps(PASSING_IDLE_FIXTURE))
-
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-runtime-idle-detector",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--idle-fixture",
- str(fixture),
- )
- )
- assert cli_json["decision"] == "runtime_idle_detector_passed", cli_json
- assert cli_json["approved_for_visible_later_turn"] is True, cli_json
- assert_boundary(cli_json)
-
- cli_local_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-runtime-idle-detector",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--observe-local-runtime",
- "--observed-surface",
- "visible_resume_prompt",
- "--turn-state",
- "idle",
- "--human-input-idle-seconds",
- "12",
- "--min-human-input-idle-seconds",
- "5",
- "--checked-before-prompt",
- "--visible-to-user",
- "--user-can-interrupt",
- "--manual-takeover-available",
- )
- )
- assert cli_local_json["decision"] == "runtime_idle_detector_passed", cli_local_json
- assert cli_local_json["source"] == "local_runtime_observation", cli_local_json
- assert cli_local_json["runtime_observation"]["human_input_idle_seconds"] == 12.0, cli_local_json
- assert_boundary(cli_local_json)
-
- cli_markdown = run_cli_fail_closed(
- "codex-cli-runtime-idle-detector",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- )
- assert "# Codex CLI Runtime Idle Detector" in cli_markdown, cli_markdown
- assert "runtime_idle_evidence_required" in cli_markdown, cli_markdown
- assert "reads_stdout_stderr: `False`" in cli_markdown, cli_markdown
-
- print("codex-cli-runtime-idle-detector-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-session-probe-smoke.py b/examples/codex-cli-session-probe-smoke.py
deleted file mode 100644
index 7f28f99030..0000000000
--- a/examples/codex-cli-session-probe-smoke.py
+++ /dev/null
@@ -1,216 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI session-attachment capability probe."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_visible_driver_plan,
- classify_codex_cli_session_surface,
-)
-
-
-HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec Run Codex non-interactively
- resume Resume a previous conversation
-""",
- "exec": """
-Usage: codex exec [OPTIONS] [PROMPT]
-
-Options:
- --resume Continue from a previous session
-""",
- "resume": """
-Usage: codex resume [SESSION_ID]
-
-Resume a previous conversation in a new Codex invocation.
-""",
-}
-
-
-ATTACH_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- resume
- attach-session Send prompt to session after checking the idle TUI
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_fallback_contract(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_session_probe_v0", payload
- capabilities = payload["capabilities"]
- assert capabilities["exec_supported"] is True, payload
- assert capabilities["resume_supported"] is True, payload
- assert capabilities["session_handle_detected"] is True, payload
- assert capabilities["visible_resume_supported"] is False, payload
- assert capabilities["remote_control_surface_detected"] is False, payload
- assert capabilities["same_tui_injection_detected"] is False, payload
- assert capabilities["safe_injection_supported"] is False, payload
- assert payload["recommended_mode"] == "tui_bootstrap_only", payload
- assert payload["automation_action"] == "ask_user_to_start_inside_codex_cli_tui", payload
- assert any("headless fallback is disabled" in warning for warning in payload["warnings"]), payload
- boundary = payload["boundary"]
- assert boundary["help_only_probe"] is True, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
-
-
-def main() -> int:
- payload = classify_codex_cli_session_surface(command_outputs=HELP_FIXTURE)
- assert_fallback_contract(payload)
-
- remote_payload = classify_codex_cli_session_surface(command_outputs=REMOTE_RESUME_HELP_FIXTURE)
- assert remote_payload["capabilities"]["visible_resume_supported"] is True, remote_payload
- assert remote_payload["capabilities"]["remote_control_surface_detected"] is True, remote_payload
- assert remote_payload["capabilities"]["same_tui_injection_detected"] is False, remote_payload
- assert remote_payload["recommended_mode"] == "visible_resume_or_remote_control_spike", remote_payload
- assert remote_payload["automation_action"] == "prototype_visible_resume_or_remote_control_with_idle_guard", remote_payload
- remote_plan = build_codex_cli_visible_driver_plan(
- project=Path("/tmp/public-codex-cli-project"),
- goal_id="public-codex-cli-goal",
- agent_id="codex-side-bypass",
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=remote_payload,
- )
- assert remote_plan["schema_version"] == "codex_cli_visible_driver_plan_v0", remote_plan
- assert remote_plan["driver_mode"] == "visible_resume_or_remote_control_spike", remote_plan
- assert remote_plan["boundary"]["dry_run_plan_only"] is True, remote_plan
- assert remote_plan["boundary"]["reads_raw_transcripts"] is False, remote_plan
- assert remote_plan["boundary"]["reads_session_files"] is False, remote_plan
- assert remote_plan["boundary"]["mutates_codex_session"] is False, remote_plan
- assert remote_plan["boundary"]["spends_loopx_quota"] is False, remote_plan
- assert "resume [PROMPT]" in " ".join(remote_plan["driver_steps"]), remote_plan
- assert remote_plan["commands"]["explicit_headless_fallback"] is None, remote_plan
- assert "headless codex exec is disabled" in remote_plan["commands"]["headless_fallback_disabled"], remote_plan
-
- attach_payload = classify_codex_cli_session_surface(command_outputs=ATTACH_HELP_FIXTURE)
- assert attach_payload["capabilities"]["safe_injection_supported"] is True, attach_payload
- assert attach_payload["recommended_mode"] == "session_attached_visible_turn", attach_payload
- attach_plan = build_codex_cli_visible_driver_plan(
- project=Path("/tmp/public-codex-cli-project"),
- goal_id="public-codex-cli-goal",
- agent_id="codex-side-bypass",
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=attach_payload,
- )
- assert attach_plan["driver_mode"] == "session_attached_visible_turn", attach_plan
- assert "visible attach primitive" in attach_plan["next_step"], attach_plan
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-probe-") as tmp:
- fixture = Path(tmp) / "codex-help.json"
- fixture.write_text(json.dumps({"command_outputs": HELP_FIXTURE}))
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-session-probe",
- "--fixture",
- str(fixture),
- )
- )
- assert_fallback_contract(cli_json)
-
- cli_markdown = run_cli("codex-cli-session-probe", "--fixture", str(fixture))
- assert "# Codex CLI Session Probe" in cli_markdown, cli_markdown
- assert "recommended_mode: `tui_bootstrap_only`" in cli_markdown, cli_markdown
- assert "same_tui_injection_detected: `False`" in cli_markdown, cli_markdown
-
- remote_fixture = Path(tmp) / "codex-remote-help.json"
- remote_fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- cli_plan_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-driver-plan",
- "--project",
- "/tmp/public-codex-cli-project",
- "--goal-id",
- "public-codex-cli-goal",
- "--agent-id",
- "codex-side-bypass",
- "--fixture",
- str(remote_fixture),
- )
- )
- assert cli_plan_json["driver_mode"] == "visible_resume_or_remote_control_spike", cli_plan_json
- assert cli_plan_json["boundary"]["dry_run_plan_only"] is True, cli_plan_json
- assert cli_plan_json["boundary"]["reads_raw_transcripts"] is False, cli_plan_json
- cli_plan_markdown = run_cli(
- "codex-cli-visible-driver-plan",
- "--project",
- "/tmp/public-codex-cli-project",
- "--goal-id",
- "public-codex-cli-goal",
- "--agent-id",
- "codex-side-bypass",
- "--fixture",
- str(remote_fixture),
- )
- assert "# Codex CLI Visible Driver Plan" in cli_plan_markdown, cli_plan_markdown
- assert "driver_mode: `visible_resume_or_remote_control_spike`" in cli_plan_markdown, cli_plan_markdown
- assert "dry_run_plan_only: `True`" in cli_plan_markdown, cli_plan_markdown
-
- print("codex-cli-session-probe-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-tui-bootstrap-smoke-bundle-smoke.py b/examples/codex-cli-tui-bootstrap-smoke-bundle-smoke.py
deleted file mode 100644
index 2b59e7a1dd..0000000000
--- a/examples/codex-cli-tui-bootstrap-smoke-bundle-smoke.py
+++ /dev/null
@@ -1,230 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the transcript-free Codex CLI TUI bootstrap bundle."""
-
-from __future__ import annotations
-
-import json
-import os
-import subprocess
-import sys
-import tarfile
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-GOAL_ID = "public-fresh-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-def add_tree(tar: tarfile.TarFile, root: Path, name: str) -> None:
- path = root / name
- if path.is_dir():
- for child in sorted(path.rglob("*")):
- if ".git" in child.parts or "__pycache__" in child.parts:
- continue
- tar.add(
- child,
- arcname=str(Path("loopx-main") / child.relative_to(root)),
- recursive=False,
- )
- else:
- tar.add(path, arcname=str(Path("loopx-main") / name))
-
-
-def run(command: list[str], *, env: dict[str, str], cwd: Path) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- command,
- check=True,
- env=env,
- cwd=cwd,
- text=True,
- capture_output=True,
- )
-
-
-def path_without_loopx(path_text: str) -> str:
- entries: list[str] = []
- for entry in path_text.split(os.pathsep):
- if not entry:
- continue
- if (Path(entry).expanduser() / "loopx").exists():
- continue
- entries.append(entry)
- return os.pathsep.join(entries)
-
-
-def main() -> None:
- install_script = REPO_ROOT / "scripts" / "install-from-github.sh"
- subprocess.run(["bash", "-n", str(install_script)], check=True)
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-tui-bundle-") as td:
- tmp = Path(td)
- archive = tmp / "loopx.tar.gz"
- home = tmp / "home"
- fake_bin = tmp / "fake-bin"
- fresh_repo = tmp / "public-fresh-repo"
- codex_called_marker = tmp / "codex-called"
- home.mkdir()
- fake_bin.mkdir()
- fresh_repo.mkdir()
- (fresh_repo / "README.md").write_text("# Public fresh repo\n", encoding="utf-8")
-
- fake_codex = fake_bin / "codex"
- fake_codex.write_text(
- "#!/usr/bin/env bash\n"
- "echo called > \"${CODEX_CALLED_MARKER:?}\"\n"
- "exit 77\n",
- encoding="utf-8",
- )
- fake_codex.chmod(0o755)
-
- with tarfile.open(archive, "w:gz") as tar:
- for name in (
- "loopx",
- "scripts",
- "skills",
- "docs",
- "examples",
- "README.md",
- "pyproject.toml",
- "LICENSE",
- ):
- add_tree(tar, REPO_ROOT, name)
-
- env = os.environ.copy()
- host_path_without_loopx = path_without_loopx(env.get("PATH", ""))
- env.update(
- {
- "HOME": str(home),
- "CODEX_HOME": str(home / ".codex"),
- "LOOPX_BIN_DIR": str(home / ".local" / "bin"),
- "LOOPX_RELEASES_DIR": str(home / ".local" / "share" / "loopx" / "releases"),
- "LOOPX_SHELL_PROFILE": str(home / ".profile"),
- "LOOPX_ARCHIVE_URL": f"file://{archive}",
- "LOOPX_INSTALL_CANARY": "0",
- "LOOPX_PYTHON": sys.executable,
- "CODEX_CALLED_MARKER": str(codex_called_marker),
- "PATH": f"{fake_bin}:{host_path_without_loopx}",
- }
- )
- run(["bash", str(install_script)], env=env, cwd=tmp)
-
- installed = home / ".local" / "bin" / "loopx"
- assert installed.exists(), installed
- run([str(installed), "doctor"], env=env, cwd=fresh_repo)
-
- bundle = json.loads(
- run(
- [
- str(installed),
- "--format",
- "json",
- "codex-cli-tui-bootstrap-smoke-bundle",
- "--project",
- str(fresh_repo),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- ],
- env=env,
- cwd=fresh_repo,
- ).stdout
- )
- assert bundle["schema_version"] == "codex_cli_tui_bootstrap_smoke_bundle_v0", bundle
- assert bundle["goal_id"] == GOAL_ID, bundle
- assert bundle["agent_id"] == AGENT_ID, bundle
- assert "--message-only" in bundle["message_only_command"], bundle
- assert str(fresh_repo) in bundle["message_only_command"], bundle
- repair = bundle["install_repair_command"]
- assert "loopx doctor" in repair, bundle
- if os.name == "nt":
- assert "| bash" not in repair, bundle
- assert (
- "install-windows.ps1" in repair
- or "-m pip install --upgrade loopx" in repair
- ), bundle
- else:
- assert "loopx-project.github.io/loopx/install.sh" in repair, bundle
- assert "python3 -m pip install --upgrade loopx" in repair, bundle
- assert "workflow-skills --install" in repair, bundle
- assert "quota should-run" in bundle["quota_guard_command"], bundle
- assert "--agent-id codex-side-bypass" in bundle["quota_guard_command"], bundle
- assert "refresh-state --goal-id public-fresh-codex-cli-goal" in bundle["refresh_command"], bundle
- assert "--delivery-batch-scale " in bundle["progress_refresh_command"], bundle
- assert "--delivery-outcome " in bundle["progress_refresh_command"], bundle
- assert "--delivery-outcome outcome_progress" not in bundle["progress_refresh_command"], bundle
- assert "--agent-id codex-side-bypass" in bundle["progress_refresh_command"], bundle
- assert "quota spend-slot" in bundle["quota_spend_command"], bundle
- assert "--source heartbeat --execute --agent-id codex-side-bypass" in bundle["quota_spend_command"], bundle
- assert any("message-only command" in item for item in bundle["validation_checklist"]), bundle
- assert any("no raw Codex transcripts" in item for item in bundle["validation_checklist"]), bundle
-
- boundary = bundle["boundary"]
- for key in (
- "runs_codex",
- "reads_raw_transcripts",
- "reads_session_files",
- "reads_credentials",
- "mutates_codex_session",
- "spends_loopx_quota",
- "requires_loopx_repo_clone",
- ):
- assert boundary[key] is False, (key, boundary)
-
- message_only = run(
- [
- str(installed),
- "codex-cli-bootstrap-message",
- "--project",
- str(fresh_repo),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--message-only",
- ],
- env=env,
- cwd=fresh_repo,
- ).stdout
- assert message_only.startswith("Install and connect LoopX for this repo"), message_only
- assert not message_only.startswith("/goal "), message_only
- assert "# Codex CLI LoopX Bootstrap Message" not in message_only, message_only
- assert "Fresh Repo Install Repair" not in message_only, message_only
- assert "loopx doctor" in message_only, message_only
- if os.name != "nt":
- assert "loopx-project.github.io/loopx/install.sh" in message_only, message_only
- assert "python3 -m pip install --upgrade loopx" in message_only, message_only
- assert "/goal " in message_only, message_only
- assert "quota should-run" in message_only, message_only
- assert "refresh-state --goal-id public-fresh-codex-cli-goal" in message_only, message_only
- assert "settlement_plan.ordered_steps" in message_only, message_only
- assert "raw Codex transcripts" in message_only, message_only
-
- markdown = run(
- [
- str(installed),
- "codex-cli-tui-bootstrap-smoke-bundle",
- "--project",
- str(fresh_repo),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- ],
- env=env,
- cwd=fresh_repo,
- ).stdout
- assert "# Codex CLI TUI Bootstrap Smoke Bundle" in markdown, markdown
- assert "Transcript-Free Boundary" in markdown, markdown
- assert "runs_codex: `False`" in markdown, markdown
- assert "requires_loopx_repo_clone: `False`" in markdown, markdown
-
- assert not codex_called_marker.exists(), codex_called_marker
-
- print("codex-cli-tui-bootstrap-smoke-bundle-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/codex-cli-visible-attach-acceptance-smoke.py b/examples/codex-cli-visible-attach-acceptance-smoke.py
deleted file mode 100644
index 913877fe31..0000000000
--- a/examples/codex-cli-visible-attach-acceptance-smoke.py
+++ /dev/null
@@ -1,265 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI visible attach acceptance packet."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_visible_attach_acceptance,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]",
-}
-
-
-ATTACH_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- resume
- attach-session Send prompt to session after checking the idle TUI
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-FALLBACK_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec Run Codex non-interactively
- resume Resume a previous conversation
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-def proof_fixture(surface: str) -> dict[str, object]:
- return {
- "observed_surface": surface,
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
- }
-
-
-PASSING_IDLE_FIXTURE = {
- "observed_surface": "same_tui_visible_attach",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def build(
- command_outputs: dict[str, str],
- *,
- proof: dict[str, object] | None = None,
- idle: dict[str, object] | None = None,
-) -> dict[str, object]:
- return build_codex_cli_visible_attach_acceptance(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=command_outputs),
- proof_payload=proof,
- idle_payload=idle,
- )
-
-
-def assert_public_safe_boundary(payload: dict[str, object]) -> None:
- boundary = payload["boundary"]
- assert boundary["acceptance_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["reads_stdout_stderr"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["writes_loopx_state"] is False, payload
-
-
-def main() -> int:
- remote_without_proof = build(REMOTE_RESUME_HELP_FIXTURE)
- assert remote_without_proof["ok"] is True, remote_without_proof
- assert remote_without_proof["decision"] == "visible_session_proof_required", remote_without_proof
- assert remote_without_proof["accepted_for_same_tui_automation"] is False, remote_without_proof
- assert "visible_session_proof_missing" in remote_without_proof["blockers"], remote_without_proof
- assert_public_safe_boundary(remote_without_proof)
-
- remote_spike = build(
- REMOTE_RESUME_HELP_FIXTURE,
- proof=proof_fixture("remote_control_visible_prompt"),
- idle={**PASSING_IDLE_FIXTURE, "observed_surface": "remote_control_visible_prompt"},
- )
- assert remote_spike["decision"] == "visible_surface_spike_passed_not_same_tui", remote_spike
- assert remote_spike["accepted_for_visible_later_turn"] is True, remote_spike
- assert remote_spike["accepted_for_same_tui_automation"] is False, remote_spike
- assert "same_tui_visible_attach_not_proven" in remote_spike["blockers"], remote_spike
- assert_public_safe_boundary(remote_spike)
-
- same_tui_accepted = build(
- ATTACH_HELP_FIXTURE,
- proof=proof_fixture("same_tui_visible_attach"),
- idle=PASSING_IDLE_FIXTURE,
- )
- assert same_tui_accepted["decision"] == "same_tui_visible_attach_accepted", same_tui_accepted
- assert same_tui_accepted["accepted_for_same_tui_automation"] is True, same_tui_accepted
- assert same_tui_accepted["accepted_for_visible_later_turn"] is True, same_tui_accepted
- assert same_tui_accepted["blockers"] == [], same_tui_accepted
- assert_public_safe_boundary(same_tui_accepted)
-
- missing_idle = build(
- ATTACH_HELP_FIXTURE,
- proof=proof_fixture("same_tui_visible_attach"),
- )
- assert missing_idle["decision"] == "runtime_idle_evidence_required", missing_idle
- assert missing_idle["accepted_for_same_tui_automation"] is False, missing_idle
- assert "missing_runtime_idle_evidence" in missing_idle["blockers"], missing_idle
- assert_public_safe_boundary(missing_idle)
-
- fallback = build(FALLBACK_HELP_FIXTURE)
- assert fallback["decision"] == "tui_bootstrap_only", fallback
- assert fallback["accepted_for_same_tui_automation"] is False, fallback
- assert fallback["accepted_for_visible_later_turn"] is False, fallback
- assert fallback["requirements"]["headless_execution_disabled"] is True, fallback
- assert_public_safe_boundary(fallback)
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-visible-attach-") as tmp:
- tmpdir = Path(tmp)
- help_fixture = tmpdir / "codex-attach-help.json"
- proof_path = tmpdir / "same-tui-proof.json"
- idle_path = tmpdir / "runtime-idle.json"
- help_fixture.write_text(json.dumps({"command_outputs": ATTACH_HELP_FIXTURE}))
- proof_path.write_text(json.dumps(proof_fixture("same_tui_visible_attach")))
- idle_path.write_text(json.dumps(PASSING_IDLE_FIXTURE))
-
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-attach-acceptance",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_path),
- "--idle-fixture",
- str(idle_path),
- )
- )
- assert cli_json["decision"] == "same_tui_visible_attach_accepted", cli_json
- assert cli_json["accepted_for_same_tui_automation"] is True, cli_json
-
- cli_markdown = run_cli(
- "codex-cli-visible-attach-acceptance",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_path),
- "--idle-fixture",
- str(idle_path),
- )
- assert "# Codex CLI Visible Attach Acceptance" in cli_markdown, cli_markdown
- assert "accepted_for_same_tui_automation: `True`" in cli_markdown, cli_markdown
- assert "same_tui_visible_attach_accepted" in cli_markdown, cli_markdown
-
- print("codex-cli-visible-attach-acceptance-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-visible-driver-run-smoke.py b/examples/codex-cli-visible-driver-run-smoke.py
deleted file mode 100644
index e5246cd71b..0000000000
--- a/examples/codex-cli-visible-driver-run-smoke.py
+++ /dev/null
@@ -1,233 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI visible driver run packet."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_visible_driver_run_packet,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-FALLBACK_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec Run Codex non-interactively
- resume Resume a previous conversation
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]",
-}
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-VISIBLE_PROOF_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "recommended_command": "codex resume public-session-id 'LoopX visible steering turn'",
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
-}
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_boundary(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_visible_driver_run_packet_v0", payload
- assert payload["driver_phase"] == "run_packet_no_execution", payload
- boundary = payload["boundary"]
- assert boundary["run_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- policy = payload["execution_policy"]
- assert policy["tui_bootstrap_primary"] is True, payload
- assert policy["same_session_attachment_requires_visible_proof"] is True, payload
- assert policy["headless_execution_disabled"] is True, payload
- assert policy["quota_guard_required"] is True, payload
- assert policy["idle_guard_required_before_visible_prompt"] is True, payload
- assert policy["spend_after_validated_writeback_only"] is True, payload
-
-
-def build_packet(
- command_outputs: dict[str, str],
- *,
- proof_payload: dict[str, object] | None = None,
- allow_headless_fallback: bool = False,
-) -> dict[str, object]:
- return build_codex_cli_visible_driver_run_packet(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=command_outputs),
- proof_payload=proof_payload,
- allow_headless_fallback=allow_headless_fallback,
- )
-
-
-def main() -> int:
- proof_required = build_packet(REMOTE_RESUME_HELP_FIXTURE)
- assert_boundary(proof_required)
- assert proof_required["decision"] == "visible_session_proof_required", proof_required
- assert proof_required["next_driver_action"] == "capture_public_safe_visible_session_proof", proof_required
- assert proof_required["visible_session_proof"]["supplied"] is False, proof_required
- assert "codex-cli-visible-session-proof" in proof_required["recommended_command"], proof_required
-
- tui_only = build_packet(FALLBACK_HELP_FIXTURE)
- assert_boundary(tui_only)
- assert tui_only["decision"] == "tui_bootstrap_only", tui_only
- assert tui_only["next_driver_action"] == "ask_user_to_start_inside_codex_cli_tui", tui_only
- assert "codex-cli-bootstrap-message" in tui_only["recommended_command"], tui_only
-
- fallback_ignored = build_packet(FALLBACK_HELP_FIXTURE, allow_headless_fallback=True)
- assert_boundary(fallback_ignored)
- assert fallback_ignored["decision"] == "tui_bootstrap_only", fallback_ignored
- assert fallback_ignored["next_driver_action"] == "ask_user_to_start_inside_codex_cli_tui", fallback_ignored
- assert "codex-cli-bootstrap-message" in fallback_ignored["recommended_command"], fallback_ignored
- assert any("allow_headless_fallback was ignored" in warning for warning in fallback_ignored["warnings"]), fallback_ignored
-
- visible_candidate = build_packet(REMOTE_RESUME_HELP_FIXTURE, proof_payload=VISIBLE_PROOF_FIXTURE)
- assert_boundary(visible_candidate)
- assert visible_candidate["decision"] == "visible_session_turn_candidate", visible_candidate
- assert visible_candidate["visible_session_proof"]["approved"] is True, visible_candidate
- assert "codex resume public-session-id" in visible_candidate["recommended_command"], visible_candidate
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-driver-run-") as tmp:
- tmp_path = Path(tmp)
- help_fixture = tmp_path / "codex-remote-help.json"
- help_fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- proof_fixture = tmp_path / "visible-proof.json"
- proof_fixture.write_text(json.dumps(VISIBLE_PROOF_FIXTURE))
-
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-driver-run",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- )
- assert_boundary(cli_json)
- assert cli_json["decision"] == "visible_session_proof_required", cli_json
-
- cli_proof_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-driver-run",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- )
- )
- assert_boundary(cli_proof_json)
- assert cli_proof_json["decision"] == "visible_session_turn_candidate", cli_proof_json
-
- cli_markdown = run_cli(
- "codex-cli-visible-driver-run",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- assert "# Codex CLI Visible Driver Run Packet" in cli_markdown, cli_markdown
- assert "decision: `visible_session_proof_required`" in cli_markdown, cli_markdown
- assert "runs_codex: `False`" in cli_markdown, cli_markdown
-
- print("codex-cli-visible-driver-run-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-visible-first-response-capture-plan-smoke.py b/examples/codex-cli-visible-first-response-capture-plan-smoke.py
deleted file mode 100644
index 4c98346826..0000000000
--- a/examples/codex-cli-visible-first-response-capture-plan-smoke.py
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI visible first-response capture plan."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_bounded_visible_pilot_adapter,
- build_codex_cli_visible_first_response_capture_plan,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-DOC = REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "codex-cli-live-tui-first-message-pilot.md"
-PRODUCT_README = (
- REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "README.md"
-)
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_boundary(payload: dict[str, object]) -> None:
- boundary = payload["boundary"]
- assert boundary["capture_plan_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["reads_stdout_stderr"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["writes_loopx_state"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["manual_paste_primary"] is True, payload
- assert boundary["argv_prompt_rejected"] is True, payload
- assert boundary["success_claim_requires_bounded_adapter"] is True, payload
-
-
-def assert_capture_plan(payload: dict[str, object]) -> None:
- assert payload["schema_version"] == "codex_cli_visible_first_response_capture_plan_v0"
- assert payload["decision"] == "manual_visible_capture_plan_ready", payload
- assert payload["start_surface"] == "codex_cli_tui_manual_paste", payload
- assert "public-first-response.json" in payload["commands"]["bounded_visible_pilot_adapter"], payload
- assert "public-runtime-idle.json" in payload["commands"]["bounded_visible_pilot_adapter"], payload
- assert "codex-cli-bootstrap-message" in payload["commands"]["bootstrap_message"], payload
- assert "codex-cli-runtime-idle-detector" in payload["commands"]["runtime_idle_detector"], payload
- assert "argv_prompt_used" in payload["sample_first_response_fixture"]["prompt_delivery"], payload
- assert payload["sample_first_response_fixture"]["prompt_delivery"]["argv_prompt_used"] is False
- assert payload["sample_runtime_idle_fixture"]["idle_guard"]["no_running_turn"] is True
- assert "the bootstrap message would have to be passed as argv" in payload["stop_conditions"], payload
- assert_boundary(payload)
-
-
-def assert_sample_fixtures_pass_adapter(payload: dict[str, object]) -> None:
- passing = build_codex_cli_bounded_visible_pilot_adapter(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- first_response_payload=payload["sample_first_response_fixture"],
- idle_payload=payload["sample_runtime_idle_fixture"],
- )
- assert passing["decision"] == "bounded_visible_pilot_ready_for_success_claim", passing
- assert passing["approved_for_live_tui_success_claim"] is True, passing
- assert passing["blockers"] == [], passing
-
-
-def assert_cli() -> None:
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-first-response-capture-plan",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- )
- )
- assert_capture_plan(cli_json)
- assert_sample_fixtures_pass_adapter(cli_json)
-
- markdown = run_cli(
- "codex-cli-visible-first-response-capture-plan",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- )
- assert "# Codex CLI Visible First-Response Capture Plan" in markdown, markdown
- assert "Sample First-Response Fixture" in markdown, markdown
- assert "argv_prompt_rejected" in markdown, markdown
- assert "reads_raw_transcripts" in markdown, markdown
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-first-response-") as tmp:
- tmp_path = Path(tmp)
- first_response = tmp_path / "public-first-response.json"
- idle = tmp_path / "public-runtime-idle.json"
- first_response.write_text(json.dumps(cli_json["sample_first_response_fixture"]))
- idle.write_text(json.dumps(cli_json["sample_runtime_idle_fixture"]))
- adapter = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-bounded-visible-pilot-adapter",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--first-response-fixture",
- str(first_response),
- "--idle-fixture",
- str(idle),
- )
- )
- assert adapter["approved_for_live_tui_success_claim"] is True, adapter
-
-
-def assert_docs() -> None:
- doc = DOC.read_text(encoding="utf-8")
- readme = PRODUCT_README.read_text(encoding="utf-8")
- assert "codex-cli-visible-first-response-capture-plan" in doc, doc
- assert "public-first-response.json" in doc, doc
- assert "public-runtime-idle.json" in doc, doc
- assert "visible first-response capture plan" in readme, readme
- assert "codex-cli-visible-first-response-capture-plan-smoke.py" in readme, readme
-
-
-def main() -> int:
- direct = build_codex_cli_visible_first_response_capture_plan(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- )
- assert_capture_plan(direct)
- assert_sample_fixtures_pass_adapter(direct)
- assert_cli()
- assert_docs()
- print("codex-cli-visible-first-response-capture-plan-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-visible-local-driver-pilot-smoke.py b/examples/codex-cli-visible-local-driver-pilot-smoke.py
deleted file mode 100644
index 3143cb5bdd..0000000000
--- a/examples/codex-cli-visible-local-driver-pilot-smoke.py
+++ /dev/null
@@ -1,290 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI visible local driver pilot packet."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import ( # noqa: E402
- build_codex_cli_visible_local_driver_pilot,
- classify_codex_cli_session_surface,
-)
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-REMOTE_RESUME_HELP_FIXTURE = {
- "root": """
-Usage: codex [OPTIONS] [PROMPT]
-
-Commands:
- exec
- remote-control Manage the app-server daemon with remote control enabled
- resume Resume a previous interactive session
-
-Options:
- --remote Connect the TUI to a remote app server endpoint
-""",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": """
-Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]
-
-Resume a previous interactive session.
-""",
-}
-
-
-VISIBLE_PROOF_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "recommended_command": "codex resume public-session-id 'LoopX visible steering turn'",
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
-}
-
-
-RUNTIME_IDLE_FIXTURE = {
- "observed_surface": "visible_resume_prompt",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {"visible_to_user": True},
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_stdout_stderr": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- },
-}
-
-
-def build_pilot(
- proof_payload: dict[str, object] | None = None,
- idle_payload: dict[str, object] | None = None,
-) -> dict[str, object]:
- return build_codex_cli_visible_local_driver_pilot(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- codex_bin="codex",
- probe_payload=classify_codex_cli_session_surface(command_outputs=REMOTE_RESUME_HELP_FIXTURE),
- proof_payload=proof_payload,
- idle_payload=idle_payload,
- )
-
-
-def assert_pilot_boundary(payload: dict[str, object]) -> None:
- assert payload["ok"] is True, payload
- assert payload["schema_version"] == "codex_cli_visible_local_driver_pilot_v0", payload
- assert payload["pilot_phase"] == "visible_local_driver_loop_no_execution", payload
- boundary = payload["boundary"]
- assert boundary["pilot_packet_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["runs_scheduler_result"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_credentials"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["reads_stdout_stderr"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["writes_loopx_state"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
- assert boundary["candidate_execution_requires_guard_and_prefix"] is True, payload
- assert boundary["blocker_writeback_requires_guard_checked"] is True, payload
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def main() -> int:
- no_proof = build_pilot()
- assert_pilot_boundary(no_proof)
- assert no_proof["start_surface"] == "codex_cli_tui_one_message", no_proof
- assert no_proof["loop_decision"] == "visible_loop_blocker_writeback_ready", no_proof
- assert no_proof["next_driver_action"] == "write_precise_blocker_after_fresh_guard", no_proof
- assert no_proof["scheduler_executor"]["scheduler_action"] == "write_precise_blocker", no_proof
- assert no_proof["scheduler_executor"]["executor_reason"] == "no_execute_flag", no_proof
- assert no_proof["scheduler_executor"]["executed"] is False, no_proof
- assert no_proof["visible_session_proof"]["approved"] is False, no_proof
- assert no_proof["runtime_idle_detector"]["approved"] is False, no_proof
- assert no_proof["runtime_idle_detector"]["decision"] == "runtime_idle_evidence_required", no_proof
- assert no_proof["idle_guard_contract"]["required_before_visible_prompt"] is True, no_proof
- assert no_proof["idle_guard_contract"]["current_pilot_implements_runtime_idle_detection"] is True, no_proof
- assert no_proof["idle_guard_contract"]["fixture_backed_runtime_idle_detector"] is True, no_proof
- assert no_proof["idle_guard_contract"]["runtime_sensor_implemented"] is True, no_proof
- assert no_proof["idle_guard_contract"]["local_observation_adapter_supported"] is True, no_proof
- assert no_proof["idle_guard_contract"]["no_private_state_observation"] is True, no_proof
- assert "codex-cli-local-scheduler-exec" in no_proof["commands"]["scheduler_exec_dry_run"], no_proof
- assert "codex-cli-runtime-idle-detector" in no_proof["commands"]["runtime_idle_detector"], no_proof
- assert "--observe-local-runtime" in no_proof["commands"]["runtime_idle_detector"], no_proof
- assert "runtime_idle_detector_fixture" in no_proof["commands"], no_proof
- assert "--idle-fixture" in no_proof["commands"]["runtime_idle_detector_fixture"], no_proof
- assert "--execute-blocker-writeback" in no_proof["commands"]["scheduler_exec_blocker_template"], no_proof
-
- with_proof = build_pilot(VISIBLE_PROOF_FIXTURE)
- assert_pilot_boundary(with_proof)
- assert with_proof["loop_decision"] == "runtime_idle_detector_required", with_proof
- assert with_proof["next_driver_action"] == "capture_public_safe_runtime_idle_observation", with_proof
- assert with_proof["scheduler_executor"]["scheduler_action"] == "write_precise_blocker", with_proof
- assert with_proof["visible_session_proof"]["supplied"] is True, with_proof
- assert with_proof["visible_session_proof"]["approved"] is True, with_proof
- assert with_proof["runtime_idle_detector"]["supplied"] is False, with_proof
- assert with_proof["runtime_idle_detector"]["approved"] is False, with_proof
-
- with_proof_and_idle = build_pilot(VISIBLE_PROOF_FIXTURE, RUNTIME_IDLE_FIXTURE)
- assert_pilot_boundary(with_proof_and_idle)
- assert with_proof_and_idle["loop_decision"] == "visible_candidate_ready_for_guarded_execution", with_proof_and_idle
- assert with_proof_and_idle["next_driver_action"] == "run_scheduler_exec_candidate_after_fresh_guard_and_prefix", with_proof_and_idle
- assert with_proof_and_idle["scheduler_executor"]["scheduler_action"] == "external_visible_command_candidate", with_proof_and_idle
- assert with_proof_and_idle["visible_session_proof"]["approved"] is True, with_proof_and_idle
- assert with_proof_and_idle["runtime_idle_detector"]["supplied"] is True, with_proof_and_idle
- assert with_proof_and_idle["runtime_idle_detector"]["approved"] is True, with_proof_and_idle
- assert with_proof["execution_policy"]["later_turns_visible_to_user"] is True, with_proof
- assert with_proof["execution_policy"]["user_can_interrupt_or_take_over"] is True, with_proof
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-visible-local-driver-") as tmp:
- tmp_path = Path(tmp)
- help_fixture = tmp_path / "codex-remote-help.json"
- help_fixture.write_text(json.dumps({"command_outputs": REMOTE_RESUME_HELP_FIXTURE}))
- proof_fixture = tmp_path / "visible-proof.json"
- proof_fixture.write_text(json.dumps(VISIBLE_PROOF_FIXTURE))
- idle_fixture = tmp_path / "runtime-idle.json"
- idle_fixture.write_text(json.dumps(RUNTIME_IDLE_FIXTURE))
- missing_registry = tmp_path / "missing-registry.json"
- runtime_root = tmp_path / "runtime"
-
- cli_json = json.loads(
- run_cli(
- "--registry",
- str(missing_registry),
- "--runtime-root",
- str(runtime_root),
- "--format",
- "json",
- "codex-cli-visible-local-driver-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- )
- assert_pilot_boundary(cli_json)
- assert cli_json["loop_decision"] == "visible_loop_blocker_writeback_ready", cli_json
-
- cli_proof_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-local-driver-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- )
- )
- assert_pilot_boundary(cli_proof_json)
- assert cli_proof_json["loop_decision"] == "runtime_idle_detector_required", cli_proof_json
-
- cli_proof_idle_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-local-driver-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- "--proof-fixture",
- str(proof_fixture),
- "--idle-fixture",
- str(idle_fixture),
- )
- )
- assert_pilot_boundary(cli_proof_idle_json)
- assert cli_proof_idle_json["loop_decision"] == "visible_candidate_ready_for_guarded_execution", cli_proof_idle_json
- assert cli_proof_idle_json["runtime_idle_detector"]["approved"] is True, cli_proof_idle_json
-
- cli_markdown = run_cli(
- "codex-cli-visible-local-driver-pilot",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(help_fixture),
- )
- assert "# Codex CLI Visible Local Driver Pilot" in cli_markdown, cli_markdown
- assert "loop_decision: `visible_loop_blocker_writeback_ready`" in cli_markdown, cli_markdown
- assert "## Runtime Idle Detector" in cli_markdown, cli_markdown
- assert "reads_raw_transcripts: `False`" in cli_markdown, cli_markdown
- assert "user_can_interrupt_or_take_over: `True`" in cli_markdown, cli_markdown
-
- print("codex-cli-visible-local-driver-pilot-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-cli-visible-session-proof-smoke.py b/examples/codex-cli-visible-session-proof-smoke.py
deleted file mode 100644
index cc8097c01c..0000000000
--- a/examples/codex-cli-visible-session-proof-smoke.py
+++ /dev/null
@@ -1,169 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex CLI visible session proof contract."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.codex_cli_probe import build_codex_cli_visible_session_proof # noqa: E402
-
-
-PROJECT = Path("/tmp/public-codex-cli-project")
-GOAL_ID = "public-codex-cli-goal"
-AGENT_ID = "codex-side-bypass"
-
-
-PASSING_PROOF = {
- "observed_surface": "visible_resume_prompt",
- "user_opt_in": True,
- "quota_guard": {"passed": True},
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": True,
- "checked_before_prompt": True,
- },
- "turn_visibility": {
- "visible_to_user": True,
- "prompt_public_safe": True,
- },
- "interruptibility": {
- "user_can_interrupt": True,
- "manual_takeover_available": True,
- },
- "boundary": {
- "reads_raw_transcripts": False,
- "reads_session_files": False,
- "reads_credentials": False,
- "mutates_hidden_session_state": False,
- "spends_quota_before_writeback": False,
- },
- "writeback": {"compact_evidence_planned": True},
-}
-
-
-FAILING_PROOF = {
- **PASSING_PROOF,
- "observed_surface": "headless_exec",
- "idle_guard": {
- "no_active_human_typing": True,
- "no_running_turn": False,
- "checked_before_prompt": True,
- },
- "boundary": {
- **PASSING_PROOF["boundary"],
- "reads_session_files": True,
- },
-}
-
-
-def run_cli(*extra_args: str) -> str:
- result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", *extra_args],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- )
- return result.stdout
-
-
-def assert_common_boundary(payload: dict[str, object]) -> None:
- assert payload["schema_version"] == "codex_cli_visible_session_proof_v0", payload
- assert payload["project"] == str(PROJECT), payload
- assert payload["goal_id"] == GOAL_ID, payload
- assert payload["agent_id"] == AGENT_ID, payload
- boundary = payload["boundary"]
- assert boundary["fixture_only"] is True, payload
- assert boundary["runs_codex"] is False, payload
- assert boundary["reads_raw_transcripts"] is False, payload
- assert boundary["reads_session_files"] is False, payload
- assert boundary["mutates_codex_session"] is False, payload
- assert boundary["spends_loopx_quota"] is False, payload
-
-
-def build(proof: dict[str, object] | None) -> dict[str, object]:
- return build_codex_cli_visible_session_proof(
- project=PROJECT,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- cli_bin="loopx",
- proof_payload=proof,
- )
-
-
-def main() -> int:
- missing = build(None)
- assert missing["ok"] is False, missing
- assert_common_boundary(missing)
- assert missing["decision"] == "proof_fixture_required", missing
- assert missing["approved_for_same_session_automation"] is False, missing
- assert "required_fixture_shape" in missing, missing
-
- passing = build(PASSING_PROOF)
- assert passing["ok"] is True, passing
- assert_common_boundary(passing)
- assert passing["decision"] == "visible_session_proof_passed", passing
- assert passing["approved_for_same_session_automation"] is True, passing
- assert passing["failures"] == [], passing
- assert all(check["passed"] for check in passing["checks"]), passing
-
- failing = build(FAILING_PROOF)
- assert failing["ok"] is True, failing
- assert_common_boundary(failing)
- assert failing["decision"] == "visible_session_proof_incomplete", failing
- assert failing["approved_for_same_session_automation"] is False, failing
- assert "idle_no_running_turn" in failing["failures"], failing
- assert "no_session_files_read" in failing["failures"], failing
- assert "unsupported_observed_surface" in failing["failures"], failing
-
- with tempfile.TemporaryDirectory(prefix="loopx-codex-cli-visible-proof-") as tmp:
- fixture = Path(tmp) / "visible-proof.json"
- fixture.write_text(json.dumps(PASSING_PROOF))
- cli_json = json.loads(
- run_cli(
- "--format",
- "json",
- "codex-cli-visible-session-proof",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--proof-fixture",
- str(fixture),
- )
- )
- assert cli_json["approved_for_same_session_automation"] is True, cli_json
- assert cli_json["observed_surface"] == "visible_resume_prompt", cli_json
-
- cli_markdown = run_cli(
- "codex-cli-visible-session-proof",
- "--project",
- str(PROJECT),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--proof-fixture",
- str(fixture),
- )
- assert "# Codex CLI Visible Session Proof" in cli_markdown, cli_markdown
- assert "approved_for_same_session_automation: `True`" in cli_markdown, cli_markdown
- assert "- [x] visible_to_user" in cli_markdown, cli_markdown
-
- print("codex-cli-visible-session-proof-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/codex-subagent-orchestration-contract-smoke.py b/examples/codex-subagent-orchestration-contract-smoke.py
deleted file mode 100644
index 0f84c1ca2f..0000000000
--- a/examples/codex-subagent-orchestration-contract-smoke.py
+++ /dev/null
@@ -1,102 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Codex sub-agent shared-control-plane contract."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-import re
-
-from loopx.control_plane.turn_driver.subagent_host_adapter import (
- project_child_context_adapter,
- supported_child_context_modes,
-)
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-DOC = REPO_ROOT / "docs" / "integrations" / "codex-subagent-orchestration.md"
-CODEX_HOST_CONTRACT = REPO_ROOT / "examples" / "fixtures" / (
- "codex-spawn-agent-contract.public.json"
-)
-
-REQUIRED_PHRASES = (
- "shared control plane",
- "subagent_control_plane_handoff_v0",
- "`parent_goal_id`",
- "`authority_artifact`",
- "`latest_state_ref`",
- "`quota_gate_snapshot`",
- "`evidence_boundary`",
- "`writeback_spend_contract`",
- "`child_guard_policy`",
- "`prevention_first_v0`",
- "temporary task coordinator",
- "child worker reports evidence only; task coordinator writes accepted state and spends",
- "control_plane_handoff_version",
- "It does not own durable goal authority",
- "one pending lease for `(goal_id, todo_id)`",
- "`goal_id` is the shared control-plane lane",
- "`todo_id` is the work item being claimed",
- '"agent_model": "peer_v1"',
- "independent worktrees",
- "Review remains `action_kind=review`",
- "Only currently actionable candidates appear under `eligible_peer_lanes`.",
- "Closed, blocked, or deferred Todos are excluded.",
- "appears under `blocked_peer_lanes`",
-)
-
-FORBIDDEN_PHRASES = (
- "PRIVATE_HOME/",
- "lark" + "office.com",
- "~/.codex/sessions",
- "raw_thread",
- "session_history",
- "coordination.primary_agent",
- "primary-agent review todo",
- "side agents",
- "main controller",
- '"role": "controller"',
- '"role": "subagent"',
- "controller owns",
- "parent writes and spends",
-)
-
-
-def main() -> int:
- text = DOC.read_text(encoding="utf-8")
- compact = " ".join(text.split())
- for phrase in REQUIRED_PHRASES:
- assert phrase in compact, phrase
- for phrase in FORBIDDEN_PHRASES:
- assert phrase not in text, phrase
- host_contract = json.loads(CODEX_HOST_CONTRACT.read_text(encoding="utf-8"))
- expected_arguments = host_contract["context_mode_arguments"]
- # The table must describe the shipped adapters, not every schema mode.
- for label, host in (("Codex CLI", "codex-cli"), ("Claude Code", "claude-code")):
- row = next(line for line in text.splitlines() if line.startswith(f"| {label} |"))
- documented_modes = tuple(re.findall(r"`([^`]+)`", row.split("|")[2]))
- assert documented_modes == supported_child_context_modes(host), host
- codex_row = next(line for line in text.splitlines() if line.startswith("| Codex CLI |"))
- for mode, fork_turns in (
- ("fresh", "none"),
- ("forked_snapshot", "all"),
- ):
- adapter = project_child_context_adapter(host="codex-cli", context_mode=mode)
- assert adapter is not None
- assert adapter["native_operation"] == "spawn_agent"
- assert adapter["arguments"] == expected_arguments[mode]
- assert f'`fork_turns="{fork_turns}"`' in codex_row
- for forbidden_argument in host_contract["forbidden_arguments"]:
- assert forbidden_argument not in codex_row
- assert all(
- forbidden_argument not in arguments
- for arguments in expected_arguments.values()
- )
- assert text.count("subagent_control_plane_handoff_v0") >= 2, text
- assert text.count("## ") >= 7, text
- print("codex-subagent-orchestration-contract-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/active-state-metadata-readmodel-smoke.py b/examples/control_plane/active-state-metadata-readmodel-smoke.py
deleted file mode 100644
index d1190bcef1..0000000000
--- a/examples/control_plane/active-state-metadata-readmodel-smoke.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test active-state metadata read-model parity."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.goals import active_state_metadata as metadata_read_model # noqa: E402
-
-
-def main() -> None:
- state_text = """---
-updated_at: "2026-07-04T10:00:00+08:00"
-owner: codex
-malformed
----
-
-## Agent Todo
-- [ ] keep working
-"""
- assert status_module.parse_state_frontmatter(state_text) == metadata_read_model.parse_state_frontmatter(
- state_text
- )
- assert status_module.parse_state_frontmatter("no frontmatter") == {}
- assert status_module.parse_state_frontmatter("---\nmissing close") == {}
-
- headings = {
- "User Todo / Owner Review Reading Queue": "user",
- "Project Agent Todo": "agent",
- "Completed Work Archive": None,
- "普通章节": None,
- }
- for heading, expected in headings.items():
- assert metadata_read_model.todo_role_for_heading(heading) == expected, heading
- assert not hasattr(status_module, "todo_role_for_heading")
-
- print("active-state-metadata-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/active-state-section-readmodel-smoke.py b/examples/control_plane/active-state-section-readmodel-smoke.py
deleted file mode 100644
index 3399499170..0000000000
--- a/examples/control_plane/active-state-section-readmodel-smoke.py
+++ /dev/null
@@ -1,82 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test active-state section parsing read-model wrappers."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.goals.active_state_sections import ( # noqa: E402
- active_state_section_entries as direct_active_state_section_entries,
- active_state_sections as direct_active_state_sections,
-)
-from loopx.status import ( # noqa: E402
- BACKLOG_HYGIENE_BULLET_PATTERN,
- SECTION_HEADING_PATTERN,
- active_state_section_entries,
- active_state_sections,
-)
-from loopx.control_plane.todos.todo_summary import normalize_todo_text # noqa: E402
-
-
-STATE_TEXT = """# Goal
-
-## Next Action
-
-- Continue canary-gated read-model cleanup
- after PR #1284
-
-## Operating Lessons
-
-Plain observation
-1. First numbered item
- continued
-
-### Nested Heading
-
-Should not land in requested sections
-"""
-
-
-def main() -> int:
- headings = ("Next Action", "Operating Lessons", "Missing Section")
- direct_sections = direct_active_state_sections(
- STATE_TEXT,
- headings,
- section_heading_pattern=SECTION_HEADING_PATTERN,
- )
- wrapper_sections = active_state_sections(STATE_TEXT, headings)
- assert wrapper_sections == direct_sections, (wrapper_sections, direct_sections)
- assert wrapper_sections["Missing Section"] == [], wrapper_sections
- assert "Continue canary-gated read-model cleanup" in "\n".join(
- wrapper_sections["Next Action"]
- ), wrapper_sections
-
- direct_entries = direct_active_state_section_entries(
- wrapper_sections["Operating Lessons"],
- bullet_pattern=BACKLOG_HYGIENE_BULLET_PATTERN,
- normalize_text=normalize_todo_text,
- )
- wrapper_entries = active_state_section_entries(wrapper_sections["Operating Lessons"])
- assert wrapper_entries == direct_entries, (wrapper_entries, direct_entries)
- assert wrapper_entries == [
- "Plain observation",
- "First numbered item continued",
- ], wrapper_entries
-
- next_entries = active_state_section_entries(wrapper_sections["Next Action"])
- assert next_entries == [
- "Continue canary-gated read-model cleanup after PR #1284",
- ], next_entries
-
- print("active-state-section-readmodel-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/agent-management-observability-mvp-smoke.py b/examples/control_plane/agent-management-observability-mvp-smoke.py
deleted file mode 100644
index a7ffd20728..0000000000
--- a/examples/control_plane/agent-management-observability-mvp-smoke.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the Agent Management Observability MVP note."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-DOC_PATH = REPO_ROOT / "docs/product/surfaces/agent-management-observability-mvp.md"
-SURFACE_INDEX_PATH = REPO_ROOT / "docs/product/surfaces/README.md"
-
-PRIVATE_PATTERNS = [
- re.compile(r"/Users/[A-Za-z0-9._-]+/"),
- re.compile(r"/home/[A-Za-z0-9._-]+/"),
- re.compile(r"/private/"),
- re.compile(r"\bBearer\s+[A-Za-z0-9._-]+"),
- re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
-]
-
-
-def read(path: Path) -> str:
- return path.read_text(encoding="utf-8")
-
-
-def assert_contains(text: str, needle: str, label: str) -> None:
- if needle not in text:
- raise AssertionError(f"{label} missing {needle!r}")
-
-
-def assert_public_safe(text: str, label: str) -> None:
- for pattern in PRIVATE_PATTERNS:
- if pattern.search(text):
- raise AssertionError(f"{label} matched private pattern {pattern.pattern!r}")
-
-
-def main() -> int:
- doc = read(DOC_PATH)
- surface_index = read(SURFACE_INDEX_PATH)
-
- assert_public_safe(doc, "mvp doc")
- assert_public_safe(surface_index, "surface index")
-
- for needle in [
- "Use the mature agent-console direction",
- "does not copy Hermes source code",
- "LoopX already has the durable work unit: `todo_id` inside `goal_id`.",
- "The MVP must not expose:",
- "claim/reclaim",
- "dispatch",
- "stale claim is a warning only",
- "agent_management_projection_v0",
- "export-agent-management-status-example.py",
- "does not invent workspace or handoff fields",
- "license/attribution note",
- ]:
- assert_contains(doc, needle, "mvp doc")
-
- for url in [
- "https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/kanban.md",
- "https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/delegation.md",
- "https://github.com/NousResearch/hermes-agent/blob/main/LICENSE",
- ]:
- assert_contains(doc, url, "source links")
-
- assert_contains(
- surface_index,
- "Agent management observability MVP",
- "surface index",
- )
-
- print("agent-management-observability-mvp-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/agent-management-projection-contract-smoke.py b/examples/control_plane/agent-management-projection-contract-smoke.py
deleted file mode 100644
index 3dae5b043e..0000000000
--- a/examples/control_plane/agent-management-projection-contract-smoke.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the agent_management_projection_v0 contract."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-CONTRACT_PATH = REPO_ROOT / "docs/reference/protocols/agent-management-projection-v0.md"
-PROTOCOL_INDEX_PATH = REPO_ROOT / "docs/reference/protocols/README.md"
-
-PRIVATE_PATTERNS = [
- re.compile(r"/Users/[A-Za-z0-9._-]+/"),
- re.compile(r"/home/[A-Za-z0-9._-]+/"),
- re.compile(r"/private/"),
- re.compile(r"[A-Za-z]:\\\\Users\\\\"),
- re.compile(r"\bBearer\s+[A-Za-z0-9._-]+"),
- re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
-]
-
-
-def read(path: Path) -> str:
- return path.read_text(encoding="utf-8")
-
-
-def assert_contains(text: str, needle: str, label: str) -> None:
- if needle not in text:
- raise AssertionError(f"{label} missing {needle!r}")
-
-
-def assert_public_safe(text: str, label: str) -> None:
- for pattern in PRIVATE_PATTERNS:
- if pattern.search(text):
- raise AssertionError(f"{label} matched private pattern {pattern.pattern!r}")
-
-
-def main() -> int:
- contract = read(CONTRACT_PATH)
- protocol_index = read(PROTOCOL_INDEX_PATH)
-
- assert_public_safe(contract, "contract")
- assert_public_safe(protocol_index, "protocol index")
-
- for needle in [
- "agent_management_projection_v0",
- "`todo_id` remains the",
- "read-only operator view",
- "does not introduce a runtime `task` object",
- '"mode": "read_only"',
- '"projection_is_writable": false',
- '"introduces_task_runtime": false',
- "not an automatic reclaim rule",
- "reuse_public_compatible_code_only",
- "copied code keeps required attribution or notice text",
- "dashboard consumers remain functional when the projection is absent",
- "top-level\n`agent_management_projection` key",
- ]:
- assert_contains(contract, needle, "contract")
-
- for forbidden in [
- "new `task_id`",
- "automatic dispatch",
- "workspace allocation runtime",
- "clear the claim, reassign work, or discard evidence",
- ]:
- assert_contains(contract, forbidden, "contract non-goals")
-
- assert_contains(protocol_index, "agent_management_projection_v0", "protocol index")
- print("agent-management-projection-contract-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/agent-material-frontier-smoke.py b/examples/control_plane/agent-material-frontier-smoke.py
deleted file mode 100644
index 1d64066eb8..0000000000
--- a/examples/control_plane/agent-material-frontier-smoke.py
+++ /dev/null
@@ -1,369 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the read-only agent material frontier contract."""
-
-from __future__ import annotations
-
-import copy
-import json
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.agents.material_frontier import ( # noqa: E402
- build_agent_material_frontier,
-)
-
-
-GOAL_ID = "material-frontier-fixture"
-AGENT_ID = "agent-builder"
-SUCCESSOR_ID = "agent-reviewer"
-TODO_ID = "todo_material_frontier"
-
-
-def authority_registry() -> dict:
- return {
- "project_materials": {
- "design-contract": {
- "id": "design-contract",
- "revision": "rev-2",
- "freshness": "current",
- "boundary": "public_safe",
- "gate_status": "registered",
- "source_ref_redacted": "registered-public-source",
- },
- "private-runbook": {
- "id": "private-runbook",
- "revision": "rev-1",
- "freshness": "current",
- "boundary": "private_redacted",
- "gate_status": "registered",
- "source_ref_redacted": "registered-private-source",
- },
- "stale-review": {
- "id": "stale-review",
- "revision": "rev-3",
- "freshness": "stale",
- "boundary": "public",
- "gate_status": "registered",
- },
- },
- "topic_authority": {
- "runtime-design": "design-contract",
- },
- }
-
-
-def requirements() -> tuple[dict, dict, dict, dict]:
- profile = {
- "agent_id": AGENT_ID,
- "material_topics": ["runtime-design"],
- }
- vision = {
- "vision_id": "vision_material_frontier",
- "material_refs": [
- {
- "material_id": "design-contract",
- "relation": "reviewer",
- "purpose": "review the current contract",
- }
- ],
- }
- todo = {
- "todo_id": TODO_ID,
- "material_refs": [
- {
- "material_id": "design-contract",
- "relation": "required",
- "purpose": "implement the current revision",
- },
- {"material_id": "private-runbook", "relation": "required"},
- {"material_id": "stale-review", "relation": "reviewer"},
- {"material_id": "missing-source", "relation": "required"},
- ],
- "evidence_refs": ["run:evidence-does-not-prove-a-read"],
- }
- handoff = {
- "schema_version": "handoff_note_v1",
- "handoff_id": "handoff_material_frontier",
- "todo_id": TODO_ID,
- "material_refs": copy.deepcopy(todo["material_refs"]),
- }
- return profile, vision, todo, handoff
-
-
-def receipt(
- *,
- agent_id: str,
- material_id: str,
- observed_revision: str,
- receipt_id: str,
-) -> dict:
- return {
- "schema_version": "material_usage_receipt_v0",
- "receipt_id": receipt_id,
- "goal_id": GOAL_ID,
- "agent_id": agent_id,
- "todo_id": TODO_ID,
- "material_id": material_id,
- "relation": "required",
- "observed_revision": observed_revision,
- "outcome": "used",
- "evidence_ref": f"todo:{TODO_ID}:evidence",
- "recorded_at": "2026-07-19T00:00:00Z",
- }
-
-
-def by_material(frontier: dict) -> dict[str, dict]:
- return {item["material_id"]: item for item in frontier["items"]}
-
-
-def assert_derivation_and_boundaries() -> dict:
- profile, vision, todo, handoff = requirements()
- receipts = [
- receipt(
- agent_id=AGENT_ID,
- material_id="design-contract",
- observed_revision="rev-2",
- receipt_id="receipt_current",
- ),
- receipt(
- agent_id=AGENT_ID,
- material_id="stale-review",
- observed_revision="rev-3",
- receipt_id="receipt_authority_stale",
- ),
- receipt(
- agent_id=SUCCESSOR_ID,
- material_id="design-contract",
- observed_revision="rev-2",
- receipt_id="receipt_other_agent",
- ),
- ]
- frontier = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=authority_registry(),
- agent_profile=profile,
- todos=[todo],
- vision=vision,
- handoffs=[handoff],
- receipts=receipts,
- generated_at="2026-07-19T00:01:00Z",
- )
- items = by_material(frontier)
- assert frontier["schema_version"] == "agent_material_frontier_v0", frontier
- assert frontier["summary"] == {
- "required_count": 4,
- "current_count": 1,
- "stale_count": 1,
- "missing_count": 1,
- "inaccessible_count": 1,
- "required_unread_count": 0,
- }, frontier
- assert items["design-contract"]["state"] == "current", items
- assert items["design-contract"]["relation"] == "required", items
- assert {binding["kind"] for binding in items["design-contract"]["bound_by"]} == {
- "profile",
- "vision",
- "todo",
- "handoff",
- }, items
- assert items["private-runbook"]["state"] == "inaccessible", items
- assert items["stale-review"]["state"] == "stale", items
- assert items["missing-source"]["state"] == "missing", items
- assert "source_ref_redacted" not in json.dumps(frontier, sort_keys=True), frontier
- assert frontier["truth_contract"] == {
- "authority_is_goal_owned": True,
- "projection_is_read_only": True,
- "introduces_task_runtime": False,
- "grants_cross_agent_authority": False,
- "evidence_log_implies_material_read": False,
- "raw_source_body_recorded": False,
- }, frontier
- return frontier
-
-
-def assert_revision_lifecycle() -> None:
- _, _, todo, _ = requirements()
- unread = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=authority_registry(),
- todos={
- "todo_id": TODO_ID,
- "material_refs": [todo["material_refs"][0]],
- "evidence_refs": ["run:still-not-a-receipt"],
- },
- receipts=[
- {
- "receipt_id": "evidence_shaped_like_receipt",
- "goal_id": GOAL_ID,
- "agent_id": AGENT_ID,
- "todo_id": TODO_ID,
- "material_id": "design-contract",
- "observed_revision": "rev-2",
- "outcome": "used",
- "recorded_at": "2026-07-19T00:01:30Z",
- }
- ],
- generated_at="2026-07-19T00:02:00Z",
- )
- assert by_material(unread)["design-contract"]["state"] == "required_unread", unread
-
- current_receipt = receipt(
- agent_id=AGENT_ID,
- material_id="design-contract",
- observed_revision="rev-2",
- receipt_id="receipt_revision_lifecycle",
- )
- current = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=authority_registry(),
- todos={"todo_id": TODO_ID, "material_refs": [todo["material_refs"][0]]},
- receipts=[current_receipt],
- generated_at="2026-07-19T00:03:00Z",
- )
- assert by_material(current)["design-contract"]["state"] == "current", current
-
- advanced_authority = authority_registry()
- advanced_authority["project_materials"]["design-contract"]["revision"] = "rev-3"
- stale = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=advanced_authority,
- todos={"todo_id": TODO_ID, "material_refs": [todo["material_refs"][0]]},
- receipts=[current_receipt],
- generated_at="2026-07-19T00:04:00Z",
- )
- assert by_material(stale)["design-contract"]["state"] == "stale", stale
-
-
-def assert_profile_topic_defaults_to_watcher() -> None:
- profile, _, _, _ = requirements()
- frontier = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=authority_registry(),
- agent_profile=profile,
- generated_at="2026-07-19T00:04:30Z",
- )
- item = by_material(frontier)["design-contract"]
- assert item["relation"] == "watcher", item
- assert item["state"] == "required_unread", item
- assert item["bound_by"] == [{"kind": "profile", "ref": AGENT_ID}], item
-
-
-def assert_handoff_preserves_refs_without_authority_or_receipts() -> None:
- _, _, todo, handoff = requirements()
- source = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=authority_registry(),
- todos=todo,
- handoffs=handoff,
- receipts=[
- receipt(
- agent_id=AGENT_ID,
- material_id="design-contract",
- observed_revision="rev-2",
- receipt_id="receipt_source_agent",
- )
- ],
- available_boundaries=["private_redacted"],
- generated_at="2026-07-19T00:05:00Z",
- )
- successor = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=SUCCESSOR_ID,
- authority_registry=authority_registry(),
- handoffs=handoff,
- receipts=[],
- available_boundaries=["private_redacted"],
- generated_at="2026-07-19T00:06:00Z",
- )
- assert set(by_material(source)) == set(by_material(successor)), (source, successor)
- assert by_material(successor)["design-contract"]["state"] == "required_unread", successor
- assert by_material(successor)["design-contract"]["required_revision"] == "rev-2", successor
- assert successor["truth_contract"]["grants_cross_agent_authority"] is False, successor
-
-
-def assert_compact_authority_fails_closed() -> None:
- try:
- build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry={"project_material_count": 4},
- todos={"todo_id": TODO_ID, "material_refs": ["design-contract"]},
- )
- except ValueError as exc:
- assert "canonical authority_registry.project_materials" in str(exc), exc
- else:
- raise AssertionError("compact authority summary must not be treated as canonical material truth")
-
- try:
- build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry=authority_registry(),
- agent_profile={
- "agent_id": AGENT_ID,
- "material_topics": ["unregistered-topic"],
- },
- )
- except ValueError as exc:
- assert "material topic is not registered" in str(exc), exc
- else:
- raise AssertionError("an unknown profile topic must not produce an empty frontier")
-
- unknown_boundary = build_agent_material_frontier(
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- authority_registry={
- "project_materials": {
- "boundary-unknown": {
- "id": "boundary-unknown",
- "revision": "rev-1",
- }
- },
- "topic_authority": {},
- },
- todos={
- "todo_id": TODO_ID,
- "material_refs": ["boundary-unknown"],
- },
- )
- assert by_material(unknown_boundary)["boundary-unknown"]["state"] == "inaccessible"
-
-
-def assert_public_fixture(frontier: dict) -> None:
- rendered = json.dumps(frontier, ensure_ascii=False, sort_keys=True)
- for forbidden in (
- "/Users/",
- "/private/",
- "/tmp/",
- "lark" + "office",
- "Authorization",
- "Bearer ",
- "AK=",
- "SK=",
- ):
- assert forbidden not in rendered, forbidden
-
-
-def main() -> int:
- frontier = assert_derivation_and_boundaries()
- assert_revision_lifecycle()
- assert_profile_topic_defaults_to_watcher()
- assert_handoff_preserves_refs_without_authority_or_receipts()
- assert_compact_authority_fails_closed()
- assert_public_fixture(frontier)
- print("agent-material-frontier-smoke: ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/agent-monitor-only-work-mode-smoke.py b/examples/control_plane/agent-monitor-only-work-mode-smoke.py
deleted file mode 100644
index 756f7f7c86..0000000000
--- a/examples/control_plane/agent-monitor-only-work-mode-smoke.py
+++ /dev/null
@@ -1,158 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test per-agent monitor-only work-mode precedence."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.scheduler.execution_context import ( # noqa: E402
- GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT,
-)
-from loopx.control_plane.testing.quota_fixtures import ( # noqa: E402
- quota_status_payload,
- quota_todo_item,
- quota_todo_summary,
-)
-from loopx.quota import build_quota_should_run # noqa: E402
-
-
-GOAL_ID = "agent-monitor-only-smoke"
-CURRENT_AGENT = "codex-current"
-PEER_AGENT = "codex-peer"
-
-
-def decision_for(items: list[dict], *, agent_id: str = CURRENT_AGENT) -> dict:
- agent_todos = quota_todo_summary(
- items,
- role="agent",
- claim_scope_agent_id=agent_id,
- )
- payload = quota_status_payload(
- goal_id=GOAL_ID,
- status="active",
- recommended_action="Continue bounded work.",
- agent_todos=agent_todos,
- coordination={
- "agent_model": "peer_v1",
- "registered_agents": [CURRENT_AGENT, PEER_AGENT],
- "agent_work_modes": {CURRENT_AGENT: "monitor_only"},
- },
- )
- return build_quota_should_run(
- payload,
- goal_id=GOAL_ID,
- agent_id=agent_id,
- scheduler_execution_context=GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT,
- )
-
-
-def assert_monitor_only_wait(decision: dict, *, action: str) -> None:
- assert decision["decision"] == "skip", decision
- assert decision["effective_action"] == action, decision
- assert decision["should_run"] is False, decision
- assert decision["agent_work_mode"] == "monitor_only", decision
- for field in (
- "normal_delivery_allowed",
- "recovery_delivery_allowed",
- "self_repair_allowed",
- "capability_repair_allowed",
- "workspace_repair_allowed",
- "actionable_by_codex",
- "requires_user_action",
- ):
- assert decision[field] is False, (field, decision)
- for field in (
- "autonomous_replan_decision",
- "autonomous_replan_obligation",
- "autonomous_replan_scope",
- "required_reads",
- "scoped_user_gate_fallback",
- "vision_continuation_audit",
- "vision_wait_state",
- ):
- assert field not in decision, (field, decision)
- assert "vision_continuation_audit" not in decision.get(
- "goal_frontier_projection", {}
- ), decision
- interaction = decision["interaction_contract"]
- assert interaction["user_channel"]["notify"] == "DONT_NOTIFY", interaction
- assert interaction["agent_channel"]["must_attempt"] is False, interaction
- assert interaction["agent_channel"]["delivery_allowed"] is False, interaction
- assert interaction["agent_channel"]["quiet_noop_allowed"] is True, interaction
- assert interaction["cli_channel"]["spend_after_validation"] is False, interaction
-
-
-def main() -> None:
- advancement = quota_todo_item(
- todo_id="todo_advancement",
- title="Open a new implementation topic.",
- claimed_by=CURRENT_AGENT,
- )
- stopped = decision_for([advancement])
- assert_monitor_only_wait(stopped, action="agent_monitor_only")
- assert stopped["interaction_contract"]["mode"] == "agent_monitor_only", stopped
- assert (
- stopped["automation_liveness"]["automation_action"]
- == "keep_active_monitor_only"
- ), stopped
- assert stopped["scheduler_hint"]["action"] == "backoff_agent_monitor_only", stopped
- assert stopped["scheduler_hint"]["cadence_class"] == "agent_monitor_only", stopped
-
- future_monitor = quota_todo_item(
- todo_id="todo_future_monitor",
- index=2,
- title="Observe an external merge result.",
- task_class="continuous_monitor",
- claimed_by=CURRENT_AGENT,
- cadence="daily",
- next_due_at="2999-01-01T00:00:00Z",
- )
- quiet = decision_for([advancement, future_monitor])
- assert_monitor_only_wait(quiet, action="monitor_quiet_skip")
- assert quiet["work_lane_contract"]["lane"] == "continuous_monitor", quiet
-
- due_monitor = {
- **future_monitor,
- "todo_id": "todo_due_monitor",
- "next_due_at": "2020-01-01T00:00:00Z",
- }
- due = decision_for([advancement, due_monitor])
- assert due["decision"] == "run", due
- assert due["effective_action"] == "monitor_due", due
- assert due["should_run"] is True, due
- assert due["work_lane_contract"]["lane"] == "continuous_monitor", due
- assert due["work_lane_contract"]["selected_todo_id"] == "todo_due_monitor", due
- assert due["interaction_contract"]["mode"] == "monitor_due", due
- assert due["interaction_contract"]["user_channel"]["notify"] == "DONT_NOTIFY", due
- assert due["interaction_contract"]["agent_channel"]["must_attempt"] is True, due
- assert (
- due["interaction_contract"]["cli_channel"]["spend_after_validation"] is True
- ), due
- assert "autonomous_replan_obligation" not in due, due
- assert due["selected_todo"]["todo_id"] == "todo_due_monitor", due
- assert "todo_advancement" not in due["interaction_contract"]["agent_channel"]["primary_action"], due
- assert "protocol_action_packet" not in due, due
-
- peer = decision_for(
- [
- quota_todo_item(
- todo_id="todo_peer_advancement",
- title="Peer-owned bounded advancement.",
- claimed_by=PEER_AGENT,
- )
- ],
- agent_id=PEER_AGENT,
- )
- assert peer["effective_action"] == "normal_run", peer
- assert peer["should_run"] is True, peer
- assert peer.get("agent_work_mode") != "monitor_only", peer
- print("agent-monitor-only-work-mode-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/agent-scope-work-lane-consistency-smoke.py b/examples/control_plane/agent-scope-work-lane-consistency-smoke.py
deleted file mode 100644
index 0c2132cf3f..0000000000
--- a/examples/control_plane/agent-scope-work-lane-consistency-smoke.py
+++ /dev/null
@@ -1,214 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test peer reassignment consistency for the work-lane projection."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.quota import build_quota_should_run, render_quota_should_run_markdown
-from loopx.status import compact_todo_group
-from loopx.control_plane.testing.quota_fixtures import quota_status_payload
-
-
-GOAL_ID = "agent-scope-work-lane-consistency-fixture"
-PRIMARY_AGENT = "codex-main-control"
-SIDE_AGENT = "codex-product-capability"
-FUTURE_DUE_AT = "2999-01-01T00:00:00+00:00"
-PAST_DUE_AT = "2000-01-01T00:00:00+00:00"
-
-
-def _status_payload() -> dict:
- next_action = (
- "Post-reporting lane should route to the planning/self-repair capability "
- "lane as the next eligible advancement turn."
- )
- agent_todos = compact_todo_group(
- [
- {
- "index": 1,
- "text": "[P1-monitor] Watch the published PR until merge.",
- "role": "agent",
- "status": "open",
- "priority": "P1-monitor",
- "task_class": "continuous_monitor",
- "action_kind": "monitor",
- "claimed_by": SIDE_AGENT,
- "todo_id": "todo_side_monitor",
- "cadence": "60m",
- "next_due_at": FUTURE_DUE_AT,
- },
- {
- "index": 2,
- "text": next_action,
- "role": "agent",
- "status": "open",
- "priority": "P0",
- "task_class": "advancement_task",
- "claimed_by": PRIMARY_AGENT,
- "todo_id": "todo_primary_frontier",
- },
- ],
- source_section="Agent Todo",
- role="agent",
- )
- assert agent_todos is not None
- coordination = {
- "agent_model": "peer_v1",
- "registered_agents": [PRIMARY_AGENT, SIDE_AGENT],
- }
- return {
- "ok": True,
- "attention_queue": {
- "items": [
- {
- "goal_id": GOAL_ID,
- "status": "active",
- "waiting_on": "codex",
- "severity": "info",
- "source": "project_asset",
- "recommended_action": next_action,
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- "slot_minutes": 1,
- "allowed_slots": 10,
- "spent_slots": 0,
- "state": "eligible",
- "reason": "eligible fixture",
- },
- "coordination": coordination,
- "project_asset": {
- "next_action": next_action,
- "agent_todos": agent_todos,
- },
- }
- ]
- },
- "run_history": {
- "goals": [
- {
- "id": GOAL_ID,
- "registry_member": True,
- "status": "active",
- "adapter_kind": "harness_self_improvement",
- "adapter_status": "connected-read-only",
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- "slot_minutes": 1,
- "allowed_slots": 10,
- },
- "coordination": coordination,
- }
- ]
- },
- }
-
-
-def main() -> None:
- guard = build_quota_should_run(
- _status_payload(),
- goal_id=GOAL_ID,
- agent_id=SIDE_AGENT,
- )
-
- assert guard["decision"] == "reassignment_required", guard
- assert guard["should_run"] is False, guard
- assert guard["effective_action"] == "reassignment_required", guard
-
- lane = guard["work_lane_contract"]
- assert lane["lane"] == "reassignment_required", lane
- assert lane["obligation"] == "wait_for_current_agent_or_unclaimed_advancement", lane
- assert lane["must_attempt_work"] is False, lane
- assert lane["blocked_by_agent_scope"] is True, lane
- assert lane["deferred_work_lane"]["obligation"] == (
- "materialize_advancement_todo_or_blocker"
- ), lane
- assert "reassignment_required" in lane["reason_codes"], lane
-
- obligation = guard["execution_obligation"]
- assert obligation["kind"] == "reassignment_required", obligation
- assert obligation["must_attempt_work"] is False, obligation
-
- contract = guard["interaction_contract"]
- assert contract["mode"] == "reassignment_required", contract
- assert contract["agent_channel"]["must_attempt"] is False, contract
- assert contract["agent_channel"]["delivery_allowed"] is False, contract
- assert contract["agent_channel"]["quiet_noop_allowed"] is True, contract
-
- markdown = render_quota_should_run_markdown(guard)
- assert "obligation=materialize_advancement_todo_or_blocker" not in markdown, markdown
- assert (
- "work_lane_contract: lane=reassignment_required next=advancement_task" in markdown
- ), markdown
-
- due_monitor_text = (
- "[P2] Monitor the todo succession contract and reschedule after checking."
- )
- external_action = (
- "Monitor public run_group compact artifacts until the batch closes."
- )
- due_guard = build_quota_should_run(
- quota_status_payload(
- goal_id=GOAL_ID,
- status="side_agent_due_monitor_with_other_claimed_frontier",
- recommended_action=external_action,
- next_action=external_action,
- claim_scope_agent_id=SIDE_AGENT,
- coordination={
- "agent_model": "peer_v1",
- "registered_agents": [PRIMARY_AGENT, SIDE_AGENT],
- },
- agent_todo_items=[
- {
- "index": 1,
- "text": due_monitor_text,
- "role": "agent",
- "status": "open",
- "priority": "P2",
- "task_class": "continuous_monitor",
- "action_kind": "todo_succession_contract_monitor",
- "claimed_by": SIDE_AGENT,
- "todo_id": "todo_side_due_monitor",
- "target_key": "todo-succession-contract",
- "cadence": "1d",
- "next_due_at": PAST_DUE_AT,
- },
- {
- "index": 2,
- "text": external_action,
- "role": "agent",
- "status": "open",
- "priority": "P0",
- "task_class": "advancement_task",
- "claimed_by": PRIMARY_AGENT,
- "todo_id": "todo_primary_external_run",
- },
- ],
- ),
- goal_id=GOAL_ID,
- agent_id=SIDE_AGENT,
- )
- assert due_guard["decision"] == "observe", due_guard
- assert due_guard["should_run"] is True, due_guard
- assert due_guard["effective_action"] == "external_evidence_observe", due_guard
- assert "agent_scope_frontier" not in due_guard, due_guard
- due_lane = due_guard["work_lane_contract"]
- assert due_lane["lane"] == "continuous_monitor", due_lane
- assert due_lane["monitor_kind"] == "external_evidence", due_lane
- assert due_lane["obligation"] == "observe_external_evidence_or_blocker", due_lane
- assert due_lane["selected_todo_id"] == "todo_side_due_monitor", due_lane
- assert due_guard["selected_todo"]["todo_id"] == "todo_side_due_monitor", due_guard
- assert (
- "Monitor the todo succession contract"
- in due_guard["interaction_contract"]["agent_channel"]["primary_action"]
- ), due_guard
- print("agent-scope-work-lane-consistency-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/auto-research-role-successor-completion-smoke.py b/examples/control_plane/auto-research-role-successor-completion-smoke.py
deleted file mode 100644
index 7270dea817..0000000000
--- a/examples/control_plane/auto-research-role-successor-completion-smoke.py
+++ /dev/null
@@ -1,183 +0,0 @@
-#!/usr/bin/env python3
-"""Canary existing-successor completion across peer task domains."""
-
-from __future__ import annotations
-
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.testing.canary_harness import ( # noqa: E402
- import_fixture_authority,
- run_json_cli,
- run_json_cli_result,
- write_fixture_registry,
-)
-
-
-GOAL_ID = "auto-research-role-successor-fixture"
-CURATOR = "research-curator"
-PROPOSER = "hypothesis-proposer"
-EXECUTOR = "research-executor"
-PROPOSER_TODO = "todo_auto_research_propose"
-EXECUTOR_TODO = "todo_auto_research_execute"
-
-
-def write_fixture(root: Path, *, auto_research: bool) -> tuple[Path, Path, Path]:
- project = root / "project"
- runtime = root / "runtime"
- registry_path = project / ".loopx" / "registry.json"
- state_path = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md"
- state_path.parent.mkdir(parents=True)
- state_path.write_text(
- "---\n"
- "status: active\n"
- "owner_mode: goal\n"
- 'objective: "Exercise role successor completion."\n'
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- "# Auto-Research Role Successor Fixture\n\n"
- "## Objective\n\n"
- "Exercise role successor completion.\n\n"
- "## Next Action\n\n"
- "- Let auto-research roles advance through existing successors.\n\n"
- "## Agent Todo\n\n"
- "- [ ] [P1] Propose a public-safe research hypothesis.\n"
- f" \n"
- "- [ ] [P1] Execute the selected public-safe hypothesis.\n"
- f" \n",
- encoding="utf-8",
- )
- write_fixture_registry(
- project=project,
- runtime_root=runtime,
- registry_path=registry_path,
- goal_id=GOAL_ID,
- domain="auto-research-demo" if auto_research else "side-agent-handoff-fixture",
- adapter_kind=(
- "auto_research_demo_local_queue"
- if auto_research
- else "side_agent_handoff_fixture_v0"
- ),
- adapter_status="connected",
- registered_agents=[CURATOR, PROPOSER, EXECUTOR],
- peer_independent_worktree_required=False,
- )
- import_fixture_authority(registry_path, GOAL_ID)
- return project, runtime, registry_path
-
-
-def complete_proposer(
- registry_path: Path,
- runtime: Path,
- *,
- actor_agent_id: str | None = PROPOSER,
-) -> tuple[int, dict]:
- cli_args = [
- "todo",
- "complete",
- "--goal-id",
- GOAL_ID,
- "--role",
- "agent",
- "--todo-id",
- PROPOSER_TODO,
- "--claimed-by",
- PROPOSER,
- ]
- if actor_agent_id is not None:
- cli_args.extend(["--agent-id", actor_agent_id])
- cli_args.extend(
- [
- "--evidence",
- "fixture produced a public-safe hypothesis packet",
- "--successor-todo-id",
- EXECUTOR_TODO,
- ]
- )
- return run_json_cli_result(
- *cli_args,
- registry_path=registry_path,
- runtime_root=runtime,
- cwd=REPO_ROOT,
- )
-
-
-def assert_actor_attribution_fails_closed() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-role-successor-actor-") as tmp:
- project, runtime, registry_path = write_fixture(Path(tmp), auto_research=True)
- state_path = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md"
- before = state_path.read_text(encoding="utf-8")
-
- missing_code, missing = complete_proposer(
- registry_path,
- runtime,
- actor_agent_id=None,
- )
- assert missing_code == 1, missing
- assert missing["error_code"] == "actor_required", missing
- assert state_path.read_text(encoding="utf-8") == before
-
- wrong_code, wrong = complete_proposer(
- registry_path,
- runtime,
- actor_agent_id=CURATOR,
- )
- assert wrong_code == 1, wrong
- assert wrong["error_code"] == "claim_owner_mismatch", wrong
- assert state_path.read_text(encoding="utf-8") == before
-
-
-def assert_auto_research_role_successor_allowed() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-auto-research-role-successor-") as tmp:
- _project, runtime, registry_path = write_fixture(Path(tmp), auto_research=True)
- returncode, completed = complete_proposer(registry_path, runtime)
- assert returncode == 0, completed
- assert completed["ok"] is True, completed
- assert completed["status"] == "done", completed
- assert completed["successor_todo_ids"] == [EXECUTOR_TODO], completed
- assert completed["next_todos"] == [], completed
-
- successor_lookup = run_json_cli(
- "todo",
- "list",
- "--goal-id",
- GOAL_ID,
- "--todo-id",
- EXECUTOR_TODO,
- registry_path=registry_path,
- runtime_root=runtime,
- cwd=REPO_ROOT,
- )
- assert successor_lookup["matched"] is True, successor_lookup
- assert successor_lookup["todo"]["status"] == "open", successor_lookup
- assert successor_lookup["todo"]["claimed_by"] == EXECUTOR, successor_lookup
-
-
-def assert_generic_peer_route_links_existing_successor() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-generic-peer-successor-") as tmp:
- _project, runtime, registry_path = write_fixture(Path(tmp), auto_research=False)
- returncode, completed = complete_proposer(registry_path, runtime)
- assert returncode == 0, completed
- assert completed["ok"] is True, completed
- assert completed["successor_todo_ids"] == [EXECUTOR_TODO], completed
-
-
-def main() -> None:
- assert_actor_attribution_fails_closed()
- assert_auto_research_role_successor_allowed()
- assert_generic_peer_route_links_existing_successor()
- print("auto-research-role-successor-completion-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/automation-liveness-state-machine-smoke.py b/examples/control_plane/automation-liveness-state-machine-smoke.py
deleted file mode 100644
index 5392482b5a..0000000000
--- a/examples/control_plane/automation-liveness-state-machine-smoke.py
+++ /dev/null
@@ -1,149 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test heartbeat automation liveness decisions outside quota."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.agents.agent_scope import AgentScopeFrontierAction # noqa: E402
-from loopx.control_plane.scheduler.automation_liveness import ( # noqa: E402
- build_automation_liveness,
-)
-
-
-def payload(
- *,
- effective_action: str = "normal_run",
- recommended_mode: str = "",
- must_attempt_work: bool = False,
- agent_scope_frontier: dict | None = None,
-) -> dict:
- result = {
- "effective_action": effective_action,
- "heartbeat_recommendation": {
- "recommended_mode": recommended_mode,
- },
- "execution_obligation": {
- "must_attempt_work": must_attempt_work,
- },
- }
- if agent_scope_frontier is not None:
- result["agent_scope_frontier"] = agent_scope_frontier
- return result
-
-
-def assert_common_liveness_fields(liveness: dict) -> None:
- assert liveness["schema_version"] == "automation_liveness_v0", liveness
- assert liveness["keep_active"] is True, liveness
- assert liveness["pause_allowed"] is False, liveness
- assert "pause/delete only after" in liveness["pause_policy"], liveness
-
-
-def assert_monitor_quiet_skip_keeps_heartbeat_active() -> None:
- liveness = build_automation_liveness(
- payload(
- effective_action="monitor_quiet_skip",
- recommended_mode="monitor_quiet_until_material_transition",
- )
- )
- assert_common_liveness_fields(liveness)
- assert liveness["automation_action"] == "keep_active_quiet", liveness
- assert "material monitor transition" in liveness["next_trigger"], liveness
- assert liveness["spend_policy"] == "no quota spend for unchanged monitor-only polls", liveness
-
-
-def assert_prompt_upgrade_repairs_identity_without_spend() -> None:
- liveness = build_automation_liveness(
- payload(effective_action="automation_prompt_upgrade_required")
- )
- assert_common_liveness_fields(liveness)
- assert liveness["automation_action"] == "repair_automation_prompt_identity", liveness
- assert "registered agent id" in liveness["reason"], liveness
- assert liveness["spend_policy"] == "no quota spend for identity prompt upgrade preflight", liveness
-
-
-def assert_successor_replan_requires_bounded_work() -> None:
- liveness = build_automation_liveness(
- payload(effective_action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED.value)
- )
- assert_common_liveness_fields(liveness)
- assert liveness["automation_action"] == "execute_bounded_work", liveness
- assert "ready deferred successor" in liveness["reason"], liveness
- assert liveness["next_trigger"] == "deferred successor replan writeback or fresh quota guard", liveness
- assert liveness["spend_policy"] == "spend once only after validated successor replan/todo writeback", liveness
-
-
-def assert_monitor_blocked_successor_replan_uses_gate_repair_copy() -> None:
- liveness = build_automation_liveness(
- payload(
- effective_action=AgentScopeFrontierAction.SUCCESSOR_REPLAN_REQUIRED.value,
- agent_scope_frontier={
- "monitor_blocked_resume_candidates": [
- {"todo_id": "todo_monitor_gated_successor"}
- ],
- },
- )
- )
- assert_common_liveness_fields(liveness)
- assert liveness["automation_action"] == "execute_bounded_work", liveness
- assert "open standing monitor" in liveness["reason"], liveness
- assert liveness["next_trigger"] == "standing monitor gate repair writeback or fresh quota guard", liveness
- assert liveness["spend_policy"] == "spend once only after validated gate repair/todo writeback", liveness
-
-
-def assert_agent_scope_no_candidate_is_quiet_no_spend() -> None:
- liveness = build_automation_liveness(
- payload(effective_action=AgentScopeFrontierAction.AGENT_SCOPE_WAIT.value)
- )
- assert_common_liveness_fields(liveness)
- assert liveness["automation_action"] == "keep_active_quiet", liveness
- assert "no in-scope runnable candidate" in liveness["reason"], liveness
- assert liveness["spend_policy"] == "no quota spend for agent-scoped no-candidate checks", liveness
-
-
-def assert_must_attempt_or_autonomous_replan_executes_bounded_work() -> None:
- must_attempt = build_automation_liveness(payload(must_attempt_work=True))
- assert_common_liveness_fields(must_attempt)
- assert must_attempt["automation_action"] == "execute_bounded_work", must_attempt
- assert must_attempt["spend_policy"] == "spend once only after validation and durable writeback", must_attempt
-
- autonomous = build_automation_liveness(
- payload(recommended_mode="autonomous_replan_required")
- )
- assert_common_liveness_fields(autonomous)
- assert autonomous["automation_action"] == "execute_bounded_work", autonomous
- assert autonomous["spend_policy"] == "spend once only after validation and durable writeback", autonomous
-
-
-def assert_mapped_noop_and_default_keep_alive() -> None:
- mapped = build_automation_liveness(payload(recommended_mode="mapped_noop_if_unchanged"))
- assert_common_liveness_fields(mapped)
- assert mapped["automation_action"] == "keep_active_noop_if_unchanged", mapped
- assert mapped["spend_policy"] == "no quota spend for unchanged mapped no-op checks", mapped
-
- default = build_automation_liveness(payload())
- assert_common_liveness_fields(default)
- assert default["automation_action"] == "keep_active", default
- assert default["spend_policy"].startswith("follow heartbeat_recommendation"), default
-
-
-def main() -> int:
- assert_monitor_quiet_skip_keeps_heartbeat_active()
- assert_prompt_upgrade_repairs_identity_without_spend()
- assert_successor_replan_requires_bounded_work()
- assert_monitor_blocked_successor_replan_uses_gate_repair_copy()
- assert_agent_scope_no_candidate_is_quiet_no_spend()
- assert_must_attempt_or_autonomous_replan_executes_bounded_work()
- assert_mapped_noop_and_default_keep_alive()
- print("automation-liveness-state-machine-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/autonomous-replan-obligation-readmodel-smoke.py b/examples/control_plane/autonomous-replan-obligation-readmodel-smoke.py
deleted file mode 100644
index cf2a384b61..0000000000
--- a/examples/control_plane/autonomous-replan-obligation-readmodel-smoke.py
+++ /dev/null
@@ -1,356 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test autonomous replan obligation builder read-model parity."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.work_items.autonomous_replan_obligation import ( # noqa: E402
- build_autonomous_replan_obligation as direct_build_autonomous_replan_obligation,
- build_autonomous_replan_obligation_payload,
-)
-from loopx.control_plane.work_items.project_asset import ( # noqa: E402
- attach_active_state_project_asset_fields,
-)
-from loopx.control_plane.goals.goal_frontier import ( # noqa: E402
- select_autonomous_replan_obligation,
-)
-from loopx.status import ( # noqa: E402
- AUTONOMOUS_REPLAN_SCHEMA_VERSION,
- AUTONOMOUS_REPLAN_STALL_THRESHOLD,
- DEAD_MONITOR_REPEAT_SCHEMA_VERSION,
- DEAD_MONITOR_REPEAT_THRESHOLD,
- autonomous_replan_obligation_from_runs,
- build_autonomous_replan_obligation,
- public_safe_compact_text,
-)
-
-
-AGENT_TODOS = {
- "first_open_items": [
- {
- "priority": "P2",
- "text": "[P2] Continue canary-gated control-plane read-model cleanup.",
- "claimed_by": "codex-control-plane",
- }
- ]
-}
-
-def direct(evidence: list[dict[str, object]]) -> dict[str, object] | None:
- return direct_build_autonomous_replan_obligation(
- evidence,
- agent_todos=AGENT_TODOS,
- public_safe_compact_text=public_safe_compact_text,
- autonomous_replan_schema_version=AUTONOMOUS_REPLAN_SCHEMA_VERSION,
- autonomous_replan_stall_threshold=AUTONOMOUS_REPLAN_STALL_THRESHOLD,
- dead_monitor_repeat_threshold=DEAD_MONITOR_REPEAT_THRESHOLD,
- dead_monitor_repeat_schema_version=DEAD_MONITOR_REPEAT_SCHEMA_VERSION,
- )
-
-
-def assert_parity(evidence: list[dict[str, object]]) -> dict[str, object]:
- wrapper = build_autonomous_replan_obligation(evidence, agent_todos=AGENT_TODOS)
- direct_result = direct(evidence)
- assert wrapper == direct_result, (wrapper, direct_result)
- assert wrapper is not None, wrapper
- return wrapper
-
-
-def assert_payload_builder_contract() -> None:
- payload = build_autonomous_replan_obligation_payload(
- schema_version=AUTONOMOUS_REPLAN_SCHEMA_VERSION,
- agent_id="codex-product-capability",
- stall_threshold=1,
- trigger_count=1,
- triggers=[
- {
- "kind": "vision_acceptance_gap",
- "section": "goal_frontier_projection.acceptance_gaps",
- "text": "active agent vision remains open",
- }
- ],
- guidance_actions=["create_successor", "record_no_followup"],
- todo_actions=[
- {
- "action": "add",
- "role": "agent",
- "priority": "P1",
- "text": "run a bounded vision-gap replan",
- }
- ],
- stop_condition="stop at private material or owner-only decisions",
- recommended_action="create a successor or record no-follow-up",
- extra_fields={"source": "goal_frontier_projection"},
- )
-
- assert payload["schema_version"] == AUTONOMOUS_REPLAN_SCHEMA_VERSION, payload
- assert payload["required"] is True, payload
- assert payload["agent_id"] == "codex-product-capability", payload
- assert payload["triggers"][0]["kind"] == "vision_acceptance_gap", payload
- assert payload["guidance_actions"] == ["create_successor", "record_no_followup"], payload
- assert payload["todo_actions"][0]["priority"] == "P1", payload
- assert payload["source"] == "goal_frontier_projection", payload
-
- unscoped_payload = build_autonomous_replan_obligation_payload(
- schema_version=AUTONOMOUS_REPLAN_SCHEMA_VERSION,
- agent_id=None,
- include_agent_id=True,
- stall_threshold=1,
- trigger_count=1,
- triggers=[],
- guidance_actions=[],
- todo_actions=[],
- stop_condition="stop at owner-only decisions",
- recommended_action="run a bounded replan",
- )
- assert "agent_id" in unscoped_payload, unscoped_payload
- assert unscoped_payload["agent_id"] is None, unscoped_payload
-
-
-def assert_peer_latest_run_does_not_hide_agent_stall() -> None:
- agent_id = "codex-quality-qualification"
- peer_id = "codex-main-control"
- target = {
- "schema_version": "quota_monitor_target_v0",
- "target_id": "blocked-successor",
- "monitor_mode": "blocked_successor_wait_without_material_transition",
- "effective_action": "monitor_quiet_skip",
- "agent_id": agent_id,
- "frontier_identity": "stable-frontier",
- }
- latest_runs = [
- {
- "classification": "peer_delivery",
- "generated_at": "2026-07-21T00:03:00+00:00",
- "agent_id": peer_id,
- "delivery_outcome": "outcome_progress",
- },
- {
- "classification": "quota_monitor_poll",
- "generated_at": "2026-07-21T00:02:00+00:00",
- "agent_id": agent_id,
- "health_check": "blocked successor wait unchanged; bounded replan after two polls",
- "monitor_target": target,
- },
- {
- "classification": "quota_monitor_poll",
- "generated_at": "2026-07-21T00:01:00+00:00",
- "agent_id": agent_id,
- "health_check": "blocked successor wait unchanged; bounded replan after two polls",
- "monitor_target": target,
- },
- ]
-
- obligation = autonomous_replan_obligation_from_runs(
- latest_runs,
- agent_todos=None,
- agent_id=agent_id,
- )
- assert obligation is not None, obligation
- assert obligation["agent_id"] == agent_id, obligation
- assert obligation["frontier_identity"] == "stable-frontier", obligation
-
- item = {
- "agent_todos": AGENT_TODOS,
- "project_asset": {},
- }
- attach_active_state_project_asset_fields(
- item,
- latest_runs=latest_runs,
- autonomous_replan_obligation_from_runs=autonomous_replan_obligation_from_runs,
- )
- selected = select_autonomous_replan_obligation(
- item,
- item["project_asset"],
- agent_id=agent_id,
- )
- assert selected == obligation, (selected, obligation)
- assert select_autonomous_replan_obligation(
- item,
- item["project_asset"],
- agent_id=peer_id,
- ) is None
-
-
-def assert_future_due_replacement_monitor_defers_stall_replan() -> None:
- agent_id = "codex-main-control"
- monitor_id = "todo_replacement_monitor"
- target = {
- "schema_version": "quota_monitor_target_v0",
- "target_id": "blocked-successor",
- "monitor_mode": "blocked_successor_wait_without_material_transition",
- "effective_action": "monitor_quiet_skip",
- "agent_id": agent_id,
- "frontier_identity": "stable-frontier",
- }
- latest_runs = [
- {
- "classification": "quota_monitor_poll",
- "generated_at": generated_at,
- "agent_id": agent_id,
- "health_check": "blocked successor wait unchanged; bounded replan after two polls",
- "monitor_target": target,
- }
- for generated_at in (
- "2026-07-23T01:45:00+00:00",
- "2026-07-23T01:42:00+00:00",
- )
- ]
- future_monitor = {
- "todo_id": monitor_id,
- "status": "open",
- "task_class": "continuous_monitor",
- "claimed_by": agent_id,
- "next_due_at": "2026-07-23T02:00:00+00:00",
- "expires_at": "2026-07-23T03:00:00+00:00",
- }
-
- def obligation_for(
- *,
- target_todo_id: str,
- successor_todo_ids: list[str] | None = None,
- monitor: dict[str, object] | None = None,
- ) -> dict[str, object] | None:
- deferred = {
- "todo_id": "todo_deferred_advancement",
- "text": "[P0] Resume advancement after the bounded monitor.",
- "status": "deferred",
- "task_class": "advancement_task",
- "claimed_by": agent_id,
- "resume_when": f"todo_done:{target_todo_id}",
- "resume_ready": False,
- "resume_condition": {
- "target_todo_id": target_todo_id,
- "target_status": "open",
- "target_task_class": "continuous_monitor",
- "satisfied": False,
- },
- }
- if successor_todo_ids:
- deferred["successor_todo_ids"] = successor_todo_ids
- return autonomous_replan_obligation_from_runs(
- latest_runs,
- agent_todos={
- "monitor_open_items": [monitor or future_monitor],
- "deferred_items": [deferred],
- },
- agent_id=agent_id,
- )
-
- assert obligation_for(target_todo_id=monitor_id) is None
- assert obligation_for(
- target_todo_id="todo_previous_monitor",
- successor_todo_ids=[monitor_id],
- ) is None
-
- overdue_monitor = {
- **future_monitor,
- "next_due_at": "2026-07-23T01:40:00+00:00",
- }
- overdue = obligation_for(
- target_todo_id="todo_previous_monitor",
- successor_todo_ids=[monitor_id],
- monitor=overdue_monitor,
- )
- assert overdue is not None, overdue
- assert overdue["triggers"][0]["kind"] == (
- "blocked_successor_no_progress_repeat"
- ), overdue
-
-
-def main() -> int:
- assert_payload_builder_contract()
- assert_peer_latest_run_does_not_hide_agent_stall()
- assert_future_due_replacement_monitor_defers_stall_replan()
-
- regular = assert_parity(
- [
- {
- "kind": "run_history_no_progress_repeat",
- "section": "run_history",
- "text": "two stalled turns repeated",
- }
- ]
- )
- assert regular["schema_version"] == AUTONOMOUS_REPLAN_SCHEMA_VERSION, regular
- assert regular["stall_threshold"] == AUTONOMOUS_REPLAN_STALL_THRESHOLD, regular
- assert regular["todo_actions"][0]["action"] == "split", regular
- assert regular["todo_actions"][1]["action"] == "add", regular
- assert regular["agent_id"] == "codex-control-plane", regular
- assert "agent_todo_writeback_required" not in regular, regular
-
- empty_frontier = direct_build_autonomous_replan_obligation(
- [
- {
- "kind": "run_history_no_progress_repeat",
- "section": "run_history",
- "text": "two stalled turns left no runnable agent todo",
- }
- ],
- agent_todos=None,
- public_safe_compact_text=public_safe_compact_text,
- autonomous_replan_schema_version=AUTONOMOUS_REPLAN_SCHEMA_VERSION,
- autonomous_replan_stall_threshold=AUTONOMOUS_REPLAN_STALL_THRESHOLD,
- dead_monitor_repeat_threshold=DEAD_MONITOR_REPEAT_THRESHOLD,
- dead_monitor_repeat_schema_version=DEAD_MONITOR_REPEAT_SCHEMA_VERSION,
- )
- assert empty_frontier is not None, empty_frontier
- assert "agent_todo_writeback_required" not in empty_frontier, empty_frontier
- assert empty_frontier["todo_actions"][0] == {
- "action": "add",
- "role": "agent",
- "priority": "P1",
- "text": (
- "write a compact replan record naming trigger, selected next slice, "
- "validation command, and stop condition"
- ),
- }, empty_frontier
-
- conflicting_agents = assert_parity(
- [
- {"kind": "no_progress_streak", "agent_id": "codex-a"},
- {"kind": "repeated_action_loop", "agent_id": "codex-b"},
- ]
- )
- assert "agent_id" not in conflicting_agents, conflicting_agents
-
- dead_monitor = assert_parity(
- [
- {
- "kind": "dead_monitor_repeat",
- "monitor_target_id": "stable-monitor-target",
- "run_count": DEAD_MONITOR_REPEAT_THRESHOLD,
- "threshold": DEAD_MONITOR_REPEAT_THRESHOLD,
- }
- ]
- )
- assert dead_monitor["stall_threshold"] == DEAD_MONITOR_REPEAT_THRESHOLD, dead_monitor
- assert dead_monitor["dead_monitor_detector"]["monitor_target_id"] == "stable-monitor-target"
- assert dead_monitor["guidance_actions"][0] == "set_watch_expiry", dead_monitor
-
- periodic = assert_parity(
- [
- {
- "kind": "periodic_review_due",
- "section": "run_history",
- "text": "periodic review threshold reached",
- }
- ]
- )
- assert periodic["todo_actions"][-1]["action"] == "ask_decision", periodic
- assert "periodic review" in periodic["recommended_action"], periodic
-
- assert build_autonomous_replan_obligation([], agent_todos=AGENT_TODOS) is None
-
- print("autonomous-replan-obligation-readmodel-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/backlog-hygiene-readmodel-smoke.py b/examples/control_plane/backlog-hygiene-readmodel-smoke.py
deleted file mode 100644
index d765a4046b..0000000000
--- a/examples/control_plane/backlog-hygiene-readmodel-smoke.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test backlog hygiene warning read-model wrappers."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.work_items.backlog_hygiene import ( # noqa: E402
- backlog_hygiene_warning as direct_backlog_hygiene_warning,
-)
-from loopx.status import ( # noqa: E402
- BACKLOG_HYGIENE_BULLET_PATTERN,
- BACKLOG_HYGIENE_HINT_PATTERN,
- BACKLOG_HYGIENE_SECTION_HEADINGS,
- active_state_sections,
- backlog_hygiene_warning,
- public_safe_compact_text,
-)
-
-
-STATE_TEXT = """# Goal
-
-## Next Action
-
-- Continue canary-gated cleanup
-
-## Operating Lessons
-
-- keep this as a plain note
-- [P2] add a durable follow-up todo
-"""
-
-
-def direct_warning(agent_todos: dict[str, object] | None) -> dict[str, object] | None:
- return direct_backlog_hygiene_warning(
- STATE_TEXT,
- agent_todos=agent_todos,
- section_headings=BACKLOG_HYGIENE_SECTION_HEADINGS,
- section_parser=active_state_sections,
- bullet_pattern=BACKLOG_HYGIENE_BULLET_PATTERN,
- hint_pattern=BACKLOG_HYGIENE_HINT_PATTERN,
- public_safe_compact_text=public_safe_compact_text,
- )
-
-
-def main() -> int:
- empty_agent_todos = {"open_count": 0}
- wrapper = backlog_hygiene_warning(STATE_TEXT, agent_todos=empty_agent_todos)
- direct = direct_warning(empty_agent_todos)
- assert wrapper == direct, (wrapper, direct)
- assert wrapper is not None, wrapper
- assert wrapper["kind"] == "hidden_backlog_without_agent_todo", wrapper
- assert wrapper["requires_agent_todo"] is True, wrapper
- assert wrapper["source_sections"] == ["Next Action", "Operating Lessons"], wrapper
- assert wrapper["evidence_count"] == 2, wrapper
-
- assert backlog_hygiene_warning(STATE_TEXT, agent_todos={"open_count": 1}) is None
- assert direct_warning({"open_count": 1}) is None
-
- no_backlog = "## Operating Lessons\n\n- just a calm observation\n"
- assert backlog_hygiene_warning(no_backlog, agent_todos={"open_count": 0}) is None
-
- print("backlog-hygiene-readmodel-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/completion-validation-accountability-smoke.py b/examples/control_plane/completion-validation-accountability-smoke.py
deleted file mode 100755
index 8b6e926fcb..0000000000
--- a/examples/control_plane/completion-validation-accountability-smoke.py
+++ /dev/null
@@ -1,259 +0,0 @@
-#!/usr/bin/env python3
-"""Keep accountable refresh and quota spend behind Todo validation authority."""
-
-from __future__ import annotations
-
-import json
-import shlex
-import sys
-import tempfile
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.testing.canary_harness import import_fixture_authority # noqa: E402
-from loopx.control_plane.quota.slot_accounting import ( # noqa: E402
- build_quota_slot_preview_for_decision,
-)
-from loopx.control_plane.todos.active_state_todo_parser import ( # noqa: E402
- parse_active_state_todos,
-)
-from loopx.state_refresh import refresh_state_run # noqa: E402
-from loopx.todos import add_goal_todo, complete_goal_todo # noqa: E402
-
-GOAL_ID = "completion-validation-accountability"
-AGENT_ID = "codex-author"
-
-
-def write_fixture(root: Path) -> tuple[Path, Path, Path]:
- project = root / "project"
- project.mkdir()
- state = project / "ACTIVE_GOAL_STATE.md"
- state.write_text(
- "\n".join(
- [
- "---",
- f"goal_id: {GOAL_ID}",
- "status: active",
- "updated_at: 2026-08-15T00:00:00+00:00",
- "---",
- "",
- "## Agent Todo",
- "",
- ]
- )
- + "\n",
- encoding="utf-8",
- )
- runtime = root / "runtime"
- registry = root / "registry.global.json"
- registry.write_text(
- json.dumps(
- {
- "schema_version": "0.1",
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "domain": "benchmark_runner",
- "status": "active",
- "repo": str(project),
- "state_file": state.name,
- "adapter": {"kind": "accountability_smoke_v0"},
- "coordination": {
- "agent_model": "peer_v1",
- "registered_agents": [AGENT_ID],
- },
- }
- ],
- }
- ),
- encoding="utf-8",
- )
- import_fixture_authority(registry, GOAL_ID)
- return registry, runtime, state
-
-
-def agent_summary(state: Path) -> dict:
- return parse_active_state_todos(
- state.read_text(encoding="utf-8"),
- item_limit=None,
- )["agent_todos"]
-
-
-def quota_preview(
- *,
- runtime: Path,
- summary: dict,
- todo_id: str,
-) -> dict:
- selected = next(item for item in summary["items"] if item["todo_id"] == todo_id)
- before = {
- "ok": True,
- "goal_id": GOAL_ID,
- "should_run": True,
- "state": "eligible",
- "effective_action": "normal_run",
- "normal_delivery_allowed": True,
- "selected_todo": selected,
- "workspace_repair_allowed": False,
- "safe_bypass_allowed": False,
- "recovery_delivery_allowed": False,
- "self_repair_allowed": False,
- "capability_repair_allowed": False,
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- "slot_minutes": 1,
- "allowed_slots": 10,
- "spent_slots": 0,
- },
- }
- after = {**before, "quota": {**before["quota"], "spent_slots": 1}}
- return build_quota_slot_preview_for_decision(
- {
- "runtime_root": str(runtime),
- "attention_queue": {
- "items": [{"goal_id": GOAL_ID, "agent_todos": summary}]
- },
- },
- goal_id=GOAL_ID,
- before=before,
- after_decision=lambda _status: after,
- quota_status_builder=lambda goal, **_kwargs: goal["quota"],
- self_repair_spend_actions=frozenset(),
- agent_id=AGENT_ID,
- todo_id=todo_id,
- )
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(
- prefix="loopx-completion-validation-accountability-"
- ) as tmp:
- root = Path(tmp)
- registry, runtime, state = write_fixture(root)
- independent_result = root / "controller-result.complete"
- validation_command = (
- f"{shlex.quote(sys.executable)} -c "
- + shlex.quote(
- "from pathlib import Path; import sys; "
- f"sys.exit(0 if Path({str(independent_result)!r}).is_file() else 1)"
- )
- )
- added = add_goal_todo(
- registry_path=registry,
- goal_id=GOAL_ID,
- role="agent",
- text="Close out one independently verified benchmark result.",
- task_class="advancement_task",
- action_kind="benchmark_result_closeout",
- claimed_by=AGENT_ID,
- validation_command=validation_command,
- validation_label="independent runner result complete",
- )
- todo_id = str(added["todo_id"])
-
- open_summary = agent_summary(state)
- projected = next(
- item for item in open_summary["items"] if item["todo_id"] == todo_id
- )
- assert projected["completion_validation_required"] is True, projected
- serialized_projection = json.dumps(open_summary)
- assert str(independent_result) not in serialized_projection
- assert "validation_command" not in serialized_projection
- assert "validation_label" not in serialized_projection
-
- try:
- refresh_state_run(
- registry_path=registry,
- runtime_root_override=str(runtime),
- goal_id=GOAL_ID,
- project=None,
- state_file=None,
- classification="provisional_benchmark_reward",
- recommended_action="wait for the independent runner result",
- delivery_batch_scale="implementation",
- delivery_outcome="outcome_progress",
- agent_id=AGENT_ID,
- progress_scope="agent_lane",
- dry_run=False,
- sync_global=False,
- )
- except ValueError as exc:
- assert "completion validation" in str(exc), exc
- else:
- raise AssertionError("provisional reward became accountable")
- assert not (runtime / "goals" / GOAL_ID / "runs" / "index.jsonl").exists()
-
- blocked_spend = quota_preview(
- runtime=runtime,
- summary=open_summary,
- todo_id=todo_id,
- )
- assert blocked_spend["ok"] is False, blocked_spend
- assert "completion validation" in blocked_spend["reason"], blocked_spend
-
- blocked_completion = complete_goal_todo(
- registry_path=registry,
- goal_id=GOAL_ID,
- todo_id=todo_id,
- agent_id=AGENT_ID,
- evidence="provisional agent-side verifier result",
- )
- assert blocked_completion["validation_blocked_completion"] is True
-
- independent_result.write_text("complete\n", encoding="utf-8")
- completed = complete_goal_todo(
- registry_path=registry,
- goal_id=GOAL_ID,
- todo_id=todo_id,
- agent_id=AGENT_ID,
- evidence="independent runner result complete",
- no_followup=True,
- )
- assert completed["ok"] is True, completed
- assert completed["changed"] is True, completed
-
- done_summary = agent_summary(state)
- durable = next(
- item for item in done_summary["items"] if item["todo_id"] == todo_id
- )
- assert durable["status"] == "done", durable
- assert durable["completion_validation_required"] is True, durable
-
- refreshed = refresh_state_run(
- registry_path=registry,
- runtime_root_override=str(runtime),
- goal_id=GOAL_ID,
- project=None,
- state_file=None,
- classification="independent_benchmark_reward_validated",
- recommended_action="inspect the next bounded benchmark action",
- delivery_batch_scale="implementation",
- delivery_outcome="outcome_progress",
- agent_id=AGENT_ID,
- progress_scope="agent_lane",
- agent_vision_packet={
- "state": "active",
- "vision_summary": "Independent runner result is authoritative.",
- },
- dry_run=False,
- sync_global=False,
- )
- assert refreshed["appended"] is True, refreshed
-
- allowed_spend = quota_preview(
- runtime=runtime,
- summary=done_summary,
- todo_id=todo_id,
- )
- assert allowed_spend["ok"] is True, allowed_spend
-
- print("completion-validation-accountability-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/decision-freshness-readmodel-smoke.py b/examples/control_plane/decision-freshness-readmodel-smoke.py
deleted file mode 100644
index 7fae650ef6..0000000000
--- a/examples/control_plane/decision-freshness-readmodel-smoke.py
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test decision freshness read-model parity."""
-
-from __future__ import annotations
-
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-import sys
-import tempfile
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.status import runtime_summaries as status_runtime_summaries # noqa: E402
-from loopx.control_plane.runtime import decision_freshness as decision_read_model # noqa: E402
-from loopx.control_plane.runtime import event_ledger as event_ledger_read_model # noqa: E402
-
-
-RUNTIME_CONTEXT = status_module.build_status_runtime_summary_context()
-
-
-def direct_decision_kinds(run: dict[str, Any]) -> list[str]:
- return status_runtime_summaries.decision_event_kinds(
- run,
- context=RUNTIME_CONTEXT,
- )
-
-
-def direct_event_class(run: dict[str, Any]) -> str:
- return status_runtime_summaries.event_ledger_event_class(
- run,
- context=RUNTIME_CONTEXT,
- )
-
-
-def direct_summary(history: dict[str, Any]) -> dict[str, Any]:
- return decision_read_model.build_decision_freshness_summary(
- history,
- parse_timestamp=status_module.parse_timestamp,
- decision_event_kinds=direct_decision_kinds,
- event_class_for_run=direct_event_class,
- blank_event_class_counts=event_ledger_read_model.blank_event_class_counts,
- window_days=status_module.DECISION_FRESHNESS_WINDOW_DAYS,
- item_limit=status_module.DECISION_FRESHNESS_ITEM_LIMIT,
- proxy_note=status_module.DECISION_FRESHNESS_PROXY_NOTE,
- )
-
-
-def normalize_generated_at(payload: dict[str, Any], reference: dict[str, Any]) -> dict[str, Any]:
- normalized = dict(payload)
- normalized["generated_at"] = reference["generated_at"]
- return normalized
-
-
-def main() -> None:
- now = datetime.now(timezone.utc)
- runs = [
- {
- "goal_id": "project-a",
- "generated_at": (now - timedelta(minutes=40)).isoformat(),
- "classification": "operator_gate_approved",
- "operator_gate": {"decision": "approved"},
- },
- {
- "goal_id": "project-a",
- "generated_at": (now - timedelta(minutes=20)).isoformat(),
- "classification": "state_refreshed",
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(days=8)).isoformat(),
- "classification": "human_reward_recorded",
- "human_reward": {"decision": "continue"},
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(hours=3)).isoformat(),
- "classification": "implementation_batch",
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(hours=2)).isoformat(),
- "classification": "read_only_project_map",
- "project_map": {"count": 2},
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(hours=1)).isoformat(),
- "classification": "quota_slot_spent",
- "quota_event": {"event_type": "quota_slot_spent", "slots": 1},
- },
- {
- "goal_id": "project-c",
- "generated_at": (now - timedelta(days=1)).isoformat(),
- "classification": "reward_overlay_acknowledged",
- },
- {
- "goal_id": "project-d",
- "generated_at": "not-a-timestamp",
- "classification": "operator_gate_approved",
- "operator_gate": {"decision": "approved"},
- },
- ]
- history = {"runs": runs}
-
- assert direct_decision_kinds(runs[0]) == ["operator_gate"]
- assert direct_decision_kinds(runs[2]) == ["human_reward"]
- assert direct_decision_kinds(runs[6]) == [
- "decision_classification"
- ]
- assert decision_read_model.decision_freshness_reason(
- stale_by_age=True,
- newer_event_count=1,
- ) == "decision older than freshness window and newer sampled events exist; rebase at decision point"
-
- with tempfile.TemporaryDirectory(prefix="loopx-decision-freshness-summary-") as raw_tmp:
- wrapper = status_module.build_status_runtime_summaries(
- history=history,
- queue={"items": []},
- runtime_root=Path(raw_tmp),
- goal_id_filter=None,
- display_limit=10,
- todo_index_limit=10,
- )["decision_freshness_summary"]
- direct = direct_summary(history)
- assert normalize_generated_at(direct, wrapper) == wrapper, (direct, wrapper)
-
- summary = wrapper["summary"]
- assert wrapper["available"] is True, wrapper
- assert wrapper["source"] == "run_history", wrapper
- assert wrapper["sample_run_count"] == len(runs), wrapper
- assert wrapper["window_days"] == 7, wrapper
- assert summary == {
- "decision_count": 3,
- "stale_count": 1,
- "rebase_required_count": 2,
- "fresh_count": 1,
- }, summary
-
- items = {
- (item["goal_id"], item["decision_kind"]): item
- for item in wrapper["items"]
- }
- project_a = items[("project-a", "operator_gate")]
- assert project_a["freshness_state"] == "rebase_required", project_a
- assert project_a["newer_event_count_7d"] == 1, project_a
- assert project_a["newer_event_classes_7d"]["state"] == 1, project_a
- assert project_a["stale_by_age"] is False, project_a
-
- project_b = items[("project-b", "human_reward")]
- assert project_b["freshness_state"] == "stale_rebase_required", project_b
- assert project_b["stale_by_age"] is True, project_b
- assert project_b["newer_event_count_7d"] == 3, project_b
- assert project_b["newer_event_classes_7d"]["accounting"] == 1, project_b
- assert project_b["newer_event_classes_7d"]["evidence"] == 1, project_b
- assert project_b["newer_event_classes_7d"]["work"] == 1, project_b
-
- project_c = items[("project-c", "decision_classification")]
- assert project_c["freshness_state"] == "fresh", project_c
- assert project_c["requires_decision_point_rebase"] is False, project_c
-
- assert ("project-d", "operator_gate") not in items, items
- print("decision-freshness-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/delivery-signals-readmodel-smoke.py b/examples/control_plane/delivery-signals-readmodel-smoke.py
deleted file mode 100644
index 63a7dc05b0..0000000000
--- a/examples/control_plane/delivery-signals-readmodel-smoke.py
+++ /dev/null
@@ -1,32 +0,0 @@
-#!/usr/bin/env python3
-"""The public status batch preserves typed streaks and unknown boundaries."""
-from pathlib import Path
-import sys
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT))
-
-from loopx.status import project_post_handoff_history # noqa: E402
-
-
-def main() -> None:
- profile = {"outcome_floor": {"outcome_markers": ["validated"]}}
- runs = [
- {"delivery_outcome": "surface_only", "delivery_batch_scale": "single_segment"},
- {"classification": "contract validated implementation"},
- {"delivery_outcome": "outcome_gap", "delivery_batch_scale": "test_only"},
- ]
- result = project_post_handoff_history(runs, profile)
- assert result["post_handoff_small_scale_streak"] == 1
- assert result["post_handoff_outcome_gap_streak"] == 1
- assert result["post_handoff_latest_run"]["delivery_batch_scale"] == "single_surface"
- assert result["post_handoff_recent_runs"][1]["delivery_outcome"] == "unknown"
- no_floor = project_post_handoff_history([{}])
- assert "post_handoff_outcome_gap_streak" not in no_floor
- assert "delivery_outcome" not in no_floor["post_handoff_latest_run"]
- assert no_floor["post_handoff_latest_run"]["delivery_turn_kind"] == "unknown"
- print("delivery-signals-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/event-ledger-readmodel-smoke.py b/examples/control_plane/event-ledger-readmodel-smoke.py
deleted file mode 100644
index 4d2a93756f..0000000000
--- a/examples/control_plane/event-ledger-readmodel-smoke.py
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test event ledger read-model parity outside benchmark fixtures."""
-
-from __future__ import annotations
-
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-import sys
-import tempfile
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.status import runtime_summaries as status_runtime_summaries # noqa: E402
-from loopx.control_plane.runtime import event_ledger as event_ledger_read_model # noqa: E402
-
-
-RUNTIME_CONTEXT = status_module.build_status_runtime_summary_context()
-
-
-def direct_event_class(run: dict[str, Any]) -> str:
- return status_runtime_summaries.event_ledger_event_class(
- run,
- context=RUNTIME_CONTEXT,
- )
-
-
-def direct_summary(history: dict[str, Any]) -> dict[str, Any]:
- return event_ledger_read_model.build_event_ledger_summary(
- history,
- parse_timestamp=status_module.parse_timestamp,
- event_class_for_run=direct_event_class,
- )
-
-
-def normalize_generated_at(payload: dict[str, Any], reference: dict[str, Any]) -> dict[str, Any]:
- normalized = dict(payload)
- normalized["generated_at"] = reference["generated_at"]
- return normalized
-
-
-def main() -> None:
- now = datetime.now(timezone.utc)
- runs = [
- {
- "goal_id": "project-a",
- "generated_at": (now - timedelta(minutes=10)).isoformat(),
- "classification": "quota_slot_spent",
- "quota_event": {"event_type": "quota_slot_spent", "source": "heartbeat", "slots": 1},
- },
- {
- "goal_id": "project-a",
- "generated_at": (now - timedelta(minutes=20)).isoformat(),
- "classification": "operator_gate_approved",
- "operator_gate": {"decision": "approved"},
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(hours=2)).isoformat(),
- "classification": "read_only_project_map",
- "project_map": {"count": 2},
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(hours=3)).isoformat(),
- "classification": "state_refreshed",
- },
- {
- "goal_id": "project-b",
- "generated_at": (now - timedelta(hours=4)).isoformat(),
- "classification": "implementation_batch",
- },
- {
- "goal_id": "project-a",
- "generated_at": (now - timedelta(days=2)).isoformat(),
- "classification": "cache_check",
- "cache_check": {"status": "hit"},
- },
- {
- "goal_id": "project-c",
- "generated_at": (now - timedelta(days=8)).isoformat(),
- "classification": "old_work",
- },
- {
- "goal_id": "project-c",
- "generated_at": "not-a-timestamp",
- "classification": "ignored_bad_time",
- },
- ]
- history = {"runs": runs}
-
- for run in runs:
- assert direct_event_class(run) in {
- "accounting",
- "decision",
- "evidence",
- "state",
- "work",
- }, run
-
- with tempfile.TemporaryDirectory(prefix="loopx-event-ledger-summary-") as raw_tmp:
- wrapper = status_module.build_status_runtime_summaries(
- history=history,
- queue={"items": []},
- runtime_root=Path(raw_tmp),
- goal_id_filter=None,
- display_limit=10,
- todo_index_limit=10,
- )["event_ledger_summary"]
- direct = direct_summary(history)
- assert normalize_generated_at(direct, wrapper) == wrapper, (direct, wrapper)
-
- assert event_ledger_read_model.blank_event_class_counts() == {
- "accounting": 0,
- "decision": 0,
- "evidence": 0,
- "state": 0,
- "work": 0,
- }
- assert event_ledger_read_model.blank_event_ledger_goal("project-z")["goal_id"] == "project-z"
-
- totals = wrapper["totals"]
- assert wrapper["available"] is True, wrapper
- assert wrapper["source"] == "run_history", wrapper
- assert wrapper["sample_run_count"] == len(runs), wrapper
- assert wrapper["event_classes"] == ["accounting", "decision", "evidence", "state", "work"], wrapper
- assert totals["events_24h"] == 5, totals
- assert totals["events_7d"] == 6, totals
- assert totals["by_class_24h"] == {
- "accounting": 1,
- "decision": 1,
- "evidence": 1,
- "state": 1,
- "work": 1,
- }, totals
- assert totals["by_class_7d"] == {
- "accounting": 1,
- "decision": 1,
- "evidence": 2,
- "state": 1,
- "work": 1,
- }, totals
-
- goals = {goal["goal_id"]: goal for goal in wrapper["goals"]}
- assert goals["project-a"]["events_24h"] == 2, goals
- assert goals["project-a"]["events_7d"] == 3, goals
- assert goals["project-a"]["latest_event_class"] == "accounting", goals
- assert goals["project-b"]["by_class_24h"] == {
- "accounting": 0,
- "decision": 0,
- "evidence": 1,
- "state": 1,
- "work": 1,
- }, goals
- assert goals["project-c"]["events_7d"] == 0, goals
-
- print("event-ledger-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/external-evidence-observation-smoke.py b/examples/control_plane/external-evidence-observation-smoke.py
deleted file mode 100644
index 1fd4203f8e..0000000000
--- a/examples/control_plane/external-evidence-observation-smoke.py
+++ /dev/null
@@ -1,558 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test external-evidence monitor observation as a scheduler seam."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-from typing import Any
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx.control_plane.scheduler.external_evidence_observation import ( # noqa: E402
- build_external_evidence_observation_obligation,
- build_external_evidence_poll_signal,
- projected_monitor_handle,
-)
-from loopx.control_plane.scheduler.execution_context import ( # noqa: E402
- GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT,
-)
-from loopx.control_plane.testing.quota_fixtures import ( # noqa: E402
- quota_status_payload,
- quota_todo_item,
- quota_todo_summary,
-)
-from loopx.control_plane.todos.contract import ( # noqa: E402
- TODO_TASK_CLASS_ADVANCEMENT,
- TODO_TASK_CLASS_MONITOR,
-)
-from loopx.control_plane.todos.projection import ( # noqa: E402
- todo_summary_open_task_counts,
-)
-from loopx.quota import build_quota_should_run # noqa: E402
-
-
-def quota_guard(status_payload: dict[str, Any]) -> dict[str, Any]:
- return build_quota_should_run(
- status_payload,
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- scheduler_execution_context=GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT,
- )
-
-
-GOAL_ID = "external-evidence-observation-fixture"
-AGENT_ID = "codex-product-capability"
-PAST_DUE_AT = "2000-01-01T00:00:00+00:00"
-FUTURE_DUE_AT = "2999-01-01T00:00:00+00:00"
-
-
-def todo(
- index: int,
- text: str,
- *,
- task_class: str,
- todo_id: str,
- **metadata: Any,
-) -> dict[str, Any]:
- return quota_todo_item(
- todo_id=todo_id,
- role="agent",
- status="open",
- index=index,
- text=text,
- task_class=task_class,
- **metadata,
- )
-
-
-def agent_todos(items: list[dict[str, Any]]) -> dict[str, Any]:
- return quota_todo_summary(
- items,
- role="agent",
- claim_scope_agent_id=AGENT_ID,
- )
-
-
-def monitor_todo(
- *,
- todo_id: str = "todo_monitor_result",
- priority: str = "P1",
- next_due_at: str = PAST_DUE_AT,
-) -> dict[str, Any]:
- return todo(
- 1,
- f"[{priority}] Monitor compact result marker and write back only if it changed.",
- task_class=TODO_TASK_CLASS_MONITOR,
- todo_id=todo_id,
- target_key="job:compact-result",
- next_due_at=next_due_at,
- claimed_by=AGENT_ID,
- )
-
-
-def pr_dependency_monitor_todo(
- *,
- result_hash: str | None = None,
- last_checked_at: str | None = None,
-) -> dict[str, Any]:
- metadata: dict[str, Any] = {
- "target_key": "pr_merged:#532",
- "next_due_at": FUTURE_DUE_AT,
- "claimed_by": AGENT_ID,
- }
- if result_hash:
- metadata["result_hash"] = result_hash
- if last_checked_at:
- metadata["last_checked_at"] = last_checked_at
- return todo(
- 3,
- "[P0] Monitor PR #532 review/merge state before resuming the rerun lane.",
- task_class=TODO_TASK_CLASS_MONITOR,
- todo_id="todo_pr_dependency_monitor",
- **metadata,
- )
-
-
-def schedule_gap_monitor_todo(*, index: int = 2, priority: str = "P2") -> dict[str, Any]:
- return todo(
- index,
- f"[{priority}] Monitor the ledger after the next batch completes.",
- task_class=TODO_TASK_CLASS_MONITOR,
- todo_id="todo_monitor_schedule_gap",
- target_key="ledger:next-batch",
- claimed_by=AGENT_ID,
- )
-
-
-def advancement_todo() -> dict[str, Any]:
- return todo(
- 2,
- "[P0] Advance the canary/refactor slice with a validated patch.",
- task_class=TODO_TASK_CLASS_ADVANCEMENT,
- todo_id="todo_advancement_now",
- claimed_by=AGENT_ID,
- )
-
-
-def unavailable_advancement_todo() -> dict[str, Any]:
- item = advancement_todo()
- item["required_capabilities"] = ["private_read"]
- return item
-
-
-def status_payload(
- summary: dict[str, Any],
- *,
- status: str = "launched_polling_result",
- waiting_on: str = "codex",
- next_action: str = "Observe compact result marker for remote job handle.",
- latest_runs: list[dict[str, Any]] | None = None,
- lifecycle_flags: list[str] | None = None,
-) -> dict[str, Any]:
- return quota_status_payload(
- goal_id=GOAL_ID,
- status=status,
- waiting_on=waiting_on,
- recommended_action=next_action,
- next_action=next_action,
- agent_todos=summary,
- quota_extra={"allowed_slots": 1440},
- coordination={
- "agent_model": "peer_v1",
- "registered_agents": ["codex-main-control", AGENT_ID],
- },
- latest_runs=latest_runs or [],
- item_extra={
- "lifecycle_flags": lifecycle_flags
- if lifecycle_flags is not None
- else ["launched polling result marker"]
- },
- )
-
-
-def selected_item(payload: dict[str, Any]) -> dict[str, Any]:
- return payload["attention_queue"]["items"][0]
-
-
-def assert_monitor_only_launched_poll_requires_observation() -> None:
- summary = agent_todos([monitor_todo()])
- item = selected_item(status_payload(summary))
-
- handle = projected_monitor_handle(summary)
- assert handle and handle["todo_id"] == "todo_monitor_result", handle
- assert handle["target_key"] == "job:compact-result", handle
-
- signal = build_external_evidence_poll_signal(item, agent_todo_summary=summary)
- assert signal and signal["matched_signal"] == "launched_wait", signal
- assert signal["monitor_handle"]["todo_id"] == "todo_monitor_result", signal
-
- obligation = build_external_evidence_observation_obligation(
- item,
- state="active",
- agent_todo_summary=summary,
- work_lane_contract={"lane": "continuous_monitor"},
- )
- assert obligation and obligation["kind"] == "launched_external_work_monitor", obligation
- assert obligation["monitor_handle"]["target_key"] == "job:compact-result", obligation
-
- guard = quota_guard(status_payload(summary))
- lane = guard["work_lane_contract"]
- assert lane["lane"] == "continuous_monitor", guard
- assert lane["monitor_kind"] == "external_evidence", guard
- assert guard["effective_action"] == "external_evidence_observe", guard
- assert guard["execution_obligation"]["kind"] == "external_evidence_observation_required", guard
- assert lane["must_attempt_work"] is True, guard
- assert lane["monitor_policy"] in {
- "material_transition_only",
- "read_only_observation_then_no_spend_if_unchanged",
- "write_once_per_material_transition_else_no_spend",
- }, guard
-
-
-def assert_recent_unchanged_observation_defers_to_capability_repair() -> None:
- summary = agent_todos(
- [
- monitor_todo(next_due_at=FUTURE_DUE_AT),
- unavailable_advancement_todo(),
- ]
- )
- guard = quota_guard(
- status_payload(
- summary,
- latest_runs=[
- {
- "classification": "quota_slot_spent",
- "agent_id": AGENT_ID,
- "recommended_action": "wait quietly for material monitor evidence",
- },
- {
- "classification": "quota_monitor_poll",
- "agent_id": AGENT_ID,
- "delivery_outcome": "surface_only",
- "health_check": "external monitor observation unchanged; no quota spend; no material transition",
- },
- ],
- )
- )
- assert guard["decision"] == "repair_bridge", guard
- assert guard["should_run"] is True, guard
- assert guard["effective_action"] == "capability_bridge_repair", guard
- interaction = guard["interaction_contract"]
- assert interaction["mode"] == "capability_bridge_repair", interaction
- assert interaction["agent_channel"]["must_attempt"] is True, interaction
- assert interaction["agent_channel"]["delivery_allowed"] is False, interaction
- assert interaction["agent_channel"]["quiet_noop_allowed"] is False, interaction
-
-
-def assert_recent_due_monitor_no_change_defers_to_capability_repair() -> None:
- summary = agent_todos(
- [
- monitor_todo(next_due_at=FUTURE_DUE_AT),
- unavailable_advancement_todo(),
- ]
- )
- guard = quota_guard(
- status_payload(
- summary,
- latest_runs=[
- {
- "classification": "quota_slot_spent",
- "agent_id": AGENT_ID,
- "recommended_action": "wait quietly for material monitor evidence",
- },
- {
- "classification": "external_monitor_observation_cooldown_repaired",
- "agent_id": AGENT_ID,
- "delivery_outcome": "outcome_progress",
- "recommended_action": "wait quietly for material monitor evidence",
- },
- {
- "classification": "quota_monitor_poll",
- "agent_id": AGENT_ID,
- "delivery_outcome": "surface_only",
- "health_check": "due monitor observation unchanged; no quota spend; next due updated",
- "monitor_event": {
- "monitor_mode": "due_monitor_observed_without_material_transition",
- "material_change": False,
- },
- },
- ],
- )
- )
- assert guard["decision"] == "repair_bridge", guard
- assert guard["should_run"] is True, guard
- assert guard["effective_action"] == "capability_bridge_repair", guard
- interaction = guard["interaction_contract"]
- assert interaction["mode"] == "capability_bridge_repair", interaction
- assert interaction["agent_channel"]["must_attempt"] is True, interaction
- assert interaction["agent_channel"]["delivery_allowed"] is False, interaction
- assert interaction["agent_channel"]["quiet_noop_allowed"] is False, interaction
-
-
-def assert_advancement_lane_keeps_external_monitor_as_context() -> None:
- summary = agent_todos(
- [
- monitor_todo(todo_id="todo_monitor_context", priority="P2"),
- advancement_todo(),
- ]
- )
- item = selected_item(status_payload(summary))
- assert build_external_evidence_poll_signal(item, agent_todo_summary=summary), item
-
- guard = quota_guard(status_payload(summary))
- lane = guard["work_lane_contract"]
- assert lane["lane"] == "advancement_task", guard
- assert lane["obligation"] == "advance_one_bounded_segment", guard
- assert "external_monitor_context" in lane["reason_codes"], guard
- assert "external_evidence_observation" not in guard, guard
- assert guard["execution_obligation"]["kind"] == "work_lane_contract", guard
- assert guard["agent_lane_next_action"]["todo_id"] == "todo_advancement_now", guard
-
-
-def assert_future_scoped_monitor_does_not_fake_external_poll() -> None:
- summary = agent_todos(
- [
- monitor_todo(
- todo_id="todo_monitor_future",
- priority="P1",
- next_due_at=FUTURE_DUE_AT,
- )
- ]
- )
- item = selected_item(status_payload(summary))
- counts = todo_summary_open_task_counts(summary)
- assert counts["monitor"] == 1 and counts["advancement"] == 0, counts
- assert build_external_evidence_poll_signal(item, agent_todo_summary=summary) is None
-
- obligation = build_external_evidence_observation_obligation(
- item,
- state="active",
- agent_todo_summary=summary,
- work_lane_contract={"lane": "continuous_monitor"},
- )
- assert obligation is None, obligation
-
- guard = quota_guard(status_payload(summary))
- lane = guard["work_lane_contract"]
- assert lane["obligation"] == "quiet_until_material_monitor_transition", guard
- assert lane["must_attempt_work"] is False, guard
- assert "external_evidence_observation" not in guard, guard
-
-
-def assert_unavailable_advancement_defers_to_capability_repair() -> None:
- summary = agent_todos(
- [
- monitor_todo(
- todo_id="todo_monitor_future",
- priority="P1",
- next_due_at=FUTURE_DUE_AT,
- ),
- unavailable_advancement_todo(),
- ]
- )
- item = selected_item(status_payload(summary))
- counts = todo_summary_open_task_counts(summary)
- assert counts["monitor"] == 1 and counts["advancement"] == 1, counts
- assert build_external_evidence_poll_signal(item, agent_todo_summary=summary), item
-
- guard = quota_guard(status_payload(summary))
- assert "external_evidence_observation" not in guard, guard
- interaction = guard["interaction_contract"]
- assert interaction["mode"] == "capability_bridge_repair", interaction
- assert interaction["agent_channel"]["must_attempt"] is True, interaction
- assert interaction["agent_channel"]["delivery_allowed"] is False, interaction
- assert interaction["agent_channel"]["quiet_noop_allowed"] is False, interaction
-
-
-def assert_selected_monitor_handle(
- items: list[dict[str, Any]],
- *,
- expected_todo_id: str,
- expected_target_key: str,
- expected_text: str,
- expected_signal: str | None = None,
- expected_channel: str | None = None,
- **status_options: Any,
-) -> None:
- summary = agent_todos(items)
- payload = status_payload(summary, **status_options)
- signal = build_external_evidence_poll_signal(
- selected_item(payload),
- agent_todo_summary=summary,
- )
- handle = projected_monitor_handle(summary)
- assert handle and handle["todo_id"] == expected_todo_id, handle
- assert handle["target_key"] == expected_target_key, handle
- assert signal and signal["monitor_handle"]["todo_id"] == expected_todo_id, signal
- if expected_signal:
- assert signal["matched_signal"] == expected_signal, signal
- if expected_channel:
- assert signal["matched_channel"] == expected_channel, signal
- guard = quota_guard(payload)
- observation = guard["external_evidence_observation"]
- assert observation["monitor_handle"]["todo_id"] == expected_todo_id, guard
- assert expected_text in observation["observation_target"], observation
- assert expected_text in guard["interaction_contract"]["agent_channel"]["primary_action"], guard
-
-
-def assert_monitor_handle_precedence() -> None:
- future = monitor_todo(
- todo_id="todo_monitor_future",
- priority="P1",
- next_due_at=FUTURE_DUE_AT,
- )
- assert_selected_monitor_handle(
- [future, schedule_gap_monitor_todo()],
- expected_todo_id="todo_monitor_schedule_gap",
- expected_target_key="ledger:next-batch",
- expected_text="Monitor the ledger",
- )
- dependency_action = (
- "Keep PR #532 in review-required state; after maintainer review/merge, "
- "resume dependent validation lane."
- )
- dependency = pr_dependency_monitor_todo()
- assert_selected_monitor_handle(
- [dependency, schedule_gap_monitor_todo()],
- expected_todo_id="todo_pr_dependency_monitor",
- expected_target_key="pr_merged:#532",
- expected_text="Monitor PR #532",
- expected_signal="external_dependency_wait",
- expected_channel="state",
- status="active",
- next_action=dependency_action,
- lifecycle_flags=[],
- )
- assert_selected_monitor_handle(
- [
- monitor_todo(todo_id="todo_monitor_due", priority="P2"),
- dependency,
- schedule_gap_monitor_todo(index=4, priority="P3"),
- ],
- expected_todo_id="todo_monitor_due",
- expected_target_key="job:compact-result",
- expected_text="Monitor compact result",
- expected_signal="direct_observe",
- expected_channel="todo",
- status="active",
- next_action=dependency_action,
- lifecycle_flags=[],
- )
-
-
-def assert_pr_dependency_wait_requires_first_observation() -> None:
- summary = agent_todos([pr_dependency_monitor_todo()])
- next_action = (
- "Keep PR #532 in review-required state; after maintainer review/merge, "
- "resume dependent validation lane."
- )
- item = selected_item(
- status_payload(
- summary,
- status="active",
- next_action=next_action,
- latest_runs=[],
- lifecycle_flags=[],
- )
- )
- signal = build_external_evidence_poll_signal(item, agent_todo_summary=summary)
- assert signal and signal["matched_signal"] == "external_dependency_wait", signal
- assert signal["monitor_handle"]["target_key"] == "pr_merged:#532", signal
-
- guard = quota_guard(
- status_payload(
- summary,
- status="active",
- next_action=next_action,
- latest_runs=[],
- lifecycle_flags=[],
- )
- )
- assert guard["should_run"] is True, guard
- assert guard["effective_action"] == "external_evidence_observe", guard
- observation = guard["external_evidence_observation"]
- assert observation["kind"] == "launched_external_work_monitor", observation
- assert observation["monitor_handle"]["target_key"] == "pr_merged:#532", observation
- assert guard["interaction_contract"]["agent_channel"]["must_attempt"] is True, guard
-
-
-def assert_pr_dependency_wait_with_observation_does_not_reobserve_before_due() -> None:
- summary = agent_todos(
- [
- pr_dependency_monitor_todo(
- result_hash="pr_532_open_review_required",
- last_checked_at="2026-07-08T18:00:00+08:00",
- )
- ]
- )
- next_action = (
- "Keep PR #532 in review-required state; after maintainer review/merge, "
- "resume dependent validation lane."
- )
- item = selected_item(
- status_payload(
- summary,
- status="active",
- next_action=next_action,
- lifecycle_flags=[],
- )
- )
- assert build_external_evidence_poll_signal(item, agent_todo_summary=summary) is None
-
- guard = build_quota_should_run(
- status_payload(
- summary,
- status="active",
- next_action=next_action,
- lifecycle_flags=[],
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- scheduler_execution_context=GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT,
- )
- assert guard["effective_action"] == "monitor_quiet_skip", guard
- assert "external_evidence_observation" not in guard, guard
- assert guard["interaction_contract"]["agent_channel"]["must_attempt"] is False, guard
- assert guard["scheduler_hint"]["cadence_class"] == "monitor_wait", guard
-
-
-def assert_explicit_external_wait_builds_registry_obligation() -> None:
- summary = agent_todos([])
- payload = status_payload(
- summary,
- status="waiting",
- waiting_on="external_evidence",
- next_action="Wait for compact result marker before continuing.",
- )
- item = selected_item(payload)
- obligation = build_external_evidence_observation_obligation(
- item,
- state="waiting",
- agent_todo_summary=summary,
- work_lane_contract=None,
- )
- assert obligation and obligation["kind"] == "external_evidence_monitor", obligation
- assert obligation["trigger"] == "registry_waiting_on_external_evidence", obligation
- assert obligation["signal_source"] == "registry", obligation
-
-
-def main() -> int:
- assert_monitor_only_launched_poll_requires_observation()
- assert_recent_unchanged_observation_defers_to_capability_repair()
- assert_recent_due_monitor_no_change_defers_to_capability_repair()
- assert_advancement_lane_keeps_external_monitor_as_context()
- assert_future_scoped_monitor_does_not_fake_external_poll()
- assert_unavailable_advancement_defers_to_capability_repair()
- assert_monitor_handle_precedence()
- assert_pr_dependency_wait_requires_first_observation()
- assert_pr_dependency_wait_with_observation_does_not_reobserve_before_due()
- assert_explicit_external_wait_builds_registry_obligation()
- print("external-evidence-observation-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/fresh-project-onboarding-regression-smoke.py b/examples/control_plane/fresh-project-onboarding-regression-smoke.py
deleted file mode 100644
index b71fa37aed..0000000000
--- a/examples/control_plane/fresh-project-onboarding-regression-smoke.py
+++ /dev/null
@@ -1,445 +0,0 @@
-#!/usr/bin/env python3
-"""Regression fixture for #3092: fresh-project onboarding defects.
-
-Covers:
- - Defect 1: guided todo template must use ``--claimed-by`` (not ``--agent-id``)
- so the emitted command is accepted by ``loopx todo add``.
- - Defect 2: ``agent-onboard`` on a project with no ``.loopx/registry.json``
- must return a typed gate, not raise ``FileNotFoundError``.
- - Guided takeover: when the goal already has a runnable Todo frontier,
- authoring is projected as a typed Todo delta instead of an
- unconditional ``write_ordered_todos`` step. `connect` no
- longer seeds that frontier, so the fixture writes the first
- agent Todo the way a real caller now does.
-
-See: https://github.com/huangruiteng/loopx/issues/3092
-Fix: https://github.com/huangruiteng/loopx/pull/3093
-"""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.bootstrap_command_pack import build_start_goal_guided_packet # noqa: E402
-
-PASS = 0
-FAIL = 0
-
-
-def run_cli(
- *args: str,
- check: bool = True,
-) -> subprocess.CompletedProcess[str]:
- """Run a ``loopx`` CLI command via subprocess, returning JSON output."""
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", "--format", "json", *args],
- cwd=REPO_ROOT,
- check=check,
- text=True,
- capture_output=True,
- timeout=300,
- )
-
-
-def check(label: str, condition: bool) -> None:
- global PASS, FAIL
- if condition:
- PASS += 1
- print(f" PASS: {label}")
- else:
- FAIL += 1
- print(f" FAIL: {label}")
-
-
-def _register_agent_in_registry(registry_path: Path, goal_id: str, agent_id: str) -> None:
- """Add an agent to the project-local registry coordination block.
-
- This mirrors the pattern used by existing smokes (e.g.
- agent-onboard-host-loop-activation-smoke.py) which write the registry
- fixture directly rather than going through ``register-agent`` (which
- requires a global registry route).
- """
- registry = json.loads(registry_path.read_text(encoding="utf-8"))
- for goal in registry.get("goals", []):
- if goal.get("id") == goal_id:
- coordination = goal.setdefault("coordination", {})
- agents = coordination.setdefault("registered_agents", [])
- if agent_id not in agents:
- agents.append(agent_id)
- break
- registry_path.write_text(
- json.dumps(registry, indent=2, ensure_ascii=False),
- encoding="utf-8",
- )
-
-
-def _require_guided_todo_delta_template(
- guided_packet: dict[str, object],
- *,
- label: str,
-) -> str:
- """Require the typed authoring path used by fresh bootstrap fixtures."""
- transaction = guided_packet.get("guided_transaction", {})
- ordered_steps = (
- transaction.get("ordered_steps", [])
- if isinstance(transaction, dict)
- else []
- )
- steps = [step for step in ordered_steps if isinstance(step, dict)]
- legacy_steps = [
- step for step in steps if step.get("id") == "write_ordered_todos"
- ]
- delta_steps = [step for step in steps if step.get("id") == "apply_todo_delta"]
-
- check(f"{label}: legacy Todo authoring is absent", not legacy_steps)
- check(f"{label}: contains exactly one Todo delta", len(delta_steps) == 1)
- if len(delta_steps) != 1:
- return ""
-
- delta_step = delta_steps[0]
- todo_delta = delta_step.get("todo_delta", {})
- check(
- f"{label}: Todo delta uses the guided takeover schema",
- isinstance(todo_delta, dict)
- and todo_delta.get("schema_version") == "loopx_guided_todo_delta_v0",
- )
- check(
- f"{label}: Todo delta exposes a runnable frontier",
- isinstance(todo_delta, dict)
- and todo_delta.get("runnable_frontier_count", 0) >= 1
- and bool(todo_delta.get("frontier")),
- )
- template = delta_step.get("add_new_command_template", "")
- check(
- f"{label}: Todo delta exposes an add-new template",
- isinstance(template, str) and bool(template),
- )
- return template if isinstance(template, str) else ""
-
-
-# ---------------------------------------------------------------------------
-# Scenario 1: agent-onboard on a bare project with no .loopx/ directory
-# (Defect 2 regression: must return a typed gate, not FileNotFoundError)
-# ---------------------------------------------------------------------------
-def test_unconnected_agent_onboard(project: Path) -> None:
- print("\n=== Scenario 1: agent-onboard on unconnected project ===")
-
- result = run_cli(
- "agent-onboard",
- "--agent-type", "claude-code",
- "--project", str(project),
- check=False,
- )
- # The command must not crash with a traceback.
- check(
- "agent-onboard exits without traceback",
- "FileNotFoundError" not in (result.stderr + result.stdout),
- )
-
- # It should produce parseable JSON.
- try:
- payload = json.loads(result.stdout)
- except (json.JSONDecodeError, ValueError):
- payload = {}
- check("agent-onboard returns valid JSON", bool(payload))
-
- # The JSON should be a typed gate or structured packet, not a crash.
- # Before the fix (#3093): FileNotFoundError traceback.
- # After the fix: an identity_selection_gate packet with
- # activation_allowed: false (the project needs bootstrap/registration).
- identity_gate = payload.get("identity_selection_gate")
- check(
- "response is a typed gate or structured packet (not a crash)",
- payload.get("gate") == "project_not_connected"
- or payload.get("ok") is False
- or payload.get("connection_state") == "not_connected"
- or (
- isinstance(identity_gate, dict)
- and identity_gate.get("activation_allowed") is False
- ),
- )
-
-
-# ---------------------------------------------------------------------------
-# Scenario 2 & 3: guided todo template uses --claimed-by and is accepted
-# (Defect 1 regression)
-# ---------------------------------------------------------------------------
-def test_guided_template_acceptance(project: Path, goal_id: str) -> None:
- print("\n=== Scenario 2: bootstrap + guided template validation ===")
-
- # Step 1: Bootstrap the project (local-only, no global sync).
- bootstrap = run_cli(
- "bootstrap",
- "--project", str(project),
- "--goal-id", goal_id,
- "--objective", "regression test for #3092",
- "--adapter-kind", "read_only_project_map_v0",
- "--adapter-status", "connected-read-only",
- "--no-global-sync",
- check=False,
- )
- check("bootstrap exits 0", bootstrap.returncode == 0)
-
- # Step 2: Register an agent by writing directly to the project registry.
- agent_id = "smoke-agent-1"
- registry_path = project / ".loopx" / "registry.json"
- check("registry.json exists after bootstrap", registry_path.exists())
- if registry_path.exists():
- _register_agent_in_registry(registry_path, goal_id, agent_id)
- registry = json.loads(registry_path.read_text(encoding="utf-8"))
- goal_entry = next(
- (g for g in registry.get("goals", []) if g.get("id") == goal_id),
- {},
- )
- registered_agents = (
- goal_entry.get("coordination", {}).get("registered_agents", [])
- )
- check(
- f"agent '{agent_id}' appears in registry after registration",
- agent_id in registered_agents,
- )
-
- # Step 2b: write the first runnable agent Todo. connect/boot no longer seeds
- # one, so the guided takeover frontier has to come from the caller.
- seeded_todo = run_cli(
- "--registry", str(registry_path),
- "todo", "add",
- "--goal-id", goal_id,
- "--role", "agent",
- "--text", "[P0] Implement the first bounded regression segment.",
- "--task-class", "advancement_task",
- "--action-kind", "implementation",
- "--claimed-by", agent_id,
- "--execute",
- check=False,
- )
- check("first agent todo exits 0", seeded_todo.returncode == 0)
-
- # Step 3: Build the guided packet via direct Python import.
- guided_packet = build_start_goal_guided_packet(
- project=project,
- goal_id=goal_id,
- agent_id=agent_id,
- cli_bin="loopx",
- host_surface="claude-code",
- goal_text="regression test for #3092",
- )
- # The fixture seeds one runnable advancement Todo, so this must not accept
- # the frontier-free legacy authoring path.
- template = _require_guided_todo_delta_template(
- guided_packet,
- label="guided packet",
- )
-
- # Defect 1 core assertion: template must use --claimed-by, not --agent-id.
- check(
- "template does NOT contain --agent-id",
- "--agent-id" not in template,
- )
- check(
- "template contains --claimed-by",
- "--claimed-by" in template,
- )
-
- print("\n=== Scenario 3: todo add with --claimed-by accepted ===")
-
- # Run a concrete todo add using the correct --claimed-by pattern.
- todo_result = run_cli(
- "--registry", str(registry_path),
- "todo", "add",
- "--goal-id", goal_id,
- "--project", str(project),
- "--role", "agent",
- "--claimed-by", agent_id,
- "--task-class", "advancement_task",
- "--action-kind", "verify",
- "--text", "[P0] regression guard for #3092",
- check=False,
- )
- check("todo add exits 0", todo_result.returncode == 0)
- try:
- todo_payload = json.loads(todo_result.stdout)
- except (json.JSONDecodeError, ValueError):
- todo_payload = {}
- check("todo add returns ok: true", todo_payload.get("ok") is True)
- check(
- "todo add returns a todo_id",
- bool(todo_payload.get("todo_id")),
- )
-
-
-# ---------------------------------------------------------------------------
-# Scenario 4: agent-onboard after bootstrap returns a real packet
-# ---------------------------------------------------------------------------
-def test_post_bootstrap_onboard(project: Path) -> None:
- print("\n=== Scenario 4: agent-onboard after bootstrap (happy path) ===")
-
- result = run_cli(
- "agent-onboard",
- "--agent-type", "claude-code",
- "--project", str(project),
- check=False,
- )
- check(
- "post-bootstrap agent-onboard has no traceback",
- "FileNotFoundError" not in (result.stderr + result.stdout),
- )
- try:
- payload = json.loads(result.stdout)
- except (json.JSONDecodeError, ValueError):
- payload = {}
- check("post-bootstrap agent-onboard returns valid JSON", bool(payload))
- # After bootstrap the packet should be a structured response, not a crash.
- check(
- "post-bootstrap agent-onboard returns a structured packet",
- isinstance(payload, dict) and len(payload) > 0,
- )
-
-
-# ---------------------------------------------------------------------------
-# Scenario 5: clean second run in a fresh temp dir
-# ---------------------------------------------------------------------------
-def test_clean_second_run() -> None:
- print("\n=== Scenario 5: clean second run (no state leakage) ===")
-
- with tempfile.TemporaryDirectory(prefix="loopx-3092-second-") as tmp:
- project = Path(tmp) / "project-second"
- project.mkdir()
- goal_id = "second-run-goal"
- agent_id = "second-agent"
-
- # Repeat the unconnected onboard check in a clean directory.
- result = run_cli(
- "agent-onboard",
- "--agent-type", "claude-code",
- "--project", str(project),
- check=False,
- )
- check(
- "second-run: agent-onboard on bare project has no traceback",
- "FileNotFoundError" not in (result.stderr + result.stdout),
- )
- try:
- second_payload = json.loads(result.stdout)
- except (json.JSONDecodeError, ValueError):
- second_payload = {}
- second_identity_gate = second_payload.get("identity_selection_gate")
- check(
- "second-run: agent-onboard returns typed response (not crash)",
- second_payload.get("gate") == "project_not_connected"
- or second_payload.get("ok") is False
- or second_payload.get("connection_state") == "not_connected"
- or (
- isinstance(second_identity_gate, dict)
- and second_identity_gate.get("activation_allowed") is False
- ),
- )
-
- # Bootstrap + register + guided template check.
- run_cli(
- "bootstrap",
- "--project", str(project),
- "--goal-id", goal_id,
- "--objective", "second run regression",
- "--adapter-kind", "read_only_project_map_v0",
- "--adapter-status", "connected-read-only",
- "--no-global-sync",
- check=False,
- )
- registry_path = project / ".loopx" / "registry.json"
- if registry_path.exists():
- _register_agent_in_registry(registry_path, goal_id, agent_id)
- run_cli(
- "--registry", str(registry_path),
- "todo", "add",
- "--goal-id", goal_id,
- "--role", "agent",
- "--text", "[P0] Implement the second-run bounded segment.",
- "--task-class", "advancement_task",
- "--action-kind", "implementation",
- "--claimed-by", agent_id,
- "--execute",
- check=False,
- )
-
- guided = build_start_goal_guided_packet(
- project=project,
- goal_id=goal_id,
- agent_id=agent_id,
- cli_bin="loopx",
- host_surface="claude-code",
- goal_text="second run check",
- )
- template = _require_guided_todo_delta_template(
- guided,
- label="second-run guided packet",
- )
- check(
- "second-run: template uses --claimed-by",
- "--claimed-by" in template,
- )
- check(
- "second-run: template does not use --agent-id",
- "--agent-id" not in template,
- )
-
- if registry_path.exists():
- todo_result = run_cli(
- "--registry", str(registry_path),
- "todo", "add",
- "--goal-id", goal_id,
- "--project", str(project),
- "--role", "agent",
- "--claimed-by", agent_id,
- "--task-class", "advancement_task",
- "--action-kind", "implement",
- "--text", "[P1] second-run guard",
- check=False,
- )
- try:
- todo_payload = json.loads(todo_result.stdout)
- except (json.JSONDecodeError, ValueError):
- todo_payload = {}
- check(
- "second-run: todo add with --claimed-by returns ok",
- todo_payload.get("ok") is True,
- )
-
-
-def main() -> int:
- with tempfile.TemporaryDirectory(prefix="loopx-3092-regression-") as tmp:
- project = Path(tmp) / "project"
- project.mkdir()
- goal_id = "regression-3092"
-
- # Scenario 1: unconnected project — must not crash.
- test_unconnected_agent_onboard(project)
-
- # Scenarios 2 & 3: bootstrap, register, guided template, todo add.
- test_guided_template_acceptance(project, goal_id)
-
- # Scenario 4: onboard after bootstrap — must succeed.
- test_post_bootstrap_onboard(project)
-
- # Scenario 5: isolated second run in a fresh temp dir.
- test_clean_second_run()
-
- print(f"\n{'=' * 50}")
- print(f"fresh-project-onboarding-regression-smoke: PASS={PASS} FAIL={FAIL}")
- if FAIL:
- print("SOME CHECKS FAILED — see above for details.")
- return 1
- print("All checks passed.")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/global-registry-health-readmodel-smoke.py b/examples/control_plane/global-registry-health-readmodel-smoke.py
deleted file mode 100644
index 0cf1407596..0000000000
--- a/examples/control_plane/global-registry-health-readmodel-smoke.py
+++ /dev/null
@@ -1,177 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test global registry health read-model parity."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.goals import global_registry_health as health_read_model # noqa: E402
-from loopx.control_plane.goals.path_resolution import same_path # noqa: E402
-from loopx.paths import global_registry_path # noqa: E402
-from loopx.registry import registry_goals # noqa: E402
-
-
-def direct_collect(
- *,
- registry_path: Path,
- runtime_root: Path,
- current_registry: dict[str, Any],
-) -> dict[str, Any]:
- return health_read_model.collect_global_registry_health(
- registry_path=registry_path,
- runtime_root=runtime_root,
- current_registry=current_registry,
- global_registry_path=global_registry_path,
- load_registry=status_module.load_registry,
- registry_goals=registry_goals,
- same_path=same_path,
- resolve_goal_local_path=status_module.resolve_goal_local_path,
- parse_timestamp=status_module.parse_timestamp,
- )
-
-
-def assert_parity(
- *,
- registry_path: Path,
- runtime_root: Path,
- current_registry: dict[str, Any],
-) -> dict[str, Any]:
- wrapper = status_module.collect_global_registry_health(
- registry_path=registry_path,
- runtime_root=runtime_root,
- current_registry=current_registry,
- )
- direct = direct_collect(
- registry_path=registry_path,
- runtime_root=runtime_root,
- current_registry=current_registry,
- )
- assert wrapper == direct, (wrapper, direct)
- return wrapper
-
-
-def write_json(path: Path, payload: dict[str, Any]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-global-registry-health-") as raw_tmp:
- root = Path(raw_tmp)
- runtime = root / "runtime"
- current_registry_path = root / "project" / ".loopx" / "registry.json"
- missing = assert_parity(
- registry_path=current_registry_path,
- runtime_root=runtime,
- current_registry={"goals": []},
- )
- assert missing["available"] is False, missing
- assert missing["summary"] == {
- "high": 0,
- "action": 0,
- "info": 0,
- "checks": 0,
- "findings": 0,
- }, missing
-
- source_registry = root / "source" / ".loopx" / "registry.json"
- source_registry.parent.mkdir(parents=True)
- source_registry.write_text("{}\n", encoding="utf-8")
- state_file = root / "source" / ".codex" / "goals" / "fresh" / "ACTIVE_GOAL_STATE.md"
- state_file.parent.mkdir(parents=True)
- state_file.write_text("---\nupdated_at: 2026-07-04T00:00:00+00:00\n---\n", encoding="utf-8")
-
- current_registry = {
- "goals": [
- {
- "id": "fresh",
- "repo": str(root / "source"),
- "state_file": ".codex/goals/fresh/ACTIVE_GOAL_STATE.md",
- }
- ]
- }
- global_registry = {
- "goals": [
- {
- "id": "fresh",
- "repo": str(root / "source"),
- "source_registry": ".loopx/registry.json",
- "state_file": ".codex/goals/fresh/ACTIVE_GOAL_STATE.md",
- "synced_at": "2026-07-04T00:00:00+00:00",
- },
- {
- "id": "duplicate",
- "repo": str(root / "missing-a"),
- "state_file": ".codex/goals/duplicate/ACTIVE_GOAL_STATE.md",
- },
- {
- "id": "duplicate",
- "repo": str(root / "missing-b"),
- "source_registry": ".loopx/registry.json",
- },
- {
- "id": "global-only",
- "repo": str(root / "missing-c"),
- "source_registry": ".loopx/registry.json",
- "state_file": ".codex/goals/global-only/ACTIVE_GOAL_STATE.md",
- },
- ]
- }
- write_json(global_registry_path(runtime), global_registry)
-
- health = assert_parity(
- registry_path=current_registry_path,
- runtime_root=runtime,
- current_registry=current_registry,
- )
- kinds = {str(finding.get("kind")) for finding in health["findings"]}
- assert health["available"] is True, health
- assert health["ok"] is False, health
- assert health["summary"]["high"] == 1, health
- assert "duplicate_goal_id" in kinds, health
- assert "source_registry_missing" in kinds, health
- assert "state_file_missing" in kinds, health
- assert "state_file_not_declared" in kinds, health
- assert "current_registry_scope_excludes_global_goals" in kinds, health
- assert health["source_registry_count"] == 3, health
- orphan_findings = [
- finding
- for finding in health["findings"]
- if finding.get("goal_id") == "global-only"
- and finding.get("kind") in {"source_registry_missing", "state_file_missing"}
- ]
- assert len(orphan_findings) == 2, orphan_findings
- assert all(
- "loopx retire-global-goal --goal-id global-only"
- in str(finding.get("recommended_action") or "")
- for finding in orphan_findings
- ), orphan_findings
-
- finding = health_read_model.global_registry_finding(
- kind="fixture",
- severity="info",
- message="fixture finding",
- recommended_action="keep parity",
- goal_id="fresh",
- path=state_file,
- goal_ids=["fresh"],
- )
- assert finding["kind"] == "fixture", finding
- assert finding["goal_id"] == "fresh", finding
- assert not hasattr(status_module, "global_registry_finding")
-
- print("global-registry-health-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/goal-artifact-lifecycle-projection-smoke.py b/examples/control_plane/goal-artifact-lifecycle-projection-smoke.py
deleted file mode 100644
index 71dfd648c6..0000000000
--- a/examples/control_plane/goal-artifact-lifecycle-projection-smoke.py
+++ /dev/null
@@ -1,502 +0,0 @@
-"""Fixture smoke for the derived Goal artifact lifecycle projection.
-
-Proves milestone, guard and next-transition derivation from synthetic goal
-payloads, including the negative cases the RFC requires: an unreached
-milestone, and a blocking guard with no legal transition.
-"""
-
-from __future__ import annotations
-
-import json
-import sys
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.goals.artifact_lifecycle import ( # noqa: E402 - source-checkout entrypoint
- GOAL_ARTIFACT_LIFECYCLE_PROJECTION_SCHEMA_VERSION,
- GUARD_KIND_EVIDENCE,
- GUARD_KIND_OWNER_DECISION,
- PHASE_CLOSED,
- PHASE_CLOSING,
- PHASE_QUALIFYING,
- PHASE_STARTING,
- PHASE_WAITING_OWNER,
- _compact_text,
- build_goal_artifact_lifecycle_projection,
-)
-from loopx.control_plane.work_items.work_lane import WorkLaneObservation # noqa: E402
-
-GOAL_ID = "artifact-lifecycle-fixture"
-
-# Split so the literal provider shape is not itself a credential hit for the
-# public boundary scan, the same convention the source fixtures follow.
-PROVIDER_TOKEN = "ghp_" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
-
-# Substrings that must never appear in a public projection.
-FORBIDDEN_LEAKS = (
- "/Users/",
- "/private/",
- "sk-",
- "ghp_",
- "BEGIN PRIVATE KEY",
- "raw_evidence_body",
-)
-
-
-def assert_no_public_leak(projection: dict) -> None:
- rendered = json.dumps(projection, ensure_ascii=False)
- for token in FORBIDDEN_LEAKS:
- assert token not in rendered, (token, rendered)
-
-
-def assert_starting_phase_without_work() -> None:
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- user_todo_summary={"gate_open_items": [], "open_count": 0},
- agent_todo_summary={"open_count": 0},
- run_history={"latest_runs": []},
- )
- assert projection["schema_version"] == (
- GOAL_ARTIFACT_LIFECYCLE_PROJECTION_SCHEMA_VERSION
- ), projection
- assert projection["lifecycle_phase"] == PHASE_STARTING, projection
- assert projection["milestones"] == [], projection
- assert projection["guards"] == [], projection
- assert projection["next_transitions"] == [], projection
- assert_no_public_leak(projection)
-
-
-def assert_outcome_gap_is_material_but_not_reached() -> None:
- """A recorded gap is retained history, never a reached marker.
-
- `MATERIAL_DELIVERY_OUTCOMES` decides what history keeps; the canonical
- progress outcomes decide what the Goal advanced, and they deliberately
- exclude `outcome_gap`.
- """
-
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- agent_todo_summary={"open_count": 2},
- run_history={"latest_runs": [{"delivery_outcome": "outcome_gap"}]},
- )
- reached = {item["id"]: item["reached"] for item in projection["milestones"]}
- assert reached == {"outcome_gap": False}, projection
- assert projection["lifecycle_phase"] == PHASE_QUALIFYING, projection
- assert_no_public_leak(projection)
-
-
-def assert_gap_only_evidence_blocks_closeout() -> None:
- """The reproduced defect: zero open agent Todos over an `outcome_gap` run.
-
- This previously read as closing / next: closed because the material set
- marked the gap reached. A gap is an unreached marker, so the Goal stays
- qualifying and is told what is still missing.
- """
-
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- user_todo_summary={"gate_open_items": []},
- agent_todo_summary={"open_count": 0},
- run_history={"latest_runs": [{"delivery_outcome": "outcome_gap"}]},
- )
- assert projection["lifecycle_phase"] == PHASE_QUALIFYING, projection
- transition = projection["next_transitions"][0]
- assert transition["target_phase"] == PHASE_QUALIFYING, projection
- assert transition["reason_codes"] == ["milestone_unreached"], projection
- assert_no_public_leak(projection)
-
-
-def assert_evidence_milestone_reached_from_run_history() -> None:
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- agent_todo_summary={"open_count": 1},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": "primary_goal_outcome",
- "delivery_batch_scale": "multi_surface",
- "evidence_ref": "run:abc123",
- },
- {"delivery_outcome": "surface_only"},
- ]
- },
- )
- assert len(projection["milestones"]) == 1, projection
- milestone = projection["milestones"][0]
- assert milestone["reached"] is True, projection
- assert milestone["reached_evidence_refs"] == ["run:abc123"], projection
- assert milestone["source"] == "evidence", projection
- assert_no_public_leak(projection)
-
-
-def assert_open_owner_gate_blocks_the_next_transition() -> None:
- """The RFC's example: a milestone is reached but the owner gate is open."""
-
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- user_todo_summary={
- "open_count": 1,
- "gate_open_items": [
- {
- "todo_id": "todo_gate_baseline",
- "task_class": "user_gate",
- "action_kind": "approve_baseline",
- "blocks_agent": "agent-a",
- }
- ],
- },
- agent_todo_summary={"open_count": 2},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": "primary_goal_outcome",
- "delivery_batch_scale": "multi_surface",
- "evidence_ref": "run:baseline",
- }
- ]
- },
- work_observation=WorkLaneObservation(
- lane="advancement_task", must_attempt=True, next_action="advance_one_bounded_segment",
- ),
- )
- assert projection["lifecycle_phase"] == PHASE_WAITING_OWNER, projection
- guard = projection["guards"][0]
- assert guard["kind"] == GUARD_KIND_OWNER_DECISION, projection
- assert guard["blocked"] is True, projection
- assert guard["owner"] == "user", projection
- assert guard["decision_scope"] is None, projection
- # A blocking guard admits no other transition, even with a selected lane.
- transitions = projection["next_transitions"]
- assert len(transitions) == 1, projection
- assert transitions[0]["reason_codes"] == ["guard_open"], projection
- assert transitions[0]["target_phase"] == PHASE_WAITING_OWNER, projection
- assert_no_public_leak(projection)
-
-
-def assert_evidence_guard_is_required_and_owned_by_the_agent() -> None:
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- user_todo_summary={"open_count": 0},
- agent_todo_summary={"open_count": 1},
- run_history={"latest_runs": []},
- acceptance_gaps=[{"kind": "vision_acceptance_gap", "agent_id": "agent-a"}],
- )
- guard = projection["guards"][0]
- assert guard["kind"] == GUARD_KIND_EVIDENCE, projection
- assert guard["evidence_required"] is True, projection
- assert guard["owner"] == "agent", projection
- assert projection["lifecycle_phase"] == PHASE_QUALIFYING, projection
- assert_no_public_leak(projection)
-
-
-def assert_closing_advice_and_observed_terminal_status_stay_distinct() -> None:
- closing = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- user_todo_summary={"gate_open_items": []},
- agent_todo_summary={"open_count": 0},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": "primary_goal_outcome",
- "delivery_batch_scale": "multi_surface",
- }
- ]
- },
- )
- assert closing["lifecycle_phase"] == PHASE_CLOSING, closing
- transition = closing["next_transitions"][0]
- assert transition["target_phase"] == PHASE_CLOSING, closing
- assert transition["target_phase"] != PHASE_CLOSED, closing
- # Closing carries verification advice, never a terminal recommendation.
- # Already-closed Goal status is still displayed without recommending a step.
- assert "no_open_agent_work" in transition["reason_codes"], closing
- assert "acceptance_unverified" in transition["reason_codes"], closing
- assert "agent_vision" in transition["precondition"], closing
- assert_no_public_leak(closing)
-
- closed = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "closed"},
- agent_todo_summary={"open_count": 0},
- )
- assert closed["lifecycle_phase"] == PHASE_CLOSED, closed
- assert closed["next_transitions"] == [], closed
- assert_no_public_leak(closed)
-
-
-def assert_projection_is_pure_and_reads_no_state() -> None:
- """Same inputs must produce the same projection, with no side effects."""
-
- kwargs = {
- "goal_id": GOAL_ID,
- "goal": {"id": GOAL_ID, "status": "active"},
- "user_todo_summary": {"open_count": 0, "gate_open_items": []},
- "agent_todo_summary": {"open_count": 3},
- "run_history": {"latest_runs": []},
- }
- first = build_goal_artifact_lifecycle_projection(**kwargs)
- second = build_goal_artifact_lifecycle_projection(**kwargs)
- assert first == second, (first, second)
- assert first["lifecycle_phase"] == PHASE_QUALIFYING, first
-
-
-def assert_progress_evidence_alone_does_not_authorize_closeout() -> None:
- """Evidence reaches closing; v0 never recommends a terminal transition.
-
- The canonical progress outcomes prove the Goal advanced. They do not prove
- the declared acceptance was assessed. The step stays inside closing.
- """
-
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- user_todo_summary={"gate_open_items": []},
- agent_todo_summary={"open_count": 0},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": "primary_goal_outcome",
- "delivery_batch_scale": "multi_surface",
- }
- ]
- },
- )
- reached = {item["id"]: item["reached"] for item in projection["milestones"]}
- assert reached == {"primary_goal_outcome": True}, projection
- assert projection["lifecycle_phase"] == PHASE_CLOSING, projection
- transition = projection["next_transitions"][0]
- assert transition["target_phase"] == PHASE_CLOSING, projection
- assert transition["target_phase"] != PHASE_CLOSED, projection
- assert "acceptance_unverified" in transition["reason_codes"], projection
-
-
-def assert_private_values_are_redacted_or_dropped() -> None:
- """A run-history reference is free text; private values must not survive."""
-
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- agent_todo_summary={"open_count": 1},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": "primary_goal_outcome",
- "delivery_batch_scale": "multi_surface",
- "evidence_ref": "/Users/private-owner/.ssh/id_rsa",
- "recommended_action": (
- f"publish {PROVIDER_TOKEN} and "
- "see /private/var/folders/secret/notes.md"
- ),
- }
- ]
- },
- )
- rendered = json.dumps(projection, ensure_ascii=False)
- for leaked in (
- "/Users/private-owner",
- "/private/var/folders",
- PROVIDER_TOKEN,
- ):
- assert leaked not in rendered, (leaked, rendered)
-
- # Unsafe references are withheld by the same validator as other status
- # projections; no local path is retained even as a truncated fragment.
- assert _compact_text("/Users/private-owner/notes.md") is None
- assert _compact_text(f"token {PROVIDER_TOKEN}") is None
- assert _compact_text("/private/var/folders/x/secret.md") is None
-
-
-def assert_batch_scale_never_promotes_an_outcome() -> None:
- """The batch scale describes delivery width; it is not Goal evidence.
-
- Regression for the counterexample the review raised: a `surface_only` run
- also carrying `delivery_batch_scale=multi_surface` must not become a reached
- milestone, because the canonical typed rule
- (`MATERIAL_DELIVERY_OUTCOMES`) excludes `surface_only`.
- """
-
- for scale in ("single_surface", "multi_surface"):
- for outcome in ("surface_only", "", "bogus", "multi_surface"):
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": outcome,
- "delivery_batch_scale": scale,
- "run_id": "run-1",
- }
- ]
- },
- )
- assert projection["milestones"] == [], (outcome, scale, projection["milestones"])
- # Every canonical material outcome is still retained as a marker at any
- # scale, but only the accountable progress outcomes are reached. Scale
- # never moves a marker in either direction.
- accountable = {"outcome_progress", "primary_goal_outcome"}
- for scale in ("single_surface", "multi_surface"):
- for outcome in ("outcome_gap", "outcome_progress", "primary_goal_outcome"):
- projection = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID,
- goal={"id": GOAL_ID, "status": "active"},
- run_history={
- "latest_runs": [
- {
- "delivery_outcome": outcome,
- "delivery_batch_scale": scale,
- "run_id": "run-1",
- }
- ]
- },
- )
- markers = {item["id"]: item["reached"] for item in projection["milestones"]}
- assert markers == {outcome: outcome in accountable}, (outcome, scale, markers)
-
-
-def assert_status_collection_attaches_a_readable_readout() -> None:
- """The RFC's smallest slice includes one readout in status markdown.
-
- Drives the same seam `loopx status` uses: collection attaches the
- projection, the presentation renderer prints it. The projection is derived
- from already-collected payloads, so this asserts no extra IO is required.
- """
-
- from loopx.control_plane.goals.artifact_lifecycle import (
- attach_goal_artifact_lifecycle_projections,
- )
- from loopx.presentation.renderers.status_markdown import render_status_markdown
-
- payload = {
- "run_history": {
- "goals": [
- {
- "id": GOAL_ID,
- "status": "active",
- }
- ]
- },
- "attention_queue": {
- "items": [
- {
- "goal_id": GOAL_ID,
- "user_todos": {
- "items": [
- {
- "todo_id": "todo_gate",
- "task_class": "user_gate",
- "text": "approve the release",
- "status": "open",
- "action_kind": "publish",
- }
- ]
- },
- "agent_todos": {"open_count": 0},
- }
- ]
- },
- }
- attach_goal_artifact_lifecycle_projections(payload, history={"goals": []})
- goal = payload["run_history"]["goals"][0]
- projection = goal["artifact_lifecycle"]
- assert projection["schema_version"] == GOAL_ARTIFACT_LIFECYCLE_PROJECTION_SCHEMA_VERSION
- assert projection["lifecycle_phase"] == PHASE_WAITING_OWNER, projection
- assert [guard["id"] for guard in projection["guards"]] == ["todo_gate"]
- markdown = render_status_markdown(payload)
- assert "artifact lifecycle: phase=waiting_owner" in markdown, markdown
- assert "blocked by owner_decision (user): todo_gate" in markdown, markdown
- assert_no_public_leak(projection)
-
-
-def assert_the_two_goal_projections_stay_distinct() -> None:
- """The lifecycle contract and the narrow acceptance observation must not mix.
-
- `#4248` shipped `goal_acceptance_observation_projection_v0` as bounded
- historical evidence and guarded that it is not the full lifecycle contract.
- Both now ship, so each renderer must refuse the other's schema rather than
- print a half-understood payload under its own heading.
- """
-
- from loopx.presentation.renderers.goal_acceptance_observation_markdown import (
- append_goal_acceptance_observation_markdown,
- )
- from loopx.presentation.renderers.goal_artifact_lifecycle_markdown import (
- append_goal_artifact_lifecycle_markdown,
- )
-
- lifecycle = build_goal_artifact_lifecycle_projection(
- goal_id=GOAL_ID, goal={"id": GOAL_ID, "status": "active"}
- )
- narrow = {
- "schema_version": "goal_acceptance_observation_projection_v0",
- "guards": [],
- "acceptance_gaps": [],
- "historical_progress": [],
- }
- # Each renderer prints only its own contract, whichever key carries it.
- for goal in ({"artifact_lifecycle": narrow}, {"artifact_lifecycle": {}}):
- lines: list[str] = []
- append_goal_artifact_lifecycle_markdown(lines, goal)
- assert lines == [], (goal, lines)
- for goal in ({"acceptance_observation": lifecycle}, {"acceptance_observation": {}}):
- lines = []
- append_goal_acceptance_observation_markdown(lines, goal)
- assert lines == [], (goal, lines)
- # And the lifecycle renderer does print its own contract.
- lines = []
- append_goal_artifact_lifecycle_markdown(lines, {"artifact_lifecycle": lifecycle})
- assert any("artifact lifecycle" in line for line in lines), lines
- # The phase/milestone/transition vocabulary belongs to the lifecycle alone.
- assert {"lifecycle_phase", "milestones", "next_transitions"} <= set(lifecycle)
- assert {"lifecycle_phase", "milestones", "next_transitions"}.isdisjoint(narrow)
-
-
-def assert_control_plane_imports_no_presentation_module() -> None:
- """The projection may not depend outward on the presentation layer."""
-
- import ast
-
- source = (
- REPO_ROOT / "loopx" / "control_plane" / "goals" / "artifact_lifecycle.py"
- ).read_text(encoding="utf-8")
- imported: list[str] = []
- for node in ast.walk(ast.parse(source)):
- if isinstance(node, ast.ImportFrom) and node.module:
- imported.append(node.module)
- elif isinstance(node, ast.Import):
- imported.extend(alias.name for alias in node.names)
- offenders = [name for name in imported if "presentation" in name]
- assert offenders == [], offenders
-
-
-def main() -> int:
- assert_starting_phase_without_work()
- assert_outcome_gap_is_material_but_not_reached()
- assert_gap_only_evidence_blocks_closeout()
- assert_evidence_milestone_reached_from_run_history()
- assert_open_owner_gate_blocks_the_next_transition()
- assert_evidence_guard_is_required_and_owned_by_the_agent()
- assert_closing_advice_and_observed_terminal_status_stay_distinct()
- assert_projection_is_pure_and_reads_no_state()
- assert_progress_evidence_alone_does_not_authorize_closeout()
- assert_private_values_are_redacted_or_dropped()
- assert_batch_scale_never_promotes_an_outcome()
- assert_status_collection_attaches_a_readable_readout()
- assert_control_plane_imports_no_presentation_module()
- assert_the_two_goal_projections_stay_distinct()
- print("goal-artifact-lifecycle-projection-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/handoff-run-readmodel-smoke.py b/examples/control_plane/handoff-run-readmodel-smoke.py
deleted file mode 100644
index 81a7b4b1fd..0000000000
--- a/examples/control_plane/handoff-run-readmodel-smoke.py
+++ /dev/null
@@ -1,84 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.handoff import handoff_runs as handoff_run_read_model # noqa: E402
-
-
-def _projection_is_handoff_ready(run: dict[str, object]) -> bool:
- return handoff_run_read_model.is_handoff_ready_run(
- run,
- handoff_ready_classifications=status_module.HANDOFF_READY_CLASSIFICATIONS,
- compact_operator_gate=status_module.compact_operator_gate,
- )
-
-
-def _projection_has_external_evidence(run: dict[str, object]) -> bool:
- return handoff_run_read_model.run_has_external_evidence_watch_signal(
- run,
- legacy_external_evidence_classification_prefixes=(
- status_module.LEGACY_EXTERNAL_EVIDENCE_CLASSIFICATION_PREFIXES
- ),
- )
-
-
-def _projection_is_custom_post_handoff(run: dict[str, object]) -> bool:
- return handoff_run_read_model.is_custom_post_handoff_work_run(
- run,
- is_status_neutral_run=status_module.is_status_neutral_run,
- is_handoff_ready_run=status_module.is_handoff_ready_run,
- run_has_external_evidence_watch_signal=status_module.run_has_external_evidence_watch_signal,
- codex_ready_classifications=status_module.CODEX_READY_CLASSIFICATIONS,
- user_or_controller_classifications=status_module.USER_OR_CONTROLLER_CLASSIFICATIONS,
- blocking_classifications=status_module.BLOCKING_CLASSIFICATIONS,
- )
-
-
-def assert_handoff_run_wrapper_parity() -> None:
- cases = [
- {"classification": next(iter(status_module.HANDOFF_READY_CLASSIFICATIONS))},
- {
- "classification": "operator_gate_approved",
- "operator_gate": {"decision": "approve", "agent_command": "continue"},
- },
- {"classification": "feature_monitoring_not_external"},
- {"classification": "research_progress_written"},
- {"classification": next(iter(status_module.CODEX_READY_CLASSIFICATIONS))},
- {"classification": next(iter(status_module.USER_OR_CONTROLLER_CLASSIFICATIONS))},
- {"classification": next(iter(status_module.BLOCKING_CLASSIFICATIONS))},
- {"classification": "custom_delivery", "waiting_on": "external_evidence"},
- {
- "classification": "custom_delivery",
- "monitor_event": {"monitor_mode": "external_signal_watch"},
- },
- {
- "classification": (
- f"{status_module.LEGACY_EXTERNAL_EVIDENCE_CLASSIFICATION_PREFIXES[0]}fixture"
- ),
- },
- {"classification": "quota_monitor_poll"},
- {},
- ]
-
- for run in cases:
- assert status_module.is_handoff_ready_run(run) == _projection_is_handoff_ready(run), run
- assert status_module.run_has_external_evidence_watch_signal(run) == _projection_has_external_evidence(
- run
- ), run
- assert status_module.is_custom_post_handoff_work_run(run) == _projection_is_custom_post_handoff(run), run
-
-
-def main() -> None:
- assert_handoff_run_wrapper_parity()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/lark-inbox-priority-smoke.py b/examples/control_plane/lark-inbox-priority-smoke.py
deleted file mode 100644
index d6be4ba975..0000000000
--- a/examples/control_plane/lark-inbox-priority-smoke.py
+++ /dev/null
@@ -1,287 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test direct Lark inbox questions preempting ordinary quota work."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from datetime import datetime, timezone
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.extensions.lark.event_inbox import ( # noqa: E402
- LARK_OPERATOR_INBOX_SOURCE_CONTRACT,
- acknowledge_lark_event_inbox,
- project_lark_event_inbox_urgency,
-)
-from loopx.control_plane.work_items.operator_inbox import ( # noqa: E402
- project_operator_inbox_urgency,
-)
-from loopx.control_plane.testing.quota_fixtures import ( # noqa: E402
- quota_status_payload,
- quota_todo_item,
-)
-from loopx.quota import build_quota_should_run, render_quota_should_run_markdown # noqa: E402
-
-
-GOAL_ID = "lark-inbox-priority-fixture"
-AGENT_ID = "codex-fix"
-
-
-def status_payload(project: Path, *, monitor_only: bool = False) -> dict:
- next_action = "Advance the ordinary implementation todo."
- payload = quota_status_payload(
- goal_id=GOAL_ID,
- status="ordinary_advancement_ready",
- recommended_action=next_action,
- next_action=next_action,
- agent_todo_items=[
- quota_todo_item(
- todo_id="todo_ordinary_advancement",
- title="Advance the ordinary implementation todo.",
- priority="P1",
- )
- ],
- latest_runs=[
- {
- "classification": "quota_monitor_poll",
- "health_check": "due monitor observation unchanged; no quota spend",
- "monitor_event": {
- "monitor_mode": "due_monitor_observed_without_material_transition",
- "material_change": False,
- },
- },
- {
- "classification": "quota_monitor_poll",
- "health_check": "due monitor observation unchanged; no quota spend",
- "monitor_event": {
- "monitor_mode": "due_monitor_observed_without_material_transition",
- "material_change": False,
- },
- },
- ],
- coordination=(
- {
- "agent_model": "peer_v1",
- "registered_agents": [AGENT_ID],
- "agent_work_modes": {AGENT_ID: "monitor_only"},
- }
- if monitor_only
- else None
- ),
- goal_extra={
- "repo": str(project),
- "control_plane": {
- "lark_event_inbox": {
- "enabled": True,
- "config_path": ".loopx/config/lark/event-inbox.json",
- }
- },
- },
- )
- registry = project / ".loopx/registry.json"
- registry.write_text(
- json.dumps(
- {
- "goals": [
- {
- "id": GOAL_ID,
- "repo": str(project),
- **(
- {
- "coordination": {
- "agent_model": "peer_v1",
- "registered_agents": [AGENT_ID],
- "agent_work_modes": {AGENT_ID: "monitor_only"},
- }
- }
- if monitor_only
- else {}
- ),
- "control_plane": {
- "lark_event_inbox": {
- "enabled": True,
- "config_path": ".loopx/config/lark/event-inbox.json",
- }
- },
- }
- ]
- }
- ),
- encoding="utf-8",
- )
- payload["registry"] = str(registry)
- return payload
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory() as raw:
- project = Path(raw)
- config = project / ".loopx/config/lark/event-inbox.json"
- inbox = project / ".loopx/inbox/team-feedback"
- config.parent.mkdir(parents=True)
- inbox.mkdir(parents=True)
- config.write_text(
- json.dumps(
- {
- "schema_version": "lark_event_inbox_config_v0",
- "enabled": True,
- "inbox_dir": ".loopx/inbox/team-feedback",
- "capture_scope": "configured_chat_all",
- "reply": {
- "enabled": True,
- "sender_profile": "project-review-bot",
- "sender_identity": "bot",
- "bot_display_name": "Project Review Bot",
- "chat_id": "oc_project_review",
- },
- }
- ),
- encoding="utf-8",
- )
- (inbox / "om_direct_question.json").write_text(
- json.dumps(
- {
- "schema_version": "lark_event_inbox_event_v0",
- "event_id": "evt-direct-question",
- "message_id": "om_direct_question",
- "create_time": "2026-07-15T00:00:00Z",
- "content": "@Project Review Bot 这个结论呢?",
- "addressed_to_bot": True,
- }
- ),
- encoding="utf-8",
- )
- (inbox / "invalid_event.json").write_text(
- json.dumps(
- {
- "schema_version": "lark_event_inbox_event_v0",
- "event_id": "invalid event id",
- "message_id": "om_invalid_event",
- "create_time": "2026-07-15T00:00:01Z",
- "content": "@Project Review Bot 这条无效事件不能进入 urgency?",
- }
- ),
- encoding="utf-8",
- )
-
- decision = build_quota_should_run(
- status_payload(project, monitor_only=True),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- operator_inbox_urgency_projector=project_lark_event_inbox_urgency,
- )
- assert decision["should_run"] is True, decision
- assert decision["effective_action"] == "lark_inbox_reply_due", decision
- assert decision["monitor_debt_arbitration"]["active"] is True, decision
- lane = decision["work_lane_contract"]
- assert lane["lane"] == "lark_event_inbox", lane
- assert lane["next_lane"] == "advancement_task", lane
- assert lane["obligation"] == "drain_lark_inbox_reply_due", lane
- assert lane["priority_preemption"] is True, lane
- assert lane["direct_question_count"] == 1, lane
- assert lane["reply_to_bot_count"] == 0, lane
- assert lane["pending_count"] == 1, lane
- assert (
- decision["execution_obligation"]["contract_obligation"]
- == lane["obligation"]
- )
- assert "durable effect" in decision["recommended_action"], decision
- urgency = decision["goal_boundary"]["capabilities"]["lark_event_inbox"][
- "urgency"
- ]
- assert urgency["schema_version"] == "lark_event_inbox_urgency_v0", urgency
- assert urgency["reply_due"] is True, urgency
- assert urgency["local_private_content_returned"] is False, urgency
- assert "items" not in urgency and "message_id" not in json.dumps(urgency), (
- urgency
- )
- parity_now = datetime(2026, 7, 15, 0, 10, tzinfo=timezone.utc)
- compatibility = project_lark_event_inbox_urgency(
- project=project,
- config_path=config,
- now=parity_now,
- )
- generic = project_operator_inbox_urgency(
- project=project,
- config_path=config,
- source_contract=LARK_OPERATOR_INBOX_SOURCE_CONTRACT,
- now=parity_now,
- )
- compatibility["schema_version"] = "operator_inbox_urgency_v0"
- compatibility["reply_to_operator_count"] = compatibility.pop(
- "reply_to_bot_count"
- )
- assert compatibility == generic, (compatibility, generic)
- markdown = render_quota_should_run_markdown(decision)
- assert "lane=lark_event_inbox" in markdown, markdown
- assert "questions=1" in markdown, markdown
- assert "bot_replies=0" in markdown, markdown
-
- acknowledge_lark_event_inbox(
- project=project,
- config_path=config,
- message_ids=["om_direct_question"],
- execute=True,
- )
- (inbox / "om_verified_bot_reply.json").write_text(
- json.dumps(
- {
- "schema_version": "lark_event_inbox_event_v0",
- "event_id": "evt-verified-bot-reply",
- "message_id": "om_verified_bot_reply",
- "parent_id": "om_bot_parent",
- "create_time": "2026-07-15T00:01:00Z",
- "content": "不带 at 的直接回复",
- "reply_context_verified": True,
- "reply_to_bot": True,
- }
- ),
- encoding="utf-8",
- )
- reply_decision = build_quota_should_run(
- status_payload(project, monitor_only=True),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- operator_inbox_urgency_projector=project_lark_event_inbox_urgency,
- )
- reply_lane = reply_decision["work_lane_contract"]
- assert reply_decision["effective_action"] == "lark_inbox_reply_due", (
- reply_decision
- )
- assert reply_lane["reply_to_bot_count"] == 1, reply_lane
- assert reply_lane["direct_question_count"] == 0, reply_lane
- acknowledge_lark_event_inbox(
- project=project,
- config_path=config,
- message_ids=["om_verified_bot_reply"],
- execute=True,
- )
- after_ack = build_quota_should_run(
- status_payload(project),
- goal_id=GOAL_ID,
- operator_inbox_urgency_projector=project_lark_event_inbox_urgency,
- )
- assert after_ack["work_lane_contract"]["lane"] == "advancement_task", after_ack
- assert after_ack["effective_action"] == "normal_run", after_ack
- monitor_only_after_ack = build_quota_should_run(
- status_payload(project, monitor_only=True),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- operator_inbox_urgency_projector=project_lark_event_inbox_urgency,
- )
- assert monitor_only_after_ack["should_run"] is False, monitor_only_after_ack
- assert (
- monitor_only_after_ack["effective_action"] == "agent_monitor_only"
- ), monitor_only_after_ack
-
- print("lark-inbox-priority-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/legacy-runtime-goal-attention-smoke.py b/examples/control_plane/legacy-runtime-goal-attention-smoke.py
deleted file mode 100644
index 783b444f5c..0000000000
--- a/examples/control_plane/legacy-runtime-goal-attention-smoke.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test legacy runtime goal attention projection."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.status import build_attention_queue # noqa: E402
-
-
-def build_queue(*, classification: str, json_exists: bool = True, markdown_exists: bool = True) -> dict:
- run = {
- "generated_at": "2026-01-01T00:00:00Z",
- "goal_id": "legacy-demo",
- "classification": classification,
- "json_exists": json_exists,
- "markdown_exists": markdown_exists,
- }
- history = {
- "goal_count": 1,
- "run_count": 1,
- "goals": [
- {
- "id": "legacy-demo",
- "status": "active",
- "registry_member": False,
- "legacy_runtime_goal": True,
- "latest_runs": [run],
- }
- ],
- "runs": [run],
- }
- return build_attention_queue(
- contract={"ok": True},
- history=history,
- global_registry={"ok": True, "findings": []},
- )
-
-
-def test_missing_artifact_projects_high_attention() -> None:
- queue = build_queue(classification="state_refreshed", markdown_exists=False)
- item = queue["items"][0]
- assert item["status"] == "unregistered_runtime_goal", item
- assert item["waiting_on"] == "controller", item
- assert item["severity"] == "high", item
- assert "archive-runtime" in item["recommended_action"], item
-
-
-def test_blocking_classification_projects_high_attention() -> None:
- queue = build_queue(classification="blocked_by_safety")
- item = queue["items"][0]
- assert item["status"] == "unregistered_runtime_goal", item
- assert item["severity"] == "high", item
- assert "blocked_by_safety" in item["recommended_action"], item
-
-
-def test_neutral_complete_legacy_runtime_goal_stays_quiet() -> None:
- queue = build_queue(classification="neutral_complete")
- assert queue["items"] == [], queue
-
-
-def main() -> int:
- test_missing_artifact_projects_high_attention()
- test_blocking_classification_projects_high_attention()
- test_neutral_complete_legacy_runtime_goal_stays_quiet()
- print("legacy-runtime-goal-attention-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/local-state-write-correctness-rollout-gate-smoke.py b/examples/control_plane/local-state-write-correctness-rollout-gate-smoke.py
deleted file mode 100644
index d100759014..0000000000
--- a/examples/control_plane/local-state-write-correctness-rollout-gate-smoke.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the local state write correctness runtime promotion gate."""
-
-from __future__ import annotations
-
-import json
-import re
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-PROTOCOL = REPO_ROOT / "docs" / "reference" / "protocols" / "local-state-write-correctness-v0.md"
-
-
-def extract_gate_packet(text: str) -> dict[str, Any]:
- marker = "## Runtime Promotion Gate"
- start = text.index(marker)
- match = re.search(r"```json\n(.*?)\n```", text[start:], re.DOTALL)
- assert match, "Runtime Promotion Gate must include a JSON code block"
- return json.loads(match.group(1))
-
-
-def main() -> int:
- text = PROTOCOL.read_text(encoding="utf-8")
- packet = extract_gate_packet(text)
-
- assert packet["schema_version"] == "local_state_write_correctness_rollout_gate_v0", packet
- assert packet["current_mode"] == "dry_run_preview", packet
- assert packet["promotion_target"] == "shadow_validate", packet
- assert packet["allowed_to_change_write_behavior"] is False, packet
-
- required = packet["required_evidence"]
- for field in (
- "dry_run_packet_smoke",
- "idempotency_key_stability",
- "expected_revision_fixture",
- "revision_conflict_fixture",
- "lease_projection_fixture",
- "public_boundary_scan",
- ):
- assert required.get(field), f"promotion gate missing evidence: {field}"
-
- exit_criteria = " ".join(packet["exit_criteria"])
- for phrase in (
- "dry-run JSON and markdown",
- "duplicate retries",
- "revision and lease conflicts",
- "compact public-safe write refs",
- ):
- assert phrase in exit_criteria, f"promotion gate missing exit criterion: {phrase}"
-
- compact = " ".join(text.split())
- assert "must not reject or rewrite a previously accepted real write" in compact
- assert "separate validated step" in compact
-
- print("local-state-write-correctness-rollout-gate-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/monitor-display-projection-smoke.py b/examples/control_plane/monitor-display-projection-smoke.py
deleted file mode 100644
index be2696448e..0000000000
--- a/examples/control_plane/monitor-display-projection-smoke.py
+++ /dev/null
@@ -1,113 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test monitor-quiet display candidate projection."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.scheduler.monitor_display import ( # noqa: E402
- attention_item_is_monitor_quiet_display_candidate as direct_monitor_candidate,
- normalize_monitor_quiet_attention_display as direct_normalize_monitor_display,
- quiet_monitor_display_action as direct_quiet_monitor_display_action,
-)
-from loopx.status import ( # noqa: E402
- MAX_STATUS_TODOS_PER_ROLE,
- MONITOR_DISPLAY_FALLBACK_ACTION,
- MONITOR_DISPLAY_SCHEMA_VERSION,
- MONITOR_DISPLAY_STOP_CONDITION,
- MONITOR_SIGNAL_WAITING_ON,
- attention_item_is_monitor_quiet_display_candidate,
- normalize_monitor_quiet_attention_display,
- open_todo_items,
- quiet_monitor_display_action,
-)
-from loopx.control_plane.todos.todo_summary import todo_item_is_actionable_open # noqa: E402
-
-
-def todo(index: int, text: str) -> dict[str, object]:
- return {"index": index, "done": False, "status": "open", "text": text}
-
-
-def monitor_item(*, with_advancement: bool = False, with_user_todo: bool = False) -> dict[str, object]:
- agent_todos = {
- "open_count": 1 + int(with_advancement),
- "monitor_open_items": [todo(1, "[P1 monitor] Observe one bounded public-safe signal.")],
- "first_executable_items": [],
- "executable_backlog_items": [],
- "claimed_advancement_open_items": [],
- }
- if with_advancement:
- agent_todos["claimed_advancement_open_items"] = [
- todo(2, "[P2] Continue canary-gated control-plane read-model cleanup.")
- ]
- return {
- "goal_id": "loopx-meta",
- "waiting_on": "codex",
- "severity": "action",
- "recommended_action": "Quiet monitor only until a material transition appears.",
- "agent_todos": agent_todos,
- "user_todos": {
- "open_count": int(with_user_todo),
- "items": [todo(1, "[P0-user] Decide something.")] if with_user_todo else [],
- },
- "project_asset": {},
- }
-
-
-def assert_status_and_projection_agree(item: dict[str, object], expected: bool) -> None:
- direct = direct_monitor_candidate(
- item,
- open_todo_items=open_todo_items,
- todo_item_is_actionable_open=todo_item_is_actionable_open,
- fallback_limit=MAX_STATUS_TODOS_PER_ROLE,
- )
- wrapper = attention_item_is_monitor_quiet_display_candidate(item)
- assert direct is expected, (direct, expected, item)
- assert wrapper == direct, (wrapper, direct, item)
-
-
-def main() -> int:
- assert_status_and_projection_agree(monitor_item(), True)
- assert_status_and_projection_agree(monitor_item(with_advancement=True), False)
- assert_status_and_projection_agree(monitor_item(with_user_todo=True), False)
-
- assert quiet_monitor_display_action(None) == MONITOR_DISPLAY_FALLBACK_ACTION
- assert direct_quiet_monitor_display_action(
- "Wait quietly for the next due time.",
- fallback_action=MONITOR_DISPLAY_FALLBACK_ACTION,
- ) == quiet_monitor_display_action("Wait quietly for the next due time.")
-
- status_item = monitor_item()
- direct_item = monitor_item()
- normalize_monitor_quiet_attention_display(status_item)
- direct_normalize_monitor_display(
- direct_item,
- is_monitor_quiet_display_candidate=lambda item: direct_monitor_candidate(
- item,
- open_todo_items=open_todo_items,
- todo_item_is_actionable_open=todo_item_is_actionable_open,
- fallback_limit=MAX_STATUS_TODOS_PER_ROLE,
- ),
- display_fallback_action=MONITOR_DISPLAY_FALLBACK_ACTION,
- monitor_signal_waiting_on=MONITOR_SIGNAL_WAITING_ON,
- monitor_display_schema_version=MONITOR_DISPLAY_SCHEMA_VERSION,
- monitor_display_stop_condition=MONITOR_DISPLAY_STOP_CONDITION,
- )
- assert status_item == direct_item, (status_item, direct_item)
- assert status_item["waiting_on"] == MONITOR_SIGNAL_WAITING_ON, status_item
- assert status_item["severity"] == "watch", status_item
- assert status_item["project_asset"]["owner"] == MONITOR_SIGNAL_WAITING_ON, status_item
- assert status_item["project_asset"]["stop_condition"] == MONITOR_DISPLAY_STOP_CONDITION, status_item
-
- print("monitor-display-projection-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/monitor-todo-policy-seam-smoke.py b/examples/control_plane/monitor-todo-policy-seam-smoke.py
deleted file mode 100644
index 27668fe6ee..0000000000
--- a/examples/control_plane/monitor-todo-policy-seam-smoke.py
+++ /dev/null
@@ -1,112 +0,0 @@
-#!/usr/bin/env python3
-"""Characterize the shared monitor todo due-time policy seam."""
-
-from __future__ import annotations
-
-from datetime import datetime, timezone
-from pathlib import Path
-import sys
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx.control_plane.scheduler.monitor_todo import ( # noqa: E402
- monitor_cadence_delta,
- monitor_next_due_at,
- monitor_todo_is_actionable_open,
- monitor_todo_is_due,
- monitor_todo_is_expired,
- monitor_todo_missing_schedule,
- monitor_todo_next_due_at,
-)
-from loopx.status import ( # noqa: E402
- todo_item_is_due_monitor,
- todo_item_is_expired_monitor,
- todo_item_missing_monitor_schedule,
- todo_item_next_due_at,
-)
-from loopx.control_plane.todos.todo_summary import todo_item_is_actionable_open # noqa: E402
-
-
-NOW = datetime(2026, 1, 1, 0, 0, tzinfo=timezone.utc)
-PAST = "2025-12-31T23:59:00Z"
-FUTURE = "2026-01-01T00:01:00+00:00"
-EXPIRED = "2025-12-31T23:58:00+00:00"
-
-
-def monitor_item(**overrides: object) -> dict[str, object]:
- item: dict[str, object] = {
- "text": "[P1] Monitor update-note draft PR.",
- "status": "open",
- "task_class": "continuous_monitor",
- "next_due_at": PAST,
- }
- item.update(overrides)
- return item
-
-
-def assert_policy_matches_wrappers(item: dict[str, object], *, due: bool, expired: bool) -> None:
- assert monitor_todo_is_due(item, now=NOW) is due, item
- assert todo_item_is_due_monitor(item, now=NOW) is due, item
- assert monitor_todo_is_expired(item, now=NOW) is expired, item
- assert todo_item_is_expired_monitor(item, now=NOW) is expired, item
- assert monitor_todo_next_due_at(item) == todo_item_next_due_at(item), item
- assert monitor_todo_is_actionable_open(item) == todo_item_is_actionable_open(item), item
- assert monitor_todo_missing_schedule(item, now=NOW) == todo_item_missing_monitor_schedule(
- item,
- now=NOW,
- ), item
-
-
-def main() -> int:
- assert_policy_matches_wrappers(monitor_item(), due=True, expired=False)
- assert_policy_matches_wrappers(monitor_item(next_due_at=FUTURE), due=False, expired=False)
- assert_policy_matches_wrappers(
- monitor_item(expires_at=EXPIRED),
- due=False,
- expired=True,
- )
- assert_policy_matches_wrappers(
- monitor_item(status="blocked"),
- due=False,
- expired=False,
- )
- assert_policy_matches_wrappers(
- monitor_item(done=True),
- due=False,
- expired=False,
- )
- assert_policy_matches_wrappers(
- monitor_item(task_class="advancement_task"),
- due=False,
- expired=False,
- )
- unscheduled = monitor_item()
- unscheduled.pop("next_due_at")
- assert_policy_matches_wrappers(unscheduled, due=False, expired=False)
- assert monitor_todo_missing_schedule(unscheduled, now=NOW) is True, unscheduled
- cadence_only = monitor_item(cadence="30m")
- cadence_only.pop("next_due_at")
- assert_policy_matches_wrappers(cadence_only, due=False, expired=False)
- assert monitor_todo_missing_schedule(cadence_only, now=NOW) is True, cadence_only
- assert monitor_todo_next_due_at({"next_due_at": "2026-01-01T00:00:00"}) == NOW
- assert monitor_cadence_delta("2h").total_seconds() == 7200
- cadence_due_at = monitor_next_due_at(
- generated_at="2026-01-01T00:00:00+00:00",
- cadence="5m",
- )
- assert (
- datetime.fromisoformat(cadence_due_at).astimezone(timezone.utc).isoformat()
- == "2026-01-01T00:05:00+00:00"
- )
- assert monitor_next_due_at(
- generated_at="ignored",
- explicit_next_due_at="2026-01-01T00:05:00+00:00",
- ) == "2026-01-01T00:05:00+00:00"
- print("monitor-todo-policy-seam-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/presentation-markdown-primitives-smoke.py b/examples/control_plane/presentation-markdown-primitives-smoke.py
deleted file mode 100644
index 760bea6886..0000000000
--- a/examples/control_plane/presentation-markdown-primitives-smoke.py
+++ /dev/null
@@ -1,377 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test shared Markdown presentation primitives across CLI surfaces."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.presentation.renderers.quota_markdown import ( # noqa: E402
- render_quota_markdown,
- render_quota_should_run_markdown,
-)
-from loopx.diagnose import render_diagnosis_markdown # noqa: E402
-from loopx.history import ( # noqa: E402
- render_history_markdown,
- render_index_duplicate_inspection_markdown,
- render_index_duplicate_repair_markdown,
-)
-from loopx.presentation.markdown import ( # noqa: E402
- as_dict,
- as_list,
- markdown_code,
- markdown_scalar,
- markdown_table_row,
- markdown_table_separator,
-)
-from loopx.presentation.public_safety import public_safe_boundary, redact_public_text # noqa: E402
-from loopx.presentation.renderers.status_markdown import ( # noqa: E402
- append_attention_queue_item_header_markdown,
-)
-from loopx.pr_review import render_pr_review_markdown # noqa: E402
-from loopx.registry import render_registry_markdown # noqa: E402
-from loopx.slash_commands import render_slash_command_catalog_markdown # noqa: E402
-from loopx.summary_all import render_summary_all_markdown # noqa: E402
-
-
-RAW_TEXT = "alpha|beta\nnext"
-ESCAPED_TEXT = "alpha\\|beta next"
-
-
-def assert_escaped(label: str, markdown: str) -> None:
- assert ESCAPED_TEXT in markdown, (label, markdown)
- assert "alpha|beta" not in markdown, (label, markdown)
- assert "alpha|beta\nnext" not in markdown, (label, markdown)
-
-
-def status_markdown() -> str:
- lines: list[str] = []
- append_attention_queue_item_header_markdown(
- lines,
- {
- "goal_id": "presentation-fixture",
- "status": "active",
- "lifecycle_phase": "running",
- "waiting_on": "codex",
- "severity": "normal",
- "source": "fixture",
- "recommended_action": RAW_TEXT,
- },
- )
- return "\n".join(lines)
-
-
-def quota_plan_markdown() -> str:
- return render_quota_markdown(
- {
- "ok": True,
- "registry": "./fixtures/registry.json",
- "runtime_root": "./fixtures/runtime",
- "goal_count": 1,
- "run_count": 0,
- "mode": "plan",
- "summary": {
- "registered_goals": 1,
- "health_blockers": 0,
- "states": {},
- },
- "groups": {
- "eligible": [
- {
- "goal_id": "presentation-fixture",
- "waiting_on": "codex",
- "status": "active",
- "lifecycle_phase": "running",
- "quota": {},
- "recommended_action": RAW_TEXT,
- }
- ]
- },
- }
- )
-
-
-def quota_should_run_markdown() -> str:
- return render_quota_should_run_markdown(
- {
- "ok": True,
- "goal_id": "presentation-fixture",
- "decision": "run",
- "should_run": True,
- "normal_delivery_allowed": True,
- "recovery_delivery_allowed": False,
- "self_repair_allowed": False,
- "effective_action": "normal_run",
- "actionable_by_codex": True,
- "state": "eligible",
- "waiting_on": "codex",
- "status": "active",
- "agent_lane_next_action": {
- "todo_id": "todo_alpha",
- "selected_by": "current_agent_claimed_todo",
- "confidence": 1.0,
- "text": RAW_TEXT,
- },
- }
- )
-
-
-def diagnosis_markdown() -> str:
- return render_diagnosis_markdown(
- {
- "ok": True,
- "packet_kind": "agent_reasoning_evidence_packet",
- "agent_must_reason": True,
- "registry": "./fixtures/registry.json",
- "runtime_root": "./fixtures/runtime",
- "selected_goal_id": "presentation-fixture",
- "goal_count": 1,
- "goal_packet_count": 1,
- "run_count": 0,
- "selected": {
- "machine_signal": "agent_work_attention",
- "status": "active",
- "waiting_on": "codex",
- "severity": "normal",
- "recommended_action": RAW_TEXT,
- "user_question": RAW_TEXT,
- "todo_evidence": {
- "user_open_count": 0,
- "agent_open_count": 1,
- "first_agent_todo": RAW_TEXT,
- },
- },
- "status_summary": {},
- "goals": [],
- }
- )
-
-
-def history_markdown() -> str:
- return render_history_markdown(
- {
- "ok": True,
- "runtime_root": "./fixtures/runtime",
- "registry": "./fixtures/registry.json",
- "goal_filter": "presentation-fixture",
- "goal_count": 1,
- "run_count": 1,
- "runs": [
- {
- "generated_at": "2026-01-01T00:00:00+00:00",
- "goal_id": "presentation-fixture",
- "classification": "fixture",
- "json_exists": True,
- "markdown_exists": True,
- "recommended_action": RAW_TEXT,
- }
- ],
- "goals": [],
- }
- )
-
-
-def history_duplicate_repair_markdown() -> str:
- return render_index_duplicate_repair_markdown(
- {
- "ok": True,
- "dry_run": True,
- "repaired": False,
- "runtime_root": "./fixtures/runtime",
- "registry": "./fixtures/registry.json",
- "goal_filter": "presentation-fixture",
- "checked_goal_count": 1,
- "raw_index_records": 2,
- "removed_row_count": 0,
- "preserved_reward_overlay_rows": 0,
- "unrepaired_group_count": 1,
- "truncated": False,
- "groups": [
- {
- "goal_id": "presentation-fixture",
- "generated_at": "2026-01-01T00:00:00+00:00",
- "action": "inspect",
- "repairable": True,
- "kept_line_numbers": [1],
- "removed_line_numbers": [],
- "reason": RAW_TEXT,
- }
- ],
- }
- )
-
-
-def history_duplicate_inspection_markdown() -> str:
- return render_index_duplicate_inspection_markdown(
- {
- "ok": True,
- "runtime_root": "./fixtures/runtime",
- "registry": "./fixtures/registry.json",
- "goal_filter": "presentation-fixture",
- "checked_goal_count": 1,
- "raw_index_records": 2,
- "duplicate_group_count": 1,
- "duplicate_row_count": 2,
- "truncated": False,
- "groups": [
- {
- "goal_id": "presentation-fixture",
- "generated_at": "2026-01-01T00:00:00+00:00",
- "duplicate_kind": "same_action",
- "severity": "warning",
- "line_numbers": [1, 2],
- "classifications": ["fixture"],
- "repair_hint": RAW_TEXT,
- }
- ],
- }
- )
-
-
-def registry_markdown() -> str:
- return render_registry_markdown(
- {
- "ok": True,
- "registry": "./fixtures/registry.json",
- "schema_version": "fixture",
- "updated_at": "2026-01-01T00:00:00Z",
- "common_runtime_root": "./fixtures/runtime",
- "goal_count": 1,
- "goals": [
- {
- "id": "presentation-fixture",
- "role": "project",
- "parent_goal_id": "",
- "domain": "fixture",
- "status": "active",
- "repo_exists": True,
- "repo_goal_count": 1,
- "state_file_exists": True,
- "adapter_kind": "local",
- "adapter_status": "ok",
- "next_probe": RAW_TEXT,
- }
- ],
- }
- )
-
-
-def slash_command_markdown() -> str:
- return render_slash_command_catalog_markdown(
- {
- "ok": True,
- "onboarding": {"suggested_user_note": ""},
- "commands": [
- {
- "command": "/loopx-fixture",
- "scope": "project",
- "intent": RAW_TEXT,
- "mutation_policy": "read-only",
- "cli_reference": "loopx fixture",
- }
- ],
- }
- )
-
-
-def assert_malformed_payloads_use_shared_coercion() -> None:
- pr_markdown = render_pr_review_markdown(
- {
- "ok": True,
- "summary": {"headline": "fixture"},
- "request": "not-a-dict",
- "review_groups": "not-a-dict",
- "review_sequence": "not-a-list",
- "pull_requests": "not-a-list",
- }
- )
- assert "## Unmerged PRs\n- none" in pr_markdown, pr_markdown
- assert "## Combined Review Sequence\n- none" in pr_markdown, pr_markdown
-
- summary_markdown = render_summary_all_markdown(
- {
- "ok": True,
- "summary": {"headline": "fixture"},
- "request": "not-a-dict",
- "lanes": "not-a-list",
- "gates": "not-a-list",
- "recent_progress": "not-a-list",
- }
- )
- assert "## Gates\n- none" in summary_markdown, summary_markdown
-
-
-def assert_shared_redaction() -> None:
- local_user_path = "/" + "Users/example/private.txt"
- local_tmp_path = "/" + "tmp/runtime"
- raw = f"open {local_user_path} and {local_tmp_path}\nthen /loopx-summary-all"
- assert redact_public_text(raw, limit=200) == (
- "open and then /loopx-summary-all"
- )
- assert redact_public_text(
- raw,
- limit=200,
- replacements={"/loopx-summary-all": "/loopx-global-summary"},
- ) == "open and then /loopx-global-summary"
- assert redact_public_text("abcdef", limit=4) == "abc..."
-
-
-def assert_public_safety_boundary() -> None:
- boundary = public_safe_boundary()
- assert set(boundary) == {
- "raw_logs_recorded",
- "raw_transcripts_recorded",
- "raw_connector_payloads_recorded",
- "credential_values_recorded",
- "absolute_paths_recorded",
- "private_source_bodies_recorded",
- }
- assert all(value is False for value in boundary.values())
- boundary["absolute_paths_recorded"] = True
- assert public_safe_boundary()["absolute_paths_recorded"] is False
-
-
-def main() -> int:
- assert as_dict({"ok": True}) == {"ok": True}
- assert as_dict(["not", "a", "dict"]) == {}
- assert as_list(["item"]) == ["item"]
- assert as_list({"not": "a list"}) == []
- assert markdown_scalar(RAW_TEXT) == ESCAPED_TEXT
- assert markdown_code(RAW_TEXT) == f"`{ESCAPED_TEXT}`"
- assert markdown_code(None) == "``"
- assert markdown_table_row([RAW_TEXT, markdown_code(RAW_TEXT)]) == f"| {ESCAPED_TEXT} | `{ESCAPED_TEXT}` |"
- assert markdown_table_separator(2) == "| --- | --- |"
- try:
- markdown_table_separator(0)
- except ValueError:
- pass
- else:
- raise AssertionError("markdown_table_separator should reject zero columns")
- assert_malformed_payloads_use_shared_coercion()
- assert_shared_redaction()
- assert_public_safety_boundary()
-
- surfaces = {
- "status": status_markdown(),
- "quota_plan": quota_plan_markdown(),
- "quota_should_run": quota_should_run_markdown(),
- "diagnose": diagnosis_markdown(),
- "history": history_markdown(),
- "history_duplicate_repair": history_duplicate_repair_markdown(),
- "history_duplicate_inspection": history_duplicate_inspection_markdown(),
- "registry": registry_markdown(),
- "slash_commands": slash_command_markdown(),
- }
- for label, markdown in surfaces.items():
- assert_escaped(label, markdown)
- print("presentation-markdown-primitives-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/primary-action-resolution-parity-smoke.py b/examples/control_plane/primary-action-resolution-parity-smoke.py
deleted file mode 100644
index 79a5100109..0000000000
--- a/examples/control_plane/primary-action-resolution-parity-smoke.py
+++ /dev/null
@@ -1,181 +0,0 @@
-#!/usr/bin/env python3
-"""Pin quota primary-action resolution across the four main decision paths."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-from typing import Any
-
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx.control_plane.testing.quota_fixtures import ( # noqa: E402
- quota_status_payload,
- quota_todo_item,
-)
-from loopx.quota import build_quota_should_run # noqa: E402
-
-
-GOAL_ID = "primary-action-resolution-parity"
-AGENT_ID = "codex-side-bypass"
-PRIMARY_AGENT_ID = "codex-main-control"
-
-
-def status_payload(
- *,
- agent_items: list[dict[str, Any]],
- user_items: list[dict[str, Any]] | None = None,
- quota_state: str = "eligible",
-) -> dict[str, Any]:
- durable_action = "Keep the durable goal route unchanged."
- return quota_status_payload(
- goal_id=GOAL_ID,
- status="operator_gate" if quota_state == "operator_gate" else "active",
- recommended_action=durable_action,
- next_action=durable_action,
- active_state_next_action=durable_action,
- agent_todo_items=agent_items,
- user_todo_items=user_items or [],
- quota_state=quota_state,
- project_asset_source="project_asset",
- coordination={
- "agent_model": "peer_v1",
- "registered_agents": [PRIMARY_AGENT_ID, AGENT_ID],
- },
- latest_runs=[],
- registry_status="active",
- )
-
-
-def signature(payload: dict[str, Any]) -> dict[str, Any]:
- contract = payload["interaction_contract"]
- agent_channel = contract["agent_channel"]
- trace = agent_channel.get("resolution_trace") or {}
- assert "authoritative_next_action" not in payload, payload
- return {
- "decision": payload["decision"],
- "effective_action": payload["effective_action"],
- "mode": contract["mode"],
- "primary_action": agent_channel["primary_action"],
- "resolution_summary": trace.get("summary"),
- }
-
-
-def main() -> int:
- run = build_quota_should_run(
- status_payload(
- agent_items=[
- quota_todo_item(
- todo_id="todo_run",
- title="Run the bounded implementation slice.",
- priority="P1",
- claimed_by=AGENT_ID,
- )
- ]
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- gate = build_quota_should_run(
- status_payload(
- agent_items=[],
- user_items=[
- quota_todo_item(
- todo_id="todo_gate",
- title="Approve the external publication boundary.",
- role="user",
- task_class="user_gate",
- blocks_agent=AGENT_ID,
- )
- ],
- quota_state="operator_gate",
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- monitor = build_quota_should_run(
- status_payload(
- agent_items=[
- quota_todo_item(
- todo_id="todo_monitor",
- title="Poll the due monitor.",
- priority="P0",
- task_class="continuous_monitor",
- claimed_by=AGENT_ID,
- cadence="15m",
- next_due_at="2026-01-01T00:00:00+00:00",
- )
- ]
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- replan = build_quota_should_run(
- status_payload(
- agent_items=[
- quota_todo_item(
- todo_id="todo_future_monitor",
- title="Watch the future monitor window.",
- priority="P1",
- task_class="continuous_monitor",
- claimed_by=AGENT_ID,
- cadence="15m",
- next_due_at="2099-01-01T00:00:00+00:00",
- )
- ]
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
-
- actual = {
- "run": signature(run),
- "gate": signature(gate),
- "monitor": signature(monitor),
- "replan": signature(replan),
- }
- expected = {
- "run": {
- "decision": "run",
- "effective_action": "normal_run",
- "mode": "bounded_delivery",
- "primary_action": "todo_run: [P1] Run the bounded implementation slice.",
- "resolution_summary": "source=agent_lane drift=true",
- },
- "gate": {
- "decision": "skip",
- "effective_action": "operator_gate_notify",
- "mode": "user_gate",
- "primary_action": "wait for user/owner action after surfacing the blocker or gate",
- "resolution_summary": "source=mode:user_gate drift=true",
- },
- "monitor": {
- "decision": "run",
- "effective_action": "normal_run",
- "mode": "bounded_delivery",
- "primary_action": "todo_monitor: [P0] Poll the due monitor.",
- "resolution_summary": "source=selected drift=true",
- },
- "replan": {
- "decision": "skip",
- "effective_action": "monitor_quiet_skip",
- "mode": "monitor_quiet_skip",
- "primary_action": (
- "ensure this heartbeat's idempotent quota receipt is committed, "
- "then stay quiet if unchanged; the guard records the eligible "
- "no-progress observation and an earlier heartbeat receipt does "
- "not satisfy this one"
- ),
- "resolution_summary": "source=mode:monitor_quiet_skip drift=true",
- },
- }
- assert actual == expected, actual
- print("primary-action-resolution-parity-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/private-boundary-monitor-priority-smoke.py b/examples/control_plane/private-boundary-monitor-priority-smoke.py
deleted file mode 100644
index 9c90aa881a..0000000000
--- a/examples/control_plane/private-boundary-monitor-priority-smoke.py
+++ /dev/null
@@ -1,149 +0,0 @@
-#!/usr/bin/env python3
-"""Guard private/local due monitors from preempting public advancement work."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.testing.quota_fixtures import quota_status_payload # noqa: E402
-from loopx.quota import build_quota_should_run # noqa: E402
-
-
-GOAL_ID = "private-boundary-monitor-priority-fixture"
-AGENT_ID = "codex-product-capability"
-PAST_DUE_AT = "2000-01-01T00:00:00+00:00"
-
-
-def status_payload(*, monitor_todo: dict, advancement_todo: dict) -> dict:
- return quota_status_payload(
- goal_id=GOAL_ID,
- status="eligible",
- registry_status="active",
- agent_todo_items=[monitor_todo, advancement_todo],
- recommended_action=advancement_todo["text"],
- next_action=advancement_todo["text"],
- claim_scope_agent_id=AGENT_ID,
- coordination={
- "agent_model": "peer_v1",
- "registered_agents": [
- "codex-main-control",
- AGENT_ID,
- ],
- },
- goal_extra={"quota": {"compute": 1.0, "window_hours": 24}},
- )
-
-
-def test_private_boundary_due_monitor_is_context_only() -> None:
- monitor_todo = {
- "index": 1,
- "text": "[P0-local] Keep private planning material aligned without authorized read.",
- "role": "agent",
- "status": "open",
- "priority": "P0-LOCAL",
- "task_class": "continuous_monitor",
- "action_kind": "local_department_doc_todo_projection_monitor",
- "claimed_by": AGENT_ID,
- "next_due_at": PAST_DUE_AT,
- "result_hash": "private_boundary_no_authorized_read",
- }
- advancement_todo = {
- "index": 2,
- "text": "[P2] Continue canary-gated read-model cleanup.",
- "role": "agent",
- "status": "open",
- "priority": "P2",
- "task_class": "advancement_task",
- "action_kind": "continue_canary_refactor",
- "claimed_by": AGENT_ID,
- }
- guard = build_quota_should_run(
- status_payload(
- monitor_todo=monitor_todo,
- advancement_todo=advancement_todo,
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- lane = guard["work_lane_contract"]
- assert guard["agent_todo_summary"]["monitor_due_count"] == 1, guard
- assert lane["lane"] == "advancement_task", lane
- assert lane["reason_codes"] == ["open_agent_todo", "due_monitor_context"], lane
- assert guard["recommended_action"] == advancement_todo["text"], guard
- primary_action = guard["interaction_contract"]["agent_channel"]["primary_action"]
- assert advancement_todo["text"] in primary_action, guard
-
-
-def test_public_due_monitor_priority_matrix() -> None:
- public_high_monitor = {
- "index": 1,
- "text": "[P0] Poll public release signal before implementation.",
- "role": "agent",
- "status": "open",
- "priority": "P0",
- "task_class": "continuous_monitor",
- "action_kind": "public_release_monitor",
- "claimed_by": AGENT_ID,
- "next_due_at": PAST_DUE_AT,
- }
- public_low_monitor = {
- **public_high_monitor,
- "text": "[P2] Poll public release signal after implementation.",
- "priority": "P2",
- }
- advancement_todo = {
- "index": 2,
- "text": "[P1] Continue canary-gated read-model cleanup.",
- "role": "agent",
- "status": "open",
- "priority": "P1",
- "task_class": "advancement_task",
- "action_kind": "continue_canary_refactor",
- "claimed_by": AGENT_ID,
- }
-
- high_guard = build_quota_should_run(
- status_payload(
- monitor_todo=public_high_monitor,
- advancement_todo=advancement_todo,
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- high_lane = high_guard["work_lane_contract"]
- assert high_lane["lane"] == "continuous_monitor", high_lane
- assert high_lane["monitor_kind"] == "todo_monitor_due", high_lane
- assert high_lane["reason_codes"] == [
- "monitor_due",
- "due_monitor_priority_preempts_advancement",
- ], high_lane
- assert high_guard["recommended_action"] == public_high_monitor["text"], high_guard
-
- low_guard = build_quota_should_run(
- status_payload(
- monitor_todo=public_low_monitor,
- advancement_todo=advancement_todo,
- ),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- low_lane = low_guard["work_lane_contract"]
- assert low_lane["lane"] == "advancement_task", low_lane
- assert low_lane["reason_codes"] == ["open_agent_todo", "due_monitor_context"], low_lane
- assert low_guard["recommended_action"] == advancement_todo["text"], low_guard
-
-
-def main() -> int:
- test_private_boundary_due_monitor_is_context_only()
- test_public_due_monitor_priority_matrix()
- print("private-boundary-monitor-priority-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/project-asset-active-state-fields-smoke.py b/examples/control_plane/project-asset-active-state-fields-smoke.py
deleted file mode 100644
index 9aeca181aa..0000000000
--- a/examples/control_plane/project-asset-active-state-fields-smoke.py
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test active-state field projection into project_asset."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.work_items.project_asset import ( # noqa: E402
- attach_active_state_project_asset_fields,
-)
-
-
-def main() -> int:
- item = {
- "project_asset": {"goal_id": "fixture-goal"},
- "active_state_next_action": "[P1] Keep active-state projection stable.",
- "latest_run_recommended_action": "[P1] Old run recommendation.",
- "issue_meta_surface": {"issue_count": 1},
- "backlog_hygiene_warning": {"requires_agent_todo": True},
- "state_projection_gap": {"requires_todo_expansion": True},
- "completed_todo_archive_warning": {"requires_archive": True},
- "agent_todos": {"open_count": 1},
- }
-
- def warning_builder(**kwargs):
- assert kwargs["active_state_next_action"] == item["active_state_next_action"]
- assert kwargs["latest_run_recommended_action"] == item["latest_run_recommended_action"]
- return {"kind": "next_action_projection_gap"}
-
- def replan_from_runs(runs, *, agent_todos):
- assert runs == [{"classification": "stalled_turn"}]
- assert agent_todos == item["agent_todos"]
- return {"required": True, "trigger_count": 1}
-
- attached = attach_active_state_project_asset_fields(
- item,
- latest_runs=[{"classification": "stalled_turn"}],
- next_action_projection_warning=warning_builder,
- autonomous_replan_obligation_from_runs=replan_from_runs,
- )
- project_asset = item["project_asset"]
- for key in (
- "active_state_next_action",
- "issue_meta_surface",
- "next_action_projection_warning",
- "backlog_hygiene_warning",
- "state_projection_gap",
- "completed_todo_archive_warning",
- "autonomous_replan_obligation",
- ):
- assert attached[key] == project_asset[key], (key, attached, project_asset)
- assert item["next_action_projection_warning"]["kind"] == "next_action_projection_gap"
- assert item["autonomous_replan_obligation"]["required"] is True
-
- no_asset = {"active_state_next_action": "ignored"}
- assert attach_active_state_project_asset_fields(no_asset) == {}
- assert "project_asset" not in no_asset
-
- print("project-asset-active-state-fields-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/public-safety-readmodel-smoke.py b/examples/control_plane/public-safety-readmodel-smoke.py
deleted file mode 100644
index 7ebed4d74b..0000000000
--- a/examples/control_plane/public-safety-readmodel-smoke.py
+++ /dev/null
@@ -1,184 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.runtime import public_safety as public_safety_read_model # noqa: E402
-from loopx.control_plane.runtime import session_runtime as session_runtime_read_model # noqa: E402
-from loopx.control_plane.work_items import project_asset as project_asset_read_model # noqa: E402
-from loopx.session_runtime import SESSION_RUNTIME_READONLY_PROJECTION_SCHEMA_VERSION # noqa: E402
-
-
-def assert_status_uses_direct_read_models() -> None:
- assert status_module.public_safe_compact_text is public_safety_read_model.public_safe_compact_text
- assert not hasattr(status_module, "compact_session_runtime_readonly_projection")
- assert (
- status_module.compact_session_runtime_projection_from_run
- is session_runtime_read_model.compact_session_runtime_projection_from_run
- )
-
-
-def assert_public_safe_text_parity() -> None:
- assert status_module.public_safe_compact_text(" keep\nthis value ") == "keep this value"
- assert project_asset_read_model.project_asset_public_safe_compact_text(
- " keep\nthis value "
- ) == "keep this value"
- assert status_module.public_safe_compact_text("") is None
-
- local_path = "/" + "tmp" + "/loopx-public-boundary-probe.json"
- secret_like_text = "tok" + "en" + "=" + ("x" * 12)
- assert status_module.public_safe_compact_text(local_path) is None
- assert project_asset_read_model.project_asset_public_safe_compact_text(local_path) is None
- assert status_module.public_safe_compact_text(secret_like_text) is None
- assert project_asset_read_model.project_asset_public_safe_compact_text(secret_like_text) is None
-
-
-def assert_public_safe_list_parity() -> None:
- local_path = "/" + "tmp" + "/loopx-public-boundary-probe.json"
- values = ["first", local_path, "second", "third"]
- expected = ["first", "second"]
- assert public_safety_read_model.public_safe_compact_list(values, limit=2) == expected
- assert public_safety_read_model.public_safe_compact_list("single", limit=4) == ["single"]
-
-
-def assert_numeric_map_compaction() -> None:
- source = {
- "count": "3",
- "ratio": "2.5",
- "native": 7,
- "false_flag": False,
- "truthy_flag": True,
- "empty": "",
- "word": "many",
- }
-
- assert public_safety_read_model.compact_numeric_map(source) == {
- "count": 3,
- "ratio": 2.5,
- "native": 7,
- }
- assert public_safety_read_model.compact_numeric_map(
- source,
- keys=("ratio", "missing", "word", "native"),
- ) == {"ratio": 2.5, "native": 7}
- assert public_safety_read_model.compact_numeric_map(["not", "a", "map"]) == {}
-
-
-def assert_loopx_command_record_compaction() -> None:
- local_path = "/" + "tmp" + "/loopx-command-record.json"
- records = [
- {
- "subcommand": "quota should-run",
- "todo_id": "todo_abc12345",
- "goal_id": "loopx-meta",
- },
- {
- "subcommand": "agent_command",
- "todo_id": "todo_private",
- "goal_id": "loopx-meta",
- },
- {
- "subcommand": "todo complete",
- "todo_id": local_path,
- "goal_id": "loopx-meta",
- },
- {
- "subcommand": "refresh-state",
- "todo_id": "todo_followup123",
- "goal_id": local_path,
- },
- ]
-
- assert public_safety_read_model.compact_loopx_command_records(records, limit=8) == [
- {
- "subcommand": "quota should-run",
- "todo_id": "todo_abc12345",
- "goal_id": "loopx-meta",
- },
- {"subcommand": "todo complete", "goal_id": "loopx-meta"},
- {"subcommand": "refresh-state", "todo_id": "todo_followup123"},
- ]
- assert public_safety_read_model.compact_loopx_command_records(records, limit=1) == [
- {
- "subcommand": "quota should-run",
- "todo_id": "todo_abc12345",
- "goal_id": "loopx-meta",
- }
- ]
- assert public_safety_read_model.compact_loopx_command_records({"not": "a-list"}) == []
-
-
-def assert_session_runtime_defaults() -> None:
- local_path = "/" + "tmp" + "/session-runtime-probe.json"
- projection = {
- "schema_version": SESSION_RUNTIME_READONLY_PROJECTION_SCHEMA_VERSION,
- "goal_id": "loopx-meta",
- "source": {
- "host_kind": "codex",
- "latest_fact_at": "2026-07-05T12:00:00Z",
- "source_refs": {
- "todos": ["todo_1", "todo_2"],
- },
- },
- "boundary": {
- "raw_material_key_names": ["safe-key", local_path],
- "raw_logs_copied": False,
- },
- "first_screen": {
- "waiting_on": "codex",
- "latest_blocker": local_path,
- "recommended_action": " continue\nvalidated seam ",
- "agent_can_continue": True,
- },
- "work_lane_contract": {"lane": "advancement_task", "must_attempt_work": True},
- "attention_item": {"kind": "todo", "title": " Public\nTitle "},
- }
-
- compact = session_runtime_read_model.compact_session_runtime_readonly_projection(projection)
- assert compact == {
- "schema_version": SESSION_RUNTIME_READONLY_PROJECTION_SCHEMA_VERSION,
- "mode": "read_only",
- "goal_id": "loopx-meta",
- "source": {
- "host_kind": "codex",
- "latest_fact_at": "2026-07-05T12:00:00Z",
- "source_ref_counts": {"todos": 2},
- },
- "boundary": {
- "raw_logs_copied": False,
- "raw_material_key_names": ["safe-key"],
- },
- "first_screen": {
- "waiting_on": "codex",
- "recommended_action": "continue validated seam",
- "agent_can_continue": True,
- },
- "work_lane_contract": {
- "lane": "advancement_task",
- "must_attempt_work": True,
- },
- "attention_item": {"kind": "todo", "title": "Public Title"},
- }
- assert status_module.compact_session_runtime_projection_from_run(
- {"session_runtime_readonly_projection": projection}
- ) == compact
-
-
-def main() -> None:
- assert_status_uses_direct_read_models()
- assert_public_safe_text_parity()
- assert_public_safe_list_parity()
- assert_numeric_map_compaction()
- assert_loopx_command_record_compaction()
- assert_session_runtime_defaults()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/quota-heartbeat-recommendation-state-machine-smoke.py b/examples/control_plane/quota-heartbeat-recommendation-state-machine-smoke.py
deleted file mode 100644
index 3a8773ca15..0000000000
--- a/examples/control_plane/quota-heartbeat-recommendation-state-machine-smoke.py
+++ /dev/null
@@ -1,277 +0,0 @@
-#!/usr/bin/env python3
-"""Canary the quota heartbeat recommendation state machine."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.quota.heartbeat_recommendation import ( # noqa: E402
- build_heartbeat_recommendation,
-)
-from loopx.control_plane.work_items.delivery_outcome import DeliveryOutcome # noqa: E402
-from loopx.control_plane.work_items.work_lane import build_work_lane_contract # noqa: E402
-
-
-GOAL_ID = "heartbeat-recommendation-fixture"
-
-
-def user_todos(open_count: int) -> dict[str, Any]:
- return {
- "schema_version": "todo_summary_v0",
- "source_section": "User Todo",
- "open_count": open_count,
- "first_open_items": [
- {
- "todo_id": f"todo_user_{index}",
- "status": "open",
- "task_class": "user_gate",
- "text": "[P0-user] Decide the owner gate.",
- }
- for index in range(open_count)
- ],
- }
-
-
-def agent_todos(open_count: int) -> dict[str, Any]:
- return {
- "schema_version": "todo_summary_v0",
- "source_section": "Agent Todo",
- "open_count": open_count,
- "first_open_items": [
- {
- "todo_id": f"todo_agent_{index}",
- "status": "open",
- "task_class": "advancement_task",
- "text": "[P1] Advance the durable heartbeat canary.",
- }
- for index in range(open_count)
- ],
- }
-
-
-def work_lane(
- *,
- open_count: int,
- advancement_count: int,
- monitor_count: int,
- monitor_due_count: int = 0,
- progress_scope: str = "agent_lane",
-) -> dict[str, Any] | None:
- due_items = [
- {
- "todo_id": "todo_monitor_due",
- "status": "open",
- "task_class": "continuous_monitor",
- "next_due_at": "2000-01-01T00:00:00+00:00",
- "text": "[P0-monitor] Observe a due material transition.",
- }
- ][:monitor_due_count]
- return build_work_lane_contract(
- progress_scope=progress_scope,
- external_poll_signal=False,
- todo_counts={
- "open": open_count,
- "advancement": advancement_count,
- "monitor": monitor_count,
- },
- monitor_due_count=monitor_due_count,
- due_monitor_items=due_items,
- first_advancement=(
- {
- "todo_id": "todo_agent_advancement",
- "status": "open",
- "task_class": "advancement_task",
- "text": "[P1] Advance the durable heartbeat canary.",
- }
- if advancement_count
- else None
- ),
- due_monitor_preempts_advancement=monitor_due_count > 0 and advancement_count == 0,
- outcome_followthrough=None,
- next_action_requires_advancement=False,
- monitor_due_item_limit=1,
- )
-
-
-def recommendation(
- item: dict[str, Any],
- *,
- state: str = "eligible",
- should_run: bool = True,
- user_summary: dict[str, Any] | None = None,
- agent_summary: dict[str, Any] | None = None,
- lane: dict[str, Any] | None = None,
- stall_self_repair: dict[str, Any] | None = None,
-) -> dict[str, Any]:
- return build_heartbeat_recommendation(
- item,
- goal_id=GOAL_ID,
- state=state,
- should_run=should_run,
- user_todo_summary=user_summary or user_todos(0),
- agent_todo_summary=agent_summary or agent_todos(0),
- work_lane_contract=lane,
- stall_self_repair=stall_self_repair,
- select_replan_obligation=False,
- )
-
-
-def assert_gate_and_repair_precedence() -> None:
- operator = recommendation({}, state="operator_gate")
- assert operator["recommended_mode"] == "ask_operator_gate", operator
- assert operator["notify"] == "NOTIFY", operator
-
- repair = recommendation(
- {},
- stall_self_repair={
- "allowed": True,
- "recommended_mode": "repair_control_plane_stall",
- "repair_focus": "state projection is stale",
- },
- )
- assert repair["recommended_mode"] == "repair_control_plane_stall", repair
- assert repair["repair_focus"] == "state projection is stale", repair
-
-
-def assert_quota_skip_and_blocker_push() -> None:
- skipped = recommendation({}, state="throttled", should_run=False)
- assert skipped["recommended_mode"] == "quota_skip", skipped
- assert "throttled" in skipped["reason"], skipped
-
- blocker = recommendation(
- {"waiting_on": "external_evidence"},
- state="focus_wait",
- user_summary=user_todos(1),
- )
- assert blocker["recommended_mode"] == "blocker_push_notify", blocker
- assert blocker["repeat_notification_required"] is True, blocker
- assert blocker["notify"] == "NOTIFY", blocker
-
-
-def assert_monitor_lanes_do_not_collapse_due_work() -> None:
- quiet_lane = work_lane(open_count=1, advancement_count=0, monitor_count=1)
- quiet = recommendation({}, lane=quiet_lane)
- assert quiet_lane and quiet_lane["must_attempt_work"] is False, quiet_lane
- assert quiet["recommended_mode"] == "monitor_quiet_until_material_transition", quiet
- assert quiet["notify"] == "DONT_NOTIFY", quiet
-
- due_lane = work_lane(
- open_count=1,
- advancement_count=0,
- monitor_count=1,
- monitor_due_count=1,
- )
- due = recommendation(
- {
- "handoff_readiness": {
- "post_handoff_latest_run": {
- "classification": "dependency_observed",
- "delivery_outcome": "outcome_progress",
- }
- }
- },
- lane=due_lane,
- )
- assert due_lane and due_lane["must_attempt_work"] is True, due_lane
- assert due_lane["obligation"] == "attempt_due_monitor", due_lane
- assert due["recommended_mode"] == "follow_work_lane_contract", due
- assert due["latest_run"]["progress_scope"] == "primary_goal", due
-
-
-def assert_read_only_map_lifecycle_modes() -> None:
- first = recommendation(
- {
- "status": "connected_without_run",
- "adapter_kind": "docs_read_only_map_v0",
- }
- )
- assert first["recommended_mode"] == "run_first_read_only_map", first
- assert first["command"] == f"loopx read-only-map --goal-id {GOAL_ID}", first
- assert first["notify"] == "NOTIFY", first
-
- mapped = recommendation(
- {
- "status": "read_only_project_map",
- "lifecycle_flags": ["mapped"],
- }
- )
- assert mapped["recommended_mode"] == "mapped_noop_if_unchanged", mapped
- assert mapped["stop_if_unchanged"] is True, mapped
- assert mapped["notify"] == "DONT_NOTIFY", mapped
-
-
-def assert_post_handoff_primary_outcome_modes() -> None:
- base_item = {
- "status": "post_handoff_run_seen",
- "adapter_kind": "harness_self_improvement",
- "control_plane": {"self_repair": {"enabled": True}},
- "handoff_readiness": {
- "post_handoff_run_seen": True,
- "handoff_status": "post_handoff_run_seen",
- "post_handoff_latest_run": {
- "classification": "implementation_merged",
- "delivery_outcome": DeliveryOutcome.PRIMARY_GOAL_OUTCOME.value,
- },
- },
- }
- no_agent = recommendation(base_item)
- assert no_agent["recommended_mode"] == "post_handoff_observe_if_unchanged", no_agent
- assert no_agent["stop_if_unchanged"] is True, no_agent
- assert no_agent["latest_run"]["progress_scope"] == "primary_goal", no_agent
-
- dependency_item = {
- **base_item,
- "handoff_readiness": {
- **base_item["handoff_readiness"],
- "post_handoff_latest_run": {
- **base_item["handoff_readiness"]["post_handoff_latest_run"],
- "classification": "dependency_observed_after_merge",
- "progress_scope": "dependency_observation",
- },
- },
- }
- with_agent = recommendation(
- dependency_item,
- agent_summary=agent_todos(1),
- lane=work_lane(
- open_count=1,
- advancement_count=1,
- monitor_count=0,
- progress_scope="dependency_observation",
- ),
- )
- assert with_agent["recommended_mode"] == "follow_work_lane_contract", with_agent
- assert with_agent.get("stop_if_unchanged") is not True, with_agent
- assert with_agent["latest_run"]["progress_scope"] == "dependency_observation", with_agent
-
-
-def assert_default_bounded_delivery_mode() -> None:
- normal = recommendation(
- {"status": "active-read-only"},
- agent_summary=agent_todos(1),
- lane=work_lane(open_count=1, advancement_count=1, monitor_count=0),
- )
- assert normal["recommended_mode"] == "steering_audit_then_one_step", normal
- assert "scope-bounded work" in normal["spend_policy"], normal
-
-
-def main() -> int:
- assert_gate_and_repair_precedence()
- assert_quota_skip_and_blocker_push()
- assert_monitor_lanes_do_not_collapse_due_work()
- assert_read_only_map_lifecycle_modes()
- assert_post_handoff_primary_outcome_modes()
- assert_default_bounded_delivery_mode()
- print("quota-heartbeat-recommendation-state-machine-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/quota-scheduler-policy-smoke.py b/examples/control_plane/quota-scheduler-policy-smoke.py
deleted file mode 100644
index 3c460f0abd..0000000000
--- a/examples/control_plane/quota-scheduler-policy-smoke.py
+++ /dev/null
@@ -1,257 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the extracted quota scheduler policy helper."""
-
-from __future__ import annotations
-
-from copy import deepcopy
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.scheduler.execution_context import ( # noqa: E402
- SchedulerRuntimeProfile,
- scheduler_execution_context_for_runtime_profile,
-)
-from loopx.control_plane.scheduler.scheduler_hint import build_scheduler_hint # noqa: E402
-from loopx.control_plane.agents.agent_scope_frontier import AgentScopeFrontierAction # noqa: E402
-from loopx.control_plane.quota.should_run_packet import _scheduler_hint # noqa: E402
-from loopx.control_plane.work_items.interaction_contract import ( # noqa: E402
- _interaction_reads_and_arbitration,
-)
-
-
-AGENT_SCOPE_ACTIONS = [action.value for action in AgentScopeFrontierAction]
-CODEX_APP_SCHEDULER_CONTEXT = scheduler_execution_context_for_runtime_profile(
- SchedulerRuntimeProfile.CODEX_APP_HEARTBEAT
-)
-
-
-def payload(
- *,
- should_run: bool,
- effective_action: str,
- recommended_mode: str = "",
- automation_action: str = "",
- user_required: bool = False,
- stop_if_unchanged: bool = False,
-) -> dict:
- mode = (
- effective_action
- if effective_action == "monitor_quiet_skip"
- else recommended_mode or effective_action
- )
- must_attempt = bool(should_run and mode != "mapped_noop_if_unchanged")
- return {
- "goal_id": "scheduler-policy-smoke",
- "should_run": should_run,
- "effective_action": effective_action,
- "recommended_action": "Run the scheduler policy smoke.",
- "heartbeat_recommendation": {
- "recommended_mode": recommended_mode,
- "notify": "DONT_NOTIFY",
- "spend_policy": "spend only after validated writeback",
- "stop_if_unchanged": stop_if_unchanged,
- },
- "execution_obligation": {
- "must_attempt_work": should_run,
- "spend_policy": "execution obligation spend policy",
- },
- "automation_liveness": {
- "automation_action": automation_action,
- "spend_policy": "automation liveness spend policy",
- },
- "interaction_contract": {
- "schema_version": "loopx_interaction_contract_v0",
- "mode": mode,
- "user_channel": {
- "action_required": user_required,
- },
- "agent_channel": {
- "must_attempt": must_attempt,
- "delivery_allowed": must_attempt,
- "quiet_noop_allowed": not user_required and not must_attempt,
- },
- "cli_channel": {},
- },
- }
-
-
-def assert_policy_case(
- name: str,
- base_payload: dict,
- *,
- expected_action: str,
- expected_rrule: str,
- expected_progression: list[int] | None = None,
- expected_same_identity_action: str = "advance_index_after_applied_interval_elapsed",
-) -> None:
- base_payload = deepcopy(base_payload)
- _, arbitration = _interaction_reads_and_arbitration(
- base_payload,
- base_payload["interaction_contract"],
- runtime_root=None,
- registry_path=None,
- agent_scope_frontier_actions=AGENT_SCOPE_ACTIONS,
- )
- quota_wrapper = _scheduler_hint(
- deepcopy(base_payload),
- arbitration=arbitration,
- scheduler_execution_context=CODEX_APP_SCHEDULER_CONTEXT,
- )
- extracted = build_scheduler_hint(
- deepcopy(base_payload),
- user_action_required=bool(
- base_payload.get("interaction_contract", {})
- .get("user_channel", {})
- .get("action_required")
- ),
- arbitration=arbitration,
- scheduler_execution_context=CODEX_APP_SCHEDULER_CONTEXT,
- )
- detailed = build_scheduler_hint(
- deepcopy(base_payload),
- user_action_required=bool(
- base_payload.get("interaction_contract", {})
- .get("user_channel", {})
- .get("action_required")
- ),
- arbitration=arbitration,
- include_detail=True,
- scheduler_execution_context=CODEX_APP_SCHEDULER_CONTEXT,
- )
- assert extracted == quota_wrapper, (name, extracted, quota_wrapper)
- assert extracted["schema_version"] == "scheduler_hint_v0", (name, extracted)
- assert extracted["source"] == "quota.should-run", (name, extracted)
- assert extracted["action"] == expected_action, (name, extracted)
- assert extracted["app_automation"]["recommended_rrule"] == expected_rrule, (name, extracted)
- assert extracted["app_automation"]["host_tool"] == "automation_update", (name, extracted)
- assert extracted["app_automation"]["host_action"] == "update_current_heartbeat_rrule", (name, extracted)
- assert extracted["app_automation"]["rrule_source"] == "scheduler_hint.app_automation.recommended_rrule", (
- name,
- extracted,
- )
- stateful_backoff = extracted["app_automation"]["stateful_backoff"]
- if expected_progression is not None:
- assert extracted["app_automation"]["example_progression_minutes"] == expected_progression, (
- name,
- extracted,
- )
- assert stateful_backoff["schema_version"] == "app_automation_stateful_backoff_v0", (name, extracted)
- assert stateful_backoff["state_key"] == "scheduler_hint.app_automation.stateful_backoff", (name, extracted)
- assert stateful_backoff["apply_needed"] is True, (name, extracted)
- assert stateful_backoff["current_rrule"] == expected_rrule, (name, extracted)
- assert stateful_backoff["state_status"] == "missing", (name, extracted)
- for omitted in (
- "progression_minutes",
- "current_interval_minutes",
- "ack_required_after_apply",
- "same_identity_action",
- "reset_action",
- "automation_update_scope",
- ):
- assert omitted not in stateful_backoff, (name, omitted, extracted)
- assert "local_scheduler" not in extracted, (name, extracted)
- assert "codex_cli_tui" not in extracted, (name, extracted)
- assert "claude_code_loop" not in extracted, (name, extracted)
- assert "cold_path_detail" not in extracted, (name, extracted)
- assert extracted["detail_ref"]["request"] == "loopx quota should-run --include-detail scheduler", (name, extracted)
- assert detailed["cold_path_detail"]["local_scheduler"]["recommended_interval_minutes"], (name, detailed)
- assert detailed["cold_path_detail"]["codex_cli_tui"]["final_quota_replan_check"], (name, detailed)
- assert detailed["cold_path_detail"]["claude_code_loop"]["after_limit"], (name, detailed)
- stateful_detail = detailed["cold_path_detail"]["stateful_backoff_detail"]
- if expected_progression is not None:
- assert stateful_detail["progression_minutes"] == expected_progression, (name, detailed)
- assert stateful_detail["ack_required_after_apply"] is True, (name, detailed)
- assert stateful_detail["same_identity_action"] == expected_same_identity_action, (
- name,
- detailed,
- )
- assert stateful_detail["reset_action"] == "clear_progression_index_apply_initial_rrule", (
- name,
- detailed,
- )
- assert stateful_detail["automation_update_scope"] == "rrule_only_preserve_body_name_status", (
- name,
- detailed,
- )
- reset = extracted["reset_policy"]
- assert isinstance(reset["reset_token"], str) and len(reset["reset_token"]) == 16, (name, reset)
- assert len(reset["identity_signature"]) == 12, (name, reset)
- reset_detail = detailed["cold_path_detail"]["reset_policy_detail"]
- assert reset_detail["schema_version"] == "scheduler_reset_policy_v0", (name, reset_detail)
- assert reset_detail["app_automation_tool"] == "automation_update", (name, reset_detail)
- assert "automation_update" in reset_detail["app_automation_apply"], (name, reset_detail)
- assert len(reset_detail["profile_signature"]) == 12, (name, reset_detail)
- assert stateful_backoff["reset_token"] == reset["reset_token"], (name, reset)
- assert stateful_backoff["identity_signature"] == reset["identity_signature"], (name, reset)
- assert "identity_snapshot" not in reset, (name, reset)
- assert "profile_snapshot" not in reset, (name, reset)
-
-
-def main() -> int:
- assert_policy_case(
- "active-work",
- payload(should_run=True, effective_action="normal_run"),
- expected_action="run_now",
- expected_rrule="FREQ=MINUTELY;INTERVAL=3",
- expected_same_identity_action="keep_initial_interval_while_active_work",
- )
- assert_policy_case(
- "mapped-noop",
- payload(
- should_run=True,
- effective_action="normal_run",
- recommended_mode="mapped_noop_if_unchanged",
- stop_if_unchanged=True,
- ),
- expected_action="backoff_until_fresh_evidence",
- expected_rrule="FREQ=MINUTELY;INTERVAL=60",
- )
- assert_policy_case(
- "human-gate",
- payload(
- should_run=False,
- effective_action="operator_gate_notify",
- recommended_mode="ask_operator_gate",
- user_required=True,
- ),
- expected_action="backoff_waiting_for_user",
- expected_rrule="FREQ=MINUTELY;INTERVAL=30",
- )
- assert_policy_case(
- "agent-scope-wait",
- payload(
- should_run=False,
- effective_action=AgentScopeFrontierAction.AGENT_SCOPE_WAIT.value,
- ),
- expected_action="backoff_until_reassigned",
- expected_rrule="FREQ=MINUTELY;INTERVAL=10",
- expected_progression=[10, 20, 30, 60],
- )
- assert_policy_case(
- "monitor-wait",
- payload(
- should_run=False,
- effective_action="monitor_quiet_skip",
- recommended_mode="monitor_quiet_until_material_transition",
- ),
- expected_action="backoff_until_material_transition",
- expected_rrule="FREQ=MINUTELY;INTERVAL=15",
- expected_progression=[15, 30, 60],
- )
- assert_policy_case(
- "quiet-wait",
- payload(should_run=False, effective_action="quota_skip"),
- expected_action="backoff_until_state_change",
- expected_rrule="FREQ=MINUTELY;INTERVAL=30",
- )
- print("ok: quota scheduler policy helper matches quota wrapper")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/quota-todo-summary-readmodel-smoke.py b/examples/control_plane/quota-todo-summary-readmodel-smoke.py
deleted file mode 100644
index 65a4bb0868..0000000000
--- a/examples/control_plane/quota-todo-summary-readmodel-smoke.py
+++ /dev/null
@@ -1,439 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the quota-facing todo summary read model."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.todos.quota_summary import ( # noqa: E402
- compact_quota_todo_summary_for_payload,
- select_quota_todo_summary,
- summarize_project_asset_todos_for_quota,
- summarize_user_todos_for_quota,
-)
-from loopx.control_plane.todos.user_gate import is_user_gate_todo_item # noqa: E402
-
-
-AGENT_IDENTITY = {"agent_id": "codex-product-capability"}
-
-
-def canonical_todo_summary() -> dict:
- return {
- "schema_version": "todo_summary_v0",
- "source_section": "agent todo",
- "total_count": 6,
- "open_count": 5,
- "done_count": 1,
- "monitor_writeback": {"supported": True, "source": "active_state"},
- "items": [
- {
- "index": 1,
- "todo_id": "todo_gate_current",
- "text": "Owner approval before product capability write",
- "task_class": "user_gate",
- "action_kind": "approval",
- "blocks_agent": "codex-product-capability",
- },
- {
- "index": 2,
- "todo_id": "todo_gate_other",
- "text": "Owner approval before main-control write",
- "task_class": "user_gate",
- "action_kind": "approval",
- "blocks_agent": "codex-main-control",
- },
- {
- "index": 3,
- "todo_id": "todo_monitor_due",
- "text": "Monitor scheduler transition",
- "task_class": "continuous_monitor",
- "claimed_by": "codex-product-capability",
- "next_due_at": "2000-01-01T00:00:00+00:00",
- "target_key": "scheduler_transition",
- },
- {
- "index": 4,
- "todo_id": "todo_monitor_gap",
- "text": "Monitor missing schedule metadata",
- "task_class": "continuous_monitor",
- "claimed_by": "codex-product-capability",
- "target_key": "schedule_gap",
- },
- {
- "index": 5,
- "todo_id": "todo_refactor_next",
- "text": "[P1] Continue quota/todo state-machine refactor",
- "task_class": "advancement_task",
- "claimed_by": "codex-product-capability",
- },
- ],
- "active_next_action_items": [
- {
- "index": 5,
- "todo_id": "todo_refactor_next",
- "text": "[P1] Continue quota/todo state-machine refactor",
- "task_class": "advancement_task",
- "claimed_by": "codex-product-capability",
- },
- {
- "index": 6,
- "todo_id": "todo_other_agent_next",
- "text": "[P1] Other agent active-next item",
- "task_class": "advancement_task",
- "claimed_by": "codex-main-control",
- },
- ],
- "todo_succession_warning": {
- "schema_version": "todo_succession_warning_v0",
- "reason_code": "completed_advancement_without_successor",
- "count": 1,
- "items": [
- {
- "index": 7,
- "todo_id": "todo_done_without_successor",
- "text": "[P1] Finished state-machine canary without successor",
- "status": "done",
- "done": True,
- "task_class": "advancement_task",
- "action_kind": "state_machine_canary_refactor",
- "claimed_by": "codex-product-capability",
- }
- ],
- },
- }
-
-
-def assert_agent_scoped_user_gate_and_monitor_state() -> None:
- summary = summarize_user_todos_for_quota(
- canonical_todo_summary(),
- agent_identity=AGENT_IDENTITY,
- filter_user_gate_blocks_agent=True,
- )
- assert summary is not None
- assert summary["open_count"] == 4, summary
- assert summary["all_open_count"] == 5, summary
- assert summary["user_action_open_count"] == 3, summary
- assert summary["other_agent_scoped_open_count"] == 1, summary
- assert summary["gate_open_items"][0]["todo_id"] == "todo_gate_current", summary
- assert {
- item.get("todo_id")
- for item in summary["other_agent_scoped_items"]
- } == {"todo_gate_other"}, summary
- assert {
- item.get("todo_id")
- for item in summary["user_action_items"]
- } == {
- "todo_monitor_due",
- "todo_monitor_gap",
- "todo_refactor_next",
- }, summary
- assert summary["other_agent_bound_user_action_open_count"] == 1, summary
- assert {
- item.get("todo_id")
- for item in summary["other_agent_bound_user_action_items"]
- } == {"todo_other_agent_next"}, summary
-
- assert summary["monitor_due_count"] == 0, summary
- assert summary["monitor_due_items"] == [], summary
- assert summary["monitor_schedule_gap_count"] == 0, summary
- assert summary["monitor_schedule_gap_items"] == [], summary
- assert summary["active_next_action_items"][0]["todo_id"] == "todo_refactor_next", summary
- assert all(
- item.get("todo_id") != "todo_other_agent_next"
- for item in summary["active_next_action_items"]
- ), summary
- assert summary["todo_succession_warning"]["count"] == 1, summary
-
-
-def assert_project_asset_fallback_and_canonical_precedence() -> None:
- raw_canonical = {
- "source_section": "raw legacy queue",
- "items": [
- {
- "index": 1,
- "text": "raw fallback should not outrank project asset",
- }
- ],
- }
- project_asset = {
- "next": "[P1] Project asset selected todo",
- "next_index": 9,
- "next_claimed_by": "codex-product-capability",
- }
- selected = select_quota_todo_summary(
- raw_canonical,
- project_asset,
- agent_identity=AGENT_IDENTITY,
- )
- assert selected is not None
- assert selected["source_section"] == "project_asset", selected
- assert selected["first_open_items"][0]["index"] == 9, selected
- assert "Project asset selected todo" in selected["first_open_items"][0]["text"], selected
-
- canonical = canonical_todo_summary()
- selected = select_quota_todo_summary(
- canonical,
- {"next": "[P1] Project asset should lose"},
- agent_identity=AGENT_IDENTITY,
- )
- assert selected is not None
- assert selected["source_section"] == "agent todo", selected
- assert any(
- item.get("todo_id") == "todo_gate_current"
- for item in selected["gate_open_items"]
- ), selected
- assert selected["first_executable_items"][0]["todo_id"] == "todo_refactor_next", selected
-
-
-def assert_project_asset_summary_reuses_canonical_shape() -> None:
- canonical_shape = canonical_todo_summary()
- summary = summarize_project_asset_todos_for_quota(
- canonical_shape,
- agent_identity=AGENT_IDENTITY,
- filter_user_gate_blocks_agent=True,
- )
- assert summary is not None
- assert summary["source_section"] == "agent todo", summary
- assert summary["monitor_due_count"] == 0, summary
- assert summary["other_agent_scoped_open_count"] == 1, summary
-
-
-def assert_agent_due_monitor_survives_claimed_lane_compaction() -> None:
- other_agent_monitors = [
- {
- "index": index,
- "todo_id": f"todo_other_monitor_{index:02d}",
- "text": f"[P2] Observe other agent monitor {index}.",
- "status": "open",
- "task_class": "continuous_monitor",
- "claimed_by": "codex-main-control",
- "target_key": f"other-monitor-{index}",
- "next_due_at": "2999-01-01T00:00:00+00:00",
- }
- for index in range(16)
- ]
- side_agent_due = {
- "index": 17,
- "todo_id": "todo_side_monitor_due_after_compaction",
- "text": "[P1] Observe the due side-agent monitor.",
- "status": "open",
- "task_class": "continuous_monitor",
- "claimed_by": "codex-side-bypass",
- "target_key": "side-monitor-due-after-compaction",
- "next_due_at": "2000-01-01T00:00:00+00:00",
- }
- canonical = {
- "schema_version": "todo_summary_v0",
- "source_section": "Agent Todo",
- "total_count": 17,
- "open_count": 17,
- "done_count": 0,
- "monitor_writeback": {"supported": True, "source": "active_state"},
- "claimed_monitor_open_items": other_agent_monitors,
- "monitor_open_items": [*other_agent_monitors, side_agent_due],
- }
-
- selected = select_quota_todo_summary(
- canonical,
- None,
- agent_identity={"agent_id": "codex-side-bypass"},
- )
- assert selected is not None
- assert selected["open_count"] == 1, selected
- assert selected["monitor_due_count"] == 1, selected
- assert (
- selected["monitor_due_items"][0]["todo_id"] == side_agent_due["todo_id"]
- ), selected
-
-
-def assert_legacy_and_canonical_shared_lanes_stay_in_parity() -> None:
- items = [
- {
- "index": 1,
- "todo_id": "todo_shared_monitor",
- "text": "[P1] Observe the shared due monitor.",
- "status": "open",
- "task_class": "continuous_monitor",
- "claimed_by": "codex-product-capability",
- "target_key": "shared-monitor",
- "next_due_at": "2000-01-01T00:00:00+00:00",
- },
- {
- "index": 2,
- "todo_id": "todo_shared_advancement",
- "text": "[P1] Continue the shared advancement lane.",
- "status": "open",
- "task_class": "advancement_task",
- "claimed_by": "codex-product-capability",
- },
- ]
- active_next = [items[1]]
- monitor_writeback = {"supported": True, "source": "active_state"}
- canonical = summarize_user_todos_for_quota(
- {
- "schema_version": "todo_summary_v0",
- "source_section": "Agent Todo",
- "total_count": 2,
- "open_count": 2,
- "done_count": 0,
- "items": items,
- "active_next_action_items": active_next,
- "monitor_writeback": monitor_writeback,
- },
- agent_identity=AGENT_IDENTITY,
- )
- legacy = summarize_project_asset_todos_for_quota(
- {
- "source_section": "project_asset",
- "open": 2,
- "done": 0,
- "first_open_items": items,
- "active_next_action_items": active_next,
- "monitor_writeback": monitor_writeback,
- },
- agent_identity=AGENT_IDENTITY,
- )
- assert canonical is not None and legacy is not None
- shared_keys = {
- "open_count",
- "first_open_items",
- "first_executable_items",
- "monitor_open_items",
- "monitor_due_count",
- "monitor_due_items",
- "active_next_action_items",
- "active_next_action_executable_items",
- "backlog_items",
- "executable_backlog_items",
- "claimed_open_count",
- "unclaimed_open_count",
- "claimed_open_items",
- "claimed_advancement_open_items",
- "claimed_monitor_open_items",
- "current_agent_claimed_open_items",
- "current_agent_claimed_advancement_items",
- "current_agent_claimed_monitor_items",
- }
- for key in shared_keys:
- assert canonical.get(key) == legacy.get(key), (key, canonical, legacy)
-
-
-def assert_user_gate_hint_detection_is_preserved() -> None:
- assert is_user_gate_todo_item(
- {
- "text": "Credential decision",
- "action_kind": "credential_rotation",
- }
- )
- assert not is_user_gate_todo_item(
- {
- "text": "Credential decision",
- "task_class": "advancement_task",
- "action_kind": "credential_rotation",
- }
- )
- assert is_user_gate_todo_item(
- {
- "text": "Public claim decision",
- "action_kind": "public_claim_review",
- }
- )
-
-
-def assert_quota_payload_summary_compacts_hot_path_lanes() -> None:
- long_text = "[P2] " + "inspect projection consistency " * 30
- source = {
- "schema_version": "todo_summary_v0",
- "source_section": "agent todo",
- "open_count": 12,
- "claimed_open_count": 12,
- "claimed_monitor_open_count": 12,
- "claimed_open_items": [
- {
- "index": index,
- "todo_id": f"todo_payload_{index:03d}",
- "text": long_text,
- "title": long_text,
- "status": "open",
- "task_class": "continuous_monitor",
- "claimed_by": "codex-main-control",
- "handoff_note": {
- "schema_version": "handoff_note_v0",
- "body": "cold path detail " * 200,
- },
- }
- for index in range(12)
- ],
- "user_action_open_count": 4,
- "user_action_items": [
- {
- "index": index,
- "todo_id": f"todo_user_action_{index:03d}",
- "text": f"Review user action {index}",
- "status": "open",
- "task_class": "user_action",
- }
- for index in range(4)
- ],
- "claim_scope": {
- "schema_version": "agent_claim_scope_v0",
- "agent_id": "codex-product-capability",
- "other_agent_claimed_open_count": 12,
- "other_agent_claimed_items": [
- {
- "index": index,
- "todo_id": f"todo_other_{index:03d}",
- "text": long_text,
- "task_class": "advancement_task",
- "claimed_by": "codex-main-control",
- }
- for index in range(12)
- ],
- },
- }
- compact = compact_quota_todo_summary_for_payload(source)
- assert compact["open_count"] == 12, compact
- assert compact["claimed_open_count"] == 12, compact
- assert len(compact["claimed_open_items"]) == 2, compact
- assert len(compact["user_action_items"]) == 3, compact
- assert len(compact["claim_scope"]["other_agent_claimed_items"]) == 2, compact
- first = compact["claimed_open_items"][0]
- assert first["todo_id"] == "todo_payload_000", compact
- assert first["text"].endswith("..."), first
- assert len(first["text"]) <= 180, first
- assert first["title"].endswith("..."), first
- assert len(first["title"]) <= 180, first
- assert "handoff_note" not in first, first
- compaction = compact["payload_compaction"]
- assert compaction["schema_version"] == "quota_todo_summary_payload_compaction_v0", compaction
- assert compaction["compacted_lanes"]["claimed_open_items"] == {
- "shown": 2,
- "total": 12,
- }, compaction
- assert compaction["compacted_lanes"]["user_action_items"] == {
- "shown": 3,
- "total": 4,
- }, compaction
- assert len(json.dumps(compact, ensure_ascii=False, sort_keys=True)) < 5000, compact
-
-
-def main() -> None:
- assert_agent_scoped_user_gate_and_monitor_state()
- assert_project_asset_fallback_and_canonical_precedence()
- assert_project_asset_summary_reuses_canonical_shape()
- assert_agent_due_monitor_survives_claimed_lane_compaction()
- assert_legacy_and_canonical_shared_lanes_stay_in_parity()
- assert_user_gate_hint_detection_is_preserved()
- assert_quota_payload_summary_compacts_hot_path_lanes()
- print("quota todo summary read model smoke passed")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/refresh-state-unique-run-path-smoke.py b/examples/control_plane/refresh-state-unique-run-path-smoke.py
deleted file mode 100644
index de6cb3bfe7..0000000000
--- a/examples/control_plane/refresh-state-unique-run-path-smoke.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test refresh-state path uniqueness on same-second collisions."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
-
-import loopx.state_refresh as state_refresh
-
-
-GOAL_ID = "refresh-state-unique-path-goal"
-GENERATED_AT = "2026-01-01T00:00:00+00:00"
-
-
-def write_fixture(root: Path) -> tuple[Path, Path, Path]:
- project = root / "project"
- runtime = root / "runtime"
- state_file = f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md"
- state_path = project / state_file
- registry_path = project / ".loopx" / "registry.json"
- runs_dir = runtime / "goals" / GOAL_ID / "runs"
-
- state_path.parent.mkdir(parents=True)
- state_path.write_text(
- "---\n"
- "status: active-read-only\n"
- "owner_mode: goal\n"
- 'objective: "Keep refresh-state append-only."\n'
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- "# Refresh State Unique Path Goal\n\n"
- "## Next Action\n\n"
- "- Append a state refresh without overwriting an existing run artifact.\n\n"
- "## Progress Ledger\n\n"
- "- Fixture initialized.\n",
- encoding="utf-8",
- )
- registry_path.parent.mkdir(parents=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": "0.1",
- "updated_at": GENERATED_AT,
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "domain": "refresh-state-fixture",
- "status": "active-read-only",
- "repo": str(project),
- "state_file": state_file,
- "adapter": {"kind": "fixture", "status": "connected-read-only"},
- "authority_sources": [],
- }
- ],
- },
- ensure_ascii=False,
- indent=2,
- )
- + "\n",
- encoding="utf-8",
- )
-
- runs_dir.mkdir(parents=True)
- existing_json = runs_dir / "2026-01-01T00-00-00-00-00.json"
- existing_markdown = runs_dir / "2026-01-01T00-00-00-00-00.md"
- existing_json.write_text('{"existing": true}\n', encoding="utf-8")
- existing_markdown.write_text("# Existing Run\n", encoding="utf-8")
- (runs_dir / "index.jsonl").write_text(
- json.dumps(
- {
- "generated_at": GENERATED_AT,
- "goal_id": GOAL_ID,
- "classification": "evidence_observation_v0",
- "recommended_action": "preserve existing artifact",
- "health_check": "compact evidence event public-safe",
- "json_path": str(existing_json),
- "markdown_path": str(existing_markdown),
- },
- ensure_ascii=False,
- )
- + "\n",
- encoding="utf-8",
- )
- from loopx.control_plane.testing.canary_harness import import_fixture_authority
- import_fixture_authority(registry_path, GOAL_ID, provider="sqlite")
- return registry_path, runtime, project
-
-
-def main() -> None:
- original_now_local = state_refresh.now_local
- try:
- state_refresh.now_local = lambda: GENERATED_AT
- with tempfile.TemporaryDirectory() as raw_tmp:
- registry_path, runtime, project = write_fixture(Path(raw_tmp))
- payload = state_refresh.refresh_state_run(
- registry_path=registry_path,
- runtime_root_override=str(runtime),
- goal_id=GOAL_ID,
- project=project,
- state_file=None,
- classification="state_refreshed",
- recommended_action="append refresh-state collision-free",
- delivery_batch_scale="single_surface",
- delivery_outcome="outcome_progress",
- dry_run=False,
- sync_global=False,
- )
- assert payload["appended"] is True, payload
- json_path = Path(payload["json_path"])
- markdown_path = Path(payload["markdown_path"])
- assert json_path.name == "2026-01-01T00-00-00-00-00-2.json", payload
- assert markdown_path.name == "2026-01-01T00-00-00-00-00-2.md", payload
- assert (runtime / "goals" / GOAL_ID / "runs" / "2026-01-01T00-00-00-00-00.json").read_text(
- encoding="utf-8"
- ) == '{"existing": true}\n'
- records = [
- json.loads(line)
- for line in (runtime / "goals" / GOAL_ID / "runs" / "index.jsonl").read_text(
- encoding="utf-8"
- ).splitlines()
- ]
- assert len(records) == 2, records
- assert records[-1]["json_path"] == str(json_path), records[-1]
- finally:
- state_refresh.now_local = original_now_local
-
- print("refresh-state-unique-run-path-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/review-packet-handoff-delivery-contract-smoke.py b/examples/control_plane/review-packet-handoff-delivery-contract-smoke.py
deleted file mode 100644
index fc6526eaff..0000000000
--- a/examples/control_plane/review-packet-handoff-delivery-contract-smoke.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test Review Packet handoff delivery-contract state transitions."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.handoff.delivery_contract import ( # noqa: E402
- handoff_delivery_contract,
- handoff_delivery_contract_summary,
-)
-
-
-def build_item(*, small_streak: int, outcome_gap_streak: int) -> dict:
- return {
- "project_asset": {
- "execution_profile": {
- "minimum_scale": "implementation",
- "must_include": [
- "implementation_artifact",
- "targeted_validation",
- "state_writeback",
- ],
- "degradation_policy": {
- "small_scale_streak_threshold": 3,
- },
- "outcome_floor": {
- "surface_streak_threshold": 2,
- "must_advance": ["ranker_or_cross_domain_evidence"],
- "avoid": ["queue_only_update"],
- },
- }
- },
- "handoff_readiness": {
- "post_handoff_small_scale_streak": small_streak,
- "post_handoff_outcome_gap_streak": outcome_gap_streak,
- "post_handoff_recent_runs": [
- {"delivery_batch_scale": "test_only"},
- {"delivery_batch_scale": "single_surface"},
- {"delivery_batch_scale": "implementation"},
- ],
- },
- }
-
-
-def assert_below_threshold_is_quiet() -> None:
- assert handoff_delivery_contract(build_item(small_streak=2, outcome_gap_streak=1)) is None
-
-
-def assert_small_scale_contract() -> None:
- contract = handoff_delivery_contract(build_item(small_streak=3, outcome_gap_streak=1))
- assert contract is not None
- assert contract["mode"] == "expand_after_repeated_small_delivery", contract
- assert contract["minimum_scale"] == "implementation", contract
- assert contract["must_include"] == [
- "implementation_artifact",
- "targeted_validation",
- "state_writeback",
- ], contract
- assert contract["recent_scales"] == ["test_only", "single_surface", "implementation"], contract
- summary = handoff_delivery_contract_summary(contract)
- assert summary and "至少 implementation" in summary, summary
- assert "targeted validation、state writeback" in summary, summary
- assert "不 spend" in summary, summary
-
-
-def assert_outcome_floor_contract() -> None:
- contract = handoff_delivery_contract(build_item(small_streak=1, outcome_gap_streak=2))
- assert contract is not None
- assert contract["mode"] == "expand_after_surface_progress_loop", contract
- assert contract["post_handoff_outcome_gap_streak"] == 2, contract
- assert contract["outcome_gap_streak_threshold"] == 2, contract
- summary = handoff_delivery_contract_summary(contract)
- assert summary and "ranker or cross domain evidence" in summary, summary
- assert "queue only update" in summary, summary
- assert "禁止 isolated test/surface-only propagation" in summary, summary
-
-
-def main() -> None:
- assert_below_threshold_is_quiet()
- assert_small_scale_contract()
- assert_outcome_floor_contract()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/run-history-agent-context-retention-smoke.py b/examples/control_plane/run-history-agent-context-retention-smoke.py
deleted file mode 100644
index f7fe0b6673..0000000000
--- a/examples/control_plane/run-history-agent-context-retention-smoke.py
+++ /dev/null
@@ -1,420 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test per-agent vision/replan context survives latest-run truncation."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
-
-from loopx.control_plane.goals.goal_frontier import (
- latest_agent_vision_from_status_payload,
-)
-from loopx.control_plane.goals.goal_frontier.outcome_continuity import (
- acceptance_gaps_from_outcome_checkpoint,
- latest_outcome_vision_checkpoint_from_status_payload,
-)
-from loopx.control_plane.runtime.run_history import build_run_history
-from loopx.history import collect_history
-
-GOAL_ID = "agent-context-retention-goal"
-COORDINATION_PEER = "codex-coordination-peer"
-PRODUCT_PEER = "codex-product-peer"
-TARGET_PEER = "codex-research-peer"
-
-
-def project_run_history(history: dict, *, display_limit: int = 3) -> dict:
- return build_run_history(
- history,
- latest_run=lambda goal: goal.get("latest_status_run"),
- goal_lifecycle_fields=lambda goal, run: {
- "lifecycle_phase": "active",
- "lifecycle_flags": [],
- },
- subagent_activity_for_goal=lambda goal: None,
- compact_run=lambda run: dict(run),
- quota_status=lambda goal: {},
- display_limit=display_limit,
- )
-
-
-def semantic_agent_context(goal: dict, *, agent_id: str) -> dict:
- semantic_history = goal["semantic_history"]
- return next(
- context
- for context in semantic_history["agents"]
- if context["agent_id"] == agent_id
- )
-
-
-def write_fixture(root: Path) -> tuple[Path, Path]:
- runtime = root / "runtime"
- project = root / "project"
- runs_dir = runtime / "goals" / GOAL_ID / "runs"
- runs_dir.mkdir(parents=True)
- registry_path = project / ".loopx" / "registry.json"
- registry_path.parent.mkdir(parents=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": "0.1",
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "status": "active",
- "repo": str(project),
- "state_file": ".local/goals/fixture.md",
- "adapter": {"kind": "fixture", "status": "connected-read-only"},
- "coordination": {
- "agent_model": "peer_v1",
- "registered_agents": [
- COORDINATION_PEER,
- TARGET_PEER,
- PRODUCT_PEER,
- ],
- },
- }
- ],
- },
- ensure_ascii=False,
- ),
- encoding="utf-8",
- )
- runs = [
- ("2026-07-06T00:06:00+00:00", COORDINATION_PEER, "latest coordination"),
- ("2026-07-06T00:05:00+00:00", PRODUCT_PEER, "latest product"),
- ("2026-07-06T00:04:00+00:00", COORDINATION_PEER, "second coordination"),
- (
- "2026-07-06T00:03:00+00:00",
- TARGET_PEER,
- "target peer vision",
- ),
- ("2026-07-06T00:02:00+00:00", TARGET_PEER, "older target peer"),
- ]
- with (runs_dir / "index.jsonl").open("w", encoding="utf-8") as handle:
- for generated_at, agent_id, action in runs:
- record = {
- "generated_at": generated_at,
- "goal_id": GOAL_ID,
- "classification": "state_refreshed",
- "agent_id": agent_id,
- "recommended_action": action,
- "json_path": str(runs_dir / f"{generated_at}.json"),
- "markdown_path": str(runs_dir / f"{generated_at}.md"),
- }
- if action == "target peer vision":
- record["agent_vision"] = {
- "schema_version": "goal_vision_replan_contract_v0",
- "agent_id": TARGET_PEER,
- "state": "active",
- "vision_patch": {
- "acceptance_summary": (
- "Keep the research peer's multi-round work runnable."
- ),
- "replan_trigger_summary": (
- "The research peer's vision would otherwise fall out of the "
- "global run window."
- ),
- },
- }
- record["vision_checkpoint"] = {
- "schema_version": "vision_checkpoint_v0",
- "agent_id": TARGET_PEER,
- "required": True,
- "satisfied": True,
- "decision": "patched",
- }
- if action == "older target peer":
- record["autonomous_replan_ack"] = {
- "schema_version": "autonomous_replan_ack_v0",
- "recorded": True,
- "source": "fixture",
- "semantic_delta": {
- "schema_version": "replan_semantic_delta_v0",
- "accepted": True,
- "outcomes": ["new_runnable_successor"],
- "satisfying_outcomes": ["new_runnable_successor"],
- "obligation_id": "replan-fixture-retained-ack",
- },
- "delta_contract": {
- "schema_version": "repair_delta_contract_v0",
- "required": True,
- "delta_present": True,
- "delta_kinds": ["runnable_todo_set"],
- "auto_evidence": [],
- "accepted_without_delta": False,
- },
- }
- handle.write(json.dumps(record, ensure_ascii=False) + "\n")
- return registry_path, runtime
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(
- prefix="loopx-agent-context-retention-"
- ) as raw_tmp:
- registry_path, runtime = write_fixture(Path(raw_tmp))
- runs_dir = runtime / "goals" / GOAL_ID / "runs"
- with (runs_dir / "index.jsonl").open("a", encoding="utf-8") as handle:
- handle.write(
- json.dumps(
- {
- "generated_at": "2026-07-06T00:07:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "state_refreshed",
- "agent_id": TARGET_PEER,
- "recommended_action": "keep peer vision unchanged",
- "json_path": str(runs_dir / "unchanged-peer-vision.json"),
- "markdown_path": str(runs_dir / "unchanged-peer-vision.md"),
- "vision_checkpoint": {
- "schema_version": "vision_checkpoint_v0",
- "agent_id": TARGET_PEER,
- "required": True,
- "satisfied": True,
- "decision": "unchanged_with_reason",
- "unchanged_reason": "The active peer vision still applies.",
- },
- },
- ensure_ascii=False,
- )
- + "\n"
- )
- history = collect_history(
- registry_path=registry_path,
- runtime_root=runtime,
- goal_id=GOAL_ID,
- limit=3,
- )
- goal = history["goals"][0]
- latest_runs = goal["latest_runs"]
- assert [run["recommended_action"] for run in latest_runs[:3]] == [
- "keep peer vision unchanged",
- "latest coordination",
- "latest product",
- ], latest_runs
- assert len(latest_runs) == 3, latest_runs
- semantic_context = semantic_agent_context(goal, agent_id=TARGET_PEER)
- assert semantic_context["latest_agent_vision_run"]["agent_vision"]
- assert semantic_context["latest_autonomous_replan_ack_run"][
- "autonomous_replan_ack"
- ]
- projected_run_history = project_run_history(history)
- projected_goal = projected_run_history["goals"][0]
- projected_runs = projected_goal["latest_runs"]
- assert len(projected_runs) == 3, projected_runs
- projected_context = semantic_agent_context(
- projected_goal,
- agent_id=TARGET_PEER,
- )
- assert projected_context["latest_agent_vision_run"]["agent_vision"]
- assert projected_context["latest_autonomous_replan_ack_run"][
- "autonomous_replan_ack"
- ]
- vision = latest_agent_vision_from_status_payload(
- {"run_history": projected_run_history},
- goal_id=GOAL_ID,
- agent_id=TARGET_PEER,
- )
- assert vision and vision["agent_id"] == TARGET_PEER, vision
- assert (
- "global run window" in vision["vision_patch"]["replan_trigger_summary"]
- ), vision
-
- zero_budget_history = collect_history(
- registry_path=registry_path,
- runtime_root=runtime,
- goal_id=GOAL_ID,
- limit=0,
- )
- assert zero_budget_history["goals"][0]["latest_runs"] == [], zero_budget_history
- zero_budget_projection = project_run_history(history, display_limit=0)
- assert zero_budget_projection["goals"][0]["latest_runs"] == [], (
- zero_budget_projection
- )
- assert semantic_agent_context(
- zero_budget_projection["goals"][0],
- agent_id=TARGET_PEER,
- )["latest_agent_vision_run"]["agent_vision"]
- with tempfile.TemporaryDirectory(prefix="loopx-agent-context-retired-") as raw_tmp:
- registry_path, runtime = write_fixture(Path(raw_tmp))
- runs_dir = runtime / "goals" / GOAL_ID / "runs"
- with (runs_dir / "index.jsonl").open("a", encoding="utf-8") as handle:
- handle.write(
- json.dumps(
- {
- "generated_at": "2026-07-06T00:07:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "state_refreshed",
- "agent_id": TARGET_PEER,
- "recommended_action": "retire peer vision",
- "json_path": str(runs_dir / "retired-peer-vision.json"),
- "markdown_path": str(runs_dir / "retired-peer-vision.md"),
- "vision_checkpoint": {
- "schema_version": "vision_checkpoint_v0",
- "agent_id": TARGET_PEER,
- "required": True,
- "satisfied": True,
- "decision": "retired_or_superseded",
- },
- },
- ensure_ascii=False,
- )
- + "\n"
- )
- history = collect_history(
- registry_path=registry_path,
- runtime_root=runtime,
- goal_id=GOAL_ID,
- limit=3,
- )
- latest_runs = history["goals"][0]["latest_runs"]
- assert [run["recommended_action"] for run in latest_runs[:3]] == [
- "retire peer vision",
- "latest coordination",
- "latest product",
- ], latest_runs
- assert not any(
- run.get("agent_id") == TARGET_PEER and run.get("agent_vision")
- for run in latest_runs
- ), latest_runs
- assert (
- semantic_agent_context(
- history["goals"][0],
- agent_id=TARGET_PEER,
- )["vision_retired_at"]
- == "2026-07-06T00:07:00+00:00"
- )
- projected_run_history = project_run_history(history)
- projected_runs = projected_run_history["goals"][0]["latest_runs"]
- assert not any(
- run.get("agent_id") == TARGET_PEER and run.get("agent_vision")
- for run in projected_runs
- ), projected_runs
- vision = latest_agent_vision_from_status_payload(
- {"run_history": projected_run_history},
- goal_id=GOAL_ID,
- agent_id=TARGET_PEER,
- )
- assert vision is None, vision
- with tempfile.TemporaryDirectory(prefix="loopx-semantic-long-thread-") as raw_tmp:
- registry_path, runtime = write_fixture(Path(raw_tmp))
- runs_dir = runtime / "goals" / GOAL_ID / "runs"
- with (runs_dir / "index.jsonl").open("a", encoding="utf-8") as handle:
- semantic_runs = [
- {
- "generated_at": "2026-07-08T00:00:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "state_refreshed",
- "agent_id": TARGET_PEER,
- "recommended_action": "plain refresh",
- "vision_checkpoint": {
- "schema_version": "vision_checkpoint_v0",
- "agent_id": TARGET_PEER,
- "required": False,
- "satisfied": True,
- "decision": "not_required",
- "triggers": [{"kind": "heartbeat_refresh"}],
- },
- },
- *[
- {
- "generated_at": f"2026-07-07T00:00:{second:02d}+00:00",
- "goal_id": GOAL_ID,
- "classification": "quota_slot_spent",
- "agent_id": TARGET_PEER,
- "recommended_action": "neutral heartbeat accounting",
- }
- for second in range(30)
- ],
- {
- "generated_at": "2026-07-06T02:00:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "human_reward_recorded",
- "agent_id": TARGET_PEER,
- "human_reward": {
- "recorded_at": "2026-07-06T02:00:00+00:00",
- "decision": "correct_direction",
- "reward": "positive",
- "reason_summary": "Keep final-outcome evidence authoritative.",
- },
- },
- {
- "generated_at": "2026-07-06T01:00:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "milestone_closeout",
- "agent_id": TARGET_PEER,
- "delivery_outcome": "outcome_progress",
- "vision_checkpoint": {
- "schema_version": "vision_checkpoint_v0",
- "agent_id": TARGET_PEER,
- "required": True,
- "satisfied": True,
- "decision": "unchanged_with_reason",
- "triggers": [
- {
- "kind": "material_delivery_outcome",
- "delivery_outcome": "outcome_progress",
- }
- ],
- },
- },
- ]
- for semantic_run in semantic_runs:
- handle.write(json.dumps(semantic_run, ensure_ascii=False) + "\n")
-
- history = collect_history(
- registry_path=registry_path,
- runtime_root=runtime,
- goal_id=GOAL_ID,
- limit=30,
- )
- projected_run_history = project_run_history(history, display_limit=30)
- projected_goal = projected_run_history["goals"][0]
- assert len(projected_goal["latest_runs"]) == 30, projected_goal
- context = semantic_agent_context(projected_goal, agent_id=TARGET_PEER)
- assert (
- context["latest_vision_checkpoint_run"]["vision_checkpoint"]["decision"]
- == "not_required"
- )
- assert (
- context["latest_outcome_vision_checkpoint_run"]["vision_checkpoint"][
- "triggers"
- ][0]["delivery_outcome"]
- == "outcome_progress"
- )
- assert context["latest_material_milestone_run"]["delivery_outcome"] == (
- "outcome_progress"
- )
- assert (
- projected_goal["semantic_history"]["latest_owner_correction_run"][
- "human_reward"
- ]["decision"]
- == "correct_direction"
- )
- assert "quota_slot_spent" not in json.dumps(
- projected_goal["semantic_history"],
- ensure_ascii=False,
- )
- status = {"run_history": projected_run_history}
- vision = latest_agent_vision_from_status_payload(
- status,
- goal_id=GOAL_ID,
- agent_id=TARGET_PEER,
- )
- checkpoint = latest_outcome_vision_checkpoint_from_status_payload(
- status,
- goal_id=GOAL_ID,
- agent_id=TARGET_PEER,
- )
- gaps = acceptance_gaps_from_outcome_checkpoint(vision, checkpoint)
- assert len(gaps) == 1, gaps
- assert gaps[0]["kind"] == "vision_outcome_checkpoint_required", gaps
- print("run-history-agent-context-retention-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/runtime-freshness-warning-readmodel-smoke.py b/examples/control_plane/runtime-freshness-warning-readmodel-smoke.py
deleted file mode 100644
index a20da89660..0000000000
--- a/examples/control_plane/runtime-freshness-warning-readmodel-smoke.py
+++ /dev/null
@@ -1,159 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test runtime freshness warnings shared by quota and review packets."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.runtime.decision_freshness import ( # noqa: E402
- DECISION_FRESHNESS_WARNING_ITEM_LIMIT,
- decision_freshness_warning,
-)
-from loopx.control_plane.runtime.promotion_readiness import ( # noqa: E402
- promotion_readiness_warning,
-)
-from loopx.review_packet import decision_freshness_packet_lines # noqa: E402
-
-
-TARGET_GOAL = "loopx-meta"
-OTHER_GOAL = "other-goal"
-
-
-def decision_item(index: int, *, goal_id: str, requires_rebase: bool = True) -> dict:
- return {
- "goal_id": goal_id,
- "decision_kind": f"human_reward_{index}",
- "freshness_state": "stale_rebase_required" if requires_rebase else "fresh",
- "decision_at": f"2026-01-0{index}T00:00:00+00:00",
- "classification": "human_reward",
- "age_days": 10 + index,
- "newer_event_count_7d": index,
- "requires_decision_point_rebase": requires_rebase,
- "reason": "decision older than freshness window; rebase at decision point",
- }
-
-
-def assert_decision_freshness_warning() -> None:
- status_payload = {
- "decision_freshness_summary": {
- "source": "run_history",
- "window_days": 7,
- "summary": {
- "rebase_required_count": 6,
- "stale_count": 4,
- },
- "items": [
- decision_item(1, goal_id=TARGET_GOAL),
- decision_item(2, goal_id=OTHER_GOAL),
- decision_item(3, goal_id=TARGET_GOAL, requires_rebase=False),
- decision_item(4, goal_id=TARGET_GOAL),
- decision_item(5, goal_id=TARGET_GOAL),
- decision_item(6, goal_id=TARGET_GOAL),
- ],
- }
- }
-
- warning = decision_freshness_warning(status_payload, goal_id=TARGET_GOAL)
- assert warning is not None, warning
- assert warning["source"] == "run_history", warning
- assert warning["window_days"] == 7, warning
- assert warning["rebase_required_count"] == 4, warning
- assert warning["global_rebase_required_count"] == 6, warning
- assert warning["global_stale_count"] == 4, warning
- assert len(warning["items"]) == DECISION_FRESHNESS_WARNING_ITEM_LIMIT, warning
- assert {item["goal_id"] for item in warning["items"]} == {TARGET_GOAL}, warning
- assert [item["decision_kind"] for item in warning["items"]] == [
- "human_reward_1",
- "human_reward_4",
- "human_reward_5",
- ], warning
- assert "rebase required" in warning["message"], warning
-
- packet_warning = decision_freshness_warning(
- status_payload,
- goal_id=TARGET_GOAL,
- message="旧 reward/gate 决策复用前需重新对齐。",
- )
- packet_lines = decision_freshness_packet_lines(packet_warning)
- assert "【决策 freshness 警告】" in "\n".join(packet_lines), packet_lines
- assert "旧 reward/gate 决策复用前需重新对齐。" in "\n".join(packet_lines), packet_lines
-
- assert decision_freshness_warning(status_payload, goal_id="fresh-only-goal") is None
- assert decision_freshness_warning({"decision_freshness_summary": {"items": []}}, goal_id=TARGET_GOAL) is None
-
-
-def assert_promotion_readiness_warning() -> None:
- fresh_status = {
- "promotion_readiness_summary": {
- "available": True,
- "source": "run_history",
- "freshness_status": "fresh",
- "requires_readiness_run": False,
- "freshness_window_hours": 24,
- }
- }
- assert promotion_readiness_warning(fresh_status) is None
-
- stale_status = {
- "promotion_readiness_summary": {
- "available": True,
- "source": "run_history_full_scan",
- "freshness_status": "stale",
- "requires_readiness_run": True,
- "freshness_window_hours": 24,
- "age_hours": 31.5,
- "sample_run_count": 2,
- "goal_id": TARGET_GOAL,
- "generated_at": "2026-01-01T00:00:00+00:00",
- "classification": "canary_promotion_readiness_smoke_group",
- "json_exists": True,
- "markdown_exists": True,
- "reason": "latest canary promotion readiness run is stale",
- }
- }
- warning = promotion_readiness_warning(stale_status)
- assert warning is not None, warning
- assert warning["source"] == "run_history_full_scan", warning
- assert warning["freshness_status"] == "stale", warning
- assert warning["requires_readiness_run"] is True, warning
- assert warning["goal_id"] == TARGET_GOAL, warning
- assert warning["json_exists"] is True, warning
- assert warning["message"].endswith(
- "python3 examples/canary/canary-promotion-readiness-smoke.py"
- ), warning
- assert "--no-write-evidence" not in warning["message"], warning
-
- missing_status = {
- "promotion_readiness_summary": {
- "available": False,
- "source": "run_history",
- "freshness_status": "unknown",
- "requires_readiness_run": True,
- "reason": "no canary promotion readiness run found in sampled history",
- }
- }
- missing_warning = promotion_readiness_warning(missing_status)
- assert missing_warning is not None, missing_warning
- assert missing_warning["available"] is False, missing_warning
- assert missing_warning["reason"] == "no canary promotion readiness run found in sampled history"
- assert missing_warning["message"].endswith(
- "python3 examples/canary/canary-promotion-readiness-smoke.py"
- ), missing_warning
- assert "--no-write-evidence" not in missing_warning["message"], missing_warning
-
-
-def main() -> int:
- assert_decision_freshness_warning()
- assert_promotion_readiness_warning()
- print("runtime-freshness-warning-readmodel-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/runtime-stale-latest-run-readmodel-smoke.py b/examples/control_plane/runtime-stale-latest-run-readmodel-smoke.py
deleted file mode 100644
index 3f9c2e14e0..0000000000
--- a/examples/control_plane/runtime-stale-latest-run-readmodel-smoke.py
+++ /dev/null
@@ -1,146 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test stale latest-run freshness as a runtime read model."""
-
-from __future__ import annotations
-
-from datetime import datetime, timezone
-import hashlib
-import sys
-import tempfile
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.goals.active_state_metadata import parse_state_frontmatter # noqa: E402
-from loopx.control_plane.runtime.stale_latest_run import ( # noqa: E402
- stale_latest_run_projection_warning,
-)
-
-
-AGENT_LANE_PROGRESS_SCOPE = "agent_lane"
-
-
-def parse_timestamp(value: Any) -> datetime | None:
- if not value:
- return None
- try:
- parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
- except ValueError:
- return None
- if parsed.tzinfo is None:
- return parsed.replace(tzinfo=timezone.utc)
- return parsed
-
-
-def resolve_goal_local_path(raw: Any, goal: dict[str, Any]) -> Path | None:
- if not raw:
- return None
- path = Path(str(raw))
- if path.is_absolute():
- return path
- repo = goal.get("repo")
- return (Path(str(repo)) if repo else Path.cwd()) / path
-
-
-def state_text(updated_at: str, body: str) -> str:
- return (
- "---\n"
- "status: active\n"
- f"updated_at: {updated_at}\n"
- "---\n\n"
- "# Active State\n\n"
- f"{body}\n"
- )
-
-
-def digest(text: str) -> str:
- return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
-
-
-def warning_for(goal: dict[str, Any], current_run: dict[str, Any]) -> dict[str, Any] | None:
- return stale_latest_run_projection_warning(
- goal,
- current_run,
- agent_lane_progress_scope=AGENT_LANE_PROGRESS_SCOPE,
- resolve_goal_local_path=resolve_goal_local_path,
- parse_state_frontmatter=parse_state_frontmatter,
- parse_timestamp=parse_timestamp,
- )
-
-
-def base_goal(project: Path, state_file: str, runs: list[dict[str, Any]] | None = None) -> dict[str, Any]:
- return {
- "id": "runtime-freshness",
- "registry_member": True,
- "repo": str(project),
- "state_file": state_file,
- "latest_runs": runs or [],
- }
-
-
-def main() -> int:
- with tempfile.TemporaryDirectory(prefix="loopx-runtime-stale-latest-run-") as tmp:
- project = Path(tmp) / "project"
- state_file = ".codex/goals/runtime-freshness/ACTIVE_GOAL_STATE.md"
- state_path = project / state_file
- state_path.parent.mkdir(parents=True, exist_ok=True)
-
- old_text = state_text("2026-01-01T00:01:00+00:00", "old snapshot")
- active_text = state_text("2026-01-01T00:03:00+00:00", "new active state")
- state_path.write_text(active_text, encoding="utf-8")
- stale_status_run = {
- "classification": "state_refreshed",
- "generated_at": "2026-01-01T00:02:00+00:00",
- "state": {
- "sha256_16": digest(old_text),
- "frontmatter": {"updated_at": "2026-01-01T00:01:00+00:00"},
- },
- }
-
- warning = warning_for(base_goal(project, state_file), stale_status_run)
- assert warning is not None, warning
- assert warning["requires_refresh_state"] is True, warning
- assert warning["active_state_updated_at"] == "2026-01-01T00:03:00+00:00", warning
- assert warning["latest_run_generated_at"] == "2026-01-01T00:02:00+00:00", warning
- assert "active_state_updated_after_latest_run" in warning["reason"], warning
- assert "active_state_updated_after_latest_run_snapshot" in warning["reason"], warning
- assert "active_state_digest_differs_from_latest_run_snapshot" in warning["reason"], warning
-
- agent_lane_current = {
- "classification": "side_lane_refresh",
- "generated_at": "2026-01-01T00:03:30+00:00",
- "progress_scope": AGENT_LANE_PROGRESS_SCOPE,
- "state": {
- "sha256_16": digest(active_text),
- "frontmatter": {"updated_at": "2026-01-01T00:03:00+00:00"},
- },
- }
- assert warning_for(base_goal(project, state_file, [agent_lane_current]), stale_status_run) is None
-
- agent_lane_stale = {
- "classification": "side_lane_old_refresh",
- "generated_at": "2026-01-01T00:02:30+00:00",
- "progress_scope": AGENT_LANE_PROGRESS_SCOPE,
- "state": {
- "sha256_16": digest(old_text),
- "frontmatter": {"updated_at": "2026-01-01T00:01:00+00:00"},
- },
- }
- stale_lane_warning = warning_for(base_goal(project, state_file, [agent_lane_stale]), stale_status_run)
- assert stale_lane_warning is not None, stale_lane_warning
- assert stale_lane_warning["requires_refresh_state"] is True, stale_lane_warning
-
- non_registry_goal = base_goal(project, state_file)
- non_registry_goal["registry_member"] = False
- assert warning_for(non_registry_goal, stale_status_run) is None
-
- print("runtime-stale-latest-run-readmodel-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/stale-primary-successor-model-behavior-qualification.py b/examples/control_plane/stale-primary-successor-model-behavior-qualification.py
deleted file mode 100644
index 17a4348769..0000000000
--- a/examples/control_plane/stale-primary-successor-model-behavior-qualification.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env python3
-"""Qualify that the live weak/default model leaves a stale open primary.
-
-This is a credentialed live qualification, not a public smoke-suite check.
-"""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.testing.selected_todo_tool_behavior import ( # noqa: E402
- SELECTED_TODO_TOOL_FIXTURE_TODO_ID,
- DoubaoSelectedTodoToolBehaviorActor,
-)
-
-ATTEMPTS_REQUIRED = 3
-
-
-def main() -> int:
- actor = DoubaoSelectedTodoToolBehaviorActor.from_environment()
- with tempfile.TemporaryDirectory(prefix="loopx-stale-primary-") as root:
- receipts = [
- actor.qualify(
- qualification_id=(
- "stale-done-primary-visible-successor-live-v0-"
- f"attempt-{attempt}"
- ),
- fixture_root=Path(root) / f"attempt-{attempt}",
- stale_done_primary_successor=True,
- )
- for attempt in range(1, ATTEMPTS_REQUIRED + 1)
- ]
- passed = all(
- receipt.get("qualification_passed") is True
- and receipt.get("selected_todo_id") == SELECTED_TODO_TOOL_FIXTURE_TODO_ID
- for receipt in receipts
- )
- summary = {
- "schema_version": "stale_primary_successor_model_behavior_qualification_v0",
- "qualification_passed": passed,
- "attempts_required": ATTEMPTS_REQUIRED,
- "attempts_completed": len(receipts),
- "actor_refs": sorted({str(receipt["actor_ref"]) for receipt in receipts}),
- "selected_todo_ids": [receipt.get("selected_todo_id") for receipt in receipts],
- "observed_tool_sequences": [
- receipt.get("observed_tool_sequence") for receipt in receipts
- ],
- "failure_codes": [
- receipt.get("failure_code")
- for receipt in receipts
- if receipt.get("failure_code") is not None
- ],
- "boundary": {
- "raw_prompts_persisted": False,
- "raw_provider_responses_persisted": False,
- "external_writes_executed": False,
- "fixture_writes_temporary": True,
- },
- }
- print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
- return 0 if passed else 1
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/examples/control_plane/status-contract-readmodel-smoke.py b/examples/control_plane/status-contract-readmodel-smoke.py
deleted file mode 100644
index 7db310fe5d..0000000000
--- a/examples/control_plane/status-contract-readmodel-smoke.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test status contract read-model parity."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.work_items import status_contract as status_contract_read_model # noqa: E402
-
-
-def direct_status_contract() -> dict[str, Any]:
- return status_contract_read_model.build_status_contract(
- schema_version=status_module.STATUS_CONTRACT_SCHEMA_VERSION,
- minimum_dashboard_schema_version=status_module.MINIMUM_DASHBOARD_STATUS_CONTRACT_SCHEMA_VERSION,
- reload_hint=status_module.STATUS_CONTRACT_RELOAD_HINT,
- )
-
-
-def direct_compact_signals(value: Any, *, limit: int | None = None) -> dict[str, Any]:
- return status_contract_read_model.compact_status_contract_signals(
- value,
- limit=status_module.STATUS_CONTRACT_SIGNAL_LIMIT if limit is None else limit,
- )
-
-
-def direct_contract_health(contract: dict[str, Any]) -> dict[str, Any]:
- return status_contract_read_model.build_contract_health_projection(
- contract,
- signal_limit=status_module.STATUS_CONTRACT_SIGNAL_LIMIT,
- )
-
-
-def main() -> None:
- assert status_module.build_status_contract() == direct_status_contract()
-
- signals = [" first ", "", None, "second", "third"]
- assert direct_compact_signals(signals, limit=2) == {
- "items": ["first", "None"],
- "total_count": 4,
- "truncated": True,
- }
- assert direct_compact_signals(signals, limit=0) == {
- "items": [],
- "total_count": 4,
- "truncated": True,
- }
-
- contract = {
- "summary": {"errors": 3, "warnings": 2, "checks": 5},
- "errors": ["error-a", "error-b", "error-c"],
- "warnings": ["warning-a", "warning-b"],
- }
- assert status_module.build_contract_health_projection(contract) == direct_contract_health(contract)
-
- empty_contract = {"summary": {"errors": 0, "warnings": 0, "checks": 1}}
- assert status_module.build_contract_health_projection(empty_contract) == direct_contract_health(empty_contract)
-
- print("status-contract-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/status-global-registry-markdown-smoke.py b/examples/control_plane/status-global-registry-markdown-smoke.py
deleted file mode 100644
index 970adce07d..0000000000
--- a/examples/control_plane/status-global-registry-markdown-smoke.py
+++ /dev/null
@@ -1,63 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test global registry status markdown rendering."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.presentation.renderers.status_markdown import render_status_markdown # noqa: E402
-
-
-def main() -> None:
- markdown = render_status_markdown(
- {
- "ok": False,
- "registry": "./fixtures/registry.json",
- "runtime_root": "./fixtures/runtime",
- "goal_count": 1,
- "run_count": 1,
- "contract": {
- "ok": True,
- "summary": {"errors": 0, "warnings": 0, "checks": 8},
- },
- "global_registry": {
- "available": True,
- "ok": False,
- "summary": {"findings": 2, "high": 1, "action": 1, "info": 0},
- "findings": [
- {
- "severity": "action",
- "kind": "source_registry_missing",
- "goal_id": "fixture-goal",
- "message": "registry source missing",
- "recommended_action": "sync the source registry",
- },
- {
- "severity": "info",
- "kind": "global_registry_shadow",
- "goal_ids": ["shadow-a", "shadow-b"],
- "message": "shadow finding compacted",
- },
- ],
- },
- "attention_queue": {"items": []},
- "run_history": {"goals": []},
- }
- )
-
- assert "global_registry: available=True, ok=False, findings=2" in markdown, markdown
- assert "## Global Registry Findings" in markdown, markdown
- assert "action source_registry_missing goal=fixture-goal: registry source missing" in markdown, markdown
- assert "action: sync the source registry" in markdown, markdown
- assert "info global_registry_shadow goal=['shadow-a', 'shadow-b']: shadow finding compacted" in markdown, markdown
- print("status-global-registry-markdown-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/status-neutral-run-window-smoke.py b/examples/control_plane/status-neutral-run-window-smoke.py
deleted file mode 100644
index 1aaea8d4b5..0000000000
--- a/examples/control_plane/status-neutral-run-window-smoke.py
+++ /dev/null
@@ -1,388 +0,0 @@
-#!/usr/bin/env python3
-"""Regression for status/diagnose after consecutive status-neutral runs."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.diagnose import collect_diagnosis # noqa: E402
-from loopx.control_plane.scheduler.execution_context import ( # noqa: E402
- GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT,
-)
-from loopx.quota import ( # noqa: E402
- QUOTA_MONITOR_POLL_CLASSIFICATION,
- QUOTA_SLOT_SPENT_CLASSIFICATION,
- QUOTA_SLOT_VOIDED_CLASSIFICATION,
- build_quota_should_run,
-)
-from loopx.status import collect_status # noqa: E402
-
-
-GOAL_ID = "neutral-window-connected-delivery"
-AGENT_LANE_GOAL_ID = "neutral-window-agent-lane-recommendation"
-AGENT_ID = "codex-main-control"
-REAL_CLASSIFICATION = "autonomous_replan_recorded_stable_monitor"
-REAL_ACTION = "Quiet monitor only until a material stable monitor transition appears."
-DISPLAY_ACTION = (
- "No immediate agent work; keep the monitor quiet until a material stable monitor transition appears."
-)
-AGENT_TODO = (
- "[P1] Monitor the stable signal; write back only a material transition, regression, or blocker."
-)
-STALE_GOAL_ACTION = "Stale docs-governance cap action."
-AGENT_LANE_ACTION = (
- "Closed stale docs-governance cap; continue with next projected runnable todo."
-)
-AGENT_LANE_TODO = "[P2-repair] Align quota/status recommended-action projection."
-
-
-def write_registry(root: Path) -> Path:
- project = root / "project"
- runtime = root / "runtime"
- state_file = f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md"
- registry_path = project / ".loopx" / "registry.json"
-
- (project / Path(state_file).parent).mkdir(parents=True, exist_ok=True)
- (project / state_file).write_text(
- "---\n"
- "status: active\n"
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- "# Neutral Window Fixture\n\n"
- "## Agent Todo\n\n"
- f"- [ ] {AGENT_TODO}\n"
- " \n",
- encoding="utf-8",
- )
- registry_path.parent.mkdir(parents=True, exist_ok=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": 1,
- "updated_at": "2026-01-01T00:00:00+00:00",
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "domain": "status-neutral-window-fixture",
- "status": "active",
- "repo": str(project),
- "state_file": state_file,
- "adapter": {
- "kind": "fixture_connected_delivery_v0",
- "status": "connected-delivery",
- },
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- },
- "coordination": {
- "write_scope": ["docs/**"],
- },
- }
- ],
- },
- indent=2,
- sort_keys=True,
- )
- + "\n",
- encoding="utf-8",
- )
- from loopx.control_plane.testing.canary_harness import import_fixture_authority
-
- import_fixture_authority(registry_path, GOAL_ID, provider="sqlite")
- return registry_path
-
-
-def write_agent_lane_registry(root: Path) -> Path:
- project = root / "project"
- runtime = root / "runtime"
- state_file = f".codex/goals/{AGENT_LANE_GOAL_ID}/ACTIVE_GOAL_STATE.md"
- registry_path = project / ".loopx" / "registry.json"
-
- (project / Path(state_file).parent).mkdir(parents=True, exist_ok=True)
- (project / state_file).write_text(
- "---\n"
- "status: active\n"
- "updated_at: 2026-01-01T00:03:00+00:00\n"
- "---\n\n"
- "# Agent Lane Recommendation Fixture\n\n"
- "## Next Action\n\n"
- "Implement broad primary app-server guard.\n\n"
- "## Agent Todo\n\n"
- f"- [ ] {AGENT_LANE_TODO}\n"
- " \n",
- encoding="utf-8",
- )
- registry_path.parent.mkdir(parents=True, exist_ok=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": 1,
- "updated_at": "2026-01-01T00:00:00+00:00",
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": AGENT_LANE_GOAL_ID,
- "domain": "status-neutral-window-agent-lane-fixture",
- "status": "active",
- "repo": str(project),
- "state_file": state_file,
- "adapter": {
- "kind": "fixture_connected_delivery_v0",
- "status": "connected-delivery",
- },
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- },
- "coordination": {
- "agent_model": "peer_v1",
- "registered_agents": [AGENT_ID],
- "write_scope": ["loopx/**", "examples/**"],
- },
- }
- ],
- },
- indent=2,
- sort_keys=True,
- )
- + "\n",
- encoding="utf-8",
- )
- from loopx.control_plane.testing.canary_harness import import_fixture_authority
-
- import_fixture_authority(registry_path, AGENT_LANE_GOAL_ID, provider="sqlite")
- return registry_path
-
-
-def append_run(
- root: Path,
- *,
- generated_at: str,
- classification: str,
- action: str,
- goal_id: str = GOAL_ID,
- **extra: object,
-) -> None:
- run_dir = root / "runtime" / "goals" / goal_id / "runs"
- run_dir.mkdir(parents=True, exist_ok=True)
- compact_time = generated_at.replace("-", "").replace(":", "")
- json_path = run_dir / f"{compact_time}-{classification}.json"
- markdown_path = run_dir / f"{compact_time}-{classification}.md"
- record = {
- "generated_at": generated_at,
- "goal_id": goal_id,
- "classification": classification,
- "recommended_action": action,
- "health_check": "status-neutral-window fixture run",
- "delivery_batch_scale": "single_surface",
- "delivery_outcome": "outcome_progress",
- }
- record.update(extra)
- json_path.write_text(json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- markdown_path.write_text(f"# {classification}\n", encoding="utf-8")
- with (run_dir / "index.jsonl").open("a", encoding="utf-8") as f:
- f.write(
- json.dumps(
- {
- **record,
- "json_path": str(json_path),
- "markdown_path": str(markdown_path),
- },
- ensure_ascii=False,
- )
- + "\n"
- )
-
-
-def write_runs(root: Path) -> None:
- append_run(
- root,
- generated_at="2026-01-01T00:00:00+00:00",
- classification=REAL_CLASSIFICATION,
- action=REAL_ACTION,
- )
- for index in range(1, 7):
- append_run(
- root,
- generated_at=f"2026-01-01T00:0{index}:00+00:00",
- classification=QUOTA_MONITOR_POLL_CLASSIFICATION,
- action="monitor poll only; no status transition",
- )
- append_run(
- root,
- generated_at="2026-01-01T00:07:00+00:00",
- classification=QUOTA_SLOT_SPENT_CLASSIFICATION,
- action="quota accounting only; no status transition",
- )
- append_run(
- root,
- generated_at="2026-01-01T00:08:00+00:00",
- classification=QUOTA_SLOT_VOIDED_CLASSIFICATION,
- action="quota void accounting only; no status transition",
- )
-
-
-def write_agent_lane_runs(root: Path) -> None:
- append_run(
- root,
- goal_id=AGENT_LANE_GOAL_ID,
- generated_at="2026-01-01T00:01:00+00:00",
- classification="stale_goal_status",
- action=STALE_GOAL_ACTION,
- )
- append_run(
- root,
- goal_id=AGENT_LANE_GOAL_ID,
- generated_at="2026-01-01T00:04:00+00:00",
- classification="stale_projected_todo_closed",
- action=AGENT_LANE_ACTION,
- progress_scope="agent_lane",
- agent_id=AGENT_ID,
- delivery_batch_scale="test_only",
- )
- append_run(
- root,
- goal_id=AGENT_LANE_GOAL_ID,
- generated_at="2026-01-01T00:05:00+00:00",
- classification=QUOTA_SLOT_SPENT_CLASSIFICATION,
- action="quota accounting only; no status transition",
- agent_id=AGENT_ID,
- )
-
-
-def main() -> int:
- with tempfile.TemporaryDirectory(prefix="loopx-status-neutral-window-") as tmp:
- root = Path(tmp)
- registry_path = write_registry(root)
- write_runs(root)
-
- status = collect_status(
- registry_path=registry_path,
- runtime_root_override=str(root / "runtime"),
- limit=5,
- )
- item = status["attention_queue"]["items"][0]
- assert item["goal_id"] == GOAL_ID, item
- assert item["status"] == REAL_CLASSIFICATION, item
- assert item["waiting_on"] == "monitor_signal", item
- assert item["severity"] == "watch", item
- assert item["execution_waiting_on"] == "codex", item
- assert item["source"] == "latest_run", item
- assert item["recommended_action"] == DISPLAY_ACTION, item
- assert item["monitor_display"]["no_immediate_agent_work"] is True, item
- project_asset = item["project_asset"]
- assert project_asset["owner"] == "monitor_signal", project_asset
- assert project_asset["support_mode"] == "read_only_observer", project_asset
- assert status["attention_queue"]["needs_codex"] == 0, status["attention_queue"]
- assert status["attention_queue"]["watching_monitor"] == 1, status["attention_queue"]
- assert status["attention_queue"]["autonomous_monitor_candidates"]["open_count"] == 1, (
- status["attention_queue"]
- )
- assert "connect an adapter" not in item["recommended_action"], item
-
- run_goal = status["run_history"]["goals"][0]
- assert run_goal["latest_status_run"]["classification"] == REAL_CLASSIFICATION, run_goal
- assert len(run_goal["latest_runs"]) == 5, run_goal
- latest_classifications = {run["classification"] for run in run_goal["latest_runs"]}
- assert QUOTA_MONITOR_POLL_CLASSIFICATION in latest_classifications, run_goal
- assert QUOTA_SLOT_SPENT_CLASSIFICATION in latest_classifications, run_goal
- assert QUOTA_SLOT_VOIDED_CLASSIFICATION in latest_classifications, run_goal
-
- readiness = item["handoff_readiness"]
- assert readiness["post_handoff_latest_run"]["classification"] == REAL_CLASSIFICATION, readiness
-
- quota = build_quota_should_run(
- status,
- goal_id=GOAL_ID,
- scheduler_execution_context=(
- GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT
- ),
- )
- assert quota["state"] != "operator_gate", quota
- assert quota["effective_action"] == "normal_run", quota
- assert quota["actionable_by_codex"] is True, quota
- lane = quota["work_lane_contract"]
- assert lane["lane"] == "advancement_task", lane
- assert lane["next_lane"] == "continuous_monitor", lane
- assert lane["obligation"] == "repair_monitor_schedule_metadata", lane
- assert lane["monitor_policy"] == "repair_schedule_metadata_before_quiet_wait", lane
- assert lane["monitor_schedule_gap_count"] == 1, lane
- assert quota["requires_user_action"] is False, quota
- user_todo_summary = quota.get("user_todo_summary") if isinstance(quota.get("user_todo_summary"), dict) else {}
- assert user_todo_summary.get("open_count", 0) == 0, quota
- assert quota["status"] == REAL_CLASSIFICATION, quota
- assert quota["waiting_on"] == "monitor_signal", quota
- assert "connect an adapter" not in quota["recommended_action"], quota
- assert quota["recommended_action"] == DISPLAY_ACTION, quota
- assert quota["interaction_contract"]["agent_channel"]["must_attempt"] is True, quota
- assert quota["interaction_contract"]["agent_channel"]["quiet_noop_allowed"] is False, quota
- assert (
- quota["handoff_readiness"]["post_handoff_latest_run"]["classification"]
- == REAL_CLASSIFICATION
- ), quota
-
- diagnosis = collect_diagnosis(
- registry_path=registry_path,
- runtime_root_override=str(root / "runtime"),
- limit=5,
- goal_id=GOAL_ID,
- )
- selected = diagnosis["selected"]
- assert selected["status"] == REAL_CLASSIFICATION, selected
- assert selected["waiting_on"] == "monitor_signal", selected
- assert selected["severity"] == "watch", selected
- assert selected["machine_signal"] == "agent_work_attention", selected
- assert selected["quota_signals"]["effective_action"] == "normal_run", selected
- assert selected["work_lane_contract"]["obligation"] == "repair_monitor_schedule_metadata", selected
- assert selected["todo_evidence"]["user_open_count"] == 0, selected
-
- with tempfile.TemporaryDirectory(prefix="loopx-status-neutral-agent-lane-") as tmp:
- root = Path(tmp)
- registry_path = write_agent_lane_registry(root)
- write_agent_lane_runs(root)
-
- status = collect_status(
- registry_path=registry_path,
- runtime_root_override=str(root / "runtime"),
- limit=5,
- )
- item = status["attention_queue"]["items"][0]
- assert item["goal_id"] == AGENT_LANE_GOAL_ID, item
- assert item["status"] == "stale_goal_status", item
- assert item["latest_run_recommended_action"] == STALE_GOAL_ACTION, item
- assert item["latest_run_recommended_action_source"] == "latest_status_run", item
- assert item["agent_lane_recommendation"]["agent_id"] == AGENT_ID, item
- assert item["agent_lane_recommendation"]["recommended_action"] == AGENT_LANE_ACTION, item
-
- quota = build_quota_should_run(
- status,
- goal_id=AGENT_LANE_GOAL_ID,
- agent_id=AGENT_ID,
- scheduler_execution_context=(
- GENERIC_CLI_OUTER_CONTROLLER_SCHEDULER_CONTEXT
- ),
- )
- assert quota["recommended_action"] == AGENT_LANE_TODO, quota
- assert quota["latest_run_recommended_action"] == AGENT_LANE_ACTION, quota
- assert quota["agent_lane_next_action"]["todo_id"] == "todo_agent_lane_repair", quota
- assert quota["next_action_projection_warning"]["severity"] == "info", quota
- assert quota["interaction_contract"]["agent_channel"]["must_attempt"] is True, quota
-
- print("status-neutral-run-window-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/status-overview-markdown-smoke.py b/examples/control_plane/status-overview-markdown-smoke.py
deleted file mode 100644
index f84b99004c..0000000000
--- a/examples/control_plane/status-overview-markdown-smoke.py
+++ /dev/null
@@ -1,132 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the status markdown overview renderer seam."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.presentation.renderers.status_markdown import ( # noqa: E402
- append_status_overview_markdown,
- render_status_markdown,
-)
-
-
-def overview_payload() -> dict:
- return {
- "ok": False,
- "registry": "/tmp/loopx-registry.json",
- "runtime_root": "/tmp/loopx-runtime",
- "goal_count": 2,
- "run_count": 7,
- "status_contract": {
- "schema_version": 2,
- "minimum_dashboard_schema_version": 2,
- "producer": "loopx status",
- },
- "goal_filter": "loopx-meta",
- "contract": {
- "ok": False,
- "summary": {
- "errors": 2,
- "warnings": 1,
- "checks": 8,
- },
- "errors": ["registry goals checked: 2"],
- "warnings": ["public boundary scan clean: 0 files"],
- "checks": ["status contract emitted"],
- },
- "contract_errors": [
- "missing dashboard status_contract",
- "stale registry pointer",
- ],
- "contract_errors_truncated": True,
- "contract_errors_total_count": 4,
- "contract_warnings": ["global registry has action findings"],
- "contract_warnings_truncated": True,
- "contract_warnings_total_count": 3,
- "global_registry": {
- "available": True,
- "ok": True,
- "summary": {
- "findings": 0,
- "high": 0,
- "action": 0,
- "info": 0,
- },
- "findings": [],
- },
- "attention_queue": {
- "item_count": 0,
- "needs_user_or_controller": 0,
- "needs_controller": 0,
- "needs_codex": 0,
- "watching_external_evidence": 0,
- "watching_monitor": 0,
- },
- "run_history": {
- "goal_count": 0,
- "run_count": 0,
- "goals": [],
- },
- }
-
-
-def assert_overview(markdown: str) -> None:
- assert markdown.startswith("# LoopX Status\n\n"), markdown
- assert "- ok: `False`" in markdown, markdown
- assert "- registry: `/tmp/loopx-registry.json`" in markdown, markdown
- assert "- runtime_root: `/tmp/loopx-runtime`" in markdown, markdown
- assert "- goals: `2`" in markdown, markdown
- assert "- runs: `7`" in markdown, markdown
- assert (
- "- status_contract: schema_version=2, "
- "minimum_dashboard_schema_version=2, producer=loopx status"
- ) in markdown, markdown
- assert "- goal_filter: `loopx-meta`" in markdown, markdown
- assert "- contract: ok=False, errors=2, warnings=1, checks=8" in markdown, markdown
- assert "## Status Contract Signals" in markdown, markdown
- assert "- error: missing dashboard status_contract" in markdown, markdown
- assert "- error: stale registry pointer" in markdown, markdown
- assert "- contract_errors_truncated: total=4" in markdown, markdown
- assert "- warning: global registry has action findings" in markdown, markdown
- assert "- contract_warnings_truncated: total=3" in markdown, markdown
-
-
-def assert_contract_details(markdown: str) -> None:
- assert "## Errors" in markdown, markdown
- assert "- registry goals checked: 2" in markdown, markdown
- assert "## Warnings" in markdown, markdown
- assert "- public boundary scan clean: 0 files" in markdown, markdown
- assert "## Checks" in markdown, markdown
- assert "- status contract emitted" in markdown, markdown
-
-
-def main() -> int:
- payload = overview_payload()
- lines: list[str] = []
- append_status_overview_markdown(lines, payload)
- overview_markdown = "\n".join(lines)
- assert_overview(overview_markdown)
- assert "## Errors" not in overview_markdown, overview_markdown
-
- full_markdown = render_status_markdown(payload)
- assert_overview(full_markdown)
- assert_contract_details(full_markdown)
-
- explicit_event_classes_markdown = render_status_markdown(
- payload,
- event_classes=("accounting", "decision", "evidence", "state", "work"),
- )
- assert explicit_event_classes_markdown == full_markdown, explicit_event_classes_markdown
- print("status-overview-markdown-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/status-runtime-summaries-readmodel-smoke.py b/examples/control_plane/status-runtime-summaries-readmodel-smoke.py
deleted file mode 100644
index ce57af6ef4..0000000000
--- a/examples/control_plane/status-runtime-summaries-readmodel-smoke.py
+++ /dev/null
@@ -1,174 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the status runtime-summary read-model adapter."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-import tempfile
-from typing import Any
-
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.runtime.time import now_utc, parse_timestamp, utc_isoformat # noqa: E402
-from loopx.control_plane.status.runtime_summaries import ( # noqa: E402
- StatusRuntimeSummaryContext,
- build_status_runtime_summaries,
-)
-
-
-GOAL_ID = "status-runtime-summary-fixture"
-
-
-def compact_run(run: dict[str, Any]) -> dict[str, Any]:
- return {
- "goal_id": run.get("goal_id"),
- "classification": run.get("classification"),
- "generated_at": run.get("generated_at"),
- }
-
-
-def build_context() -> StatusRuntimeSummaryContext:
- return StatusRuntimeSummaryContext(
- latest_run=lambda goal: (goal.get("latest_runs") or [None])[0],
- goal_lifecycle_fields=lambda goal, current_run: {
- "lifecycle_phase": "fixture",
- "lifecycle_flags": ["fixture"],
- },
- subagent_activity_for_goal=lambda goal: None,
- compact_run=compact_run,
- quota_status=lambda goal: {"state": "eligible"},
- parse_timestamp=parse_timestamp,
- run_has_external_evidence_watch_signal=lambda run: False,
- decision_classifications={"operator_gate_notify"},
- evidence_classifications=set(),
- evidence_hints=(),
- state_classifications={"state_refreshed"},
- promotion_readiness_classifications=set(),
- add_promotion_readiness_freshness=lambda readiness: {
- **readiness,
- "freshness_status": "unknown",
- "requires_readiness_run": True,
- },
- latest_promotion_readiness_event=lambda root, *, goal_id=None: {},
- promotion_readiness_freshness_hours=24,
- promotion_readiness_proxy_note="fixture readiness proxy",
- public_safe_compact_text=lambda value, *, limit=320: str(value or "").strip()[:limit],
- )
-
-
-def build_history() -> dict[str, Any]:
- now = now_utc()
- accounting_run = {
- "goal_id": GOAL_ID,
- "classification": "quota_slot_spent",
- "generated_at": utc_isoformat(now),
- # event_type is what the spend commit always stamps; the ledger and the
- # usage summary both read the slot accounting from it.
- "quota_event": {
- "event_type": "quota_slot_spent",
- "slots": 1,
- "source": "heartbeat",
- },
- }
- decision_run = {
- "goal_id": GOAL_ID,
- "classification": "operator_gate_notify",
- "generated_at": utc_isoformat(now),
- "operator_gate": {"state": "open"},
- }
- return {
- "goal_count": 1,
- "run_count": 2,
- "goals": [
- {
- "id": GOAL_ID,
- "domain": "loopx-platform",
- "status": "active",
- "registry_member": True,
- "latest_runs": [accounting_run, decision_run],
- }
- ],
- "runs": [accounting_run, decision_run],
- }
-
-
-def build_queue() -> dict[str, Any]:
- return {
- "items": [
- {
- "goal_id": GOAL_ID,
- "agent_todos": {
- "items": [
- {
- "todo_id": "todo_status_runtime_summary_fixture",
- "status": "open",
- "title": "Keep runtime summaries behind one read-model adapter.",
- "index": 0,
- }
- ]
- },
- "user_todos": {"items": []},
- }
- ]
- }
-
-
-def assert_status_module_wrapper_parity() -> None:
- with tempfile.TemporaryDirectory() as raw_root:
- kwargs = {
- "history": build_history(),
- "queue": build_queue(),
- "runtime_root": Path(raw_root),
- "goal_id_filter": GOAL_ID,
- "display_limit": 1,
- "todo_index_limit": 10,
- }
- wrapper = status_module.build_status_runtime_summaries(**kwargs)
- direct = build_status_runtime_summaries(
- **kwargs,
- context=status_module.build_status_runtime_summary_context(),
- )
-
- assert wrapper == direct, (wrapper, direct)
- assert wrapper["run_history"]["run_count"] == 2, wrapper["run_history"]
- assert wrapper["usage_summary"]["totals"]["quota_spend_slots_24h"] == 1, wrapper["usage_summary"]
- assert wrapper["todo_index"]["total_count"] == 1, wrapper["todo_index"]
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory() as raw_root:
- summaries = build_status_runtime_summaries(
- history=build_history(),
- queue=build_queue(),
- runtime_root=Path(raw_root),
- goal_id_filter=GOAL_ID,
- display_limit=1,
- todo_index_limit=10,
- context=build_context(),
- )
-
- assert set(summaries) == {
- "run_history",
- "event_ledger_summary",
- "promotion_readiness_summary",
- "decision_freshness_summary",
- "usage_summary",
- "todo_index",
- }, summaries
- assert summaries["run_history"]["run_count"] == 2, summaries["run_history"]
- assert len(summaries["run_history"]["recent_runs"]) == 1, summaries["run_history"]
- assert summaries["event_ledger_summary"]["totals"]["events_24h"] == 2, summaries["event_ledger_summary"]
- assert summaries["usage_summary"]["totals"]["quota_spend_slots_24h"] == 1, summaries["usage_summary"]
- assert summaries["decision_freshness_summary"]["summary"]["decision_count"] == 1, summaries["decision_freshness_summary"]
- assert summaries["todo_index"]["total_count"] == 1, summaries["todo_index"]
- assert_status_module_wrapper_parity()
- print("status-runtime-summaries-readmodel-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/status-watch-routing-attribute-smoke.py b/examples/control_plane/status-watch-routing-attribute-smoke.py
deleted file mode 100644
index 64857824de..0000000000
--- a/examples/control_plane/status-watch-routing-attribute-smoke.py
+++ /dev/null
@@ -1,70 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test status watch routing uses explicit attributes, not monitor names."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx.status import goal_attention # noqa: E402
-
-
-def attention_for(run: dict[str, object]) -> dict[str, object]:
- item = goal_attention(
- {
- "id": "status-watch-routing-fixture",
- "registry_member": True,
- "adapter_status": "connected-read-only",
- "latest_status_run": run,
- "latest_runs": [run],
- }
- )
- assert item is not None, run
- return item
-
-
-def main() -> int:
- product_monitor_run = {
- "classification": "monitor_due_scheduler_todos_planned",
- "recommended_action": "Implement monitor scheduler runtime routing.",
- "json_exists": True,
- "markdown_exists": True,
- "delivery_outcome": "surface_only",
- }
- product_item = attention_for(product_monitor_run)
- assert product_item["waiting_on"] == "codex", product_item
- assert product_item["severity"] == "action", product_item
-
- explicit_external_run = {
- "classification": "runtime_result_pending",
- "waiting_on": "external_evidence",
- "recommended_action": "Observe the external worker result.",
- "json_exists": True,
- "markdown_exists": True,
- "delivery_outcome": "surface_only",
- }
- explicit_item = attention_for(explicit_external_run)
- assert explicit_item["waiting_on"] == "external_evidence", explicit_item
- assert explicit_item["severity"] == "watch", explicit_item
-
- legacy_external_run = {
- "classification": "external_evidence_observation_contract_validated_v0",
- "recommended_action": "Observe the external result channel.",
- "json_exists": True,
- "markdown_exists": True,
- "delivery_outcome": "surface_only",
- }
- legacy_item = attention_for(legacy_external_run)
- assert legacy_item["waiting_on"] == "external_evidence", legacy_item
- assert legacy_item["severity"] == "watch", legacy_item
-
- print("status-watch-routing-attribute-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/todo-claim-lease-roadmap-smoke.py b/examples/control_plane/todo-claim-lease-roadmap-smoke.py
deleted file mode 100644
index 8b90a2dec1..0000000000
--- a/examples/control_plane/todo-claim-lease-roadmap-smoke.py
+++ /dev/null
@@ -1,134 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the public soft-claim and optional hard-lease contract."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-ARCHITECTURE = REPO_ROOT / "docs" / "architecture.md"
-ROADMAP = REPO_ROOT / "docs" / "product" / "roadmaps" / "frontstage-channel-lease-roadmap.md"
-TODO_CONTRACT = REPO_ROOT / "docs" / "project-agent-todo-contract.md"
-REGISTRY_EXAMPLE = REPO_ROOT / "examples" / "registry.example.json"
-PEER_AGENTS_EXAMPLE = (
- REPO_ROOT / "examples" / "peer-agent-task-orchestration.registry.example.json"
-)
-
-
-def require(text: str, snippets: list[str], *, source: Path) -> None:
- compact = " ".join(text.split())
- missing = [
- snippet
- for snippet in snippets
- if snippet not in text and " ".join(snippet.split()) not in compact
- ]
- assert not missing, f"{source}: missing {missing}"
-
-
-def main() -> int:
- architecture = ARCHITECTURE.read_text(encoding="utf-8")
- roadmap = ROADMAP.read_text(encoding="utf-8")
- todo_contract = TODO_CONTRACT.read_text(encoding="utf-8")
-
- require(
- architecture,
- [
- "a **goal** is the stable `goal_id` boundary",
- "A **todo** is a structured active-state checkbox",
- "There is no separate issue object",
- "`(goal_id, todo_id)` is the contention unit",
- "Different todos under the same goal may proceed in parallel",
- "Registered identities are peers",
- "workspace-isolation rule",
- ],
- source=ARCHITECTURE,
- )
- require(
- roadmap,
- [
- "A **task claim is a soft per-todo route by default**",
- "an optional hard lease adds TTL",
- "pending key is per todo: `(goal_id, todo_id)`",
- "LoopX does not have a separate issue object",
- "Do not serialize an entire\ngoal",
- "does not replace\nthe default soft `claimed_by` route or participate in quota decisions",
- "registered-owner validation",
- "repository-writing peers use isolated worktrees",
- "self-merge with\nevidence",
- "review action over an independent handoff",
- ],
- source=ROADMAP,
- )
- require(
- todo_contract,
- [
- "a `goal_id` is the LoopX control-plane boundary",
- "A `todo_id` is a structured work item inside that goal",
- "does not\ncurrently model issues as a separate runtime object",
- "`coordination.agent_model=peer_v1`",
- "Create or switch to a separate worktree",
- "`--next-claimed-by`",
- ],
- source=TODO_CONTRACT,
- )
- for source in (REGISTRY_EXAMPLE, PEER_AGENTS_EXAMPLE):
- registry = json.loads(source.read_text(encoding="utf-8"))
- for goal in registry.get("goals") or []:
- coordination = goal.get("coordination") or {}
- assert "claim_ttl_minutes" not in coordination, (
- f"{source}: soft claims must not advertise an inert TTL"
- )
-
- help_result = subprocess.run(
- [sys.executable, "-m", "loopx.cli", "bootstrap", "--help"],
- cwd=REPO_ROOT,
- check=True,
- text=True,
- capture_output=True,
- )
- assert "--claim-ttl-minutes" not in help_result.stdout, help_result.stdout
-
- with tempfile.TemporaryDirectory(prefix="loopx-soft-claim-ttl-smoke-") as tmp:
- root = Path(tmp)
- registry_path = root / "registry.json"
- result = subprocess.run(
- [
- sys.executable,
- "-m",
- "loopx.cli",
- "--registry",
- str(registry_path),
- "--format",
- "json",
- "bootstrap",
- "--project",
- str(root / "project"),
- "--goal-id",
- "soft-claim-ttl-smoke",
- "--objective",
- "verify soft claim TTL compatibility",
- "--claim-ttl-minutes",
- "5",
- "--no-global-sync",
- ],
- cwd=REPO_ROOT,
- check=False,
- text=True,
- capture_output=True,
- )
- assert result.returncode == 0, result.stdout or result.stderr
- registry = json.loads(registry_path.read_text(encoding="utf-8"))
- coordination = registry["goals"][0]["coordination"]
- assert "claim_ttl_minutes" not in coordination, coordination
-
- print("todo-claim-lease-roadmap-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/todo-deferred-resume-lanes-smoke.py b/examples/control_plane/todo-deferred-resume-lanes-smoke.py
deleted file mode 100644
index 361029f1ef..0000000000
--- a/examples/control_plane/todo-deferred-resume-lanes-smoke.py
+++ /dev/null
@@ -1,212 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test todo deferred/resume-blocked lane projection helpers."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.todos.resume_planning import project_todo_resume_planning # noqa: E402
-
-
-CURRENT_AGENT = "codex-product-capability"
-OTHER_AGENT = "codex-main-control"
-
-
-def monitor_todo() -> dict:
- return {
- "index": 1,
- "todo_id": "todo_monitor_open",
- "text": "[P1 monitor] Watch the upstream signal.",
- "status": "open",
- "task_class": "continuous_monitor",
- "claimed_by": CURRENT_AGENT,
- }
-
-
-def blocked_advancement(
- todo_id: str,
- *,
- index: int,
- claimed_by: str | None,
- target_task_class: str | None = "continuous_monitor",
- target_status: str = "open",
-) -> dict:
- condition = {
- "target_todo_id": "todo_monitor_open",
- "target_status": target_status,
- }
- if target_task_class is not None:
- condition["target_task_class"] = target_task_class
- item = {
- "index": index,
- "todo_id": todo_id,
- "text": f"[P1] Resume blocked advancement {todo_id}.",
- "status": "open",
- "task_class": "advancement_task",
- "claimed_by": claimed_by,
- "resume_when": "todo_done:todo_monitor_open",
- "resume_ready": False,
- "resume_condition": condition,
- }
- return {key: value for key, value in item.items() if value is not None}
-
-
-def ready_deferred(
- todo_id: str,
- *,
- index: int,
- claimed_by: str | None,
- excluded_agents: list[str] | None = None,
-) -> dict:
- item = {
- "index": index,
- "todo_id": todo_id,
- "text": f"[P1] Ready deferred candidate {todo_id}.",
- "status": "deferred",
- "task_class": "advancement_task",
- "claimed_by": claimed_by,
- "resume_when": "todo_done:todo_gate",
- "resume_ready": True,
- "required_write_scopes": [" loopx/** ", "loopx/**"],
- "decision_scope": "direction:action:resume",
- "excluded_agents": excluded_agents,
- }
- return {key: value for key, value in item.items() if value is not None}
-
-
-def assert_deferred_resume_lanes_filter_current_unclaimed_and_other_agents() -> None:
- summary = {
- "schema_version": "todo_summary_v0",
- "items": [
- {
- "index": 0,
- "todo_id": "todo_deferred_backlog",
- "text": "[P2] Deferred backlog item.",
- "status": "deferred",
- "task_class": "advancement_task",
- },
- ],
- "deferred_resume_candidates": [
- ready_deferred("todo_current_ready", index=2, claimed_by=CURRENT_AGENT),
- ready_deferred("todo_unclaimed_ready", index=3, claimed_by=None),
- ready_deferred("todo_other_ready", index=4, claimed_by=OTHER_AGENT),
- ready_deferred(
- "todo_excluded_ready",
- index=5,
- claimed_by=None,
- excluded_agents=[CURRENT_AGENT],
- ),
- {
- **ready_deferred("todo_not_ready", index=6, claimed_by=CURRENT_AGENT),
- "resume_ready": False,
- },
- ],
- }
-
- lanes = project_todo_resume_planning(
- summary,
- agent_id=CURRENT_AGENT,
- item_limit=10,
- )["deferred_lanes"]
- assert lanes["deferred_count"] == 1, lanes
- assert lanes["deferred_visibility_limit"] == 10, lanes
- assert lanes["deferred_items"][0]["todo_id"] == "todo_deferred_backlog", lanes
- assert [item["todo_id"] for item in lanes["deferred_resume_candidates"]] == [
- "todo_current_ready",
- "todo_unclaimed_ready",
- "todo_other_ready",
- "todo_excluded_ready",
- ], lanes
- assert lanes["current_agent_deferred_resume_count"] == 1, lanes
- assert lanes["unclaimed_deferred_resume_count"] == 1, lanes
- assert lanes["other_agent_deferred_resume_count"] == 1, lanes
- assert lanes["executor_excluded_self_deferred_resume_count"] == 1, lanes
- assert lanes["executor_excluded_self_deferred_resume_candidates"][0]["todo_id"] == (
- "todo_excluded_ready"
- ), lanes
- current = lanes["current_agent_deferred_resume_candidates"][0]
- assert current["required_write_scopes"] == ["loopx/**"], current
- assert current["decision_scope"]["scope_key"] == "resume", current
-
-
-def assert_monitor_blocked_resume_lanes_filter_by_claim_and_monitor_target() -> None:
- current = blocked_advancement(
- "todo_current_blocked",
- index=2,
- claimed_by=CURRENT_AGENT,
- )
- unclaimed = blocked_advancement(
- "todo_unclaimed_blocked",
- index=3,
- claimed_by=None,
- target_task_class=None,
- )
- other = blocked_advancement(
- "todo_other_blocked",
- index=4,
- claimed_by=OTHER_AGENT,
- )
- non_monitor = blocked_advancement(
- "todo_non_monitor_blocked",
- index=5,
- claimed_by=CURRENT_AGENT,
- target_task_class="advancement_task",
- )
- non_monitor["resume_condition"]["target_todo_id"] = "todo_regular_open"
- excluded = blocked_advancement(
- "todo_excluded_blocked",
- index=6,
- claimed_by=None,
- )
- excluded["excluded_agents"] = [CURRENT_AGENT]
- summary = {
- "schema_version": "todo_summary_v0",
- "items": [monitor_todo(), current, unclaimed, other, non_monitor, excluded],
- "backlog_items": [current],
- }
-
- projection = project_todo_resume_planning(summary, agent_id=CURRENT_AGENT, item_limit=10)
- lanes = projection["resume_blocked_lanes"]
- resume_blocked = lanes["resume_blocked_items"]
- assert [item["todo_id"] for item in resume_blocked] == [
- "todo_current_blocked",
- "todo_unclaimed_blocked",
- "todo_other_blocked",
- "todo_non_monitor_blocked",
- "todo_excluded_blocked",
- ], resume_blocked
- monitor_blocked = projection["monitor_blocked_items"]
- assert [item["todo_id"] for item in monitor_blocked] == [
- "todo_current_blocked",
- "todo_unclaimed_blocked",
- "todo_other_blocked",
- "todo_excluded_blocked",
- ], monitor_blocked
- assert all(
- item["blocking_monitor_todo_id"] == "todo_monitor_open"
- for item in monitor_blocked
- ), monitor_blocked
-
- assert lanes["resume_blocked_count"] == 5, lanes
- assert lanes["monitor_blocked_resume_count"] == 4, lanes
- assert lanes["current_agent_monitor_blocked_resume_count"] == 1, lanes
- assert lanes["unclaimed_monitor_blocked_resume_count"] == 1, lanes
- assert lanes["other_agent_monitor_blocked_resume_count"] == 1, lanes
- assert lanes["executor_excluded_self_monitor_blocked_resume_count"] == 1, lanes
-
-
-def main() -> int:
- assert_deferred_resume_lanes_filter_current_unclaimed_and_other_agents()
- assert_monitor_blocked_resume_lanes_filter_by_claim_and_monitor_target()
- print("todo-deferred-resume-lanes-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/todo-index-rollout-status-smoke.py b/examples/control_plane/todo-index-rollout-status-smoke.py
deleted file mode 100644
index 5874550562..0000000000
--- a/examples/control_plane/todo-index-rollout-status-smoke.py
+++ /dev/null
@@ -1,118 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx import status as status_module # noqa: E402
-from loopx.control_plane.todos.todo_index import build_todo_index as build_todo_index_read_model # noqa: E402
-
-
-def write_event(path: Path, payload: dict[str, object]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- with path.open("a", encoding="utf-8") as handle:
- handle.write(json.dumps(payload, sort_keys=True) + "\n")
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory() as raw_tmp:
- runtime_root = Path(raw_tmp)
- event_log = runtime_root / "goals" / "loopx-meta" / "rollout-event-log.jsonl"
- write_event(
- event_log,
- {
- "schema_version": "loopx_rollout_event_v0",
- "event_kind": "todo_add",
- "goal_id": "loopx-meta",
- "todo_id": "todo_done_status",
- "status": "open",
- "recorded_at": "2026-06-22T16:00:00Z",
- "details": {"role": "agent"},
- },
- )
- write_event(
- event_log,
- {
- "schema_version": "loopx_rollout_event_v0",
- "event_kind": "todo_complete",
- "goal_id": "loopx-meta",
- "todo_id": "todo_done_status",
- "recorded_at": "2026-06-22T16:05:00Z",
- "details": {"role": "agent"},
- },
- )
-
- history = {"goals": [{"id": "loopx-meta"}]}
- event_only_index = status_module.build_status_runtime_summaries(
- history=history,
- queue={"items": []},
- runtime_root=runtime_root,
- goal_id_filter=None,
- display_limit=10,
- todo_index_limit=10,
- )["todo_index"]
- queue = {
- "items": [
- {
- "goal_id": "loopx-meta",
- "agent_todos": {
- "items": [
- {
- "todo_id": "todo_done_status",
- "status": "open",
- "title": "Confirm rollout status merge",
- "text": "Confirm rollout status merge",
- }
- ]
- },
- }
- ]
- }
- index = status_module.build_status_runtime_summaries(
- history=history,
- queue=queue,
- runtime_root=runtime_root,
- goal_id_filter=None,
- display_limit=10,
- todo_index_limit=10,
- )["todo_index"]
- read_model_index = build_todo_index_read_model(
- queue=queue,
- history=history,
- runtime_root=runtime_root,
- public_safe_compact_text=status_module.public_safe_compact_text,
- limit=10,
- )
-
- event_only_items = event_only_index["items"]
- assert len(event_only_items) == 1, event_only_items
- assert event_only_items[0]["source"] == "rollout_event_log", event_only_items[0]
- assert event_only_items[0]["status"] == "done", event_only_items[0]
- assert event_only_items[0]["done"] is True, event_only_items[0]
-
- assert read_model_index == index, (read_model_index, index)
- assert index["current_projected_count"] == 1, index
- assert index["rollout_event_count"] == 2, index
- items = index["items"]
- assert len(items) == 1, items
- item = items[0]
- assert item["todo_id"] == "todo_done_status", item
- assert item["source"] == "attention_queue", item
- assert item["event_count"] == 2, item
- assert item["event_kinds"] == ["todo_add", "todo_complete"], item
- assert item["latest_event_kind"] == "todo_complete", item
- assert item["latest_event_status"] == "done", item
- # Historical completion remains diagnostic; the current queue owns status.
- assert item["status"] == "open", item
- assert item["done"] is False, item
- print("todo-index-rollout-status smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/control_plane/todo-route-continuation-lanes-smoke.py b/examples/control_plane/todo-route-continuation-lanes-smoke.py
deleted file mode 100644
index 24da534cba..0000000000
--- a/examples/control_plane/todo-route-continuation-lanes-smoke.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test todo route-continuation lane projection helpers."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.todos.quota_selection import project_quota_planning # noqa: E402
-
-
-def assert_route_continuation_lanes_filter_current_unclaimed_and_other_agents() -> None:
- summary = {
- "schema_version": "todo_summary_v0",
- "source_section": "Agent Todo",
- "route_continuation_replan_candidates": [
- {
- "index": 2,
- "todo_id": "todo_current_claimed_route",
- "text": "[P1] Continue current claimed route.",
- "task_class": "advancement_task",
- "claimed_by": "codex-side-bypass",
- "route_id": "current-route",
- "route_continuation_replan_required": True,
- "required_write_scopes": [" loopx/** ", "loopx/**"],
- "decision_scope": "direction:action:route",
- },
- {
- "index": 1,
- "route_key": "unclaimed-route",
- "recommended_action": "[P1] Continue unclaimed route.",
- "task_class": "advancement_task",
- "route_continuation_replan_required": True,
- },
- {
- "index": 3,
- "todo_id": "todo_other_agent_route",
- "text": "[P1] Continue other agent route.",
- "task_class": "advancement_task",
- "claimed_by": "codex-main-control",
- "route_id": "other-route",
- "route_continuation_replan_required": True,
- },
- {
- "index": 4,
- "todo_id": "todo_false_route",
- "text": "[P1] Do not project this route.",
- "task_class": "advancement_task",
- "route_continuation_replan_required": False,
- },
- {
- "index": 5,
- "todo_id": "todo_monitor_route",
- "text": "[P1] Monitor route is not advancement replan.",
- "task_class": "continuous_monitor",
- "route_continuation_replan_required": True,
- },
- ],
- "handoff_gates": [
- {
- "index": 0,
- "todo_id": "todo_blocking_route_gate",
- "text": "[P0-review] Review route gate.",
- "task_class": "advancement_task",
- "claimed_by": "codex-side-bypass",
- "excluded_agents": ["codex-main-control"],
- "route_id": "blocked-route",
- "route_continuation_replan_required": True,
- "route_continuation_reason": "same route has a next slice",
- }
- ],
- }
-
- lanes = project_quota_planning(
- summary,
- all_open_items=[],
- source_open_count=0,
- agent_identity={"agent_id": "codex-side-bypass"},
- filter_user_gate_blocks_agent=False,
- available_capabilities=[],
- )["route_lanes"]
- assert lanes["route_continuation_replan_count"] == 4, lanes
- assert [
- item.get("route_id") or item.get("route_key")
- for item in lanes["route_continuation_replan_candidates"]
- ] == [
- "blocked-route",
- "unclaimed-route",
- "current-route",
- "other-route",
- ], lanes
- assert lanes["current_agent_route_continuation_replan_count"] == 3, lanes
- assert [
- item.get("route_id") or item.get("route_key")
- for item in lanes["current_agent_route_continuation_replan_candidates"]
- ] == ["blocked-route", "unclaimed-route", "current-route"], lanes
- assert lanes["unclaimed_route_continuation_replan_count"] == 1, lanes
- assert (
- lanes["unclaimed_route_continuation_replan_candidates"][0]["route_key"]
- == "unclaimed-route"
- ), lanes
- assert lanes["other_agent_route_continuation_replan_count"] == 1, lanes
- assert lanes["other_agent_route_continuation_replan_candidates"][0]["route_id"] == (
- "other-route"
- ), lanes
- current = lanes["current_agent_route_continuation_replan_candidates"][2]
- assert current["required_write_scopes"] == ["loopx/**"], current
- assert current["decision_scope"]["scope_key"] == "route", current
- assert (
- lanes["route_continuation_replan_selection_policy"]
- == "quota may wake the current peer for route continuation replan "
- "candidates claimed by that agent or unclaimed; other-agent route candidates remain diagnostic visibility"
- ), lanes
-
-
-def main() -> int:
- assert_route_continuation_lanes_filter_current_unclaimed_and_other_agents()
- print("todo-route-continuation-lanes-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/todo-succession-contract-smoke.py b/examples/control_plane/todo-succession-contract-smoke.py
deleted file mode 100644
index 5e1b69a5cd..0000000000
--- a/examples/control_plane/todo-succession-contract-smoke.py
+++ /dev/null
@@ -1,214 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test completed todo succession warnings in status and quota views."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.testing.quota_fixtures import ( # noqa: E402
- quota_status_payload,
- quota_todo_item,
- quota_todo_summary,
-)
-from loopx.quota import build_quota_should_run, render_quota_should_run_markdown # noqa: E402
-from loopx.control_plane.todos.succession_warning import ( # noqa: E402
- build_todo_succession_warning_lanes,
-)
-
-
-GOAL_ID = "todo-succession-contract-fixture"
-AGENT_ID = "codex-product-capability"
-
-
-def build_agent_todos() -> dict:
- summary = quota_todo_summary(
- [
- quota_todo_item(
- todo_id="todo_open_next",
- text="[P1] Continue the next canary-backed control-plane cleanup.",
- priority="P1",
- claimed_by=AGENT_ID,
- ),
- quota_todo_item(
- todo_id="todo_missing_successor",
- text="[P1] Complete a tracked canary cleanup without recording the next slice.",
- status="done",
- priority="P1",
- action_kind="canary_gated_control_plane_cleanup",
- claimed_by=AGENT_ID,
- updated_at="2026-07-04T20:00:00+08:00",
- ),
- quota_todo_item(
- todo_id="todo_no_followup",
- text="[P2] Complete a tracked cleanup that intentionally needs no follow-up.",
- status="done",
- priority="P2",
- action_kind="documentation_cleanup",
- claimed_by=AGENT_ID,
- no_followup=True,
- updated_at="2026-07-04T19:00:00+08:00",
- ),
- quota_todo_item(
- todo_id="todo_with_successor",
- text="[P2] Complete a tracked cleanup and link the next slice.",
- status="done",
- priority="P2",
- action_kind="projection_cleanup",
- claimed_by=AGENT_ID,
- updated_at="2026-07-04T18:00:00+08:00",
- ),
- quota_todo_item(
- todo_id="todo_with_explicit_successor",
- text="[P2] Complete a tracked cleanup and link existing successor metadata.",
- status="done",
- priority="P2",
- action_kind="projection_cleanup",
- claimed_by=AGENT_ID,
- successor_todo_ids=["todo_explicit_successor"],
- updated_at="2026-07-04T17:30:00+08:00",
- ),
- quota_todo_item(
- todo_id="todo_successor",
- text="[P2] Continue after the linked cleanup.",
- priority="P2",
- claimed_by=AGENT_ID,
- resume_when="todo_done:todo_with_successor",
- ),
- quota_todo_item(
- todo_id="todo_explicit_successor",
- text="[P2] Continue after the explicit successor link.",
- priority="P2",
- claimed_by=AGENT_ID,
- ),
- {
- "todo_id": "todo_legacy_done",
- "index": 6,
- "status": "done",
- "done": True,
- "role": "agent",
- "task_class": "advancement_task",
- "text": "[P3] Legacy markdown checkbox without tracking metadata.",
- },
- ],
- role="agent",
- )
- return summary
-
-
-def status_payload(agent_todos: dict) -> dict:
- return quota_status_payload(
- goal_id=GOAL_ID,
- status="active",
- recommended_action="Continue the next canary-backed cleanup.",
- agent_todos=agent_todos,
- source="active_state",
- registry_status="active",
- coordination={
- "agent_model": "peer_v1",
- "registered_agents": ["codex-main-control", AGENT_ID],
- },
- latest_runs=[],
- goal_extra={
- "adapter_kind": "fixture_adapter_v0",
- "adapter_status": "connected",
- },
- )
-
-
-def assert_status_summary_warning() -> None:
- summary = build_agent_todos()
- assert summary["completed_without_successor_count"] == 1, summary
- warning = summary["todo_succession_warning"]
- assert warning["schema_version"] == "todo_succession_warning_v0", warning
- assert warning["reason_code"] == "completed_advancement_without_successor", warning
- assert warning["items"][0]["todo_id"] == "todo_missing_successor", warning
- assert warning["items"][0]["succession_tracked"] is True, warning
- assert "todo_no_followup" not in {
- item["todo_id"] for item in warning["items"] if item.get("todo_id")
- }, warning
- assert "todo_with_successor" not in {
- item["todo_id"] for item in warning["items"] if item.get("todo_id")
- }, warning
- assert "todo_with_explicit_successor" not in {
- item["todo_id"] for item in warning["items"] if item.get("todo_id")
- }, warning
- assert "todo_legacy_done" not in {
- item["todo_id"] for item in warning["items"] if item.get("todo_id")
- }, warning
-
-
-def assert_quota_projects_warning() -> None:
- payload = build_quota_should_run(
- status_payload(build_agent_todos()),
- goal_id=GOAL_ID,
- agent_id=AGENT_ID,
- )
- assert payload["decision"] == "run", payload
- warning = payload["agent_todo_summary"]["todo_succession_warning"]
- assert warning["count"] == 1, payload
- assert warning["items"][0]["todo_id"] == "todo_missing_successor", payload
- markdown = render_quota_should_run_markdown(payload)
- assert "agent_todo_succession_warning" in markdown, markdown
- assert "todo_missing_successor" in markdown, markdown
-
-
-def assert_quota_warning_lanes_strip_transient_evidence() -> None:
- lanes = build_todo_succession_warning_lanes(
- {
- "todo_succession_warning": {
- "count": 1,
- "items": [
- {
- "todo_id": "todo_missing_successor",
- "text": "[P1] Missing successor.",
- "note": "operator-only note should not project",
- "evidence": "local run evidence should not project",
- "reason": "local rationale should not project",
- "required_write_scopes": "loopx/quota.py,../unsafe-scope.txt",
- "decision_scope": "write_scope:goal:loopx-meta",
- "required_decision_scopes": (
- "private_read:goal:loopx-meta,private_read:goal:loopx-meta"
- ),
- "action_kind": "monitor",
- "succession_tracked": True,
- }
- ],
- }
- },
- item_limit=8,
- )
- item = lanes["todo_succession_warning"]["items"][0]
- assert item["todo_id"] == "todo_missing_successor", lanes
- assert item["succession_tracked"] is True, lanes
- assert "note" not in item, lanes
- assert "evidence" not in item, lanes
- assert "reason" not in item, lanes
- assert item["required_write_scopes"] == ["loopx/quota.py"], lanes
- assert item["decision_scope"]["kind"] == "write_scope", lanes
- assert item["required_decision_scopes"] == [
- {
- "schema_version": "decision_scope_v0",
- "kind": "private_read",
- "granularity": "goal",
- "scope_key": "loopx-meta",
- }
- ], lanes
- assert item["task_class"] == "continuous_monitor", lanes
-
-
-def main() -> int:
- assert_status_summary_warning()
- assert_quota_projects_warning()
- assert_quota_warning_lanes_strip_transient_evidence()
- print("todo-succession-contract-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/todo-summary-item-source-smoke.py b/examples/control_plane/todo-summary-item-source-smoke.py
deleted file mode 100644
index b47a79b5cf..0000000000
--- a/examples/control_plane/todo-summary-item-source-smoke.py
+++ /dev/null
@@ -1,114 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test shared todo summary item compaction and source aggregation."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.todos.summary_item import ( # noqa: E402
- compact_todo_summary_item,
- todo_summary_source_items,
-)
-
-
-GATE_ID = "todo_gate_done"
-SUCCESSOR_ID = "todo_successor"
-SUCCESSOR_TEXT = "[P1] Resume after the handoff gate is cleared."
-DUPLICATE_TEXT = "[P2] Keep only one no-id duplicate."
-
-
-def successor_item(**overrides: object) -> dict:
- item = {
- "index": 2,
- "todo_id": SUCCESSOR_ID,
- "text": SUCCESSOR_TEXT,
- "status": "open",
- "task_class": "advancement_task",
- "resume_when": f"todo_done:{GATE_ID}",
- "unblocks_todo_id": GATE_ID,
- "required_write_scopes": [" loopx/** ", "loopx/**"],
- "decision_scope": "direction:action:claim",
- "claimed_by": "codex-product-capability",
- }
- item.update(overrides)
- return item
-
-
-def assert_compact_item_normalizes_shared_contract() -> None:
- compact = compact_todo_summary_item(successor_item())
- assert compact["todo_id"] == SUCCESSOR_ID, compact
- assert compact["required_write_scopes"] == ["loopx/**"], compact
- assert compact["decision_scope"]["scope_key"] == "claim", compact
- assert compact["task_class"] == "advancement_task", compact
-
-
-def assert_source_items_dedupe_and_mark_handoff_successor_ready() -> None:
- value = {
- "first_open_items": [
- successor_item(),
- {
- "index": 4,
- "text": DUPLICATE_TEXT,
- "status": "open",
- "task_class": "advancement_task",
- },
- {
- "index": 5,
- "text": " ",
- "status": "open",
- },
- ],
- "backlog_items": [
- successor_item(text="[P1] Later duplicate must not replace first source."),
- {
- "index": 4,
- "text": DUPLICATE_TEXT,
- "status": "open",
- "task_class": "advancement_task",
- },
- ],
- "items": [
- {
- "index": 1,
- "todo_id": GATE_ID,
- "text": "[P0] Cleared handoff gate.",
- "status": "done",
- "done": True,
- "task_class": "blocker",
- "continuation_policy": "independent_handoff",
- "excluded_agents": ["codex-product-capability"],
- "unblocks_todo_id": SUCCESSOR_ID,
- },
- successor_item(index=3),
- ],
- }
-
- items = todo_summary_source_items(value)
- assert [item.get("todo_id") for item in items] == [SUCCESSOR_ID, None], items
- successor = items[0]
- assert successor["text"] == SUCCESSOR_TEXT, successor
- assert successor["resume_ready"] is True, successor
- assert successor["resume_condition"] == {
- "schema_version": "todo_resume_condition_v0",
- "resume_when": f"todo_done:{GATE_ID}",
- "satisfied": True,
- "source": "handoff_gate_cleared_with_successor",
- }, successor
- assert items[1]["text"] == DUPLICATE_TEXT, items
-
-
-def main() -> int:
- assert_compact_item_normalizes_shared_contract()
- assert_source_items_dedupe_and_mark_handoff_successor_ready()
- print("todo-summary-item-source-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/control_plane/todo-user-gate-readmodel-smoke.py b/examples/control_plane/todo-user-gate-readmodel-smoke.py
deleted file mode 100644
index 4c9c9c0d63..0000000000
--- a/examples/control_plane/todo-user-gate-readmodel-smoke.py
+++ /dev/null
@@ -1,221 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the shared user-gate todo read model."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.todos.quota_summary import ( # noqa: E402
- summarize_user_todos_for_quota,
-)
-from loopx.control_plane.todos.user_gate import ( # noqa: E402
- build_gate_prompt,
- has_open_user_gate_todo,
- is_user_gate_todo_item,
- open_todo_count,
- open_user_gate_todo_items,
- should_notify_user_on_open_todo,
- user_gate_todo_notify_reason,
-)
-
-
-AGENT_IDENTITY = {"agent_id": "codex-product-capability"}
-
-
-def raw_todos() -> dict:
- return {
- "schema_version": "todo_summary_v0",
- "open_count": 6,
- "items": [
- {
- "index": 1,
- "todo_id": "todo_gate_current",
- "text": "Approve product capability runtime write.",
- "task_class": "user_gate",
- "action_kind": "approval",
- "blocks_agent": "codex-product-capability",
- },
- {
- "index": 2,
- "todo_id": "todo_gate_other",
- "text": "Approve main-control production rollout.",
- "task_class": "user_gate",
- "action_kind": "production_rollout",
- "blocks_agent": "codex-main-control",
- },
- {
- "index": 3,
- "todo_id": "todo_next",
- "text": "Continue non-benchmark control-plane refactor.",
- "task_class": "user_action",
- "bound_agent": "codex-product-capability",
- },
- {
- "index": 4,
- "todo_id": "todo_action_other",
- "text": "Review main-control follow-up notes.",
- "task_class": "user_action",
- "bound_agent": "codex-main-control",
- },
- {
- "index": 5,
- "todo_id": "todo_action_goal",
- "text": "Review the goal-wide follow-up note.",
- "task_class": "user_action",
- "goal_bound": True,
- },
- {
- "index": 6,
- "todo_id": "todo_action_legacy_other",
- "text": "Review a legacy main-control follow-up note.",
- "task_class": "user_action",
- "claimed_by": "codex-main-control",
- },
- ],
- }
-
-
-def assert_shared_gate_detection() -> None:
- assert is_user_gate_todo_item(
- {
- "action_kind": "public_claim_review",
- "text": "Review the public claim.",
- }
- )
- assert not is_user_gate_todo_item(
- {
- "task_class": "advancement_task",
- "action_kind": "public_claim_review",
- "text": "Review the public claim.",
- }
- )
- assert is_user_gate_todo_item(
- {
- "task_class": "user_gate",
- "action_kind": "public_claim_review",
- "text": "Review the public claim.",
- }
- )
- assert not is_user_gate_todo_item(
- {
- "task_class": "user_action",
- "action_kind": "approval",
- "text": "Non-blocking user follow-up.",
- }
- )
- summary = summarize_user_todos_for_quota(
- raw_todos(),
- agent_identity=AGENT_IDENTITY,
- filter_user_gate_blocks_agent=True,
- )
- assert summary is not None
- assert summary["open_count"] == 3, summary
- assert summary["all_open_count"] == 6, summary
- assert summary["other_agent_scoped_open_count"] == 1, summary
- assert summary["user_action_open_count"] == 2, summary
- assert summary["other_agent_bound_user_action_open_count"] == 2, summary
- assert [
- item["todo_id"]
- for item in summary["other_agent_bound_user_action_items"]
- ] == ["todo_action_legacy_other", "todo_action_other"], summary
-
- with_duplicate = {
- "open_count": "2",
- "gate_open_items": [summary["gate_open_items"][0]],
- "first_open_items": [
- summary["gate_open_items"][0],
- summary["user_action_items"][0],
- ],
- }
- gate_items = open_user_gate_todo_items(with_duplicate)
- assert [item["todo_id"] for item in gate_items] == ["todo_gate_current"], gate_items
- assert open_todo_count(with_duplicate) == 2
- assert has_open_user_gate_todo(with_duplicate)
- assert user_gate_todo_notify_reason(with_duplicate) == (
- "open user_gate todo requires owner decision before approval"
- )
-
-
-def assert_notification_policy() -> None:
- summary = {"open_count": 1, "first_open_items": [{"text": "Need owner decision"}]}
- assert should_notify_user_on_open_todo(
- state="waiting",
- waiting_on="codex",
- user_todo_summary=summary,
- )
- assert should_notify_user_on_open_todo(
- state="eligible",
- waiting_on="external_evidence",
- user_todo_summary=summary,
- )
- assert not should_notify_user_on_open_todo(
- state="operator_gate",
- waiting_on="controller",
- user_todo_summary=summary,
- )
- assert not should_notify_user_on_open_todo(
- state="eligible",
- waiting_on="codex",
- user_todo_summary={"open_count": 0},
- )
-
-
-def assert_operator_gate_prompt() -> None:
- prompt = build_gate_prompt(
- {
- "operator_question": "Can the side agent self-merge this refactor?",
- "recommended_action": "Approve after premerge canary.",
- "next_handoff_condition": "PR merged and successor todo linked.",
- "missing_gates": ["owner_approval"],
- },
- user_todo_summary={
- "open_count": 1,
- "first_open_items": [
- {
- "index": 1,
- "todo_id": "todo_gate_current",
- "text": "Approve the scoped refactor.",
- "task_class": "user_gate",
- }
- ],
- },
- )
- assert prompt is not None
- assert "Can the side agent self-merge this refactor?" in prompt, prompt
- assert "owner_approval" in prompt, prompt
- assert "Approve the scoped refactor." in prompt, prompt
-
- other_agent_prompt = build_gate_prompt(
- {},
- user_todo_summary={
- "open_count": 0,
- "other_agent_scoped_open_count": 1,
- "all_open_count": 2,
- "other_agent_scoped_items": [
- {
- "index": 7,
- "todo_id": "todo_other",
- "text": "Approve another agent boundary.",
- }
- ],
- },
- )
- assert other_agent_prompt is not None
- assert "其他 agent/global 用户待办" in other_agent_prompt, other_agent_prompt
-
-
-def main() -> None:
- assert_shared_gate_detection()
- assert_notification_policy()
- assert_operator_gate_prompt()
- print("todo user-gate read model smoke passed")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/coordination/remote-authority-client.ts b/examples/coordination/remote-authority-client.ts
index 9485c66d48..21232642b7 100644
--- a/examples/coordination/remote-authority-client.ts
+++ b/examples/coordination/remote-authority-client.ts
@@ -15,5 +15,5 @@ const result = await callRemoteAuthority(values.endpoint, process.env.LOOPX_AUTH
decodeRemoteAuthorityRequest(JSON.parse(raw)), {mode: values.recover ? "recover" : "execute",
...(values.ca ? {ca: await readFile(values.ca)} : {})});
process.stdout.write(`${JSON.stringify(result)}\n`);
-if (!["found", "missing", "result"].includes(String(result.status)) ||
+if (!["found", "missing", "result", "snapshot"].includes(String(result.status)) ||
result.status === "result" && !["applied", "no_change", "replayed", "recovered"].includes(String((result.result as Record)?.status))) process.exitCode = 1;
diff --git a/examples/coordination/remote-authority-compose/.dockerignore b/examples/coordination/remote-authority-compose/.dockerignore
new file mode 100644
index 0000000000..322bd34d38
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/.dockerignore
@@ -0,0 +1,5 @@
+*
+!loopx-source.tar.gz
+!Dockerfile
+!provision.mjs
+!launch.mjs
diff --git a/examples/coordination/remote-authority-compose/Dockerfile b/examples/coordination/remote-authority-compose/Dockerfile
new file mode 100644
index 0000000000..f1f1186164
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/Dockerfile
@@ -0,0 +1,14 @@
+FROM public.ecr.aws/docker/library/node:24.21.0-bookworm@sha256:3d27e5c11e5786e309ec3e03f93ae536eb36e6e5eb3714d5eb3300a36157add0
+ARG LOOPX_REVISION
+ARG LOOPX_SOURCE_SHA256
+WORKDIR /opt/loopx
+LABEL org.opencontainers.image.source="https://github.com/loopx-project/loopx" \
+ org.opencontainers.image.revision="${LOOPX_REVISION}"
+COPY loopx-source.tar.gz /tmp/loopx-source.tar.gz
+RUN printf '%s %s\n' "$LOOPX_SOURCE_SHA256" /tmp/loopx-source.tar.gz | sha256sum -c - \
+ && tar -xzf /tmp/loopx-source.tar.gz \
+ && rm /tmp/loopx-source.tar.gz \
+ && command -v openssl \
+ && npm ci --ignore-scripts --no-audit --no-fund --include=dev
+COPY provision.mjs launch.mjs ./
+USER 1000:1000
diff --git a/examples/coordination/remote-authority-compose/README.en.md b/examples/coordination/remote-authority-compose/README.en.md
new file mode 100644
index 0000000000..abd42cbe9e
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/README.en.md
@@ -0,0 +1,58 @@
+# Self-hosted LoopX coordination
+
+Extract a built bundle on a machine with Docker Engine and Compose, then run the commands below. The first start uses container registries and npm. Select a free loopback port with `LOOPX_PORT`, which defaults to 8443.
+
+```sh
+./start.sh
+./client.sh a read
+./client.sh b read
+./client.sh reader read
+```
+
+Two trusted writers have distinct credentials and can hand off the same starter Todo. An additional `reader` has its own credential and can read only the allowed starter task. The first start provisions PostgreSQL authority state, a private CA and clients. Later starts reuse the task, store identity and policies from the volumes. The database runs on an internal network.
+
+Use `./client.sh a descriptor` to get the tenant, Goal, actor and store identity. Pass the request on standard input to `./client.sh a request`. When a reply is lost, keep the original request and `request_id` and pass them to `./client.sh a recover`.
+
+A remote client can forward the server's loopback port over SSH and use the same revision of `remote-authority-client.ts` with `--ca`. Export the CA with `./client.sh a ca` and deliver the client's `credential` and `request.json` privately from its volume. The CLI reads the credential from `LOOPX_AUTHORITY_CREDENTIAL`. [Gateway requests and recovery](https://github.com/loopx-project/loopx/blob/main/docs/reference/remote-authority-task-service-v0.md)
+
+Both TLS gateways publish loopback ports: trusted writers use `LOOPX_PORT` (8443 by default), while the scoped reader uses `LOOPX_READ_PORT` (8444 by default). Its private policy binds the exact Goal lifetime, Todo and original creation/binding receipt. Unlisted resources are denied. Snapshots return only allowed state, without notes, lease keys or a global cursor. Todo access does not authorize historical operation receipts.
+
+The trusted writer endpoint retains v0 scope/operation grants; a/b can read other tasks in the same scope. The v1 resource ACL supports read/snapshot, not resource-scoped writes. Give observers only the reader credential and read port. Both listeners reuse the existing service and restricted database role. Reader isolation does not qualify resource isolation for writers. TLS covers client-to-gateway connections; database connections use the isolated backend network.
+
+## Build and qualify
+
+Run this from the reviewed template checkout. Supply the complete Git commit to use for the gateway build.
+
+```sh
+python3 examples/coordination/remote-authority-compose/build_bundle.py \
+ --source-revision "$(git rev-parse HEAD)" --output /tmp/loopx-authority.tar.gz
+```
+
+The same source commit and template contents produce the same archive. The bundle contains `LICENSE`, `NOTICE`, the source digest and pinned image manifests. Docker verifies the digest before unpacking the source. Keep generated bundles, credentials, data and backups in their respective release or runtime storage.
+
+The source revision must include scoped v1 reads (#8861). Qualify from an unpacked bundle on a disposable Docker host with a unique project name and two free loopback ports. On amd64, verify the architecture of the host and running services. Time cold and cached starts through image pull, build, readiness and client reads. Check that PostgreSQL has no published port, clients have no route to the backend network and they have no database credential.
+
+Run the rehearsal from the repository. It creates a temporary project, exercises writer claim, expiry, takeover, original receipt recovery and replay after restart for creation and completion, plus reader filtering, write denial, persistent revocation and missing/malformed policy refusal, then removes its own containers and volumes.
+
+```sh
+node examples/coordination/remote-authority-compose/rehearse.mjs /path/to/unpacked-bundle
+```
+
+Compose limits CPU, memory, processes and retained logs. Check the Docker data disk and current load before a shared-host trial. Use dedicated projects, ports, networks and volumes. Tests with two local clients qualify the protocol. Qualifying two physical hosts requires a client on the second host.
+
+## Back up, restore and rotate
+
+```sh
+./state.sh backup /absolute/path/to/new-backup
+./start.sh
+COMPOSE_PROJECT_NAME=loopx-restored ./state.sh restore /absolute/path/to/new-backup
+COMPOSE_PROJECT_NAME=loopx-restored LOOPX_PORT=8445 LOOPX_READ_PORT=8446 ./start.sh
+```
+
+Backup stops the project and captures its database and credential volumes together. Keep backups encrypted and access-controlled. Restore verifies the digests and bundle version, and requires a new project with no existing target volumes. Read back tasks and original operation receipts before switching clients, and stop admitting requests on the old project first.
+
+- Revoke access by atomically replacing `policy.json` in the relevant gateway volume: `reader-gateway` for scoped reads and `gateway` for trusted writes. Removing a resource entry or credential rejects the next request. Replacing a running v1 listener's policy with v0 cannot downgrade its permissions. Rotate high-entropy credentials together with their private policy digest and client file. Earlier backups still contain earlier credentials.
+- The generated leaf certificate lasts 397 days. Reissue it before expiry with the CA in `pg-admin` and the original SANs. Before switching, verify the new certificate with the existing CA on the clients and confirm their clocks have reached its `notBefore` time. Replace the matching `cert.pem` and `key.pem` in both the `gateway` and `reader-gateway` volumes. With the same Compose project settings, run `docker compose restart gateway reader-gateway`. Use `docker compose ps gateway reader-gateway` to confirm both services are healthy, then verify both TLS endpoints and read back the task with `./client.sh a read`, `./client.sh b read` and `./client.sh reader read`. Distribute trust before rotating a CA.
+- Back up before changing database credentials or versions. Rehearse migration and rollback in an isolated project. Update database roles and credential files together. Follow PostgreSQL's supported migration procedure across major versions.
+
+[简体中文](README.md)
diff --git a/examples/coordination/remote-authority-compose/README.md b/examples/coordination/remote-authority-compose/README.md
new file mode 100644
index 0000000000..32965aead0
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/README.md
@@ -0,0 +1,58 @@
+# LoopX 远程协同自托管
+
+在装有 Docker Engine 和 Compose 的机器上解压构建好的包,进入目录运行。首次启动需要访问镜像仓库和 npm。选一个空闲的回环端口,默认使用 8443。
+
+```sh
+./start.sh
+./client.sh a read
+./client.sh b read
+./client.sh reader read
+```
+
+两个可信写客户端拥有不同凭据,可以交接同一个示例任务。额外的 `reader` 使用独立凭据,只能读取获准的示例任务。首次启动创建 PostgreSQL 权威库、私有 CA 和客户端。重复启动沿用卷里的任务、存储身份和撤权策略。数据库在内部网络中运行。
+
+用 `./client.sh a descriptor` 取得请求的租户、Goal、Actor 和存储实例。把请求放在标准输入上,用 `./client.sh a request` 执行。发送超时后,保留原请求及 `request_id`,通过 `./client.sh a recover` 查询回执。
+
+远端客户端可用 SSH 将网关的回环端口转发到本机,再用同一版本的 `remote-authority-client.ts` 和 `--ca` 连接。管理员可导出 `./client.sh a ca`,并私下交付对应客户端卷中的 `credential` 和 `request.json`。客户端通过 `LOOPX_AUTHORITY_CREDENTIAL` 接收凭据。 [网关请求与重试说明(英文)](https://github.com/loopx-project/loopx/blob/main/docs/reference/remote-authority-task-service-v0.md)
+
+两个 TLS 网关都只发布回环端口:可信写客户端使用 `LOOPX_PORT`(默认 8443),受限读者使用 `LOOPX_READ_PORT`(默认 8444)。`reader` 的私有策略绑定当前 Goal 实例、具体 Todo 及其原始创建/绑定回执;未列入的资源默认拒绝。snapshot 仅返回获准状态,不含 note、租约密钥或全局游标。读授权不授予历史操作回执访问。
+
+可信写入口保留 v0 的范围和操作授权,a/b 可读取同范围任务;当前 v1 资源 ACL 只支持 read/snapshot,不能提供资源级写隔离。向观察者仅交付 `reader` 的凭据和只读端口。两入口共用原服务和受限数据库角色,不能将读者隔离表述为写客户端也被资源 ACL 限制。客户端到网关使用 TLS,数据库连接走隔离 backend 网络。
+
+## 构建和验收
+
+从经审阅的模板 checkout 运行。选择用于构建网关的完整 Git 提交。
+
+```sh
+python3 examples/coordination/remote-authority-compose/build_bundle.py \
+ --source-revision "$(git rev-parse HEAD)" --output /tmp/loopx-authority.tar.gz
+```
+
+同一源码提交和模板内容生成相同的归档。归档内含 `LICENSE`、`NOTICE`、源码摘要及固定镜像清单。Docker 构建前会校验源码摘要。生成物、运行凭据、数据库和备份应存放在各自的发布或运行位置。
+
+源码版本须包含 scoped v1 读取实现(#8861)。在专用测试 Docker 环境中解压验证,使用唯一的 Compose 项目名和两个空闲回环端口。在 amd64 主机上验证本机架构和实际运行架构。冷启动与缓存启动分别记录镜像拉取、构建、就绪与客户端首次读回时间。确认数据库端口未发布,客户端无法访问 backend 网络,网关不向客户端提供数据库凭据。
+
+从仓库运行下列演练。它会创建临时项目,验证写客户端的认领、到期接管、新增任务与完成操作的原回执恢复及重启重放,以及只读客户端的资源过滤、拒写、撤权重启和策略缺失/损坏拒绝,最后清理自己的容器和卷。
+
+```sh
+node examples/coordination/remote-authority-compose/rehearse.mjs /path/to/unpacked-bundle
+```
+
+Compose 为数据库、网关及辅助容器设置 CPU、内存、进程数和日志轮转。共享主机还需核对 Docker 数据盘空间与已有负载。选择独立项目名、端口、网络和卷。两个同主机容器可以验证协议,跨物理主机资格需从另一台主机连接验证。
+
+## 备份、恢复和轮换
+
+```sh
+./state.sh backup /absolute/path/to/new-backup
+./start.sh
+COMPOSE_PROJECT_NAME=loopx-restored ./state.sh restore /absolute/path/to/new-backup
+COMPOSE_PROJECT_NAME=loopx-restored LOOPX_PORT=8445 LOOPX_READ_PORT=8446 ./start.sh
+```
+
+备份会停止当前 Compose 项目,保存同一时点的数据库和凭据卷。请将含私钥及数据库凭据的备份放在加密受限的位置。恢复前校验摘要和包版本,并要求新项目的目标卷尚未创建。启动后读回任务和原操作回执,确认旧项目已停止接收请求再切换入口。
+
+- 撤权时原子替换对应网关卷中的 `policy.json`。只读策略位于 `reader-gateway` 卷,写策略位于 `gateway` 卷;撤销资源条目或凭据后下一次请求即拒绝。不能把 v0 策略放到已启动的 v1 监听器来降级权限。轮换密钥须生成新的高熵凭据,同步更新私有策略和客户端凭据。备份也含历史凭据。
+- 自动生成的服务叶证书有效期为 397 天。到期前用 `pg-admin` 中的 CA 续签,保留原 SAN。切换前在客户端用原 CA 校验新证书,确认各客户端时钟已到新证书的 `notBefore` 时间。将配对的 `cert.pem` 和 `key.pem` 更新到 `gateway` 与 `reader-gateway` 两个卷中。沿用同一 Compose 项目配置运行 `docker compose restart gateway reader-gateway`。用 `docker compose ps gateway reader-gateway` 确认两个服务均已就绪(`healthy`),再校验两个 TLS 入口,再用 `./client.sh a read`、`./client.sh b read` 和 `./client.sh reader read` 读回任务。更换 CA 时提前分发新信任。
+- 更新 PostgreSQL 口令或版本前先备份,在隔离项目演练迁移和回退。同步修改数据库角色与对应凭据文件。PostgreSQL 跨大版本需使用其正式迁移流程。
+
+[English](README.en.md)
diff --git a/examples/coordination/remote-authority-compose/build_bundle.py b/examples/coordination/remote-authority-compose/build_bundle.py
new file mode 100644
index 0000000000..baa8f4beb0
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/build_bundle.py
@@ -0,0 +1,102 @@
+#!/usr/bin/env python3
+"""Build a source-pinned, reproducible LoopX self-hosting bundle."""
+
+import argparse
+import gzip
+import hashlib
+import io
+import os
+from pathlib import Path
+import re
+import subprocess
+import tarfile
+import tempfile
+
+
+TEMPLATE = Path(__file__).resolve().parent
+REPOSITORY = TEMPLATE.parents[2]
+BUNDLE_NAME = "loopx-remote-authority-compose"
+SOURCE_PATHS = (
+ "LICENSE",
+ "NOTICE",
+ "package.json",
+ "package-lock.json",
+ "examples/coordination/remote-authority-client.ts",
+ "examples/coordination/remote-authority-service.ts",
+ "loopx/control_plane",
+)
+BUNDLE_FILES = (
+ ".dockerignore",
+ "Dockerfile",
+ "README.en.md",
+ "README.md",
+ "client.sh",
+ "compose.yaml",
+ "launch.mjs",
+ "provision.mjs",
+ "start.sh",
+ "state.sh",
+)
+
+
+def git(*args: str) -> bytes:
+ return subprocess.check_output(["git", *args], cwd=REPOSITORY)
+
+
+def gzip_archive(data: bytes) -> bytes:
+ encoded = io.BytesIO()
+ with gzip.GzipFile(filename="", fileobj=encoded, mode="wb", mtime=0) as compressed:
+ compressed.write(data)
+ return encoded.getvalue()
+
+
+def bundle(revision: str) -> bytes:
+ source_tar = git("archive", "--format=tar", revision, "--", *SOURCE_PATHS)
+ source_archive = gzip_archive(source_tar)
+ source_digest = hashlib.sha256(source_archive).hexdigest()
+ files = {name: (TEMPLATE / name).read_bytes() for name in BUNDLE_FILES}
+ image_id = hashlib.sha256(b"".join(
+ hashlib.sha256(data).digest()
+ for data in (source_archive, files["Dockerfile"], files["compose.yaml"],
+ files["provision.mjs"], files["launch.mjs"])
+ )).hexdigest()
+ files[".env"] = (
+ f"LOOPX_REVISION={revision}\nLOOPX_SOURCE_SHA256={source_digest}\n"
+ f"LOOPX_IMAGE_ID={image_id}\n"
+ ).encode("ascii")
+ files["loopx-source.tar.gz"] = source_archive
+ for name in ("LICENSE", "NOTICE"):
+ files[name] = git("show", f"{revision}:{name}")
+
+ archive = io.BytesIO()
+ with tarfile.open(fileobj=archive, mode="w", format=tarfile.USTAR_FORMAT) as output:
+ for name, contents in sorted(files.items()):
+ entry = tarfile.TarInfo(f"{BUNDLE_NAME}/{name}")
+ entry.size = len(contents)
+ entry.mode = 0o755 if name.endswith(".sh") else 0o644
+ output.addfile(entry, io.BytesIO(contents))
+ return gzip_archive(archive.getvalue())
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source-revision", required=True, help="full LoopX Git commit")
+ parser.add_argument("--output", type=Path, required=True, help="new tar.gz file")
+ args = parser.parse_args()
+ if not re.fullmatch(r"[0-9a-f]{40}", args.source_revision):
+ parser.error("--source-revision must be a full lowercase Git commit SHA")
+ try:
+ if git("cat-file", "-t", args.source_revision).strip() != b"commit":
+ parser.error("--source-revision must identify a commit")
+ contents = bundle(args.source_revision)
+ with tempfile.TemporaryDirectory(dir=args.output.parent) as work:
+ temporary = Path(work) / "bundle.tar.gz"
+ temporary.write_bytes(contents)
+ os.link(temporary, args.output)
+ except (OSError, subprocess.CalledProcessError) as error:
+ parser.exit(1, f"Could not build bundle: {error}\n")
+ print(f"{hashlib.sha256(contents).hexdigest()} {args.output}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/coordination/remote-authority-compose/client.sh b/examples/coordination/remote-authority-compose/client.sh
new file mode 100755
index 0000000000..97c343ddfb
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/client.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+set -eu
+case "${1:-}" in
+ a|b|reader) actor=$1; shift ;;
+ *) printf '%s\n' "Usage: ./client.sh a|b|reader [read|request|recover|descriptor|ca]" >&2; exit 2 ;;
+esac
+directory=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+cd "$directory"
+[ "$#" -gt 0 ] || set -- read
+exec docker compose run --rm --no-deps -T "client-${actor}" "$@"
diff --git a/examples/coordination/remote-authority-compose/compose.yaml b/examples/coordination/remote-authority-compose/compose.yaml
new file mode 100644
index 0000000000..79b17816d4
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/compose.yaml
@@ -0,0 +1,147 @@
+name: loopx-authority
+x-app: &app
+ image: loopx/remote-authority:${LOOPX_IMAGE_ID:?unpack a generated bundle}
+ pull_policy: never
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: [no-new-privileges:true]
+ cpus: "0.50"
+ mem_limit: 512m
+ pids_limit: 128
+ logging: &bounded-logs
+ driver: local
+ options:
+ max-size: "10m"
+ max-file: "3"
+services:
+ secrets:
+ <<: *app
+ build:
+ context: .
+ args:
+ LOOPX_REVISION: ${LOOPX_REVISION:?unpack a generated bundle}
+ LOOPX_SOURCE_SHA256: ${LOOPX_SOURCE_SHA256:?unpack a generated bundle}
+ user: "0:0"
+ cap_add: [CHOWN, DAC_OVERRIDE]
+ network_mode: none
+ tmpfs: [/tmp]
+ command: [node, --experimental-strip-types, provision.mjs, secrets]
+ volumes:
+ - pg-admin:/secrets/admin
+ - pg-auth:/secrets/pg-auth
+ - pg-data:/secrets/database:ro
+ - gateway:/secrets/gateway
+ - reader-gateway:/secrets/reader-gateway
+ - client-a:/secrets/client-a
+ - client-b:/secrets/client-b
+ - reader:/secrets/reader
+ - health:/secrets/health
+ db:
+ image: public.ecr.aws/docker/library/postgres:16.16-bookworm@sha256:a49f7438ba03589f9b1ca062f2da82e899b48ea1dc50d2449fa09a70be83ebca
+ depends_on:
+ secrets:
+ condition: service_completed_successfully
+ environment:
+ POSTGRES_DB: authority
+ POSTGRES_USER: bootstrap
+ POSTGRES_PASSWORD_FILE: /secrets/pg-auth/postgres-password
+ volumes:
+ - pg-auth:/secrets/pg-auth:ro
+ - pg-data:/var/lib/postgresql/data
+ networks: [backend]
+ cpus: "0.75"
+ mem_limit: 768m
+ pids_limit: 128
+ logging: *bounded-logs
+ restart: unless-stopped
+ healthcheck:
+ test: [CMD, pg_isready, -h, 127.0.0.1, -U, bootstrap, -d, authority]
+ interval: 2s
+ timeout: 2s
+ retries: 40
+ setup:
+ <<: *app
+ user: "0:0"
+ cap_add: [DAC_OVERRIDE]
+ depends_on:
+ db:
+ condition: service_healthy
+ command: [node, --experimental-strip-types, provision.mjs, database]
+ volumes:
+ - pg-admin:/secrets/admin
+ - pg-auth:/secrets/pg-auth:ro
+ - gateway:/secrets/gateway:ro
+ networks: [backend]
+ gateway:
+ <<: *app
+ depends_on:
+ setup:
+ condition: service_completed_successfully
+ command: [node, --experimental-strip-types, launch.mjs, gateway]
+ volumes:
+ - gateway:/secrets/gateway:ro
+ - health:/secrets/health:ro
+ networks: [frontend, backend]
+ ports:
+ - "127.0.0.1:${LOOPX_PORT:-8443}:8443"
+ restart: unless-stopped
+ healthcheck:
+ test: [CMD, node, --experimental-strip-types, launch.mjs, health]
+ interval: 3s
+ timeout: 4s
+ retries: 25
+ client-a:
+ <<: *app
+ profiles: [clients]
+ entrypoint: [node, --experimental-strip-types, launch.mjs, client]
+ volumes:
+ - client-a:/secrets/client:ro
+ networks: [frontend]
+ client-b:
+ <<: *app
+ profiles: [clients]
+ entrypoint: [node, --experimental-strip-types, launch.mjs, client]
+ volumes:
+ - client-b:/secrets/client:ro
+ networks: [frontend]
+ reader-gateway:
+ <<: *app
+ depends_on:
+ setup:
+ condition: service_completed_successfully
+ command: [node, --experimental-strip-types, launch.mjs, reader-gateway]
+ volumes:
+ - reader-gateway:/secrets/reader-gateway:ro
+ - reader:/secrets/client:ro
+ networks: [frontend, backend]
+ ports:
+ - "127.0.0.1:${LOOPX_READ_PORT:-8444}:8443"
+ restart: unless-stopped
+ healthcheck:
+ test: [CMD, node, --experimental-strip-types, launch.mjs, reader-health]
+ interval: 3s
+ timeout: 4s
+ retries: 25
+ client-reader:
+ <<: *app
+ profiles: [clients]
+ entrypoint: [node, --experimental-strip-types, launch.mjs, client]
+ environment:
+ LOOPX_SERVICE_HOST: reader-gateway
+ volumes:
+ - reader:/secrets/client:ro
+ networks: [frontend]
+networks:
+ backend:
+ internal: true
+ frontend:
+volumes:
+ pg-admin:
+ pg-auth:
+ pg-data:
+ gateway:
+ reader-gateway:
+ client-a:
+ client-b:
+ reader:
+ health:
diff --git a/examples/coordination/remote-authority-compose/launch.mjs b/examples/coordination/remote-authority-compose/launch.mjs
new file mode 100644
index 0000000000..33bc880fe6
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/launch.mjs
@@ -0,0 +1,44 @@
+import {readFileSync} from "node:fs";
+import {callRemoteAuthority} from "./loopx/control_plane/coordination/remote_authority_http.ts";
+
+const [mode, action = "read"] = process.argv.slice(2);
+const port = "8443";
+const read = (directory, file) => readFileSync(`/secrets/${directory}/${file}`, "utf8");
+
+async function main() {
+ if (mode === "gateway" || mode === "reader-gateway") {
+ const password = read(mode, "database-password");
+ process.env.LOOPX_AUTHORITY_DATABASE_URL = `postgresql://loopx_gateway:${encodeURIComponent(password)}@db:5432/authority`;
+ process.argv.splice(2, Infinity, "--policy", `/secrets/${mode}/policy.json`,
+ "--cert", `/secrets/${mode}/cert.pem`, "--key", `/secrets/${mode}/key.pem`,
+ "--host", "0.0.0.0", "--port", port);
+ await import("./examples/coordination/remote-authority-service.ts");
+ return;
+ }
+ const directory = mode === "health" ? "health" : "client";
+ const descriptor = read(directory, "request.json");
+ const ca = read(directory, "ca.pem");
+ if (action === "descriptor" || action === "ca") {
+ process.stdout.write(action === "descriptor" ? descriptor + "\n" : ca);
+ return;
+ }
+ const endpoint = mode === "health" || mode === "reader-health" ? `https://127.0.0.1:${port}`
+ : `https://${process.env.LOOPX_SERVICE_HOST ?? "gateway"}:${port}`;
+ const credential = read(directory, "credential");
+ if (action === "request" || action === "recover") {
+ process.env.LOOPX_AUTHORITY_CREDENTIAL = credential;
+ process.argv.splice(2, Infinity, "--endpoint", endpoint, "--ca", `/secrets/${directory}/ca.pem`);
+ if (action === "recover") process.argv.push("--recover");
+ await import("./examples/coordination/remote-authority-client.ts");
+ return;
+ }
+ if (action !== "read") throw new Error("Unknown command");
+ const result = await callRemoteAuthority(endpoint, credential, JSON.parse(descriptor), {ca: Buffer.from(ca)});
+ if (mode === "client") process.stdout.write(JSON.stringify(result) + "\n");
+ if (result.status !== "found") process.exitCode = 1;
+}
+
+main().catch(() => {
+ console.error("LoopX command failed");
+ process.exitCode = 1;
+});
diff --git a/examples/coordination/remote-authority-compose/provision.mjs b/examples/coordination/remote-authority-compose/provision.mjs
new file mode 100644
index 0000000000..0d1d68c718
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/provision.mjs
@@ -0,0 +1,223 @@
+import {createHash, randomBytes} from "node:crypto";
+import {execFileSync} from "node:child_process";
+import {chmodSync, chownSync, existsSync, linkSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync} from "node:fs";
+import {dirname, join} from "node:path";
+import {REMOTE_AUTHORITY_POLICY, REMOTE_AUTHORITY_SCOPED_READ_POLICY} from "./loopx/control_plane/coordination/remote_authority_policy.ts";
+
+const admin = "/secrets/admin";
+const pgAuth = "/secrets/pg-auth";
+const generationFile = join(admin, "generation.json");
+const provisionedFlag = join(admin, "volumes-ready");
+const installedFlag = join(admin, "database-ready");
+const tenant = "local";
+const goal = "collaboration";
+const todo = "todo_welcome";
+const actors = ["client-a", "client-b", "health", "reader"];
+const bindingOperation = "compose-bind-starter-goal";
+const goalRef = identity => ({goal_id: goal, goal_instance_id: `ginst_${identity.slice("postgresql:".length)}`});
+const secret = () => randomBytes(32).toString("hex");
+const read = path => readFileSync(path, "utf8");
+const policyDigest = value => createHash("sha256").update(value).digest("hex");
+
+function createFile(path, value, uid = 0, replace = false) {
+ const temporary = mkdtempSync(join(dirname(path), ".init-"));
+ const entry = join(temporary, "file");
+ try {
+ writeFileSync(entry, value, {mode: 0o400, flag: "wx", flush: true});
+ chownSync(entry, uid, uid);
+ try {
+ if (replace) renameSync(entry, path);
+ else linkSync(entry, path);
+ } catch (error) {
+ if (error.code !== "EEXIST") throw error;
+ }
+ } finally {
+ rmSync(temporary, {recursive: true, force: true});
+ }
+}
+
+function newGeneration() {
+ const scratch = mkdtempSync("/tmp/authority-certs-");
+ const openssl = (...args) => execFileSync("openssl", args, {cwd: scratch, stdio: "ignore", timeout: 15000});
+ try {
+ openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
+ "-subj", "/CN=LoopX Local CA", "-days", "3650", "-sha256",
+ "-addext", "basicConstraints=critical,CA:TRUE,pathlen:0",
+ "-addext", "keyUsage=critical,keyCertSign,cRLSign",
+ "-keyout", "ca.key", "-out", "ca.pem");
+ openssl("req", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:P-256", "-nodes",
+ "-subj", "/CN=gateway", "-keyout", "server.key", "-out", "server.csr");
+ writeFileSync(join(scratch, "server.ext"), "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:gateway,DNS:reader-gateway,DNS:localhost,IP:127.0.0.1\n");
+ openssl("x509", "-req", "-in", "server.csr", "-CA", "ca.pem", "-CAkey", "ca.key",
+ "-CAcreateserial", "-days", "397", "-sha256", "-extfile", "server.ext", "-out", "server.pem");
+ return {
+ identity: `postgresql:${randomBytes(16).toString("hex")}`,
+ databasePassword: secret(),
+ runtimePassword: secret(),
+ credentials: Object.fromEntries(actors.map(actor => [actor, secret()])),
+ root: read(join(scratch, "ca.pem")),
+ rootKey: read(join(scratch, "ca.key")),
+ key: read(join(scratch, "server.key")),
+ cert: read(join(scratch, "server.pem")),
+ };
+ } finally {
+ rmSync(scratch, {recursive: true, force: true});
+ }
+}
+
+function prepareSecretVolumes() {
+ const requiredFiles = {
+ gateway: ["database-password", "policy.json", "cert.pem", "key.pem"],
+ "reader-gateway": ["database-password", "policy.json", "cert.pem", "key.pem"],
+ ...Object.fromEntries(actors.map(actor => [actor, ["credential", "ca.pem", "request.json"]])),
+ "pg-auth": ["postgres-password"],
+ };
+ const hasDatabase = existsSync("/secrets/database/PG_VERSION");
+ if (!existsSync(generationFile)) {
+ const previous = hasDatabase || Object.keys(requiredFiles).some(volume => existsSync(`/secrets/${volume}/identity`));
+ if (previous) throw new Error("bootstrap identity missing for existing state");
+ chmodSync(admin, 0o700);
+ createFile(generationFile, JSON.stringify(newGeneration()));
+ }
+ const generation = JSON.parse(read(generationFile));
+ const {identity} = generation;
+ const initialized = existsSync(provisionedFlag);
+ if ((initialized && read(provisionedFlag) !== identity) || (existsSync(installedFlag) && !hasDatabase)) {
+ throw new Error("mismatched bootstrap identity or missing existing database volume");
+ }
+ if (!initialized) {
+ populateSecretVolumes(generation);
+ createFile(join(admin, "ca.key"), generation.rootKey);
+ createFile(join(admin, "ca.pem"), generation.root);
+ }
+ for (const [volume, files] of Object.entries(requiredFiles)) {
+ const location = `/secrets/${volume}`;
+ if (read(join(location, "identity")) !== identity || files.some(file => !existsSync(join(location, file)))) {
+ throw new Error("credential volume needs restoration");
+ }
+ }
+ createFile(provisionedFlag, identity);
+ // The generation record needs plaintext copies only to resume an interrupted first start.
+ if (generation.credentials) createFile(generationFile, JSON.stringify({identity}), 0, true);
+}
+
+function populateSecretVolumes({identity, credentials, root, cert, key, runtimePassword, databasePassword}) {
+ const scopes = [{tenant_id: tenant, goal_id: goal, store_identity: identity, registered_agents: actors}];
+ const principals = actors.filter(actor => actor !== "reader").map(actor => ({
+ principal_id: `principal-${actor}`,
+ credential_sha256: policyDigest(credentials[actor]),
+ grants: [{
+ tenant_id: tenant, goal_id: goal, actor_id: actor,
+ operations: actor === "health" ? ["read"] : [
+ "read", "claim", "progress", "renew", "release", "complete", ...(actor === "client-a" ? ["todo_add"] : []),
+ ],
+ }],
+ }));
+ const files = {
+ gateway: {"database-password": runtimePassword, "policy.json": JSON.stringify({
+ schema_version: REMOTE_AUTHORITY_POLICY, scopes, principals,
+ }), "cert.pem": cert, "key.pem": key},
+ "reader-gateway": {"database-password": runtimePassword, "policy.json": JSON.stringify({
+ schema_version: REMOTE_AUTHORITY_SCOPED_READ_POLICY,
+ scopes: [{...scopes[0], registered_agents: ["reader"], todo_read_acl: [{
+ goal_ref: goalRef(identity), todo_id: todo, principal_id: "principal-reader", actor_id: "reader",
+ todo_origin_operation_id: bindingOperation,
+ }]}],
+ principals: [{principal_id: "principal-reader", credential_sha256: policyDigest(credentials.reader),
+ grants: [{tenant_id: tenant, goal_id: goal, actor_id: "reader", goal_ref: goalRef(identity),
+ operations: ["read", "snapshot"]}]}],
+ }), "cert.pem": cert, "key.pem": key},
+ ...Object.fromEntries(actors.map(actor => [actor, {
+ credential: credentials[actor], "ca.pem": root,
+ "request.json": JSON.stringify({
+ schema_version: "loopx_remote_authority_request_v0", tenant_id: tenant, goal_id: goal,
+ store_identity: identity, actor_id: actor, todo_id: todo, operation: "read",
+ }),
+ }])),
+ "pg-auth": {"postgres-password": databasePassword},
+ };
+ for (const [volume, contents] of Object.entries(files)) {
+ const location = `/secrets/${volume}`;
+ const owner = volume === "pg-auth" ? 0 : 1000;
+ chmodSync(location, 0o700);
+ chownSync(location, owner, owner);
+ const marker = join(location, "identity");
+ createFile(marker, identity, owner);
+ if (read(marker) !== identity) throw new Error("mismatched credential volume");
+ for (const [file, value] of Object.entries(contents)) createFile(join(location, file), value, owner);
+ }
+}
+
+async function prepareDatabase() {
+ const {Pool} = await import("pg");
+ const {setupPostgreSqlAuthoritySchemaAndRole} = await import("./loopx/control_plane/coordination/postgresql_authority_seed.ts");
+ const {PostgreSqlAuthorityStore} = await import("./loopx/control_plane/coordination/postgresql_authority_store.ts");
+ const {coordinationTodoReadModel} = await import("./loopx/control_plane/coordination/coordination_projection.ts");
+ const {canonicalTodoDomainRecord, TODO_DOMAIN_ITEM_SCHEMA, TODO_DOMAIN_READ_RECORD_SCHEMA} =
+ await import("./loopx/control_plane/coordination/coordination_state_contract.ts");
+ const {materializeTodoRecordForSchema} = await import("./loopx/control_plane/coordination/todo_presentation.ts");
+ const {transitionGoalAcceptanceLifecycle} = await import("./loopx/control_plane/goals/acceptance_authority.ts");
+ const {identity} = JSON.parse(read(generationFile));
+ const runtimePassword = read("/secrets/gateway/database-password");
+ const installed = existsSync(installedFlag);
+ if (read(provisionedFlag) !== identity || (installed && read(installedFlag) !== identity)
+ || !/^[a-f0-9]{64}$/.test(runtimePassword)) throw new Error("mismatched database initialization state");
+ const opts = {host: "db", port: 5432, database: "authority", connectionTimeoutMillis: 5000, statement_timeout: 15000};
+ const scopedStore = pool => new PostgreSqlAuthorityStore({connect: async () => {
+ const client = await pool.connect();
+ return {query: (sql, args) => client.query(sql, args ? [...args] : undefined), release: error => client.release(error)};
+ }}, {tenant_id: tenant, goal_id: goal, expected_store_identity: identity});
+ const setup = new Pool({...opts, user: "bootstrap", password: read(join(pgAuth, "postgres-password"))});
+ const runtime = new Pool({...opts, user: "loopx_gateway", password: runtimePassword});
+ try {
+ if (!installed) {
+ const database = {connect: async () => {
+ const client = await setup.connect();
+ return {query: (sql, args) => client.query(sql, args ? [...args] : undefined), release: error => client.release(error)};
+ }};
+ const schema = await setupPostgreSqlAuthoritySchemaAndRole({database, storeIdentity: identity, runtimeRole: "loopx_gateway"});
+ if (schema.status !== "installed") throw new Error("authority schema installation failed");
+ const role = await setup.query("SELECT rolcanlogin FROM pg_roles WHERE rolname = 'loopx_gateway'");
+ if (!role.rows[0]?.rolcanlogin) {
+ await setup.query(`ALTER ROLE loopx_gateway LOGIN PASSWORD '${runtimePassword}'`);
+ }
+ await setup.query("REVOKE CONNECT, TEMPORARY ON DATABASE authority FROM PUBLIC; GRANT CONNECT ON DATABASE authority TO loopx_gateway");
+ const store = scopedStore(runtime);
+ const before = await store.loadAuthority();
+ if (before.status === "missing") {
+ const record = materializeTodoRecordForSchema(canonicalTodoDomainRecord({
+ schema_version: TODO_DOMAIN_ITEM_SCHEMA, todo_id: todo, role: "agent", status: "open",
+ done: false, archive_state: "active", task_class: "advancement_task",
+ text: "Verify the two-client handoff from claim to accepted result",
+ }), TODO_DOMAIN_READ_RECORD_SCHEMA, "starter Todo");
+ const todos = [record];
+ const seeded = await store.commitAuthority({operation_id: "compose-initial-state", expected_provider_revision: null,
+ next_projection: {goal_id: goal, handoff_mode: "hard_lease", todos, leases: [],
+ todo_read_model: coordinationTodoReadModel(todos, TODO_DOMAIN_READ_RECORD_SCHEMA)}, events: [], receipts: []});
+ if (seeded.status !== "applied") throw new Error("initial task could not be committed");
+ }
+ const bound = await transitionGoalAcceptanceLifecycle(store, {
+ goal_id: goal, actor_agent_id: null, operation_id: bindingOperation,
+ transition: {kind: "bind_existing", goal_ref: goalRef(identity)},
+ });
+ if (bound.status !== "applied" && bound.status !== "replayed") throw new Error("starter Goal could not be bound");
+ }
+ const after = await scopedStore(runtime).loadAuthority();
+ if (after.status !== "loaded") throw new Error("initialized database is unavailable");
+ createFile(installedFlag, identity);
+ } finally {
+ await Promise.all([setup.end(), runtime.end()]);
+ }
+}
+
+const phase = process.argv[2];
+try {
+ if (phase === "secrets") prepareSecretVolumes();
+ else if (phase === "database") await prepareDatabase();
+ else throw new Error("unknown bootstrap command");
+ process.stdout.write(`LoopX ${phase} ready\n`);
+} catch (error) {
+ // Database/crypto errors may reveal credentials. Expose the phase and stable code only.
+ console.error(`LoopX ${phase} failed (${error.code ?? "init_state"})`);
+ process.exitCode = 1;
+}
diff --git a/examples/coordination/remote-authority-compose/rehearse.mjs b/examples/coordination/remote-authority-compose/rehearse.mjs
new file mode 100644
index 0000000000..5cc85c59b2
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/rehearse.mjs
@@ -0,0 +1,175 @@
+#!/usr/bin/env node
+// Exercise the packaged entry points against a disposable Compose project.
+import assert from "node:assert/strict";
+import {spawnSync} from "node:child_process";
+import {randomBytes} from "node:crypto";
+import {createServer} from "node:net";
+import {resolve} from "node:path";
+import {performance} from "node:perf_hooks";
+import {setTimeout as sleep} from "node:timers/promises";
+
+const [bundle] = process.argv.slice(2);
+if (!bundle || process.argv.length !== 3 || bundle === "--help") {
+ console.log("Usage: node rehearse.mjs ");
+ process.exit(bundle === "--help" ? 0 : 2);
+}
+
+const project = `loopx-rehearsal-${randomBytes(6).toString("hex")}`;
+const cwd = resolve(bundle);
+const env = {...process.env, COMPOSE_PROJECT_NAME: project, LOOPX_PORT: await freeLoopbackPort(),
+ LOOPX_READ_PORT: await freeLoopbackPort()};
+const started = performance.now();
+let readySeconds;
+let operationError;
+
+async function freeLoopbackPort() {
+ const server = createServer();
+ await new Promise((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const port = server.address().port;
+ await new Promise(resolve => server.close(resolve));
+ return String(port);
+}
+
+function run(command, args, {input, allowRejected = false} = {}) {
+ const result = spawnSync(command, args, {cwd, env, input, encoding: "utf8", timeout: 150_000});
+ if (result.error) throw result.error;
+ if (result.signal || (result.status !== 0 && !allowRejected)) {
+ throw new Error(`${command} ${args.join(" ")} exited ${result.status ?? result.signal}: ${result.stderr.slice(-2048)}`);
+ }
+ return result.stdout;
+}
+
+function client(actor, action, request) {
+ return JSON.parse(run("./client.sh", [actor, action], {
+ input: request === undefined ? undefined : JSON.stringify(request),
+ allowRejected: true,
+ }));
+}
+
+try {
+ const startup = run("./start.sh", []);
+ const a = client("a", "descriptor");
+ const b = client("b", "descriptor");
+ const reader = client("reader", "descriptor");
+ const aStart = client("a", "read");
+ const bStart = client("b", "read");
+ assert.equal(aStart.status, "found");
+ assert.equal(bStart.status, "found");
+ assert.equal(aStart.provider_revision, bStart.provider_revision);
+ assert.deepEqual(aStart.todo, bStart.todo);
+ assert.notEqual(a.actor_id, b.actor_id);
+ assert.equal(client("reader", "read").schema_version, "loopx_remote_authority_scoped_read_response_v1");
+ readySeconds = Math.round((performance.now() - started) / 100) / 10;
+ const wrongStore = {...b, store_identity: "postgresql:" + "0".repeat(32)};
+ assert.equal(client("b", "request", wrongStore).status, "rejected");
+ assert.equal(client("b", "request", {...b, actor_id: a.actor_id}).status, "rejected");
+ const hidden = "todo_outside_read_grant";
+ const createHidden = {...a, todo_id: hidden, operation: "todo_add",
+ request_id: "rehearsal-create-hidden", text: "Task outside the reader grant",
+ note: "Private writer-only note"};
+ assert.equal(client("a", "request", createHidden).result.status, "applied");
+ const createdReceipt = client("a", "recover", createHidden);
+ assert.equal(createdReceipt.status, "found");
+ assert.equal(createdReceipt.historical_only, true);
+ assert.equal(createdReceipt.result.changed, true);
+ assert.equal(createdReceipt.result.todo.todo_id, hidden);
+ const beforeReadChecks = client("a", "read").provider_revision;
+ assert.equal(client("reader", "request", {...reader, todo_id: hidden}).status, "rejected");
+ assert.equal(client("reader", "request", {...reader, operation: "claim", request_id: "reader-cannot-claim"}).status, "rejected");
+ for (const scope of [{tenant_id: "other"}, {goal_id: "other"}, {actor_id: a.actor_id},
+ {store_identity: "postgresql:" + "0".repeat(32)}]) {
+ assert.equal(client("reader", "request", {...reader, ...scope}).status, "rejected");
+ }
+ const {todo_id: ignored, ...readerScope} = reader;
+ const snapshot = client("reader", "request", {...readerScope, operation: "snapshot"});
+ assert.equal(snapshot.status, "snapshot");
+ assert.deepEqual(snapshot.todos.map(row => row.todo_id), [reader.todo_id]);
+ assert.equal(Object.hasOwn(snapshot, "provider_revision"), false);
+ assert.equal(JSON.stringify(snapshot).includes("Private writer-only note"), false);
+ assert.equal(client("a", "read").provider_revision, beforeReadChecks);
+
+ const claimA = {...a, operation: "claim", request_id: "rehearsal-claim-a"};
+ const acquired = client("a", "request", claimA).result;
+ assert.equal(acquired.status, "applied");
+ const progressA = {...a, operation: "progress", request_id: "rehearsal-progress-a",
+ claim_request_id: claimA.request_id, note: "First client prepared the handoff"};
+ assert.equal(client("a", "request", progressA).result.status, "applied");
+ const readA = client("a", "read");
+ const renewed = client("a", "request", {...a, operation: "renew", ttl_seconds: 20,
+ idempotency_key: acquired.lease.idempotency_key, expected_version: readA.lease.version}).result;
+ assert.equal(renewed.status, "applied");
+ const beforeTakeover = client("b", "request", {...b, operation: "claim", request_id: "rehearsal-too-early"});
+ assert.equal(beforeTakeover.result.status, "failed");
+ // Both timestamps belong to the authority; the host clock may differ.
+ const leaseDuration = Date.parse(renewed.lease.expires_at) - Date.parse(renewed.lease.updated_at);
+ assert(Number.isFinite(leaseDuration) && leaseDuration > 0 && leaseDuration <= 21_000);
+ await sleep(leaseDuration + 250);
+
+ const claimB = {...b, operation: "claim", request_id: "rehearsal-claim-b"};
+ const takeover = client("b", "request", claimB).result;
+ assert.equal(takeover.status, "applied");
+ assert(takeover.lease.lease_epoch > renewed.lease.lease_epoch);
+ assert.equal(client("a", "request", {...progressA, request_id: "rehearsal-stale-owner"}).result.status, "failed");
+ const complete = {...b, operation: "complete", request_id: "rehearsal-complete",
+ claim_request_id: claimB.request_id, evidence: "evidence:compose-rehearsal"};
+ assert.equal(client("b", "request", complete).result.status, "applied");
+ const recover = client("b", "recover", complete);
+ assert.equal(recover.status, "found");
+ assert.equal(recover.historical_only, true);
+ assert.match(recover.receipt_sha256, /^[a-f0-9]{64}$/);
+
+ run("docker", ["compose", "down", "--timeout", "5"]);
+ run("./start.sh", []);
+ assert.equal(client("a", "recover", createHidden).receipt_sha256, createdReceipt.receipt_sha256);
+ assert.equal(client("a", "request", createHidden).result.status, "replayed");
+ assert.equal(client("b", "recover", complete).receipt_sha256, recover.receipt_sha256);
+ assert.equal(client("b", "request", complete).result.status, "replayed");
+ const aEnd = client("a", "read");
+ const bEnd = client("b", "read");
+ assert.equal(aEnd.todo.status, "done");
+ assert.deepEqual(aEnd.todo, bEnd.todo);
+ assert.equal(aEnd.provider_revision, bEnd.provider_revision);
+ assert.equal(client("reader", "read").todo.status, "done");
+ assert.equal(client("reader", "recover", {...complete, actor_id: reader.actor_id}).status, "rejected");
+ function policyScript(code) {
+ run("docker", ["compose", "run", "--rm", "--no-deps", "-T", "--entrypoint", "node", "secrets", "-e", code]);
+ }
+ const readerPolicy = "/secrets/reader-gateway/policy.json";
+ policyScript(`const fs = require('node:fs'); const p = '${readerPolicy}';
+ fs.renameSync(p, p + '.saved'); fs.writeFileSync(p + '.next', JSON.stringify({
+ ...JSON.parse(fs.readFileSync(p + '.saved')), principals: []})); fs.renameSync(p + '.next', p);`);
+ assert.equal(client("reader", "read").status, "rejected");
+ run("docker", ["compose", "restart", "reader-gateway"]);
+ const listeningDeadline = performance.now() + 15_000;
+ let revoked = client("reader", "read");
+ while (revoked.status === "unavailable" && performance.now() < listeningDeadline) {
+ await sleep(200);
+ revoked = client("reader", "read");
+ }
+ assert.equal(revoked.status, "rejected");
+ assert.equal(revoked.reason_code, "principal_unauthenticated");
+ policyScript(`const fs = require('node:fs'); const p = '${readerPolicy}'; fs.unlinkSync(p);`);
+ assert.equal(client("reader", "read").status, "unavailable");
+ policyScript(`const fs = require('node:fs'); const p = '${readerPolicy}'; fs.writeFileSync(p, '{');`);
+ assert.equal(client("reader", "read").status, "unavailable");
+ policyScript(`const fs = require('node:fs'); const p = '${readerPolicy}'; fs.renameSync(p + '.saved', p);`);
+ assert.equal(client("reader", "read").todo.status, "done");
+ assert.equal(client("a", "read").provider_revision, aEnd.provider_revision);
+ const architecture = run("docker", ["compose", "exec", "-T", "gateway", "uname", "-m"]).trim();
+ console.log(JSON.stringify({ok: true, architecture, twoClientReadySeconds: readySeconds,
+ startup: startup.trim(), leaseTakeover: true, receiptPreserved: true,
+ scopedReadDefaultDeny: true, scopedWriteUnavailable: true, revocationPreserved: true}));
+} catch (error) {
+ operationError = error;
+ throw error;
+} finally {
+ try {
+ run("docker", ["compose", "down", "--timeout", "5", "--volumes"]);
+ } catch (error) {
+ if (!operationError) throw error;
+ console.error(`Cleanup of ${project} also failed: ${error.message}`);
+ }
+}
diff --git a/examples/coordination/remote-authority-compose/start.sh b/examples/coordination/remote-authority-compose/start.sh
new file mode 100755
index 0000000000..d9052909a9
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/start.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+set -eu
+directory=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+cd "$directory"
+started=$(date +%s)
+docker compose pull --policy missing db
+pulled=$(date +%s)
+docker compose build secrets
+built=$(date +%s)
+docker compose up --detach --no-build --wait --wait-timeout 120
+ready=$(date +%s)
+printf 'LoopX ready at https://127.0.0.1:%s (DB image %ss, build %ss, startup %ss, total %ss)\n' \
+ "${LOOPX_PORT:-8443}" "$((pulled - started))" "$((built - pulled))" "$((ready - built))" "$((ready - started))"
+printf 'Inspect the starter Todo with ./client.sh a read\n'
+printf 'Scoped reads: ./client.sh reader read (https://127.0.0.1:%s)\n' "${LOOPX_READ_PORT:-8444}"
diff --git a/examples/coordination/remote-authority-compose/state.sh b/examples/coordination/remote-authority-compose/state.sh
new file mode 100755
index 0000000000..db4433a831
--- /dev/null
+++ b/examples/coordination/remote-authority-compose/state.sh
@@ -0,0 +1,74 @@
+#!/bin/sh
+set -eu
+
+usage() {
+ printf '%s\n' 'Usage: ./state.sh backup /absolute/new-directory' \
+ ' COMPOSE_PROJECT_NAME=new-name ./state.sh restore /absolute/backup-directory' >&2
+ exit 2
+}
+
+[ "$#" -eq 2 ] || usage
+operation=$1
+archive=$2
+case "$archive" in /*) ;; *) usage ;; esac
+directory=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
+cd "$directory"
+project=${COMPOSE_PROJECT_NAME:-loopx-authority}
+case "$project" in ''|*[!a-z0-9_-]*) usage ;; esac
+image=$(docker compose config --images | awk '/^loopx\/remote-authority:/ { print; exit }')
+[ -n "$image" ] || { printf '%s\n' 'Cannot resolve the packaged gateway image' >&2; exit 1; }
+volumes='pg-admin pg-auth pg-data gateway reader-gateway client-a client-b reader health'
+umask 077
+
+digest() {
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum < "$1"
+ else
+ shasum -a 256 < "$1"
+ fi
+}
+
+case "$operation" in
+ backup)
+ for volume in $volumes; do
+ label=$(docker volume inspect --format '{{index .Labels "com.docker.compose.project"}}/{{index .Labels "com.docker.compose.volume"}}' "${project}_${volume}")
+ [ "$label" = "$project/$volume" ] || { printf '%s\n' 'Unexpected Compose volume ownership' >&2; exit 1; }
+ done
+ docker image inspect "$image" >/dev/null
+ mkdir -m 700 "$archive"
+ docker compose --project-name "$project" down
+ for volume in $volumes; do
+ docker run --rm --pull never --read-only --network none --user 0:0 \
+ --cpus 0.25 --memory 256m --pids-limit 64 --log-driver none \
+ --mount "type=volume,src=${project}_${volume},dst=/state,readonly" \
+ --entrypoint tar "$image" --numeric-owner -C /state -cpf - . > "$archive/$volume.tar"
+ digest "$archive/$volume.tar" > "$archive/$volume.sha256"
+ done
+ printf '%s\n' "$image" > "$archive/COMPLETE"
+ printf '%s\n' 'Backup complete. Run ./start.sh to bring this project back online.'
+ ;;
+ restore)
+ [ -n "${COMPOSE_PROJECT_NAME:-}" ] || usage
+ [ "$(cat "$archive/COMPLETE")" = "$image" ] ||
+ { printf '%s\n' 'Incomplete backup or bundle version mismatch' >&2; exit 1; }
+ for volume in $volumes; do
+ [ "$(digest "$archive/$volume.tar")" = "$(cat "$archive/$volume.sha256")" ] ||
+ { printf 'Checksum mismatch for %s\n' "$volume" >&2; exit 1; }
+ if docker volume inspect "${project}_${volume}" >/dev/null 2>&1; then
+ printf 'Remove or choose a different restore project for %s\n' "${project}_${volume}" >&2
+ exit 1
+ fi
+ done
+ docker compose --project-name "$project" build secrets
+ for volume in $volumes; do
+ docker volume create --label "com.docker.compose.project=$project" \
+ --label "com.docker.compose.volume=$volume" "${project}_${volume}" >/dev/null
+ docker run --rm --pull never --interactive --read-only --network none --user 0:0 \
+ --cpus 0.25 --memory 256m --pids-limit 64 --log-driver none \
+ --mount "type=volume,src=${project}_${volume},dst=/state" \
+ --entrypoint tar "$image" --numeric-owner --same-owner --same-permissions -C /state -xpf - < "$archive/$volume.tar"
+ done
+ printf '%s\n' 'Restore complete. Run ./start.sh with the same COMPOSE_PROJECT_NAME.'
+ ;;
+ *) usage ;;
+esac
diff --git a/examples/coordination/remote-authority-service.ts b/examples/coordination/remote-authority-service.ts
index 45a98cab92..f4b9507dee 100644
--- a/examples/coordination/remote-authority-service.ts
+++ b/examples/coordination/remote-authority-service.ts
@@ -12,12 +12,12 @@ const port = Number(values.port);
if (!values.policy || !values.cert || !values.key || !Number.isSafeInteger(port) || port < 0 || port > 65535 ||
!process.env.LOOPX_AUTHORITY_DATABASE_URL) throw new Error("Provide policy, TLS certificate/key and service-owned database configuration");
// Validate before listening; updates are read again for each admission.
-await readRemoteAuthorityPolicy(values.policy);
+const policy = await readRemoteAuthorityPolicy(values.policy);
const pool = new Pool({connectionString: process.env.LOOPX_AUTHORITY_DATABASE_URL,
max: 8, connectionTimeoutMillis: 2000, query_timeout: 6000, idleTimeoutMillis: 10000,
statement_timeout: 5000, lock_timeout: 2000, idle_in_transaction_session_timeout: 10000});
pool.on("error", () => process.stderr.write("Authority database connection unavailable\n"));
-const service = new RemoteAuthorityService({admit: fileRemoteAuthorityAdmission(values.policy),
+const service = new RemoteAuthorityService({admit: fileRemoteAuthorityAdmission(values.policy, String(policy.schema_version)),
database: {connect: async () => {
const connection = await pool.connect();
return {query: (sql, args) => connection.query(sql, args ? [...args] : undefined),
diff --git a/examples/core-control-plane-diagrams-smoke.py b/examples/core-control-plane-diagrams-smoke.py
deleted file mode 100644
index c4c170874f..0000000000
--- a/examples/core-control-plane-diagrams-smoke.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env python3
-"""Validate the public core-control-plane diagram docs stay linked and safe."""
-
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-DOC_DIR = ROOT / "docs" / "product" / "core-control-plane"
-
-FILES = [
- DOC_DIR / "README.md",
- DOC_DIR / "interaction-catalog.md",
- DOC_DIR / "state-definitions.md",
- DOC_DIR / "state-machine.md",
-]
-
-FORBIDDEN_PUBLIC_STRINGS = [
- "bytedance",
- "la" + "rk" + "office",
- "EAAt" + "dvU1bokXbyxXdv7cDAAbnSb",
- "/Users/",
- "/private/tmp",
- "127.0.0.1",
- "localhost",
- "appSecret",
- "accessToken",
-]
-
-
-def read(path: Path) -> str:
- assert path.exists(), f"missing doc: {path}"
- return path.read_text(encoding="utf-8")
-
-
-def main() -> None:
- docs = {path.name: read(path) for path in FILES}
- combined = "\n".join(docs.values())
-
- for text in FORBIDDEN_PUBLIC_STRINGS:
- assert text.lower() not in combined.lower(), f"private marker leaked: {text}"
-
- readme = docs["README.md"]
- for filename in ("interaction-catalog.md", "state-definitions.md", "state-machine.md"):
- assert f"]({filename})" in readme, f"README does not link {filename}"
-
- assert "interaction_pattern_lens_v0" in docs["interaction-catalog.md"]
- assert "Core Pattern Map" in docs["interaction-catalog.md"]
- assert "State Definitions" in docs["state-definitions.md"]
- assert "Canonical State Bodies" in docs["state-definitions.md"]
- assert "Runtime Decisions, Phases, And Read Conditions" in docs["state-definitions.md"]
- assert "State Machines" in docs["state-machine.md"]
- for section in (
- "Todo Lifecycle Machine",
- "Quota / Runtime Machine",
- "Gate Decision Scope Machine",
- "Owner Route / Multi-Agent Handoff Machine",
- "Evidence / Rollout / Rollback Machine",
- "Scheduler / Heartbeat Machine",
- "Projection Sink Machine",
- "Agent Onboarding / Automation Enablement Machine",
- "Agent Vision / Replan Machine",
- ):
- assert section in docs["state-machine.md"], f"missing state machine: {section}"
- assert "```mermaid" in combined
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/cs-notes-explore-capability-map-smoke.py b/examples/cs-notes-explore-capability-map-smoke.py
deleted file mode 100644
index e9d6ff3993..0000000000
--- a/examples/cs-notes-explore-capability-map-smoke.py
+++ /dev/null
@@ -1,83 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the public-safe CS-Notes exploration capability map."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-DOC = REPO_ROOT / "docs" / "reference" / "protocols" / "cs-notes-explore-capability-map-v0.md"
-INDEX = REPO_ROOT / "docs" / "reference" / "protocols" / "README.md"
-
-
-REQUIRED_CAPABILITIES = (
- "material_intake_profile_v0",
- "trusted_source_scan_plan_v0",
- "pre_tick_gate_v0",
- "todo_triage_index_v0",
- "snippet_registry_contract_v0",
- "guarded_heartbeat_visibility_v0",
-)
-
-REQUIRED_SECTIONS = (
- "## Boundary",
- "## Selected Capabilities",
- "## Scenario Fit",
- "## Not Imported",
- "## Recommended Next Step",
-)
-
-PRIVATE_PATTERNS = (
- re.compile(r"/Users/[A-Za-z0-9._-]+/"),
- re.compile(r"/home/[A-Za-z0-9._-]+/"),
- re.compile(r"/private/"),
- re.compile(r"[A-Za-z]:\\\\Users\\\\"),
- re.compile(r"https?://"),
- re.compile(r"BEGIN [A-Z ]*PRIVATE KEY"),
- re.compile(r"\bBearer\s+[A-Za-z0-9._-]+"),
- re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
-)
-
-FORBIDDEN_TERMS = tuple(
- "".join(parts)
- for parts in (
- (".", "local"),
- ("LEARNING", "_MATERIAL", "_CANDIDATES"),
- ("coo", "kie"),
- ("pass", "word"),
- ("se", "cret"),
- ("to", "ken="),
- ("raw", " transcript"),
- )
-)
-
-
-def main() -> int:
- text = DOC.read_text(encoding="utf-8")
- assert text.startswith("# cs_notes_explore_capability_map_v0"), text[:80]
- for section in REQUIRED_SECTIONS:
- assert section in text, section
- for capability in REQUIRED_CAPABILITIES:
- assert capability in text, capability
- assert "exploration_plan_packet_v0" in text, text
- assert "Repo issue fix" in text, text
- assert "Self-media and creator operations" in text, text
- assert "Experiment and other vertical state surfaces" in text, text
-
- for pattern in PRIVATE_PATTERNS:
- assert not pattern.search(text), pattern.pattern
- lowered = text.lower()
- leaked = [term for term in FORBIDDEN_TERMS if term.lower() in lowered]
- assert not leaked, leaked
-
- index = INDEX.read_text(encoding="utf-8")
- assert "cs-notes-explore-capability-map-v0.md" in index, "protocol index link"
-
- print("cs-notes-explore-capability-map-smoke: ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/dashboard-attention-details-browser-smoke.mjs b/examples/dashboard-attention-details-browser-smoke.mjs
index 12026f0344..b214289d3f 100644
--- a/examples/dashboard-attention-details-browser-smoke.mjs
+++ b/examples/dashboard-attention-details-browser-smoke.mjs
@@ -17,7 +17,7 @@ const packaged = process.env.LOOPX_ATTENTION_DETAILS_PACKAGED === "1";
const output = resolve(root, "output/playwright/attention-details");
const server = packaged
? spawn(resolveTestPython(), ["-m", "http.server", String(port), "--bind", "127.0.0.1", "--directory", resolve(root, "loopx/web")], { stdio: "ignore" })
- : startViteDashboardServer({ dashboardDir, port });
+ : await startViteDashboardServer({ dashboardDir, port });
const url = `http://127.0.0.1:${port}/${packaged ? "chat/" : ""}?statusUrl=/status.json`;
const requestBody = "Review **version 2.0** for the stable channel.\n\n- Publish after independent acceptance.\n- Keep the preview channel available.\n\nPublish version 2.0 to stable only after acceptance.";
const reason = "Recommend **waiting for acceptance**. Publishing now would omit the independent check; waiting keeps the preview usable.";
diff --git a/examples/dashboard-browser-smoke-support.mjs b/examples/dashboard-browser-smoke-support.mjs
index f0a4b14e7f..80289f9b63 100644
--- a/examples/dashboard-browser-smoke-support.mjs
+++ b/examples/dashboard-browser-smoke-support.mjs
@@ -76,14 +76,48 @@ export async function launchBrowser(chromium) {
return chromium.launch({ executablePath, headless: true });
}
-export function startViteDashboardServer({ dashboardDir, port }) {
+export async function startViteDashboardServer({ dashboardDir, port }) {
const nodeBin = process.env.LOOPX_NODE_BIN || process.execPath;
- const viteBin = resolve(dashboardDir, "node_modules/vite/bin/vite.js");
- return spawn(nodeBin, [viteBin, "--host", "127.0.0.1", "--port", String(port), "--strictPort", "--force"], {
+ // HTTP from the selected port could belong to a different Vite process.
+ // Confirm the bind over the channel owned by this child before browsing.
+ const entry = `
+import { createServer } from "vite";
+const port = Number(process.argv[1]);
+const vite = await createServer({
+ server: { host: "127.0.0.1", port, strictPort: true },
+ forceOptimizeDeps: true,
+});
+await vite.listen();
+process.send(vite.httpServer.address().port);
+`;
+ const server = spawn(nodeBin, ["--input-type=module", "--eval", entry, String(port)], {
cwd: dashboardDir,
env: { ...process.env },
- stdio: "ignore",
+ stdio: ["ignore", "ignore", "pipe", "ipc"],
});
+ let diagnostic = "";
+ server.stderr.on("data", chunk => { diagnostic = (diagnostic + chunk).slice(-8000); });
+ const startup = new AbortController();
+ let timer;
+ try {
+ const [boundPort] = await Promise.race([
+ once(server, "message", { signal: startup.signal }),
+ once(server, "close", { signal: startup.signal }).then(([code, signal]) => {
+ throw new Error(`Dashboard Vite server exited (${code ?? signal}) before binding port ${port}: ${diagnostic.trim()}`);
+ }),
+ new Promise((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`Dashboard Vite server did not confirm port ${port} within 20 seconds`)), 20_000);
+ }),
+ ]);
+ if (boundPort !== port) throw new Error(`Dashboard Vite server bound port ${boundPort}; expected ${port}`);
+ return server;
+ } catch (error) {
+ await stopServer(server);
+ throw error;
+ } finally {
+ clearTimeout(timer);
+ startup.abort();
+ }
}
export async function waitForHttp(url, timeoutMs = 20_000) {
@@ -100,15 +134,16 @@ export async function waitForHttp(url, timeoutMs = 20_000) {
}
async function stopServer(server) {
- if (!server || server.exitCode !== null || server.signalCode !== null) {
+ if (!server?.pid || server.exitCode !== null || server.signalCode !== null) {
return;
}
const exited = once(server, "exit");
server.kill("SIGTERM");
+ let timer;
const stopped = await Promise.race([
exited.then(() => true),
- new Promise((resolveTimeout) => setTimeout(() => resolveTimeout(false), 5_000)),
- ]);
+ new Promise((resolveTimeout) => { timer = setTimeout(() => resolveTimeout(false), 5_000); }),
+ ]).finally(() => clearTimeout(timer));
if (!stopped && server.exitCode === null && server.signalCode === null) {
const forceExited = once(server, "exit");
server.kill("SIGKILL");
diff --git a/examples/dashboard-goal-acceptance-browser-smoke.mjs b/examples/dashboard-goal-acceptance-browser-smoke.mjs
index 34b2864e22..c4144d7b06 100644
--- a/examples/dashboard-goal-acceptance-browser-smoke.mjs
+++ b/examples/dashboard-goal-acceptance-browser-smoke.mjs
@@ -16,7 +16,7 @@ const payload = JSON.parse(execFileSync(python, ["-c", "import runpy,tempfile,js
const dashboardDir = resolve(root, "apps/presentation/dashboard");
const server = packaged
? spawn(python, ["-m", "http.server", String(port), "--bind", "127.0.0.1", "--directory", resolve(root, "loopx/web")], { stdio: "ignore" })
- : startViteDashboardServer({ dashboardDir, port });
+ : await startViteDashboardServer({ dashboardDir, port });
let browser;
try {
await waitForHttp(`http://127.0.0.1:${port}/`);
diff --git a/examples/dashboard-installed-quickstart-doc-smoke.py b/examples/dashboard-installed-quickstart-doc-smoke.py
deleted file mode 100644
index 95283c6c16..0000000000
--- a/examples/dashboard-installed-quickstart-doc-smoke.py
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env python3
-"""Keep installed Dashboard quick starts on the single-process contract."""
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-DEFAULT_WORKSPACE_URL = "http://127.0.0.1:8767/chat/"
-DEFAULT_STATUS_URL = "http://127.0.0.1:8767/status.json"
-
-
-def read(path: str) -> str:
- return (REPO_ROOT / path).read_text(encoding="utf-8")
-
-
-def compact(text: str) -> str:
- return " ".join(text.split())
-
-
-def main() -> int:
- documents = {
- "getting started": read("docs/guides/getting-started.md"),
- "dashboard README": read("apps/presentation/dashboard/README.md"),
- "workspace guide": read("docs/guides/personal-workspace-user-guide.md"),
- }
-
- for label, content in documents.items():
- normalized = compact(content)
- assert "loopx dashboard" in normalized, label
- assert "--no-open" in normalized, label
- assert DEFAULT_WORKSPACE_URL in normalized, label
- assert DEFAULT_STATUS_URL in normalized, label
-
- installed_run = compact(
- documents["dashboard README"].split("## Run", 1)[1].split(
- "Source-checkout development is a separate mode:", 1
- )[0]
- )
- assert "does not require a separate `loopx serve-status` process" in installed_run
- assert "127.0.0.1:5173" not in installed_run
- assert "installs the dashboard's npm dependencies" not in installed_run
-
- print("dashboard-installed-quickstart-doc-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/dashboard-usage-browser-smoke.mjs b/examples/dashboard-usage-browser-smoke.mjs
index f73923fd76..5a52513179 100644
--- a/examples/dashboard-usage-browser-smoke.mjs
+++ b/examples/dashboard-usage-browser-smoke.mjs
@@ -72,7 +72,7 @@ async function main() {
const { chromium } = loadPlaywright();
const server = packaged
? spawn(resolveTestPython(), ["-m", "http.server", String(port), "--bind", "127.0.0.1", "--directory", resolve(repoRoot, "loopx/web")], { stdio: "ignore" })
- : startViteDashboardServer({ dashboardDir, port });
+ : await startViteDashboardServer({ dashboardDir, port });
let browser;
try {
const baseUrl = `http://127.0.0.1:${port}${packaged ? "/chat" : ""}`;
diff --git a/examples/delivery-turn-kind-enum-smoke.py b/examples/delivery-turn-kind-enum-smoke.py
deleted file mode 100644
index fbb33c9e8c..0000000000
--- a/examples/delivery-turn-kind-enum-smoke.py
+++ /dev/null
@@ -1,78 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test structured delivery_turn_kind enum handling."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.work_items.delivery_history import project_delivery_history # noqa: E402
-from loopx.control_plane.work_items.delivery_outcome import ( # noqa: E402
- DELIVERY_TURN_KIND_CHOICES,
- DeliveryOutcome,
- DeliveryTurnKind,
- normalize_delivery_turn_kind,
- require_delivery_turn_kind,
-)
-from loopx.status import compact_post_handoff_run # noqa: E402
-
-
-def assert_enum_sets() -> None:
- assert DELIVERY_TURN_KIND_CHOICES == (
- "contract_only_preparation",
- "compact_evidence",
- "blocker_writeback",
- "product_path_execution",
- "outcome_gap",
- "unknown",
- )
- assert require_delivery_turn_kind("compact_evidence") == DeliveryTurnKind.COMPACT_EVIDENCE
- assert normalize_delivery_turn_kind("contract_v0_delivered") is None
- try:
- require_delivery_turn_kind("contract_v0_delivered")
- except ValueError as exc:
- assert "delivery_turn_kind must be one of:" in str(exc)
- else:
- raise AssertionError("invalid delivery turn kind accepted")
-
-
-def assert_invalid_explicit_kind_does_not_fallback_to_classification() -> None:
- run = {
- "classification": "runner_contract_v0_delivered",
- "delivery_outcome": DeliveryOutcome.SURFACE_ONLY.value,
- "delivery_turn_kind": "contract_v0_delivered",
- }
- assert project_delivery_history([run])["runs"][0]["delivery_turn_kind"] == DeliveryTurnKind.UNKNOWN.value
- assert compact_post_handoff_run(run)["delivery_turn_kind"] == DeliveryTurnKind.UNKNOWN.value
-
-
-def assert_inference_still_works_when_kind_is_absent() -> None:
- contract_run = {
- "classification": "runner_contract_v0_delivered",
- "delivery_outcome": DeliveryOutcome.SURFACE_ONLY.value,
- }
- assert (
- project_delivery_history([contract_run])["runs"][0]["delivery_turn_kind"]
- == DeliveryTurnKind.CONTRACT_ONLY_PREPARATION.value
- )
- assert (
- project_delivery_history([{"delivery_outcome": DeliveryOutcome.PRIMARY_GOAL_OUTCOME.value}])["runs"][0]["delivery_turn_kind"]
- == DeliveryTurnKind.PRODUCT_PATH_EXECUTION.value
- )
-
-
-def main() -> int:
- assert_enum_sets()
- assert_invalid_explicit_kind_does_not_fallback_to_classification()
- assert_inference_still_works_when_kind_is_absent()
- print("delivery turn kind enum smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/desktop-update-browser-smoke.mjs b/examples/desktop-update-browser-smoke.mjs
index b47a06356a..f23175cbea 100644
--- a/examples/desktop-update-browser-smoke.mjs
+++ b/examples/desktop-update-browser-smoke.mjs
@@ -363,7 +363,7 @@ try {
nativeState = { phase: "idle", details: {} };
await page.reload();
await page.getByRole("button", { name: "更新 LoopX", exact: true }).click();
- await page.getByText(/先打开本地版本,更新在后台准备,下次打开时生效/).waitFor();
+ await page.getByText(/启动直接打开本地工作区,更新在后台准备/).waitFor();
await page.getByText("高级选项", { exact: true }).click();
assert.equal(await page.getByRole("button", { name: "修复当前版本", exact: true }).isEnabled(), true, "legacy native status retains its available repair action");
@@ -572,6 +572,25 @@ try {
await page.getByText(/启动用时较长/).waitFor();
nativeState = { phase: "service_error", details: { code: "service_start_failed" } };
await page.getByText("本地服务连接失败,正在等待重试", { exact: true }).waitFor();
+ await page.locator("details.recovery > summary").click();
+ // Core's refusal reason must survive the native-to-browser projection. A
+ // missing provider is not a rolled-back service transaction.
+ for (const code of ["native_observer_provider_binding_required", "native_observer_provider_upgrade_required", "native_observer_requires_target_runtime", "native_account_work_pending"]) {
+ nativeState = { phase: "service_error", details: { code, retry_after_ms: 30000 } };
+ await page.waitForFunction((expected) => JSON.parse(document.querySelector("#diagnostics").value).error_code === expected, code);
+ assert.ok((await page.locator("#update-status").innerText()).includes("现有服务保持运行"));
+ assert.ok(!(await page.locator("#update-status").innerText()).includes("已尝试恢复原配置"));
+ if (code !== "native_account_work_pending") {
+ assert.ok((await page.locator("#boot-detail").innerText()).includes("重复重启不会补齐组件"));
+ }
+ }
+ nativeState = { phase: "service_error", details: { code: "native_observer_provider_binding_required", retry_after_ms: 30000 } };
+ await page.getByText("需要兼容的账号服务组件", { exact: true }).waitFor();
+ await page.screenshot({ path: resolve(output, "startup-provider-prerequisite.png") });
+ nativeState = { phase: "ready", details: {} };
+ await page.getByText("本地服务已就绪,正在打开工作区", { exact: true }).waitFor();
+ assert.equal(calls.length, beforeBootFailures, "projecting refusal/recovery must not invoke installation or task execution");
+
// Background preparation observes native progress without disabling a
// user's explicit action or manufacturing an installation/restart effect.
const beforeBackground = calls.length;
@@ -602,7 +621,7 @@ try {
nativeState = { phase: "available", details: { channel: "stable", version: "0.5.5", background: true, prepared: true } };
await page.reload();
await page.getByRole("button", { name: "更新已准备" }).click();
- await page.getByText(/下次打开时自动安装/).waitFor();
+ await page.getByText(/可更新并重启/).waitFor();
await page.screenshot({ path: resolve(output, "background-prepared-desktop.png") });
await page.setViewportSize({ width: 390, height: 844 });
await page.getByRole("button", { name: "打开 Goal 导航" }).click();
@@ -612,7 +631,7 @@ try {
await page.reload();
await page.getByRole("button", { name: "Open Goal navigation" }).click();
await page.getByRole("button", { name: "Update prepared" }).click();
- await page.getByText(/It installs on the next open/).waitFor();
+ await page.getByText(/Update and restart when ready/).waitFor();
assert.deepEqual(calls.slice(beforeBackground).map((call) => call.args?.action), ["check"]);
// Reopening observes a transfer; it must neither restart it nor invent a
// total/percentage when the native source has not reported Content-Length.
diff --git a/examples/execution-obligation-policy-smoke.py b/examples/execution-obligation-policy-smoke.py
deleted file mode 100644
index 307413345f..0000000000
--- a/examples/execution-obligation-policy-smoke.py
+++ /dev/null
@@ -1,248 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the extracted execution-obligation policy helper."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.control_plane.work_items.execution_obligation import build_execution_obligation # noqa: E402
-
-
-def obligation(
- *,
- should_run: bool = True,
- effective_action: str = "normal_run",
- recommendation: dict | None = None,
- work_lane_contract: dict | None = None,
- external_evidence_observation: dict | None = None,
- successor_replan_mode: str = "successor_replan_required",
-) -> dict:
- return build_execution_obligation(
- should_run=should_run,
- effective_action=effective_action,
- heartbeat_recommendation=recommendation or {},
- work_lane_contract=work_lane_contract,
- external_evidence_observation=external_evidence_observation,
- successor_replan_mode=successor_replan_mode,
- )
-
-
-def assert_exact_mode(
- name: str,
- payload: dict,
- *,
- kind: str,
- minimum: str | None,
- contract: str | None = None,
- delivery_allowed: bool | None = None,
-) -> None:
- assert payload["kind"] == kind, (name, payload)
- assert payload["must_attempt_work"] is True, (name, payload)
- assert payload["notify_is_execution_gate"] is False, (name, payload)
- if minimum is None:
- assert "minimum" not in payload, (name, payload)
- else:
- assert payload["minimum"] == minimum, (name, payload)
- if contract is not None:
- assert payload["contract"] == contract, (name, payload)
- if delivery_allowed is not None:
- assert payload["delivery_allowed"] is delivery_allowed, (name, payload)
-
-
-def main() -> int:
- peer_workspace = obligation(
- recommendation={
- "recommended_mode": "repair_agent_workspace",
- "spend_policy": "no spend until relocated",
- }
- )
- assert_exact_mode(
- "peer-agent-workspace",
- peer_workspace,
- kind="agent_workspace_repair",
- minimum="one_workspace_move_then_guard_rerun",
- contract="agent_workspace_guard",
- delivery_allowed=False,
- )
- assert peer_workspace["spend_policy"] == "no spend until relocated", peer_workspace
-
- evidence = obligation(
- should_run=False,
- external_evidence_observation={
- "required": True,
- "spend_policy": "no spend until observed",
- },
- )
- assert_exact_mode(
- "external-evidence",
- evidence,
- kind="external_evidence_observation_required",
- minimum="one_read_only_observation_or_compact_blocker",
- contract="external_evidence_observation",
- delivery_allowed=False,
- )
- assert evidence["spend_policy"] == "no spend until observed", evidence
-
- quiet = obligation(
- recommendation={"stop_if_unchanged": True},
- )
- assert quiet == {
- "must_attempt_work": False,
- "kind": "quiet_noop_if_unchanged",
- "notify_is_execution_gate": False,
- "reason": (
- "this mode allows a quiet no-op only after confirming the current state "
- "source is unchanged and no concrete safe handoff exists"
- ),
- }, quiet
-
- replan = obligation(
- recommendation={
- "recommended_mode": "autonomous_replan_required",
- "replan_obligation": {"stall_threshold": 6},
- }
- )
- assert_exact_mode(
- "autonomous-replan",
- replan,
- kind="autonomous_replan_required",
- minimum="one_bounded_replan_with_typed_outcome",
- )
- assert replan["stall_threshold"] == 6, replan
-
- empty_frontier_replan = obligation(
- recommendation={
- "recommended_mode": "autonomous_replan_required",
- "replan_obligation": {
- "stall_threshold": 2,
- "agent_todo_writeback_required": True,
- },
- }
- )
- assert_exact_mode(
- "empty-frontier-autonomous-replan",
- empty_frontier_replan,
- kind="autonomous_replan_required",
- minimum="one_bounded_replan_with_typed_outcome",
- )
- assert "only when an executable target is known" in empty_frontier_replan[
- "contract_obligation"
- ], empty_frontier_replan
-
- successor = obligation(
- recommendation={
- "recommended_mode": "custom_successor_mode",
- "spend_policy": "spend after projection repair",
- },
- successor_replan_mode="custom_successor_mode",
- )
- assert_exact_mode(
- "successor-replan",
- successor,
- kind="custom_successor_mode",
- minimum="one_successor_replan_or_no_followup_writeback",
- contract="deferred_resume_projection",
- delivery_allowed=False,
- )
- assert successor["spend_policy"] == "spend after projection repair", successor
-
- state_gap = obligation(
- recommendation={
- "recommended_mode": "repair_state_projection_gap",
- "spend_policy": "spend after projection repair",
- }
- )
- assert_exact_mode(
- "state-projection-gap",
- state_gap,
- kind="state_projection_gap_repair",
- minimum="one_replan_or_todo_expansion_or_blocker_writeback_segment",
- contract="state_projection_gap",
- delivery_allowed=False,
- )
-
- boundary = obligation(
- recommendation={"recommended_mode": "repair_boundary_projection"}
- )
- assert_exact_mode(
- "boundary-projection",
- boundary,
- kind="boundary_projection_repair",
- minimum="one_boundary_projection_or_blocker_writeback_segment",
- contract="goal_boundary.write_scope",
- delivery_allowed=False,
- )
-
- capability = obligation(
- recommendation={"recommended_mode": "repair_capability_bridge"}
- )
- assert_exact_mode(
- "capability-bridge",
- capability,
- kind="capability_bridge_repair",
- minimum="one_bridge_or_environment_repair_or_blocker_writeback_segment",
- contract="capability_gate",
- delivery_allowed=False,
- )
-
- work_lane = obligation(
- recommendation={"recommended_mode": "follow_work_lane_contract"},
- work_lane_contract={
- "obligation": "advance_one_bounded_segment",
- "must_attempt_work": True,
- },
- )
- assert work_lane == {
- "must_attempt_work": True,
- "kind": "work_lane_contract",
- "contract": "work_lane_contract",
- "contract_obligation": "advance_one_bounded_segment",
- "notify_is_execution_gate": False,
- "reason": (
- "work_lane_contract.obligation is the machine execution contract; "
- "heartbeat_recommendation is explanatory"
- ),
- }, work_lane
-
- generic_run = obligation(
- recommendation={"recommended_mode": "steering_audit_then_one_step"},
- effective_action="normal_run",
- )
- assert generic_run == {
- "must_attempt_work": True,
- "kind": "normal_run",
- "minimum": "one_bounded_segment",
- "notify_is_execution_gate": False,
- "reason": (
- "should_run=true means a Codex-actionable turn exists; heartbeat notify "
- "only controls whether to interrupt the user"
- ),
- }, generic_run
-
- generic_skip = obligation(
- should_run=False,
- effective_action="quota_wait",
- recommendation={"recommended_mode": "wait"},
- )
- assert generic_skip == {
- "must_attempt_work": False,
- "kind": "quota_wait",
- "notify_is_execution_gate": False,
- "reason": (
- "should_run=false blocks delivery unless an explicit safe-bypass or "
- "self-repair action is exposed"
- ),
- }, generic_skip
-
- print("execution-obligation-policy-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/explore-executive-projection-contract-smoke.py b/examples/explore-executive-projection-contract-smoke.py
deleted file mode 100644
index be6849268b..0000000000
--- a/examples/explore-executive-projection-contract-smoke.py
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env python3
-"""Guard owner-facing Explore views against default cardinality caps."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-CONTRACT_PATHS = (
- ROOT / "skills" / "loopx-project" / "references" / "materials-explore-quality.md",
- ROOT / "loopx" / "capabilities" / "explore" / "README.md",
-)
-
-REQUIRED_FRAGMENTS = (
- "default cardinality policy is graph growth",
- "material decision and evidence nodes",
- "semantic sections or linked subgraphs",
- "20 nodes",
- "explicit opt-in presentation policy",
- "overlap and text-overflow checks",
-)
-
-FORBIDDEN_DEFAULTS = (
- "display contract with node/edge budgets",
- "give the projection explicit node and edge budgets",
-)
-
-
-def main() -> int:
- skill = (ROOT / "skills/loopx-project/SKILL.md").read_text(encoding="utf-8")
- assert "references/materials-explore-quality.md" in skill
- assert "Read the matching procedure" in skill
- for path in CONTRACT_PATHS:
- text = path.read_text(encoding="utf-8")
- normalized = " ".join(text.lower().split())
- for fragment in REQUIRED_FRAGMENTS:
- assert fragment in normalized, f"{path}: missing {fragment!r}"
- for fragment in FORBIDDEN_DEFAULTS:
- assert fragment not in normalized, f"{path}: retained hard-cap default {fragment!r}"
- assert "`max_nodes`" in text and "`max_edges`" in text, (
- f"{path}: explicit hard-cap field contract missing"
- )
-
- print("explore-executive-projection-contract-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/explore-visual-cross-role-integrity-smoke.py b/examples/explore-visual-cross-role-integrity-smoke.py
deleted file mode 100644
index c50fd6c9da..0000000000
--- a/examples/explore-visual-cross-role-integrity-smoke.py
+++ /dev/null
@@ -1,170 +0,0 @@
-#!/usr/bin/env python3
-"""Verify cross-role token isolation and batch-final Explore marker readback."""
-
-from __future__ import annotations
-
-import sys
-import tempfile
-from pathlib import Path
-from typing import Any, Mapping
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.extensions.lark.presentation import explore_results # noqa: E402
-
-
-def _bundle(
- _: Mapping[str, Any], policy: Mapping[str, Any] | None = None
-) -> dict[str, Any]:
- del policy
- roles = {}
- for role in ("canonical", "executive"):
- roles[role] = {
- "view_role": role,
- "nodes": [{"node_id": f"{role}_node"}],
- "edges": [],
- "stage_views": [
- {
- "stage_index": 1,
- "node_ids": [f"{role}_node"],
- "mermaid": "flowchart TB",
- "svg": " ",
- }
- ],
- }
- return {
- "presentation_mode": "dual_view",
- "reason_codes": ["readability_check_failed"],
- "source_digest": "public-source-digest",
- "source_revision": "public-source-revision",
- **roles,
- }
-
-
-def _sink(token: str) -> dict[str, Any]:
- return {
- "stage_capacity": 14,
- "board_style": "semantic_lane_columns",
- "stage_whiteboards": [{"stage_index": 1, "whiteboard_token": token}],
- }
-
-
-def main() -> int:
- original_bundle = explore_results.build_explore_presentation_bundle
- original_ensure = explore_results.ensure_stage_whiteboards
- original_sync = explore_results.sync_explore_visual_to_lark
- original_settle = explore_results.settle_visual_stage_readbacks
- writes: list[str] = []
- settlements: list[list[str]] = []
-
- def ensure(
- config: Any,
- *,
- role: str,
- role_sink: Mapping[str, Any],
- stage_views: list[Mapping[str, Any]],
- **_: Any,
- ) -> tuple[dict[int, dict[str, Any]], list[Any], list[Any], dict[str, Any], None]:
- del config, role, stage_views
- item = dict(role_sink["stage_whiteboards"][0])
- return {1: item}, [], [], {"required": False}, None
-
- def sync(
- config: Any,
- *,
- view_key: str,
- visual_sink: Mapping[str, Any],
- **_: Any,
- ) -> dict[str, Any]:
- del config
- writes.append(view_key)
- marker = f"marker:{view_key}"
- return {
- "ok": False,
- "status": "publish_unverified",
- "published": False,
- "external_write_performed": True,
- "retryable": True,
- "delivery_digest": view_key,
- "board_style": "semantic_lane_columns",
- "renderer": "mermaid",
- "command": {"ok": True},
- "readback": {"expected_marker": marker, "retryable": True},
- }
-
- def settle(*, stage_targets: list[tuple[dict[str, Any], str]], **_: Any) -> None:
- settlements.append(
- [str(item[0]["readback"]["expected_marker"]) for item in stage_targets]
- )
- assert writes == ["canonical_stage_01", "executive_stage_01"], writes
- for result, _token in stage_targets:
- result.update(
- ok=True,
- status="published",
- published=True,
- retryable=False,
- readback={"ok": True, "verified": True},
- )
-
- explore_results.build_explore_presentation_bundle = _bundle
- explore_results.ensure_stage_whiteboards = ensure
- explore_results.sync_explore_visual_to_lark = sync
- explore_results.settle_visual_stage_readbacks = settle
- try:
- config = explore_results.LarkExploreConfig(
- **{"base_" + "token": "PUBLIC_BASE"},
- table_ids={"nodes": "N", "edges": "E", "findings": "F"},
- )
- with tempfile.TemporaryDirectory(prefix="loopx-visual-integrity-") as tmp:
- config_path = Path(tmp) / "lark-explore.json"
- conflict = explore_results.sync_explore_visuals_to_lark(
- config,
- projection={},
- visual_sinks={
- "canonical": _sink("shared-board"),
- "executive": _sink("shared-board"),
- },
- config_path=config_path,
- execute=True,
- )
- assert conflict["status"] == "configuration_conflict", conflict
- assert (
- conflict["views"]["canonical"]["status"]
- == "stage_whiteboard_token_conflict"
- ), conflict
- assert "shared-board" not in str(conflict), conflict
- assert not writes and not settlements, (writes, settlements)
-
- delivered = explore_results.sync_explore_visuals_to_lark(
- config,
- projection={},
- visual_sinks={
- "canonical": _sink("canonical-board"),
- "executive": _sink("executive-board"),
- },
- config_path=config_path,
- execute=True,
- )
- assert delivered["ok"] is True and delivered["status"] == "published", (
- delivered
- )
- assert settlements == [
- ["marker:canonical_stage_01", "marker:executive_stage_01"]
- ], settlements
- assert all(view["ok"] is True for view in delivered["views"].values()), (
- delivered
- )
- finally:
- explore_results.build_explore_presentation_bundle = original_bundle
- explore_results.ensure_stage_whiteboards = original_ensure
- explore_results.sync_explore_visual_to_lark = original_sync
- explore_results.settle_visual_stage_readbacks = original_settle
- print("explore visual cross-role integrity smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/finance-value-discovery-extension-smoke.py b/examples/finance-value-discovery-extension-smoke.py
deleted file mode 100644
index e701fe775a..0000000000
--- a/examples/finance-value-discovery-extension-smoke.py
+++ /dev/null
@@ -1,103 +0,0 @@
-#!/usr/bin/env python3
-"""Prove standalone finance extension semantics and lifecycle binding."""
-
-from __future__ import annotations
-
-import json
-import os
-import sys
-import tempfile
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-EXTENSION_ROOT = ROOT / "packages" / "loopx-finance-value-discovery"
-EXTENSION_SRC = EXTENSION_ROOT / "src"
-MANIFEST = EXTENSION_ROOT / "extension.toml"
-EXAMPLE = EXTENSION_ROOT / "examples" / "paypal-debeta-discovery.json"
-sys.path.insert(0, str(ROOT))
-sys.path.insert(0, str(EXTENSION_SRC))
-
-from loopx.capabilities.catalog import build_capability_catalog_packet # noqa: E402
-from loopx.extensions.runtime import ( # noqa: E402
- default_extension_state_file,
- install_extension,
- run_standalone_extension,
-)
-from loopx.extensions.manifest import load_extension_manifest # noqa: E402
-from loopx_finance_value_discovery.reducer import ( # noqa: E402
- build_finance_value_discovery_packet,
-)
-
-
-def main() -> int:
- evidence = json.loads(EXAMPLE.read_text(encoding="utf-8"))
- direct = build_finance_value_discovery_packet(evidence)
- assert direct["projection"]["next_targets"] == ["PYPL"]
- assert direct["projection"]["control_count"] == 3
- assert direct["truth_contract"]["group_wide_derating_is_not_idiosyncratic_alpha"]
- assert direct["boundary"]["investment_advice"] is False
- assert direct["boundary"]["trading_allowed"] is False
- assert direct["boundary"]["continuous_watch_allowed"] is False
-
- catalog = build_capability_catalog_packet([MANIFEST])
- assert "finance-value-discovery" not in {
- item["id"] for item in catalog["capabilities"]
- }
- manifest = load_extension_manifest(MANIFEST)
- assert manifest["capabilities"] == []
- assert manifest["implementations"] == []
-
- with tempfile.TemporaryDirectory() as temporary:
- directory = Path(temporary)
- provider = directory / "finance-provider"
- provider.write_text(
- f"#!{sys.executable}\n"
- "from loopx_finance_value_discovery.cli import main\n"
- "raise SystemExit(main())\n",
- encoding="utf-8",
- )
- provider.chmod(0o755)
- manifest = directory / "extension.toml"
- manifest.write_text(
- MANIFEST.read_text(encoding="utf-8").replace(
- 'entrypoint = "loopx-finance-value-discovery"',
- f"entrypoint = {json.dumps(str(provider))}",
- ),
- encoding="utf-8",
- )
- runtime_root = directory / "runtime"
- state_file = default_extension_state_file(runtime_root)
- previous_pythonpath = os.environ.get("PYTHONPATH")
- os.environ["PYTHONPATH"] = os.pathsep.join(
- part
- for part in [str(EXTENSION_SRC), str(ROOT), previous_pythonpath]
- if part
- )
- try:
- installed = install_extension(
- manifest,
- state_file=state_file,
- execute=True,
- )
- assert installed["doctor"]["verified"] is True
- receipt = run_standalone_extension(
- "loopx-finance-value-discovery",
- state_file=state_file,
- request=evidence,
- execute=True,
- )
- finally:
- if previous_pythonpath is None:
- os.environ.pop("PYTHONPATH", None)
- else:
- os.environ["PYTHONPATH"] = previous_pythonpath
- assert receipt["status"] == "succeeded"
- assert receipt["provider_result"] == direct
-
- print("finance-value-discovery-extension-smoke: ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/fixtures/codex-cli-visible-proof/codex-same-tui-help.public.json b/examples/fixtures/codex-cli-visible-proof/codex-same-tui-help.public.json
deleted file mode 100644
index da63099084..0000000000
--- a/examples/fixtures/codex-cli-visible-proof/codex-same-tui-help.public.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "command_outputs": {
- "root": "Usage: codex [OPTIONS] [PROMPT]\n\nCommands:\n exec\n resume\n attach-session Send prompt to session after checking the idle TUI\n",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [SESSION_ID]"
- }
-}
diff --git a/examples/fixtures/codex-cli-visible-proof/codex-visible-resume-help.public.json b/examples/fixtures/codex-cli-visible-proof/codex-visible-resume-help.public.json
deleted file mode 100644
index 8784e9fd39..0000000000
--- a/examples/fixtures/codex-cli-visible-proof/codex-visible-resume-help.public.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "command_outputs": {
- "root": "Usage: codex [OPTIONS] [PROMPT]\n\nCommands:\n exec\n remote-control Manage the app-server daemon with remote control enabled\n resume Resume a previous interactive session\n\nOptions:\n --remote Connect the TUI to a remote app server endpoint\n",
- "exec": "Usage: codex exec [OPTIONS] [PROMPT]",
- "resume": "Usage: codex resume [OPTIONS] [SESSION_ID] [PROMPT]"
- }
-}
diff --git a/examples/fixtures/codex-cli-visible-proof/runtime-idle-same-tui.public.json b/examples/fixtures/codex-cli-visible-proof/runtime-idle-same-tui.public.json
deleted file mode 100644
index fdc6db1628..0000000000
--- a/examples/fixtures/codex-cli-visible-proof/runtime-idle-same-tui.public.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "observed_surface": "same_tui_visible_attach",
- "idle_guard": {
- "no_active_human_typing": true,
- "no_running_turn": true,
- "checked_before_prompt": true
- },
- "turn_visibility": {
- "visible_to_user": true
- },
- "interruptibility": {
- "user_can_interrupt": true,
- "manual_takeover_available": true
- },
- "boundary": {
- "reads_raw_transcripts": false,
- "reads_session_files": false,
- "reads_stdout_stderr": false,
- "reads_credentials": false,
- "mutates_hidden_session_state": false
- },
- "proof_result": "fresh idle guard passed for a same-TUI demo fixture"
-}
diff --git a/examples/fixtures/codex-cli-visible-proof/runtime-idle-visible-resume.public.json b/examples/fixtures/codex-cli-visible-proof/runtime-idle-visible-resume.public.json
deleted file mode 100644
index 6bf03bc21e..0000000000
--- a/examples/fixtures/codex-cli-visible-proof/runtime-idle-visible-resume.public.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "observed_surface": "visible_resume_prompt",
- "idle_guard": {
- "no_active_human_typing": true,
- "no_running_turn": true,
- "checked_before_prompt": true
- },
- "turn_visibility": {
- "visible_to_user": true
- },
- "interruptibility": {
- "user_can_interrupt": true,
- "manual_takeover_available": true
- },
- "boundary": {
- "reads_raw_transcripts": false,
- "reads_session_files": false,
- "reads_stdout_stderr": false,
- "reads_credentials": false,
- "mutates_hidden_session_state": false
- },
- "proof_result": "fresh idle guard passed for a visible resume proof prompt"
-}
diff --git a/examples/fixtures/codex-cli-visible-proof/same-tui-proof.public.json b/examples/fixtures/codex-cli-visible-proof/same-tui-proof.public.json
deleted file mode 100644
index bdb232917f..0000000000
--- a/examples/fixtures/codex-cli-visible-proof/same-tui-proof.public.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "observed_surface": "same_tui_visible_attach",
- "user_opt_in": true,
- "quota_guard": {
- "passed": true
- },
- "idle_guard": {
- "no_active_human_typing": true,
- "no_running_turn": true,
- "checked_before_prompt": true
- },
- "turn_visibility": {
- "visible_to_user": true,
- "prompt_public_safe": true
- },
- "interruptibility": {
- "user_can_interrupt": true,
- "manual_takeover_available": true
- },
- "boundary": {
- "reads_raw_transcripts": false,
- "reads_session_files": false,
- "reads_credentials": false,
- "mutates_hidden_session_state": false,
- "spends_quota_before_writeback": false
- },
- "writeback": {
- "compact_evidence_planned": true
- },
- "proof_result": "same-TUI visible attach proof passed for a public demo fixture"
-}
diff --git a/examples/fixtures/codex-cli-visible-proof/visible-resume-proof.public.json b/examples/fixtures/codex-cli-visible-proof/visible-resume-proof.public.json
deleted file mode 100644
index 7eb97140d4..0000000000
--- a/examples/fixtures/codex-cli-visible-proof/visible-resume-proof.public.json
+++ /dev/null
@@ -1,31 +0,0 @@
-{
- "observed_surface": "visible_resume_prompt",
- "user_opt_in": true,
- "quota_guard": {
- "passed": true
- },
- "idle_guard": {
- "no_active_human_typing": true,
- "no_running_turn": true,
- "checked_before_prompt": true
- },
- "turn_visibility": {
- "visible_to_user": true,
- "prompt_public_safe": true
- },
- "interruptibility": {
- "user_can_interrupt": true,
- "manual_takeover_available": true
- },
- "boundary": {
- "reads_raw_transcripts": false,
- "reads_session_files": false,
- "reads_credentials": false,
- "mutates_hidden_session_state": false,
- "spends_quota_before_writeback": false
- },
- "writeback": {
- "compact_evidence_planned": true
- },
- "proof_result": "visible spike proof only; same-TUI attach not proven"
-}
diff --git a/examples/fixtures/decentralized-auto-research-knn.public.json b/examples/fixtures/decentralized-auto-research-knn.public.json
deleted file mode 100644
index 8cb070c3da..0000000000
--- a/examples/fixtures/decentralized-auto-research-knn.public.json
+++ /dev/null
@@ -1,130 +0,0 @@
-{
- "schema_version": "decentralized_auto_research_fixture_v0",
- "generated_at": "2026-06-28T00:00:00Z",
- "research_contract": {
- "schema_version": "research_contract_v0",
- "goal_id": "loopx-auto-research-knn",
- "research_objective": "Improve exact k-nearest-neighbor inference speed under a protected evaluator.",
- "editable_scope": ["solution.py"],
- "protected_scope": ["eval.py", "task.py", "generated_data"],
- "metric": {
- "name": "speedup",
- "direction": "maximize",
- "baseline": 1.0
- },
- "dev_eval": "eval_dev_alias",
- "holdout_eval": "eval_holdout_alias",
- "promotion_policy": "requires_holdout_improvement_and_clean_boundary"
- },
- "agents": ["codex-side-bypass", "codex-product-capability"],
- "hypotheses": [
- {
- "schema_version": "research_hypothesis_v0",
- "hypothesis_id": "hyp_001",
- "parent_hypothesis_id": null,
- "todo_id": "todo_auto_research_001",
- "claimed_by": "codex-side-bypass",
- "mechanism_family": "vectorized_distance_kernel",
- "hypothesis": "Vectorize pairwise distance calculation while preserving exact nearest-neighbor output.",
- "status": "supported",
- "grounding_refs": ["grounding_public_numpy_vectorization"],
- "novelty_audit_ref": "novelty_audit_public_exact_knn",
- "blocked_by": []
- },
- {
- "schema_version": "research_hypothesis_v0",
- "hypothesis_id": "hyp_002",
- "parent_hypothesis_id": "hyp_001",
- "todo_id": "todo_auto_research_002",
- "claimed_by": "codex-side-bypass",
- "mechanism_family": "partial_selection",
- "hypothesis": "Use partial selection to avoid a full distance sort for each query.",
- "status": "active",
- "grounding_refs": ["grounding_public_selection_algorithms"],
- "novelty_audit_ref": null,
- "blocked_by": []
- },
- {
- "schema_version": "research_hypothesis_v0",
- "hypothesis_id": "hyp_003",
- "parent_hypothesis_id": "hyp_002",
- "todo_id": "todo_auto_research_003",
- "claimed_by": "codex-product-capability",
- "mechanism_family": "batch_query_path",
- "hypothesis": "Batch query points so shared array layout work is reused across requests.",
- "status": "active",
- "grounding_refs": ["grounding_public_batching"],
- "novelty_audit_ref": null,
- "blocked_by": []
- },
- {
- "schema_version": "research_hypothesis_v0",
- "hypothesis_id": "hyp_004",
- "parent_hypothesis_id": "hyp_003",
- "todo_id": "todo_auto_research_004",
- "claimed_by": "codex-side-bypass",
- "mechanism_family": "approximate_search_guardrail",
- "hypothesis": "Try approximate search only as a negative control because exact output is required.",
- "status": "contradicted",
- "grounding_refs": ["grounding_public_ann_tradeoff"],
- "novelty_audit_ref": "novelty_audit_public_ann_exactness",
- "blocked_by": ["correctness_guardrail_failed"]
- }
- ],
- "evidence_events": [
- {
- "schema_version": "research_evidence_event_v0",
- "hypothesis_id": "hyp_001",
- "todo_id": "todo_auto_research_001",
- "agent_id": "codex-side-bypass",
- "attempt": 1,
- "split": "dev",
- "metric": {
- "name": "speedup",
- "value": 4.8,
- "direction": "maximize"
- },
- "baseline_metric": 1.0,
- "eval_status": "scored",
- "primary_metric_status": "improved",
- "artifact_refs": ["experiment_hyp001_report", "diff_hyp001"],
- "protected_scope_clean": true
- },
- {
- "schema_version": "research_evidence_event_v0",
- "hypothesis_id": "hyp_001",
- "todo_id": "todo_auto_research_001",
- "agent_id": "codex-side-bypass",
- "attempt": 2,
- "split": "holdout",
- "metric": {
- "name": "speedup",
- "value": 4.3,
- "direction": "maximize"
- },
- "baseline_metric": 1.0,
- "eval_status": "scored",
- "primary_metric_status": "improved",
- "artifact_refs": ["experiment_hyp001_holdout_report"],
- "protected_scope_clean": true
- },
- {
- "schema_version": "research_evidence_event_v0",
- "hypothesis_id": "hyp_004",
- "todo_id": "todo_auto_research_004",
- "agent_id": "codex-side-bypass",
- "attempt": 1,
- "split": "dev",
- "metric": {
- "name": "speedup",
- "value": null,
- "direction": "maximize"
- },
- "baseline_metric": 1.0,
- "eval_status": "guardrail_failed",
- "primary_metric_status": "failed",
- "artifact_refs": ["experiment_hyp004_guardrail_note"],
- "protected_scope_clean": true
- }
- ]
-}
diff --git a/examples/fixtures/knn-eval-dev.public.json b/examples/fixtures/knn-eval-dev.public.json
deleted file mode 100644
index 00940be90e..0000000000
--- a/examples/fixtures/knn-eval-dev.public.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "ok": true,
- "split": "dev",
- "score": 1.352,
- "metric_name": "speedup",
- "direction": "maximize",
- "baseline_score": 1.0,
- "editable_scope": ["solution.py"],
- "protected_scope": ["task.py", "eval.py", "eval.sh"]
-}
diff --git a/examples/fixtures/knn-eval-holdout.public.json b/examples/fixtures/knn-eval-holdout.public.json
deleted file mode 100644
index 668ed46c2e..0000000000
--- a/examples/fixtures/knn-eval-holdout.public.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "ok": true,
- "split": "test",
- "score": 1.281,
- "metric_name": "speedup",
- "direction": "maximize",
- "baseline_score": 1.0,
- "editable_scope": ["solution.py"],
- "protected_scope": ["task.py", "eval.py", "eval.sh"]
-}
diff --git a/examples/history-reserved-run-path-smoke.py b/examples/history-reserved-run-path-smoke.py
deleted file mode 100644
index 55d5c8eec1..0000000000
--- a/examples/history-reserved-run-path-smoke.py
+++ /dev/null
@@ -1,120 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test reserved run paths for same-second append writers."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import history, state_refresh # noqa: E402
-
-
-GOAL_ID = "reserved-run-path-fixture"
-FIXED_TIME = "2026-01-01T00:00:00+00:00"
-
-
-def write_registry(root: Path) -> Path:
- project = root / "project"
- runtime = root / "runtime"
- state_file = f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md"
- state_path = project / state_file
- state_path.parent.mkdir(parents=True, exist_ok=True)
- state_path.write_text(
- "---\n"
- "status: reserved-run-path-fixture\n"
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- "# Reserved Run Path Fixture\n\n"
- "## Next Action\n\n"
- "- continue reserved run path validation\n\n"
- "## Agent Todo\n\n",
- encoding="utf-8",
- )
- registry_path = project / ".loopx" / "registry.json"
- registry_path.parent.mkdir(parents=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": "0.1",
- "updated_at": "2026-01-01T00:00:00+00:00",
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "domain": "reserved-run-path-fixture",
- "status": "active-read-only",
- "repo": str(project),
- "state_file": state_file,
- "adapter": {"kind": "fixture", "status": "connected-read-only"},
- }
- ],
- },
- ensure_ascii=False,
- indent=2,
- )
- + "\n",
- encoding="utf-8",
- )
- from loopx.control_plane.testing.canary_harness import import_fixture_authority
- import_fixture_authority(registry_path, GOAL_ID, provider="sqlite")
- return registry_path
-
-
-def artifact_identity(payload: dict[str, object]) -> tuple[str, str, str]:
- return (
- str(payload.get("generated_at") or ""),
- str(payload.get("json_path") or ""),
- str(payload.get("markdown_path") or ""),
- )
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-reserved-run-path-") as raw_tmp:
- root = Path(raw_tmp)
- registry_path = write_registry(root)
- original_refresh_now = state_refresh.now_local
- state_refresh.now_local = lambda: FIXED_TIME
- try:
- payloads = [
- state_refresh.refresh_state_run(
- registry_path=registry_path,
- runtime_root_override=None,
- goal_id=GOAL_ID,
- project=None,
- state_file=None,
- classification=f"reserved_run_path_refresh_{suffix}",
- recommended_action="continue reserved run path validation",
- dry_run=False,
- sync_global=False,
- )
- for suffix in ("a", "b", "c", "d")
- ]
- finally:
- state_refresh.now_local = original_refresh_now
-
- identities = [artifact_identity(payload) for payload in payloads]
- assert len(identities) == len(set(identities)), identities
- assert [Path(payload["json_path"]).name for payload in payloads] == [
- "2026-01-01T00-00-00-00-00.json",
- "2026-01-01T00-00-00-00-00-2.json",
- "2026-01-01T00-00-00-00-00-3.json",
- "2026-01-01T00-00-00-00-00-4.json",
- ], payloads
-
- duplicate_report = history.inspect_index_duplicates(
- registry_path=registry_path,
- runtime_root_override=None,
- goal_id=GOAL_ID,
- limit=10,
- )
- assert duplicate_report["duplicate_group_count"] == 0, duplicate_report
- print("history-reserved-run-path-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/host-integration-plugin-plan-smoke.py b/examples/host-integration-plugin-plan-smoke.py
deleted file mode 100644
index d3090b658e..0000000000
--- a/examples/host-integration-plugin-plan-smoke.py
+++ /dev/null
@@ -1,97 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the host integration plugin plan contract."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-PLAN = REPO_ROOT / "docs" / "reference" / "protocols" / "host-integration-plugin-plan-v0.md"
-PROTOCOL_INDEX = REPO_ROOT / "docs" / "reference" / "protocols" / "README.md"
-DOCS_INDEX = REPO_ROOT / "docs" / "README.md"
-
-
-def require(text: str, snippets: list[str], *, source: Path) -> None:
- compact = " ".join(text.split())
- missing = [
- snippet
- for snippet in snippets
- if snippet not in text and " ".join(snippet.split()) not in compact
- ]
- assert not missing, f"{source}: missing {missing}"
-
-
-def main() -> int:
- plan = PLAN.read_text(encoding="utf-8")
- protocol_index = PROTOCOL_INDEX.read_text(encoding="utf-8")
- docs_index = DOCS_INDEX.read_text(encoding="utf-8")
-
- require(
- plan,
- [
- "host_integration_plugin_plan_v0",
- "skill-level LoopX slash-command fallback",
- "host-owned command registry",
- "not a shipped plugin manifest",
- "LoopX CLI as the source of truth",
- "codex_app_host_command_registry_v0",
- "host_integration_surface_v0",
- "session_runtime_loopx_projection_v0",
- "## Plugin Capability Set",
- "## Phased Path",
- "### Phase 0: Skill Fallback",
- "### Phase 1: Host Command Alias",
- "### Phase 2: Heartbeat Installer",
- "### Phase 3: Scheduler Hint Adapter",
- "### Phase 4: Controlled Write Tools",
- "## Acceptance Matrix",
- "loopx heartbeat-prompt --thin --goal-id ",
- "stateful_backoff.apply_needed",
- "quota scheduler-ack-current",
- "last applied RRULE",
- "does not spend quota",
- "Raw transcript offered to plugin",
- "Plugin rejects or redacts the payload",
- "CLI unavailable",
- "install/doctor blocker",
- "raw_transcripts_accepted",
- "credentials_accepted",
- "public_local_paths_allowed",
- ],
- source=PLAN,
- )
- require(
- plan,
- [
- "Do not replace the CLI",
- "Do not store raw transcripts",
- "Do not treat a chat slash command as approval",
- "Do not make hidden headless execution the default",
- "Unknown `/loopx-debug-me`",
- "fails closed with `loopx slash-commands` help",
- ],
- source=PLAN,
- )
- assert plan.index("### Phase 0: Skill Fallback") < plan.index("### Phase 1: Host Command Alias")
- assert plan.index("### Phase 1: Host Command Alias") < plan.index("### Phase 2: Heartbeat Installer")
- assert plan.index("### Phase 2: Heartbeat Installer") < plan.index("### Phase 3: Scheduler Hint Adapter")
- assert plan.index("### Phase 3: Scheduler Hint Adapter") < plan.index("### Phase 4: Controlled Write Tools")
- assert "raw transcript material" not in plan.lower()
-
- require(
- protocol_index,
- ["host_integration_plugin_plan_v0", "host-integration-plugin-plan-v0.md"],
- source=PROTOCOL_INDEX,
- )
- require(
- docs_index,
- ["reference/README.md"],
- source=DOCS_INDEX,
- )
- print("host-integration-plugin-plan-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/host-mode-plan-smoke.py b/examples/host-mode-plan-smoke.py
deleted file mode 100755
index 2549f85a25..0000000000
--- a/examples/host-mode-plan-smoke.py
+++ /dev/null
@@ -1,513 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the LoopX Turn-based host-mode selector.
-
-This proves the selector added for GH-C56 stays useful without becoming a
-parallel runner:
-- intent selects visible, isolated headless Turn, gateway, timer, and hybrid modes;
-- headless modes map to the shipped `loopx turn plan` preview;
-- scoped `--agent-id` flows into Turn and quota preview commands;
-- readiness reports missing host capabilities instead of pretending execution is ready;
-- no-spend, independent-validation, writeback-before-spend, and boundary rules remain visible;
-- docs are wired without scanning unrelated catalog prose with broad private-word bans.
-"""
-
-from __future__ import annotations
-
-import os
-import re
-import sys
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.host_mode_planner import ( # noqa: E402
- CANONICAL_MODES,
- MODE_HYBRID_HANDOFF,
- MODE_IM_GATEWAY,
- MODE_ISOLATED_HEADLESS_TURN,
- MODE_SHELL_SERVICE,
- MODE_VISIBLE_TUI,
- HostModePlanError,
- build_host_mode_plan,
- render_host_mode_plan_markdown,
-)
-
-CONTRACT_PATH = REPO_ROOT / "docs" / "reference" / "protocols" / "host-mode-plan-v0.md"
-TURN_CONTRACT_PATH = REPO_ROOT / "docs" / "reference" / "protocols" / "loopx-turn-v0.md"
-PROTOCOL_INDEX_PATH = REPO_ROOT / "docs" / "reference" / "protocols" / "README.md"
-CONNECTOR_CATALOG_PATH = REPO_ROOT / "docs" / "integrations" / "runtime-connector-catalog.md"
-
-PRIVATE_PATTERNS = [
- re.compile(r"/Users/[A-Za-z0-9._-]+/"),
- re.compile(r"/home/[A-Za-z0-9._-]+/"),
- re.compile(r"\bBearer\s+[A-Za-z0-9._-]+"),
- re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
-]
-
-INTENT_TO_MODE = {
- "watch_each_turn": MODE_VISIBLE_TUI,
- "continue_without_ui": MODE_ISOLATED_HEADLESS_TURN,
- "intake_from_chat": MODE_IM_GATEWAY,
- "timer_keepalive": MODE_SHELL_SERVICE,
- "escalate_between_modes": MODE_HYBRID_HANDOFF,
-}
-
-
-def assert_public_safe(text: str, label: str) -> None:
- for pattern in PRIVATE_PATTERNS:
- if pattern.search(text):
- raise AssertionError(f"{label} matched private pattern {pattern.pattern!r}")
-
-
-def assert_contains(text: str, needle: str, label: str) -> None:
- if needle not in text:
- raise AssertionError(f"{label} missing {needle!r}")
-
-
-def build_full_plan(intent: str) -> dict[str, object]:
- return build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent=intent,
- host_capabilities=[
- "visible_session",
- "loopx_turn",
- "typed_host_adapter",
- "independent_validator",
- "chat_gateway",
- "service_timer",
- "shell",
- ],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control", "codex-side-peer"],
- available_capabilities=["shell", "network"],
- host_identity="codex-cli",
- )
-
-
-def option(plan: dict[str, object], mode: str) -> dict[str, object]:
- for item in plan["mode_options"]: # type: ignore[index]
- if isinstance(item, dict) and item.get("mode") == mode:
- return item
- raise AssertionError(f"missing mode option {mode}")
-
-
-def test_intent_selects_distinct_host_modes() -> None:
- for intent, expected_mode in INTENT_TO_MODE.items():
- plan = build_full_plan(intent)
- assert plan["ok"] is True, plan
- assert plan["schema_version"] == "host_mode_plan_v0", plan
- assert plan["mode"] == "dry_run_host_mode_selector", plan
- assert plan["selected_mode"] == expected_mode, (intent, plan)
- modes = [item["mode"] for item in plan["mode_options"]] # type: ignore[index]
- assert set(modes) == set(CANONICAL_MODES), modes
- assert len(modes) == len(CANONICAL_MODES), modes
-
-
-def test_headless_maps_to_loopx_turn_plan_not_parallel_runner() -> None:
- plan = build_full_plan("continue_without_ui")
- selected = plan["selected_turn_mapping"]
- assert selected["host"] == "generic-cli", selected
- assert selected["host_selection"] == "resolved_default", selected
- assert selected["execution_mode"] == "isolated-headless", selected
- assert selected["scheduler_owner"] == "outer_controller", selected
- command = selected["plan_command"]
- assert "loopx turn plan" in command, command
- # The preview keeps the shipped host resolution, so it does not freeze the
- # compatibility adapter path as the product default.
- assert "--host" not in command, command
- assert "--execution-mode isolated-headless" in command, command
- assert "--scheduler-owner outer_controller" in command, command
- assert "--agent-id codex-main-control" in command, command
- assert "--available-capability shell" in command, command
- rollback = selected["plan_command_rollback"]
- assert "--host generic-cli" in rollback, rollback
- assert plan["turn_contract"]["schema_version"] == "loopx_turn_v0", plan
- assert plan["turn_contract"]["independent_validation_required"] is True, plan
- assert plan["turn_contract"]["writeback_before_quota_spend"] is True, plan
-
-
-def test_headless_preview_ignores_operator_credential() -> None:
- credential_env = "DEEPSEEK_API_KEY"
- previous = os.environ.pop(credential_env, None)
- try:
- without_credential = build_full_plan("continue_without_ui")["selected_turn_mapping"]
- os.environ[credential_env] = "host-mode-plan-smoke-not-a-credential"
- with_credential = build_full_plan("continue_without_ui")["selected_turn_mapping"]
- finally:
- if previous is None:
- os.environ.pop(credential_env, None)
- else:
- os.environ[credential_env] = previous
- # `loopx turn plan`/`run-once` resolve one shipped default that
- # `LOOPX_TURN_HOST` or an explicit `--host` re-points. The preview never
- # performs that resolution, so its shape must not depend on the credential
- # that would resolve it at run time: a preview that changed shape once a
- # credential appeared would freeze one machine's resolution into a plan.
- assert with_credential == without_credential, (without_credential, with_credential)
- assert without_credential["host_selection"] == "resolved_default", without_credential
- assert "--host" not in without_credential["plan_command"], without_credential
-
-
-def test_visible_mode_stays_visible_and_scoped() -> None:
- plan = build_workflow_identity_plan("watch_each_turn", host_identity="codex-cli")
- selected = plan["selected_turn_mapping"]
- assert selected["host"] == "codex-cli", selected
- assert selected["execution_mode"] == "interactive-visible", selected
- assert selected["scheduler_owner"] == "agent_cli_loop", selected
- assert "--host codex-cli" in selected["plan_command"], selected
- assert "--agent-id codex-main-control" in selected["plan_command"], selected
- visible = option(plan, MODE_VISIBLE_TUI)
- assert visible["connector_id"] == "codex_cli_tui", visible
- assert visible["capability_ready"] is True, visible
- assert plan["host_identity"] == "codex-cli", plan
-
-
-def build_workflow_identity_plan(intent: str, host_identity: str | None) -> dict[str, object]:
- return build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent=intent,
- host_capabilities=[
- "visible_session",
- "loopx_turn",
- "typed_host_adapter",
- "independent_validator",
- "chat_gateway",
- "service_timer",
- "shell",
- ],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control", "codex-side-peer"],
- available_capabilities=["shell", "network"],
- host_identity=host_identity,
- )
-
-
-def test_visible_mode_preserves_distinct_host_identities() -> None:
- expected_connectors = {
- "codex-cli": "codex_cli_tui",
- "claude-code": "claude_code_loop",
- "generic-cli": "opencode_goal_loop",
- }
- for host_identity, connector_id in expected_connectors.items():
- plan = build_workflow_identity_plan("watch_each_turn", host_identity=host_identity)
- selected = plan["selected_turn_mapping"]
- assert selected["host"] == host_identity, (host_identity, selected)
- assert f"--host {host_identity}" in selected["plan_command"], selected
- visible = option(plan, MODE_VISIBLE_TUI)
- assert visible["connector_id"] == connector_id, visible
- assert visible["host_identity"] == host_identity, visible
- assert plan["host_identity"] == host_identity, plan
- assert plan["selected_connector_id"] == connector_id, plan
-
-
-def test_visible_mode_fails_closed_without_host_identity() -> None:
- plan = build_workflow_identity_plan("watch_each_turn", host_identity=None)
- visible = option(plan, MODE_VISIBLE_TUI)
- assert visible["capability_ready"] is False, visible
- # Unresolved mapping must not emit a non-catalog connector id; the
- # resolution state lives in a separately typed field instead.
- assert visible["connector_id"] is None, visible
- assert visible["host_resolution"] == "identity_required", visible
- assert visible["host_identity"] is None, visible
- assert visible["turn_mapping"]["host"] is None, visible
- assert visible["recommended_next_steps"][0]["kind"] == "stop", visible
- assert plan["selected_capability_ready"] is False, plan
- assert plan["selected_connector_id"] is None, plan
- assert plan["selected_turn_mapping"]["host"] is None, plan
- assert any("host_identity" in reason for reason in plan["selected_blocking_reasons"]), plan
- assert plan["operator_next_steps"][0]["kind"] == "stop", plan
- # No fabricated codex-cli preview command when identity is unknown.
- assert "--host codex-cli" not in plan["next_preview_command"], plan
- assert "codex-cli" not in str(plan["next_preview_command"]), plan
-
-
-def test_opencode_alias_resolves_to_goal_loop_connector() -> None:
- plan = build_workflow_identity_plan("watch_each_turn", host_identity="opencode")
- visible = option(plan, MODE_VISIBLE_TUI)
- assert visible["capability_ready"] is True, visible
- assert visible["connector_id"] == "opencode_goal_loop", visible
- assert visible["host_resolution"] == "resolved", visible
- assert plan["selected_connector_id"] == "opencode_goal_loop", plan
- assert plan["selected_turn_mapping"]["host"] == "generic-cli", plan
- assert "--host generic-cli" in plan["next_preview_command"], plan
-
-
-def test_pi_alias_resolves_to_goal_loop_connector() -> None:
- plan = build_workflow_identity_plan("watch_each_turn", host_identity="pi")
- visible = option(plan, MODE_VISIBLE_TUI)
- assert visible["capability_ready"] is True, visible
- assert visible["connector_id"] == "pi_goal_loop", visible
- assert visible["host_resolution"] == "resolved", visible
- assert plan["selected_connector_id"] == "pi_goal_loop", plan
- # Pi runs through the generic-cli Turn host, same as OpenCode.
- assert plan["selected_turn_mapping"]["host"] == "generic-cli", plan
- assert "--host generic-cli" in plan["next_preview_command"], plan
-
-
-def test_visible_mode_fails_closed_for_unknown_host_identity() -> None:
- for host_identity in ("not-a-host", "dsh"):
- try:
- build_workflow_identity_plan("watch_each_turn", host_identity=host_identity)
- except HostModePlanError as exc:
- payload = exc.to_payload()
- else:
- raise AssertionError(
- f"unsupported visible host identity {host_identity!r} should fail closed"
- )
- assert payload["ok"] is False, payload
- assert payload["field"] == "host_identity", payload
-
-
-def test_emitted_connector_ids_exist_in_catalog() -> None:
- catalog = CONNECTOR_CATALOG_PATH.read_text()
- # Resolved identities emit only catalog-registered connector ids.
- for host_identity in ["codex-cli", "claude-code", "generic-cli", "opencode", "pi"]:
- plan = build_workflow_identity_plan("watch_each_turn", host_identity=host_identity)
- connector = plan["selected_connector_id"]
- assert connector is not None, (host_identity, plan)
- assert f"`{connector}`" in catalog, (connector, "missing from runtime connector catalog")
- # Unresolved paths (omitted or unregistered identity) must not emit any
- # non-catalog value in the connector id field.
- for host_identity in [None]:
- plan = build_workflow_identity_plan("watch_each_turn", host_identity=host_identity)
- assert plan["selected_connector_id"] is None, (host_identity, plan)
- visible = option(plan, MODE_VISIBLE_TUI)
- assert visible["connector_id"] is None, (host_identity, visible)
- for intent, mode in INTENT_TO_MODE.items():
- if mode == MODE_HYBRID_HANDOFF:
- continue # selector-internal handoff contract, not a catalog connector
- plan = build_full_plan(intent)
- connector = plan["selected_connector_id"]
- assert connector is not None, (intent, plan)
- assert f"`{connector}`" in catalog, (intent, connector, "missing from runtime connector catalog")
-
-
-def test_readiness_fails_closed_without_required_host_capabilities() -> None:
- plan = build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent="continue_without_ui",
- host_capabilities=["loopx_turn"],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control"],
- )
- headless = option(plan, MODE_ISOLATED_HEADLESS_TURN)
- assert headless["capability_ready"] is False, headless
- assert headless["required_host_capabilities"] == [
- "loopx_turn",
- "typed_host_adapter",
- "independent_validator",
- ], headless
- assert headless["missing_host_capabilities"] == [
- "typed_host_adapter",
- "independent_validator",
- ], headless
- assert any("typed host adapter" in reason for reason in headless["blocking_reasons"]), headless
- assert any("independent validator" in reason for reason in headless["blocking_reasons"]), headless
- steps = headless["recommended_next_steps"]
- assert steps[0]["kind"] == "stop", steps
- assert any(step["kind"] == "capability_gap" for step in steps), steps
- assert steps[-1]["kind"] == "repreview", steps
- assert plan["selected_capability_ready"] is False, plan
- assert plan["selected_missing_host_capabilities"] == [
- "typed_host_adapter",
- "independent_validator",
- ], plan
- assert plan["operator_next_steps"][0]["kind"] == "stop", plan
-
-
-def test_shell_service_fails_closed_without_adapter_and_validator() -> None:
- # Regression: with only service_timer, shell, and loopx_turn the planner
- # previously reported shell_service ready even though its required proofs
- # include typed_host_adapter and independent_validation.
- plan = build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent="timer_keepalive",
- host_capabilities=["service_timer", "shell", "loopx_turn"],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control"],
- )
- shell_service = option(plan, MODE_SHELL_SERVICE)
- assert shell_service["capability_ready"] is False, shell_service
- assert shell_service["missing_host_capabilities"] == [
- "typed_host_adapter",
- "independent_validator",
- ], shell_service
- assert plan["selected_capability_ready"] is False, plan
-
-
-def test_hybrid_requires_two_ready_modes_and_names_handoffs() -> None:
- one_ready = build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent="escalate_between_modes",
- host_capabilities=["visible_session"],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control"],
- )
- hybrid_one = option(one_ready, MODE_HYBRID_HANDOFF)
- assert hybrid_one["capability_ready"] is False, hybrid_one
- assert hybrid_one["blocking_reasons"], hybrid_one
- assert hybrid_one["recommended_next_steps"][0]["kind"] == "stop", hybrid_one
-
- two_ready = build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent="escalate_between_modes",
- host_capabilities=[
- "visible_session",
- "loopx_turn",
- "typed_host_adapter",
- "independent_validator",
- ],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control"],
- host_identity="codex-cli",
- )
- assert option(two_ready, MODE_HYBRID_HANDOFF)["capability_ready"] is True, two_ready
- transition_ids = {item["transition"] for item in two_ready["transitions"]}
- assert "visible_bootstrap_to_isolated_headless_turn" in transition_ids, transition_ids
- assert "isolated_headless_turn_to_visible_tui_escalation" in transition_ids, transition_ids
- for transition in two_ready["transitions"]:
- assert transition["preserves_agent_id"] is True, transition
- assert transition["spends_quota"] is False, transition
- assert "--agent-id codex-main-control" in transition["guard_command"], transition
- # The transition policy is the same rule as the mode preview: a target that
- # resolves its host must not pin the compatibility adapter path, while a
- # target that needs a visible identity still pins it.
- by_id = {item["transition"]: item for item in two_ready["transitions"]}
- for transition_id in (
- "visible_bootstrap_to_isolated_headless_turn",
- "im_gateway_to_isolated_headless_turn",
- ):
- command = by_id[transition_id]["target_turn_plan_command"]
- assert "--host" not in command, (transition_id, command)
- for transition_id in (
- "isolated_headless_turn_to_visible_tui_escalation",
- "shell_service_to_visible_tui_escalation",
- ):
- command = by_id[transition_id]["target_turn_plan_command"]
- assert "--host codex-cli" in command, (transition_id, command)
- assert "--execution-mode interactive-visible" in command, (transition_id, command)
-
-
-def test_identity_gate_and_no_spend_boundary() -> None:
- plan = build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent="watch_each_turn",
- host_capabilities=["visible_session"],
- registered_agents=["codex-main-control", "codex-side-peer"],
- )
- identity = plan["identity_contract"]
- assert identity["state"] == "selection_required", identity
- assert identity["action_required"] is True, identity
- assert plan["agent_id"] is None, plan
- assert "--agent-id" not in plan["next_preview_command"], plan
-
- no_spend = plan["no_spend_policy"]
- assert no_spend["selector_preview"] is True, no_spend
- assert no_spend["turn_plan_preview"] is True, no_spend
- assert no_spend["quiet_monitor_skip"] is True, no_spend
- assert no_spend["spends_only_after_validated_delivery_writeback"] is True, no_spend
- boundary = plan["boundary"]
- assert boundary["selector_is_authoritative"] is False, boundary
- assert boundary["turn_envelope_is_authoritative_for_execution"] is True, boundary
- for key in [
- "starts_process",
- "writes_state",
- "spends_quota",
- "infers_production_permission",
- "infers_credential_access",
- "infers_destructive_authority",
- ]:
- assert boundary[key] is False, (key, boundary)
-
-
-def test_unknown_values_fail_closed() -> None:
- try:
- build_host_mode_plan(goal_id="g", user_intent="launch_missiles")
- except HostModePlanError as exc:
- payload = exc.to_payload()
- else:
- raise AssertionError("unknown intent should fail")
- assert payload["ok"] is False, payload
- assert payload["field"] == "user_intent", payload
- assert "continue_without_ui" in payload["suggestions"], payload
-
- try:
- build_host_mode_plan(
- goal_id="g",
- user_intent="continue_without_ui",
- host_capabilities=["root_shell"],
- )
- except HostModePlanError as exc:
- payload = exc.to_payload()
- else:
- raise AssertionError("unknown capability should fail")
- assert payload["field"] == "host_capabilities", payload
- assert "independent_validator" in payload["suggestions"], payload
-
-
-def test_markdown_and_docs_are_wired() -> None:
- plan = build_full_plan("continue_without_ui")
- markdown = render_host_mode_plan_markdown(plan)
- assert_contains(markdown, "LoopX Host Mode Plan", "markdown")
- assert_contains(markdown, "loopx turn plan", "markdown")
- assert_contains(markdown, "Operator Next Steps", "markdown")
- assert_contains(markdown, "Escalate back to visible_tui", "markdown")
- assert_contains(markdown, "Why This Helps", "markdown")
- assert_public_safe(markdown, "markdown")
-
- blocked = build_host_mode_plan(
- goal_id="workflow-selector-fixture",
- user_intent="continue_without_ui",
- host_capabilities=["loopx_turn"],
- agent_id="codex-main-control",
- registered_agents=["codex-main-control"],
- )
- blocked_markdown = render_host_mode_plan_markdown(blocked)
- assert_contains(blocked_markdown, "Blocking Reasons", "blocked markdown")
- assert_contains(blocked_markdown, "typed host adapter", "blocked markdown")
- assert_contains(blocked_markdown, "Stop before attempting this host mode", "blocked markdown")
- assert_public_safe(blocked_markdown, "blocked markdown")
-
- contract = CONTRACT_PATH.read_text()
- assert_contains(contract, "dry_run_host_mode_selector", "workflow contract")
- assert_contains(contract, "loopx turn plan", "workflow contract")
- assert_contains(contract, "independent validation", "workflow contract")
- assert_contains(contract, "typed_host_adapter", "workflow contract")
- assert_public_safe(contract, "workflow contract")
-
- turn_contract = TURN_CONTRACT_PATH.read_text()
- assert_contains(turn_contract, "LoopX decides -> agent CLI executes", "turn contract")
- assert_contains(turn_contract, "independent validator", "turn contract")
-
- protocol_index = PROTOCOL_INDEX_PATH.read_text()
- assert_contains(protocol_index, "host_mode_plan_v0", "protocol index")
-
- catalog = CONNECTOR_CATALOG_PATH.read_text()
- assert_contains(catalog, "`loopx_turn`", "connector catalog")
- assert_contains(catalog, "Host mode plan v0", "connector catalog")
-
-
-def main() -> int:
- test_intent_selects_distinct_host_modes()
- test_headless_maps_to_loopx_turn_plan_not_parallel_runner()
- test_headless_preview_ignores_operator_credential()
- test_visible_mode_stays_visible_and_scoped()
- test_visible_mode_preserves_distinct_host_identities()
- test_visible_mode_fails_closed_without_host_identity()
- test_opencode_alias_resolves_to_goal_loop_connector()
- test_visible_mode_fails_closed_for_unknown_host_identity()
- test_emitted_connector_ids_exist_in_catalog()
- test_readiness_fails_closed_without_required_host_capabilities()
- test_shell_service_fails_closed_without_adapter_and_validator()
- test_hybrid_requires_two_ready_modes_and_names_handoffs()
- test_identity_gate_and_no_spend_boundary()
- test_unknown_values_fail_closed()
- test_markdown_and_docs_are_wired()
- print("host-mode-planner-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/lark-capability-layout-smoke.py b/examples/lark-capability-layout-smoke.py
deleted file mode 100644
index fed2f81d69..0000000000
--- a/examples/lark-capability-layout-smoke.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test extension-owned Lark presentation sinks without core facades."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.extensions.lark.presentation import explore_results, kanban, message_card # noqa: E402
-
-
-def main() -> int:
- assert kanban.lark_kanban_schema_payload()["schema_version"] == "loopx_lark_kanban_control_plane_v0"
- assert message_card.build_lark_markdown_reply_card("ok")["elements"][0]["text"]["content"] == "ok"
- assert (
- explore_results.lark_explore_schema_payload()["schema_version"]
- == "loopx_lark_explore_result_board_v0"
- )
- assert not list((REPO_ROOT / "loopx" / "capabilities" / "lark").glob("*.py"))
- assert not list(
- (REPO_ROOT / "loopx" / "presentation" / "sinks" / "lark").glob("*.py")
- )
- print("lark capability layout smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/lark-message-card-smoke.py b/examples/lark-message-card-smoke.py
deleted file mode 100644
index 35204e8bf7..0000000000
--- a/examples/lark-message-card-smoke.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test public-safe Lark/Feishu message card rendering."""
-
-from __future__ import annotations
-
-import json
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.extensions.lark.presentation.message_card import ( # noqa: E402
- build_lark_markdown_reply_card,
- compact_markdown,
- compact_plain_text,
- extract_reply_message_id,
-)
-
-
-def main() -> int:
- card = build_lark_markdown_reply_card(
- "**Done**\n- Validated card formatting",
- title="LoopX result",
- template="green",
- )
-
- assert card["config"] == {"wide_screen_mode": True, "enable_forward": True}, card
- assert card["header"]["template"] == "green", card
- assert card["header"]["title"] == {"tag": "plain_text", "content": "LoopX result"}, card
- assert card["elements"][0] == {
- "tag": "div",
- "text": {"tag": "lark_md", "content": "**Done**\n- Validated card formatting"},
- }, card
- assert all(element["tag"] != "note" for element in card["elements"]), card
- assert all(element["tag"] != "hr" for element in card["elements"]), card
- footer_card = build_lark_markdown_reply_card("body", footer="LoopX automated reply")
- assert footer_card["elements"][1]["tag"] == "hr", footer_card
- assert footer_card["elements"][2] == {
- "tag": "note",
- "elements": [{"tag": "plain_text", "content": "LoopX automated reply"}],
- }, footer_card
- escaped_newline_content = build_lark_markdown_reply_card("first\\nsecond")["elements"][0]["text"]["content"]
- assert "\\n" not in escaped_newline_content, escaped_newline_content
- assert "first\nsecond" in escaped_newline_content, escaped_newline_content
-
- assert compact_plain_text(" one\n\n two ", max_chars=20) == "one two"
- assert len(compact_plain_text("x" * 100, max_chars=12)) <= 12
- truncated = compact_markdown("x" * 100, max_chars=32)
- assert len(truncated) <= 32, truncated
- assert truncated.endswith("...truncated."), truncated
-
- parent = "om_parent"
- nested = json.dumps({"data": {"message_id": parent, "reply": {"message_id": "om_reply_json"}}})
- assert extract_reply_message_id(nested, parent_message_id=parent) == "om_reply_json"
- assert extract_reply_message_id("sent parent=om_parent reply=om_reply_plain", parent_message_id=parent) == "om_reply_plain"
- assert extract_reply_message_id("message_id=om_parent", parent_message_id=parent) is None
-
- print("lark message card smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/long-horizon-agent-state-protocol-smoke.py b/examples/long-horizon-agent-state-protocol-smoke.py
deleted file mode 100644
index 6574d1b68c..0000000000
--- a/examples/long-horizon-agent-state-protocol-smoke.py
+++ /dev/null
@@ -1,61 +0,0 @@
-#!/usr/bin/env python3
-"""Validate the public long-horizon agent state protocol contract."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-PROTOCOL_PATH = (
- REPO_ROOT
- / "docs"
- / "reference"
- / "protocols"
- / "long-horizon-agent-state-protocol-v0.md"
-)
-INDEX_PATH = REPO_ROOT / "docs" / "reference" / "protocols" / "README.md"
-
-FORBIDDEN_PRIVATE_PATTERNS = [
- re.compile(r"/" + r"Users/[A-Za-z0-9._-]+/"),
- re.compile(r"/home/[A-Za-z0-9._-]+/"),
- re.compile(r"/" + "private/"),
- re.compile(r"\b" + "depart" + "ment" + r"\b", re.IGNORECASE),
- re.compile("\u90e8\u95e8"),
- re.compile("\u6c47\u62a5"),
-]
-
-
-def assert_contains(source: str, snippet: str, label: str) -> None:
- if snippet not in source:
- raise AssertionError(f"missing {label}: {snippet}")
-
-
-def assert_public_safe(source: str) -> None:
- for pattern in FORBIDDEN_PRIVATE_PATTERNS:
- if pattern.search(source):
- raise AssertionError(f"protocol matched private pattern {pattern.pattern!r}")
-
-
-def main() -> int:
- protocol = PROTOCOL_PATH.read_text(encoding="utf-8")
- index = INDEX_PATH.read_text(encoding="utf-8")
- assert_public_safe(protocol)
- assert_public_safe(index)
-
- assert_contains(index, "long_horizon_agent_state_protocol_v0", "protocol index")
- assert_contains(protocol, "## Source Protocol", "source protocol section")
- assert_contains(protocol, "## Projection Protocol", "projection protocol section")
- assert_contains(protocol, '"projection_is_writable": false', "read-only projection flag")
- assert_contains(protocol, "interaction_contract_v0", "interaction contract anchor")
- assert_contains(protocol, "agent_lane_next_action_v0", "agent lane next action anchor")
- assert_contains(protocol, "loopx_rollout_event_v0", "rollout event anchor")
- assert_contains(protocol, "rollback_packet_v0", "rollback future contract")
- assert_contains(protocol, "candidate todos are not silently promoted", "candidate todo acceptance")
- print("long-horizon-agent-state-protocol smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/loopx-chat-actions-smoke.py b/examples/loopx-chat-actions-smoke.py
index 63b921ef5e..d0ac017b36 100644
--- a/examples/loopx-chat-actions-smoke.py
+++ b/examples/loopx-chat-actions-smoke.py
@@ -105,25 +105,43 @@ def __init__(self, chat_store: ChatSessionStore) -> None:
def open_session(self, **kwargs: object) -> tuple[dict[str, object], bool]:
self.opened_sessions.append(dict(kwargs))
- existing = self.chat_store.latest_session(
+ managed_agent = kwargs.get("managed_agent_id")
+ channel = f"agent.{managed_agent}" if managed_agent is not None else str(kwargs["channel_id"])
+ session_id = kwargs.get("session_id")
+ existing = self.chat_store.load_session(str(session_id)) if session_id is not None else self.chat_store.latest_session(
goal_id=str(kwargs["goal_id"]),
agent_id=str(kwargs["agent_id"]),
- channel_id=str(kwargs["channel_id"]),
+ channel_id=channel,
)
if existing is not None:
return existing, True
session = self.chat_store.create_session(
goal_id=str(kwargs["goal_id"]),
+ goal_instance_id=kwargs.get("goal_instance_id"),
+ **({"session_id": str(session_id)} if session_id is not None else {}),
+ **({"managed_agent_id": str(managed_agent), "managed_workspace_path": str(Path(str(kwargs["work_dir"])).resolve())}
+ if managed_agent is not None else {}),
agent_id=str(kwargs["agent_id"]),
adapter_kind="fake",
upstream_thread_id="thread-goal-create",
- channel_id=str(kwargs["channel_id"]),
+ upstream_mode="chat" if kwargs["agent_id"] == "codex" else "default",
+ channel_id=channel,
)
return session, False
def submit_turn(self, **kwargs: object) -> tuple[dict[str, object], bool]:
self.submissions.append(dict(kwargs))
- return ({"turn_id": "turn-correction-1", "status": "queued"}, True)
+ session_id = str(kwargs["session_id"])
+ turn, created = self.chat_store.create_turn(session_id,
+ client_turn_id=str(kwargs["client_turn_id"]), message=str(kwargs["message"]))
+ if created:
+ # The synchronous fake finishes its ordinary reply through the real
+ # Chat completion owner; it never accepts a Goal or Task outcome.
+ self.chat_store.update_turn(session_id, str(turn["turn_id"]),
+ status="completing", started_at=turn["created_at"], completed_at=turn["created_at"],
+ upstream_turn_id=f"synthetic-{turn['turn_id']}", response={"message": "Synthetic ordinary reply."})
+ turn = self.chat_store.finalize_managed_turn_completion(session_id, str(turn["turn_id"]))
+ return turn, created
def capabilities(self) -> list[dict[str, object]]:
return [
@@ -369,7 +387,8 @@ def assert_http_action_api(root: Path) -> None:
)
assert code == 202, correction_applied
assert correction_applied["proposal"]["status"] == "applied", correction_applied
- assert correction_applied["turn"]["turn_id"] == "turn-correction-1", correction_applied
+ original_correction = chat_store.turn_for_client(session["session_id"], str(runtime_controller.submissions[1]["client_turn_id"]))
+ assert correction_applied["turn"]["turn_id"] == original_correction["turn_id"], correction_applied
assert runtime_controller.submissions[1]["session_id"] == session["session_id"]
goal_proposal = previews["goal.create"]
diff --git a/examples/loopx-chat-agent-smoke.py b/examples/loopx-chat-agent-smoke.py
deleted file mode 100644
index 788351c6b1..0000000000
--- a/examples/loopx-chat-agent-smoke.py
+++ /dev/null
@@ -1,518 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test the persistent read-only Codex app-server chat seam."""
-
-from __future__ import annotations
-
-import json
-import os
-import queue
-import stat
-import sys
-import tempfile
-import time
-from pathlib import Path
-from unittest.mock import patch
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.chat import CHAT_REVIEW_OPEN_TAG, VisibleResponseStreamFilter, redact_local_paths # noqa: E402
-from loopx.chat_agent import ( # noqa: E402
- CodexChatAgentError,
- CodexChatAgentSession,
-)
-
-
-FAKE_CODEX = r'''#!/usr/bin/env python3
-import json
-import os
-import sys
-import time
-from pathlib import Path
-
-if sys.argv[1:3] == ["debug", "models"]:
- marker = os.environ.get("LOOPX_FAKE_DEBUG_MODELS_MARKER")
- if marker:
- Path(marker).write_text("invoked", encoding="utf-8")
- if os.environ.get("LOOPX_FAKE_DEBUG_MODELS_FAIL") == "1":
- raise SystemExit(2)
- print(json.dumps({"models": [{"slug": "fake-current", "base_instructions": "Current built-in instructions."}]}))
- raise SystemExit(0)
-
-catalog_override = None
-for index, value in enumerate(sys.argv):
- if value == "-c" and index + 1 < len(sys.argv):
- key, separator, encoded = sys.argv[index + 1].partition("=")
- if separator and key == "model_catalog_json":
- catalog_override = Path(json.loads(encoded))
-
-turn_count = 0
-assert "goals" not in sys.argv, sys.argv
-for line in sys.stdin:
- message = json.loads(line)
- method = message.get("method")
- request_id = message.get("id")
- if method == "initialized":
- continue
- if method == "initialize":
- result = {"serverInfo": {"name": "fake-codex"}}
- elif method in {"thread/start", "thread/resume"}:
- params = message.get("params", {})
- if os.environ.get("LOOPX_FAKE_OTHER_THREAD_ERROR") == "1":
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32602, "message": "unrelated thread configuration error"},
- }), flush=True)
- continue
- if os.environ.get("LOOPX_FAKE_LEGACY_MODEL_CATALOG") == "1" and catalog_override is None:
- print(json.dumps({
- "id": request_id,
- "error": {
- "code": -32600,
- "message": "failed to parse model_catalog_json: missing field `base_instructions`",
- },
- }), flush=True)
- continue
- if catalog_override is not None:
- catalog = json.loads(catalog_override.read_text(encoding="utf-8"))
- if not catalog.get("models") or not all(model.get("base_instructions") for model in catalog["models"]):
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32600, "message": "compatibility catalog is incomplete"},
- }), flush=True)
- continue
- if params.get("sandbox") not in {"read-only", "workspace-write"} or params.get("approvalPolicy") != "never":
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32602, "message": "unsafe chat boundary"},
- }), flush=True)
- continue
- result = {"thread": {"id": "thread-loopx-chat"}}
- elif method in {"thread/goal/set", "thread/goal/get"}:
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32601, "message": "Goal mode must not be used for Chat"},
- }), flush=True)
- continue
- elif method == "turn/start":
- turn_count += 1
- params = message.get("params", {})
- prompt = params.get("input", [{}])[0].get("text", "")
- if (
- "" not in prompt
- or "protected_action" not in prompt
- or "user message" not in prompt
- or "loopx-chat-smoke: Keep the review loop bounded." not in prompt
- ):
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32602, "message": "missing review contract"},
- }), flush=True)
- continue
- if "execute confirmed task" in prompt and "execution agent for a confirmed LoopX Task" not in prompt:
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32602, "message": "missing execution contract"},
- }), flush=True)
- continue
- if "inspect attached image" in prompt:
- inputs = params.get("input", [])
- if len(inputs) != 2 or inputs[1] != {
- "type": "image",
- "url": "data:image/png;base64,aW1hZ2U=",
- "detail": "auto",
- }:
- print(json.dumps({
- "id": request_id,
- "error": {"code": -32602, "message": "missing image input"},
- }), flush=True)
- continue
- turn_id = f"turn-loopx-chat-{turn_count}"
- print(json.dumps({
- "method": "turn/started",
- "params": {
- "threadId": "thread-loopx-chat",
- "turn": {"id": turn_id, "status": "inProgress"},
- },
- }), flush=True)
- result = {"turn": {"id": turn_id, "status": "running"}}
- print(json.dumps({"id": request_id, "result": result}), flush=True)
- if "force idle timeout" in prompt:
- continue
- if "activity keeps alive" in prompt:
- for index in range(3):
- time.sleep(0.1)
- print(json.dumps({
- "method": "item/started",
- "params": {"threadId": "thread-loopx-chat", "turnId": turn_id, "item": {"id": f"work-{index}"}},
- }), flush=True)
- if "retryable error" in prompt:
- print(json.dumps({
- "method": "error",
- "params": {
- "threadId": "thread-loopx-chat",
- "turnId": turn_id,
- "willRetry": True,
- "error": {"message": "synthetic transient failure"},
- },
- }), flush=True)
- if "ends in terminal failure" in prompt:
- print(json.dumps({
- "method": "turn/completed",
- "params": {
- "threadId": "thread-loopx-chat",
- "turn": {"id": turn_id, "status": "failed"},
- },
- }), flush=True)
- continue
- visible_answer = "Reviewed " + params.get("cwd", "") + ".\n"
- protected_action = ({
- "operation": "merge",
- "target": "PR #123",
- "summary": "Prepare the protected merge preview.",
- } if "explicit protected action" in prompt else None)
- response = (
- visible_answer + ''
- + json.dumps({
- "schema_version": "loopx_chat_agent_response_v0",
- "message": visible_answer.strip(),
- "proposals": [{
- "kind": "todo",
- "text": "[P1] Add the selected review flow.",
- "priority": "P1",
- "rationale": "This is the smallest reviewable step.",
- }],
- "protected_action": protected_action,
- "gate": None,
- })
- + ' '
- )
- marker_split = response.index("") + 7
- for chunk in (response[:marker_split], response[marker_split:]):
- print(json.dumps({
- "method": "item/agentMessage/delta",
- "params": {
- "threadId": "thread-loopx-chat",
- "turnId": turn_id,
- "itemId": f"item-{turn_count}",
- "delta": chunk,
- },
- }), flush=True)
- print(json.dumps({
- "method": "turn/completed",
- "params": {
- "threadId": "thread-loopx-chat",
- "turn": {"id": turn_id, "status": "completed"},
- },
- }), flush=True)
- continue
- elif method == "turn/interrupt":
- result = {}
- else:
- result = {}
- print(json.dumps({"id": request_id, "result": result}), flush=True)
-'''
-
-
-def main() -> None:
- class EmptyThenMessageQueue:
- def __init__(self) -> None:
- self.empty_reads = 0
-
- def get(self, *, timeout: float) -> dict[str, object]:
- assert timeout > 0
- self.empty_reads += 1
- if self.empty_reads <= 1_200:
- raise queue.Empty
- return {"kind": "ready"}
-
- polling_session = object.__new__(CodexChatAgentSession)
- polling_session.messages = EmptyThenMessageQueue()
- assert polling_session._next_message(deadline=time.monotonic() + 5) == {"kind": "ready"}
-
- stream_filter = VisibleResponseStreamFilter()
- long_sentence_chunks = ["This is a deliberately long visible response segment " for _ in range(5)]
- early_visible = "".join(stream_filter.feed(chunk) for chunk in long_sentence_chunks)
- assert early_visible, "long prose must become visible before sentence punctuation"
- assert early_visible + stream_filter.finish() == "".join(long_sentence_chunks)
-
- chinese_filter = VisibleResponseStreamFilter()
- long_chinese = "持续输出让用户更早看到有效结果并及时调整方向" * 20
- chinese_early = "".join(
- chinese_filter.feed(long_chinese[index : index + 12])
- for index in range(0, len(long_chinese), 12)
- )
- assert chinese_early, "Chinese prose must stream without whitespace or sentence punctuation"
- assert chinese_early + chinese_filter.finish() == long_chinese
-
- english_filter = VisibleResponseStreamFilter()
- english_chunks = ["Version 1.2 is ready", ".", " See example.com for notes! Next,", " run the check? Done"]
- english_visible = [english_filter.feed(chunk) for chunk in english_chunks]
- assert english_visible[0] == "", "a decimal or version point must not end a sentence"
- assert english_visible[1] == "", "sentence punctuation waits for the following whitespace"
- assert english_visible[2] == "Version 1.2 is ready. See example.com for notes! ", english_visible
- assert english_visible[3] == "Next, run the check? ", english_visible
- assert "".join(english_visible) + english_filter.finish() == "".join(english_chunks)
-
- # An early sentence end must not hold back a long tail in the same chunk:
- # the tail still streams through the length fallback before the provider
- # sends anything else.
- tail_filter = VisibleResponseStreamFilter()
- tail_chunk = "Ready. " + "word " * 100
- tail_visible = tail_filter.feed(tail_chunk)
- assert tail_visible.startswith("Ready. word "), tail_visible[:40]
- assert len(tail_chunk) - len(tail_visible) < 160, len(tail_visible)
- assert tail_visible + tail_filter.finish() == tail_chunk
-
- protected_path = "/home/example/project"
- tail_path_filter = VisibleResponseStreamFilter(protected_paths=[protected_path])
- tail_path_text = "Ready. " + "word " * 40 + f"see {protected_path}/notes.txt " + "word " * 40
- tail_path_chunks = [tail_path_text, CHAT_REVIEW_OPEN_TAG + '{"hidden": true}']
- tail_path_early = tail_path_filter.feed(tail_path_chunks[0])
- assert len(tail_path_text) - len(tail_path_early) < 160, len(tail_path_early)
- tail_path_visible = tail_path_early + tail_path_filter.feed(tail_path_chunks[1]) + tail_path_filter.finish()
- assert protected_path not in tail_path_visible, tail_path_visible
- assert "hidden" not in tail_path_visible, tail_path_visible
- assert tail_path_visible == redact_local_paths(tail_path_text, protected_paths=[protected_path], project_relative=True), tail_path_visible
-
- english_path_filter = VisibleResponseStreamFilter(protected_paths=[protected_path])
- english_path_text = f"The report is in {protected_path}/notes.txt. Review it next. "
- english_path_visible = "".join(
- english_path_filter.feed(english_path_text[index : index + 7])
- for index in range(0, len(english_path_text), 7)
- ) + english_path_filter.finish()
- assert protected_path not in english_path_visible, english_path_visible
- # Splitting at sentences must not change what redaction produces.
- assert english_path_visible == redact_local_paths(english_path_text, protected_paths=[protected_path], project_relative=True), english_path_visible
-
- path_filter = VisibleResponseStreamFilter(protected_paths=[protected_path])
- path_text = ("前" * 150) + protected_path + "/secret.txt 后续内容"
- path_early = "".join(
- path_filter.feed(path_text[index : index + 12])
- for index in range(0, len(path_text), 12)
- )
- path_visible = path_early + path_filter.finish()
- assert path_early, "a protected path crossing the segment boundary must not stall the stream"
- assert protected_path not in path_visible, path_visible
- assert "./secret.txt" in path_visible, path_visible
-
- with tempfile.TemporaryDirectory(prefix="loopx-chat-agent-") as raw_tmp:
- root = Path(raw_tmp)
- fake_codex = root / "codex"
- fake_codex.write_text(FAKE_CODEX, encoding="utf-8")
- fake_codex.chmod(fake_codex.stat().st_mode | stat.S_IXUSR)
-
- session = CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=3.0,
- )
- try:
- observed = []
- result = session.send(
- "user message: suggest the next bounded step",
- on_event=lambda kind, payload: observed.append((kind, payload)),
- )
- image_result = session.send(
- "inspect attached image",
- attachments=[{"data_url": "data:image/png;base64,aW1hZ2U="}],
- )
- protected_result = session.send("explicit protected action")
- retry_events = []
- retry_result = session.send(
- "recover after retryable error",
- on_event=lambda kind, payload: retry_events.append((kind, payload)),
- )
- try:
- session.send("retryable error ends in terminal failure")
- except CodexChatAgentError as exc:
- assert str(exc) == "Codex app-server reported a terminal turn failure.", exc
- else:
- raise AssertionError("terminal failed status should fail the Chat turn")
- finally:
- session.close()
-
- assert result["message"] == "Reviewed [project].", result
- assert result["proposals"] == [
- {
- "kind": "todo",
- "text": "[P1] Add the selected review flow.",
- "priority": "P1",
- "rationale": "This is the smallest reviewable step.",
- }
- ], result
- assert result["gate"] is None, result
- assert result["protected_action"] is None, result
- assert protected_result["protected_action"] == {
- "operation": "merge",
- "target": "PR #123",
- "summary": "Prepare the protected merge preview.",
- }, protected_result
- assert image_result["message"] == "Reviewed [project].", image_result
- assert retry_result["message"] == "Reviewed [project].", retry_result
- assert any(
- kind == "agent.phase"
- and payload.get("method") == "error"
- and payload.get("label") == "Codex 正在重试"
- for kind, payload in retry_events
- ), retry_events
- assert not any(kind == "turn.failed" for kind, _ in retry_events), retry_events
- assert str(root) not in json.dumps(result), result
- visible = "".join(
- str(payload.get("text") or "")
- for kind, payload in observed
- if kind == "answer.delta"
- )
- assert visible.strip() == "Reviewed [project].", observed
- assert "" not in visible, visible
- assert not any(kind == "assistant.delta" for kind, _ in observed), observed
- delta_index = next(index for index, item in enumerate(observed) if item[0] == "answer.delta")
- completed_phase_index = next(
- index
- for index, item in enumerate(observed)
- if item[0] == "agent.phase" and item[1].get("method") == "turn/completed"
- )
- assert delta_index < completed_phase_index, observed
-
- resumed = CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- resume_thread_id="thread-loopx-chat",
- response_timeout_sec=3.0,
- )
- assert resumed.thread_id == "thread-loopx-chat"
- resumed.close()
-
- execution_session = CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- execution_mode=True,
- response_timeout_sec=3.0,
- )
- try:
- execution_result = execution_session.send("execute confirmed task")
- finally:
- execution_session.close()
- assert execution_result["message"] == "Reviewed [project].", execution_result
-
- with patch.dict(os.environ, {"LOOPX_FAKE_LEGACY_MODEL_CATALOG": "1"}):
- compatibility_session = CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=3.0,
- )
- try:
- compatibility_result = compatibility_session.send("user message after catalog repair")
- finally:
- compatibility_session.close()
- assert compatibility_session.model_catalog_compatibility_applied is True
- assert compatibility_result["message"] == "Reviewed [project].", compatibility_result
-
- debug_models_marker = root / "debug-models-invoked"
- with patch.dict(
- os.environ,
- {
- "LOOPX_FAKE_DEBUG_MODELS_MARKER": str(debug_models_marker),
- "LOOPX_FAKE_OTHER_THREAD_ERROR": "1",
- },
- ):
- try:
- CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=3.0,
- )
- except CodexChatAgentError as exc:
- assert "rejected thread/start" in str(exc), exc
- else:
- raise AssertionError("unrelated thread errors must fail without a catalog retry")
- assert not debug_models_marker.exists(), debug_models_marker
-
- with patch.dict(
- os.environ,
- {
- "LOOPX_FAKE_DEBUG_MODELS_FAIL": "1",
- "LOOPX_FAKE_LEGACY_MODEL_CATALOG": "1",
- },
- ):
- try:
- CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=3.0,
- )
- except CodexChatAgentError as exc:
- assert exc.gate["kind"] == "host_tool_gate", exc.gate
- assert "compatible model catalog" in exc.gate["summary"], exc.gate
- assert "legacy override" in exc.gate["next_action"], exc.gate
- else:
- raise AssertionError("catalog generation failures must surface a host-tool gate")
-
- active_session = CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=3.0,
- idle_timeout_sec=0.15,
- hard_timeout_sec=2.0,
- )
- try:
- active_result = active_session.send("activity keeps alive")
- finally:
- active_session.close()
- assert active_result["proposals"], active_result
-
- timeout_session = CodexChatAgentSession.start(
- codex_bin=str(fake_codex),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=3.0,
- idle_timeout_sec=0.2,
- hard_timeout_sec=2.0,
- )
- try:
- timeout_session.send("force idle timeout")
- except CodexChatAgentError as exc:
- assert exc.gate["kind"] == "host_tool_gate", exc.gate
- assert exc.error_code == "idle_timeout", exc.error_code
- assert "activity" in exc.gate["summary"], exc.gate
- else:
- raise AssertionError("Codex timeout must stop at a recoverable host-tool gate")
- finally:
- timeout_session.close()
-
- try:
- CodexChatAgentSession.start(
- codex_bin=str(root / "missing-codex"),
- work_dir=root,
- goal_id="loopx-chat-smoke",
- objective="Keep the review loop bounded.",
- response_timeout_sec=0.2,
- )
- except CodexChatAgentError as exc:
- assert exc.gate["kind"] == "host_tool_gate", exc.gate
- assert "Codex" in exc.gate["summary"], exc.gate
- else:
- raise AssertionError("missing Codex binary must stop at a host-tool gate")
-
- print("loopx-chat-agent-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/loopx-chat-contract-smoke.py b/examples/loopx-chat-contract-smoke.py
deleted file mode 100644
index bb97cc60f1..0000000000
--- a/examples/loopx-chat-contract-smoke.py
+++ /dev/null
@@ -1,317 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test LoopX Chat's review envelope and preview-locked Todo write."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.chat import ( # noqa: E402
- TodoReviewPreviewConflict,
- apply_todo_review_preview,
- build_todo_review_preview,
- parse_agent_response,
-)
-from loopx.control_plane.testing.canary_harness import import_fixture_authority # noqa: E402
-from loopx.control_plane.coordination.local_authority import read_canonical_todos_if_promoted # noqa: E402
-from loopx.control_plane.todos.provider_projection import project_current_canonical_todos # noqa: E402
-
-
-GOAL_ID = "loopx-chat-contract-smoke"
-TODO_TEXT = "[P0] Add a reviewable Goal Studio interaction."
-
-
-def write_fixture(root: Path, *, todo_anchor: bool = True) -> tuple[Path, Path, Path]:
- project = root / "project"
- runtime = root / "runtime"
- state_file = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md"
- state_file.parent.mkdir(parents=True)
- state_file.write_text(
- "---\n"
- "status: active\n"
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- "# Active Goal State\n\n"
- "## Objective\n\n"
- "Keep LoopX Chat reviewable.\n\n"
- "## Next Action\n\n"
- "- Review the next bounded proposal.\n" + ("\n## Agent Todo\n" if todo_anchor else ""),
- encoding="utf-8",
- )
- registry_path = project / ".loopx" / "registry.json"
- registry_path.parent.mkdir(parents=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": 1,
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "repo": str(project),
- "state_file": f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md",
- "domain": "product-engineering",
- "status": "active",
- "adapter": {
- "kind": "read_only_project_map_v0",
- "status": "connected-read-only",
- },
- }
- ],
- },
- ensure_ascii=False,
- indent=2,
- )
- + "\n",
- encoding="utf-8",
- )
- import_fixture_authority(registry_path, GOAL_ID)
- return registry_path, state_file, project
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-chat-contract-") as raw_tmp:
- root = Path(raw_tmp)
- registry_path, state_file, project = write_fixture(root)
-
- raw_response = (
- "draft text that must not become authority\n"
- ""
- + json.dumps(
- {
- "schema_version": "loopx_chat_agent_response_v0",
- "message": f"I inspected {project} and recommend one bounded step.",
- "proposals": [
- {
- "kind": "todo",
- "text": TODO_TEXT,
- "priority": "P0",
- "rationale": "It closes the first human review loop.",
- }
- ],
- "protected_action": {
- "operation": "merge",
- "target": "PR #123",
- "summary": "Prepare a protected merge preview.",
- },
- "gate": None,
- }
- )
- + " "
- )
- parsed = parse_agent_response(raw_response, protected_paths=[project, root])
- assert parsed["schema_version"] == "loopx_chat_agent_response_v0", parsed
- assert parsed["message"] == "I inspected [local-path] and recommend one bounded step.", parsed
- assert parsed["proposals"] == [
- {
- "kind": "todo",
- "text": TODO_TEXT,
- "priority": "P0",
- "rationale": "It closes the first human review loop.",
- }
- ], parsed
- assert parsed["protected_action"] == {
- "operation": "merge",
- "target": "PR #123",
- "summary": "Prepare a protected merge preview.",
- }, parsed
- assert parsed["gate"] is None, parsed
- assert str(project) not in json.dumps(parsed), parsed
-
- fallback = parse_agent_response(
- f"The host stopped at {root / 'private' / 'gate.json'}.",
- protected_paths=[project, root],
- )
- assert fallback["message"] == "The host stopped at [local-path].", fallback
- assert fallback["proposals"] == [], fallback
- assert fallback["protected_action"] is None, fallback
-
- unsupported_action = parse_agent_response(
- ""
- + json.dumps(
- {
- "message": "Unsupported action stays conversational.",
- "proposals": [],
- "protected_action": {
- "operation": "shell",
- "target": "rm -rf target",
- "summary": "Run a command.",
- },
- "gate": None,
- }
- )
- + " "
- )
- assert unsupported_action["protected_action"] is None, unsupported_action
-
- local_target = parse_agent_response(
- ""
- + json.dumps(
- {
- "message": "Local targets stay conversational.",
- "proposals": [],
- "protected_action": {
- "operation": "delete",
- "target": str(project / "private.txt"),
- "summary": "Delete one file.",
- },
- "gate": None,
- }
- )
- + " ",
- protected_paths=[project, root],
- )
- assert local_target["protected_action"] is None, local_target
-
- malformed = parse_agent_response(
- 'tool narration that must stay hidden\n{"message":"Clean answer.",} ',
- )
- assert malformed["message"] == "Clean answer.", malformed
- assert malformed["protected_action"] is None, malformed
- assert "tool narration" not in malformed["message"], malformed
-
- original = state_file.read_text(encoding="utf-8")
- authority_before = read_canonical_todos_if_promoted(runtime_root=root / "runtime", goal_id=GOAL_ID)
- preview = build_todo_review_preview(
- registry_path=registry_path,
- goal_id=GOAL_ID,
- text=TODO_TEXT,
- )
- assert preview["ok"] is True, preview
- assert preview["dry_run"] is True, preview
- assert preview["preview_id"], preview
- assert preview["todo"] == {
- "goal_id": GOAL_ID,
- "todo_id": preview["todo"]["todo_id"],
- "text": TODO_TEXT,
- "status": "open",
- "task_class": "advancement_task",
- "action_kind": "loopx_chat_proposal",
- }, preview
- assert state_file.read_text(encoding="utf-8") == original
- assert read_canonical_todos_if_promoted(runtime_root=root / "runtime", goal_id=GOAL_ID) == authority_before
- assert "state_file" not in json.dumps(preview), preview
- assert "project" not in json.dumps(preview), preview
-
- try:
- apply_todo_review_preview(
- registry_path=registry_path,
- goal_id=GOAL_ID,
- text=TODO_TEXT,
- preview_id="stale-preview",
- )
- except TodoReviewPreviewConflict as exc:
- assert "stale todo preview" in str(exc), exc
- no_write_receipt = exc.receipt
- assert no_write_receipt["schema_version"] == "loopx_chat_todo_no_write_receipt_v0", no_write_receipt
- assert no_write_receipt["status"] == "not_applied", no_write_receipt
- assert no_write_receipt["outcome"] == "preview_stale", no_write_receipt
- assert no_write_receipt["write_attempted"] is False, no_write_receipt
- assert no_write_receipt["goal_id"] == GOAL_ID, no_write_receipt
- assert no_write_receipt["receipt_id"], no_write_receipt
- assert str(project) not in json.dumps(no_write_receipt), no_write_receipt
- else:
- raise AssertionError("stale preview must be rejected")
- assert state_file.read_text(encoding="utf-8") == original
- assert read_canonical_todos_if_promoted(runtime_root=root / "runtime", goal_id=GOAL_ID) == authority_before
-
- applied = apply_todo_review_preview(
- registry_path=registry_path,
- goal_id=GOAL_ID,
- text=TODO_TEXT,
- preview_id=preview["preview_id"],
- )
- assert applied["ok"] is True, applied
- assert applied["applied"] is True, applied
- # Canonical creation allocates its id at commit; preview locks the
- # intent and provider revision, not a dry-run's provisional id.
- for field in ("goal_id", "text", "status", "task_class", "action_kind"):
- assert applied["todo"][field] == preview["todo"][field], applied
- committed = read_canonical_todos_if_promoted(runtime_root=root / "runtime", goal_id=GOAL_ID)
- assert committed["decision_read_from_provider"] is True and committed["legacy_fallback_used"] is False
- assert len(committed["todos"]) == 1, committed
- assert committed["todos"][0]["todo_id"] == applied["todo"]["todo_id"], committed
- assert committed["todos"][0]["text"] == TODO_TEXT, committed
- receipt = applied["receipt"]
- assert receipt["schema_version"] == "loopx_chat_todo_receipt_v0", receipt
- assert receipt["receipt_id"], receipt
- assert receipt["preview_id"] == preview["preview_id"], receipt
- assert receipt["goal_id"] == GOAL_ID, receipt
- assert receipt["todo_id"] == applied["todo"]["todo_id"], receipt
- assert receipt["status"] == "applied", receipt
- assert receipt["outcome"] == "todo_added", receipt
- assert receipt["already_exists"] is False, receipt
- assert receipt["preview_revision"], receipt
- assert str(project) not in json.dumps(receipt), receipt
- assert state_file.read_text(encoding="utf-8").count(TODO_TEXT) == 1
-
- # Display edits cannot replace the committed record or create a
- # duplicate. Restore the document before another explicit write.
- display = state_file.read_text(encoding="utf-8")
- state_file.write_text(display.replace(TODO_TEXT, "Spoofed display proposal"), encoding="utf-8")
- assert read_canonical_todos_if_promoted(runtime_root=root / "runtime", goal_id=GOAL_ID) == committed
-
- state_file.write_text(display, encoding="utf-8")
-
- retry_preview = build_todo_review_preview(
- registry_path=registry_path,
- goal_id=GOAL_ID,
- text=TODO_TEXT,
- )
- assert retry_preview["already_exists"] is True, retry_preview
- assert retry_preview["todo"]["todo_id"] == receipt["todo_id"], retry_preview
- retry_applied = apply_todo_review_preview(
- registry_path=registry_path,
- goal_id=GOAL_ID,
- text=TODO_TEXT,
- preview_id=retry_preview["preview_id"],
- )
- retry_receipt = retry_applied["receipt"]
- assert retry_receipt["outcome"] == "todo_already_exists", retry_receipt
- assert retry_receipt["already_exists"] is True, retry_receipt
- assert retry_receipt["todo_id"] == receipt["todo_id"], retry_receipt
- assert state_file.read_text(encoding="utf-8").count(TODO_TEXT) == 1
- assert read_canonical_todos_if_promoted(runtime_root=root / "runtime", goal_id=GOAL_ID) == committed
-
- # An anchorless historical document is retained as a separate display
- # recovery case. A successful canonical commit cannot repair its prose
- # implicitly or turn display failure into a second business write.
- recovery_root = root / "display-recovery"
- recovery_registry, recovery_state, _ = write_fixture(recovery_root, todo_anchor=False)
- original_narrative = recovery_state.read_text(encoding="utf-8")
- recovery_preview = build_todo_review_preview(registry_path=recovery_registry, goal_id=GOAL_ID, text=TODO_TEXT)
- recovery_applied = apply_todo_review_preview(registry_path=recovery_registry, goal_id=GOAL_ID,
- text=TODO_TEXT, preview_id=recovery_preview["preview_id"])
- assert recovery_applied["applied"] is True, recovery_applied
- assert recovery_state.read_text(encoding="utf-8") == original_narrative
- accepted = read_canonical_todos_if_promoted(runtime_root=recovery_root / "runtime", goal_id=GOAL_ID)
- assert len(accepted["todos"]) == 1, accepted
- try:
- project_current_canonical_todos(registry_path=recovery_registry,
- runtime_root=recovery_root / "runtime", goal_id=GOAL_ID)
- except ValueError as error:
- assert "no projection anchor" in str(error), error
- else:
- raise AssertionError("an anchorless document must refuse implicit projection")
- assert recovery_state.read_text(encoding="utf-8") == original_narrative
- recovery_state.write_text(original_narrative + "\n## Agent Todo\n", encoding="utf-8")
- delivered = project_current_canonical_todos(registry_path=recovery_registry,
- runtime_root=recovery_root / "runtime", goal_id=GOAL_ID,
- expected_provider_revision=accepted["provider_revision"])
- assert delivered["status"] == "delivered" and delivered["narrative_preserved"] is True, delivered
- assert recovery_state.read_text(encoding="utf-8").startswith(original_narrative)
- assert recovery_state.read_text(encoding="utf-8").count(TODO_TEXT) == 1
- assert read_canonical_todos_if_promoted(runtime_root=recovery_root / "runtime", goal_id=GOAL_ID) == accepted
-
- print("loopx-chat-contract-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/loopx-chat-endpoint-registry-smoke.py b/examples/loopx-chat-endpoint-registry-smoke.py
deleted file mode 100644
index 32606a34d2..0000000000
--- a/examples/loopx-chat-endpoint-registry-smoke.py
+++ /dev/null
@@ -1,74 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test owner-only Agent endpoint binding and public redaction."""
-
-from __future__ import annotations
-
-import json
-import os
-from pathlib import Path
-import stat
-import sys
-import tempfile
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.chat_endpoints import AgentEndpointRegistry # noqa: E402
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-chat-endpoints-") as raw_tmp:
- root = Path(raw_tmp)
- executable = root / "fake-acp"
- executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
- executable.chmod(executable.stat().st_mode | stat.S_IXUSR)
- local_root = root / "workspace"
- local_root.mkdir()
- registry = AgentEndpointRegistry(root / "chat")
- endpoint = registry.upsert(
- {
- "agent_id": "remote-reviewer",
- "display_name": "Remote Reviewer",
- "adapter_kind": "acp",
- "transport": "stdio",
- "location": "remote",
- "trust_scope": "read_only",
- "command": [str(executable), "--private-endpoint-reference"],
- "workspace_mapping": [
- {"local_root": str(local_root), "agent_root": "/srv/workspace"}
- ],
- }
- )
- public = endpoint.public_summary()
- assert public["available"] is True, public
- assert "command" not in public and "workspace_mapping" not in public, public
- assert "private-endpoint-reference" not in json.dumps(public), public
- assert endpoint.mapped_work_dir(local_root / "nested") == Path("/srv/workspace/nested")
- assert registry.get("remote-reviewer") == endpoint
- mode = stat.S_IMODE(registry.path.stat().st_mode)
- assert mode == 0o600, oct(mode)
- stored = registry.path.read_text(encoding="utf-8")
- assert "private-endpoint-reference" in stored
- assert registry.delete("remote-reviewer") is True
- assert registry.list() == []
- assert registry.delete("remote-reviewer") is False
- try:
- registry.upsert(
- {
- "agent_id": "codex",
- "display_name": "Override",
- "command": [str(executable)],
- }
- )
- except ValueError as exc:
- assert "reserved" in str(exc)
- else:
- raise AssertionError("built-in Agent id override was accepted")
- assert stat.S_IMODE(os.stat(registry.root).st_mode) == 0o700
-
- print("loopx-chat-endpoint-registry-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/loopx-chat-store-smoke.py b/examples/loopx-chat-store-smoke.py
deleted file mode 100644
index 735206c1ac..0000000000
--- a/examples/loopx-chat-store-smoke.py
+++ /dev/null
@@ -1,174 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test owner-local durable Chat session state."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-import sys
-import tempfile
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.chat_store import ChatSessionStore # noqa: E402
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-chat-store-") as raw_tmp:
- root = Path(raw_tmp)
- store = ChatSessionStore(root)
- session = store.create_session(
- goal_id="goal-one",
- agent_id="codex",
- adapter_kind="codex_app_server",
- upstream_thread_id="thread-private",
- upstream_mode="chat",
- )
- session_id = session["session_id"]
- public = store.public_session(session)
- assert public["resumable"] is True, public
- assert "upstream_thread_id" not in public, public
- assert "upstream_mode" not in public, public
- assert public["transcript_revision"] is None, public
- store.append_message(session_id, role="agent", text="First result", message_id="first-result")
- first_revision = store.public_session(session)["transcript_revision"]
- assert len(first_revision) == 64
- store.append_message(session_id, role="agent", text="Later result", message_id="later-result", origin="manager_followup")
- later = store.list_sessions(goal_id="goal-one", agent_id="codex")[0]
- assert later["updated_at"] == public["updated_at"], "Transcript writes must not invent execution activity"
- assert later["transcript_revision"] != first_revision, later
- assert store.session_snapshot(session_id)["session"]["transcript_revision"] == later["transcript_revision"]
- store.append_message(session_id, role="agent", text="Later result", message_id="later-result", origin="manager_followup")
- assert store.public_session(session)["transcript_revision"] == later["transcript_revision"], "Idempotent publication is quiet"
- assert session["upstream_mode"] == "chat", session
- assert store.latest_session(goal_id="goal-one", agent_id="codex") == session
- store.update_session(session_id, status="resume_failed", last_error_code="resume_failed")
- assert store.latest_session(goal_id="goal-one", agent_id="codex") is None
- assert store.public_session(store.load_session(session_id))["resumable"] is False
- failed_history = store.list_sessions(
- goal_id="goal-one",
- agent_id="codex",
- channel_id="goal.goal-one",
- )
- assert failed_history[0]["session_id"] == session_id, failed_history
- assert failed_history[0]["status"] == "resume_failed", failed_history
- store.update_session(session_id, status="ready", last_error_code=None)
-
- manager_session = store.create_session(
- goal_id="goal-one",
- agent_id="codex",
- adapter_kind="codex_app_server",
- upstream_thread_id="thread-manager-private",
- channel_id="manager",
- )
- assert store.latest_session(
- goal_id="goal-one",
- agent_id="codex",
- channel_id="manager",
- ) == manager_session
- assert store.latest_session(
- goal_id=None,
- agent_id="codex",
- channel_id="manager",
- ) == manager_session
- try:
- store.latest_session(goal_id=None, agent_id="codex")
- except ValueError as exc:
- assert "channel_id" in str(exc), exc
- else:
- raise AssertionError("goal-less latest session lookup accepted no channel")
- assert store.latest_session(
- goal_id="goal-one",
- agent_id="codex",
- channel_id="goal.goal-one",
- )["session_id"] == session_id
- assert store.list_sessions(
- goal_id=None,
- agent_id="codex",
- channel_id="manager",
- )[0]["session_id"] == manager_session["session_id"]
-
- turn, created = store.create_turn(
- session_id,
- client_turn_id="client-turn-one",
- message="visible user message",
- )
- assert created is True, turn
- duplicate, created = store.create_turn(
- session_id,
- client_turn_id="client-turn-one",
- message="visible user message",
- )
- assert created is False and duplicate["turn_id"] == turn["turn_id"], duplicate
- event = store.append_event(
- session_id,
- turn["turn_id"],
- kind="assistant.delta",
- payload={"text": "visible delta"},
- )
- assert event["event_id"] == "2", event
- assert [row["kind"] for row in store.events_after(session_id, turn["turn_id"], "1")] == [
- "assistant.delta"
- ]
-
- store.update_turn(
- session_id,
- turn["turn_id"],
- status="completed",
- response={"message": "visible final", "proposals": [], "gate": None},
- completed_at="2000-01-01T00:00:00Z",
- )
- store.append_message(
- session_id,
- role="agent",
- text="visible final",
- turn_id=turn["turn_id"],
- )
- store.update_session(session_id, status="ready", active_turn_id=None)
- snapshot = store.session_snapshot(session_id)
- assert [item["role"] for item in snapshot["messages"]] == ["agent", "agent", "user", "agent"], snapshot
- assert "thread-private" not in json.dumps(snapshot), snapshot
- store.append_message(
- manager_session["session_id"],
- role="user",
- text="visible manager message",
- )
- assert store.compact_completed_events(older_than_hours=24) == 1
-
- restarted_store = ChatSessionStore(root)
- restarted_manager = restarted_store.list_sessions(
- goal_id=None,
- agent_id="codex",
- channel_id="manager",
- )[0]
- restarted_snapshot = restarted_store.session_snapshot(restarted_manager["session_id"])
- assert [item["text"] for item in restarted_snapshot["messages"]] == [
- "visible manager message"
- ], restarted_snapshot
-
- session_path = root / "chat" / "sessions" / session_id / "session.json"
- legacy_session = json.loads(session_path.read_text(encoding="utf-8"))
- legacy_session.pop("channel_id", None)
- session_path.write_text(json.dumps(legacy_session) + "\n", encoding="utf-8")
- legacy_store = ChatSessionStore(root)
- legacy_history = legacy_store.list_sessions(
- goal_id="goal-one",
- agent_id="codex",
- channel_id="goal.goal-one",
- )
- assert legacy_history[0]["channel_id"] == "goal.goal-one", legacy_history
- assert not any(
- event["kind"] == "assistant.delta"
- for event in store.events_after(session_id, turn["turn_id"], None)
- )
-
- assert session_path.stat().st_mode & 0o777 == 0o600
- assert session_path.parent.stat().st_mode & 0o777 == 0o700
-
- print("loopx-chat-store-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/loopx-chat-stream-throughput-smoke.py b/examples/loopx-chat-stream-throughput-smoke.py
deleted file mode 100644
index b86d3fcd79..0000000000
--- a/examples/loopx-chat-stream-throughput-smoke.py
+++ /dev/null
@@ -1,134 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test bounded persistence overhead for a burst of Chat deltas."""
-
-from __future__ import annotations
-
-import os
-import sys
-import tempfile
-import time
-from pathlib import Path
-from typing import Any, Callable
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx import chat_store as chat_store_module # noqa: E402
-from loopx.chat_runtime import ChatRuntimeController # noqa: E402
-from loopx.chat_store import ChatSessionStore # noqa: E402
-
-
-class BurstAdapter:
- upstream_thread_id = "burst-thread"
-
- def capabilities(self) -> dict[str, Any]:
- return {"streaming": True, "resume": True, "interrupt": True}
-
- def start_turn(
- self,
- message: str,
- event_sink: Callable[[str, dict[str, Any]], None],
- ) -> dict[str, Any]:
- event_sink("turn.started", {"upstream_turn_id": "burst-turn"})
- for index in range(500):
- event_sink("answer.delta", {"text": f"chunk-{index} "})
- return {"message": "Burst complete.", "proposals": [], "gate": None}
-
- def interrupt_turn(self, turn_id: str | None = None) -> None:
- del turn_id
-
- def close_session(self) -> None:
- return None
-
- def healthcheck(self) -> bool:
- return True
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-chat-throughput-") as raw_tmp:
- root = Path(raw_tmp)
- store = ChatSessionStore(root / "runtime")
- session = store.create_session(
- goal_id="throughput-goal",
- agent_id="codex",
- adapter_kind="codex_app_server",
- upstream_thread_id="burst-thread",
- )
- session_id = str(session["session_id"])
- controller = ChatRuntimeController(store=store, codex_bin="codex")
- controller.adapters[session_id] = BurstAdapter()
-
- fsync_calls = 0
- original_fsync = os.fsync
-
- def counted_fsync(file_descriptor: int) -> None:
- nonlocal fsync_calls
- fsync_calls += 1
- original_fsync(file_descriptor)
-
- os.fsync = counted_fsync
- started = time.monotonic()
- try:
- turn, created = controller.submit_turn(
- session_id=session_id,
- client_turn_id="burst-client-turn",
- message="stream a burst",
- work_dir=root,
- objective="Measure streaming persistence.",
- )
- assert created is True
- completed = controller.wait_for_turn(
- session_id=session_id,
- turn_id=str(turn["turn_id"]),
- timeout_sec=10,
- )
- ready_deadline = time.monotonic() + 2
- while time.monotonic() < ready_deadline:
- if (store.load_session(session_id) or {}).get("status") == "ready":
- break
- time.sleep(0.01)
- assert (store.load_session(session_id) or {}).get("status") == "ready"
- finally:
- os.fsync = original_fsync
-
- elapsed = time.monotonic() - started
- assert completed["status"] == "completed", completed
- assert completed["delta_count"] == 500, completed
- assert fsync_calls < 100, f"delta persistence used {fsync_calls} fsync calls"
- # The fsync count above is the real budget: it proves no per-delta fsync
- # regardless of runner speed. The wall-clock bound is only a hang guard,
- # so it stays loose enough for a slow shared CI runner.
- assert elapsed < 5.0, f"delta persistence hung for {elapsed:.3f}s"
-
- replay_store = ChatSessionStore(root / "runtime")
- original_read_jsonl = chat_store_module._read_jsonl
- read_calls = 0
-
- def counted_read_jsonl(path: Path) -> list[dict[str, Any]]:
- nonlocal read_calls
- read_calls += 1
- return original_read_jsonl(path)
-
- chat_store_module._read_jsonl = counted_read_jsonl
- try:
- for _ in range(20):
- events = replay_store.events_after(session_id, str(turn["turn_id"]), "0")
- assert len(events) >= 502, len(events)
- finally:
- chat_store_module._read_jsonl = original_read_jsonl
- controller.close()
- assert read_calls <= 1, f"SSE replay reread the event log {read_calls} times"
- assert [int(event["sequence"]) for event in events] == list(range(1, len(events) + 1))
- assert [
- event["payload"]["text"]
- for event in events
- if event["kind"] == "answer.delta"
- ] == [f"chunk-{index} " for index in range(500)]
-
- print(f"loopx-chat-stream-throughput-smoke: {fsync_calls} fsync, {elapsed:.3f}s")
- print("loopx-chat-stream-throughput-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/loopx-project-skill-goal-text-precedence-smoke.py b/examples/loopx-project-skill-goal-text-precedence-smoke.py
deleted file mode 100644
index bad96a5aa3..0000000000
--- a/examples/loopx-project-skill-goal-text-precedence-smoke.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env python3
-"""Guard the loopx-project skill against downgrading goal text to bare /loopx."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-SKILL = ROOT / "skills" / "loopx-project" / "SKILL.md"
-
-
-def require(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def main() -> int:
- text = SKILL.read_text(encoding="utf-8")
- compact = " ".join(text.split())
- require("Recognized project-local goal-start command:" in text, "goal-start heading missing")
- require("- `/loopx `" in text, "goal-text command missing")
- require("- `/loopx`\n" not in text, "bare /loopx should not be listed as project-local fallback")
- require("Otherwise every non-whitespace character after `/loopx` is goal text." in compact, "goal text precedence missing")
- require("Never infer a product capability route" in text, "implicit capability route guard missing")
- require("Do not downgrade either form into a status or inspection turn." in compact, "downgrade guard missing")
- require("Bare `/loopx` is read/status-first" not in text, "bare /loopx status-first branch should not steer this skill")
- print("loopx-project-skill-goal-text-precedence-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/loopx-turn-codex-cli-quickstart-smoke.py b/examples/loopx-turn-codex-cli-quickstart-smoke.py
deleted file mode 100644
index 3a990623e7..0000000000
--- a/examples/loopx-turn-codex-cli-quickstart-smoke.py
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env python3
-"""Keep the LoopX Turn partner quickstart small and concept-frozen."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-QUICKSTART = REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "loopx-turn-codex-cli-quickstart.md"
-README = REPO_ROOT / "README.md"
-
-
-def main() -> int:
- text = QUICKSTART.read_text(encoding="utf-8")
- compact_text = " ".join(text.split())
- runtime_index = (
- REPO_ROOT / "docs" / "product" / "runtimes" / "codex-cli" / "README.md"
- ).read_text(
- encoding="utf-8"
- )
- readme = README.read_text(encoding="utf-8")
-
- assert len(text.splitlines()) <= 110, "quickstart must remain one page"
- for required in [
- "Agent CLI adapter",
- "Independent validator",
- "One Turn command",
- "loopx turn run-once",
- "--host codex-cli",
- "--validation-command-json",
- "status=committed",
- "result_kind=repair_required",
- "result_kind=replan_required",
- "result_kind=wait",
- "result_kind=user_action_required",
- "turn_key",
- "raw event stream",
- "they do not become new Turn states",
- "scenario owner",
- "loopx-turn-codex-cli-e2e-smoke.py",
- "codex_cli_model_requires_newer_codex",
- "--real-codex-cli",
- "--turn-count 3",
- "validation_status=passed",
- "session_resumed=true",
- "committed_turn_count=3",
- "three quota spends",
- ]:
- assert required in compact_text, required
-
- opening = "\n".join(text.splitlines()[:50])
- for internal_concept in [
- "TurnEnvelope",
- "scheduler hint",
- "journal",
- "resume eligibility",
- "benchmark bridge",
- ]:
- assert internal_concept not in opening, internal_concept
-
- link = "loopx-turn-codex-cli-quickstart.md"
- assert link in runtime_index, "runtime index link"
- assert "docs/product/runtimes/codex-cli/loopx-turn-codex-cli-quickstart.md" in readme
- assert "LoopX Turn for Codex CLI" in readme
-
- print("loopx-turn-codex-cli-quickstart-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/loopx-turn-dsh-real-e2e-smoke.py b/examples/loopx-turn-dsh-real-e2e-smoke.py
index 38552f77d4..196551816d 100755
--- a/examples/loopx-turn-dsh-real-e2e-smoke.py
+++ b/examples/loopx-turn-dsh-real-e2e-smoke.py
@@ -21,9 +21,11 @@
import sys
import tempfile
import threading
+from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
+from unittest.mock import patch
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT))
@@ -38,10 +40,31 @@
ADAPTER = REPO_ROOT / "scripts" / "dsh_turn_host_adapter.py"
+@contextlib.contextmanager
+def _isolated_machine_profile(root: Path, endpoint: str) -> Iterator[None]:
+ """Keep the real managed-host credential owner inside this local fixture."""
+ from loopx import paths
+ from loopx.control_plane.operator_provider import write_operator_provider
+
+ machine = root / "machine-owner"
+ with (
+ patch.object(paths, "DEFAULT_RUNTIME_ROOT", machine),
+ patch.object(paths, "LEGACY_RUNTIME_ROOT", root / "absent-legacy-machine"),
+ ):
+ write_operator_provider(
+ runtime_root=machine,
+ api_key="dsh-real-e2e-mock-key",
+ base_url=endpoint,
+ )
+ yield
+
+
def _write_fixture(root: Path) -> tuple[Path, Path, Path, Path]:
project = root / "project"
runtime = root / "runtime"
- workspace = root / "workspace"
+ # The native host and accountable writeback share the actual local Goal
+ # workspace; a separate sibling is not a producing-worktree receipt.
+ workspace = project
runtime.mkdir(parents=True)
workspace.mkdir(parents=True)
(workspace / "docs").mkdir()
@@ -113,6 +136,10 @@ def _write_fixture(root: Path) -> tuple[Path, Path, Path, Path]:
+ "\n",
encoding="utf-8",
)
+ from loopx.control_plane.testing.canary_harness import import_fixture_authority
+
+ for goal in json.loads(registry.read_text())["goals"]:
+ import_fixture_authority(registry, goal["id"], provider="sqlite")
return project, runtime, workspace, registry
@@ -276,6 +303,8 @@ def main() -> int:
{
"result_kind": "validated_progress",
"classification": "real_dsh_mock_llm",
+ "work_evidence": [f"artifact:{MARKER_NAME}"],
+ "validation_evidence": ["fixture:independent-marker-validator"],
"summary": "Real dsh runtime returned a typed result through the mock LLM.",
"recommended_action": "Review the real dsh e2e marker.",
"next_action": "Inspect the marker and replay idempotently.",
@@ -326,7 +355,10 @@ def log_message(self, _format: str, *args: object) -> None:
os.environ["DEEPSEEK_API_KEY"] = "dsh-real-e2e-mock-key"
for key in ("DSH_CWD", "DSH_HOME", "DSH_SESSION_ROOT"):
os.environ.pop(key, None)
- with tempfile.TemporaryDirectory(prefix="loopx-turn-dsh-real-e2e-") as directory:
+ with (
+ tempfile.TemporaryDirectory(prefix="loopx-turn-dsh-real-e2e-") as directory,
+ _isolated_machine_profile(Path(directory), base_url),
+ ):
root = Path(directory)
project, runtime, workspace, registry = _write_fixture(root)
session_root = root / "sessions"
@@ -344,7 +376,8 @@ def log_message(self, _format: str, *args: object) -> None:
host=args.host,
timeout_seconds=args.timeout_seconds,
)
- exit_code, payload = _run_cli([*base, "--execute"])
+ with contextlib.chdir(workspace):
+ exit_code, payload = _run_cli([*base, "--execute"])
marker_valid = (
marker_path.is_file()
@@ -357,9 +390,10 @@ def log_message(self, _format: str, *args: object) -> None:
replay_base = list(base)
idx = replay_base.index("--turn-instance-id")
del replay_base[idx : idx + 2]
- replay_exit_code, replay = _run_cli(
- [*replay_base, "--resume-turn-key", turn_key, "--execute"]
- )
+ with contextlib.chdir(workspace):
+ replay_exit_code, replay = _run_cli(
+ [*replay_base, "--resume-turn-key", turn_key, "--execute"]
+ )
summary = {
"schema_version": "loopx_turn_dsh_real_e2e_v1",
diff --git a/examples/maintenance-latest-run-routing-smoke.py b/examples/maintenance-latest-run-routing-smoke.py
deleted file mode 100644
index 0497fcdd3d..0000000000
--- a/examples/maintenance-latest-run-routing-smoke.py
+++ /dev/null
@@ -1,137 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test that maintenance runs do not mask actionable quota routing."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.quota import build_quota_should_run # noqa: E402
-from loopx.control_plane.work_items.autonomous_candidates import ( # noqa: E402
- autonomous_todo_candidates as build_autonomous_todo_candidates,
-)
-from loopx.control_plane.todos.contract import TODO_TASK_CLASS_ADVANCEMENT # noqa: E402
-from loopx.control_plane.todos.todo_summary import ( # noqa: E402
- normalize_todo_text,
- todo_item_is_actionable_open,
-)
-from loopx.status import ( # noqa: E402
- autonomous_backlog_candidates,
- goal_attention,
- open_todo_items,
-)
-
-
-GOAL_ID = "loopx-meta"
-READINESS_ACTION = (
- "Canary promotion-readiness smoke passed; promotion may proceed after "
- "doctor/status reports fresh evidence."
-)
-WORK_ACTION = "Continue the benchmark e2e-first evidence lane."
-AGENT_TODO = "[P1] Benchmark e2e-first evidence lane: run one bounded hard-case treatment."
-
-
-def main() -> int:
- goal = {
- "id": GOAL_ID,
- "status": "active",
- "registry_member": True,
- "adapter_status": "connected-read-only",
- "quota": {
- "compute": 1,
- "window_hours": 24,
- "slot_minutes": 1,
- "allowed_slots": 1440,
- "spent_slots": 0,
- "state": "eligible",
- "reason": "fixture eligible quota",
- },
- "latest_runs": [
- {
- "generated_at": "2026-06-10T09:00:00+00:00",
- "classification": "canary_promotion_readiness_smoke_group",
- "recommended_action": READINESS_ACTION,
- "json_exists": True,
- "markdown_exists": True,
- },
- {
- "generated_at": "2026-06-10T08:00:00+00:00",
- "classification": "state_refreshed",
- "recommended_action": WORK_ACTION,
- "json_exists": True,
- "markdown_exists": True,
- },
- ],
- }
- item = goal_attention(goal)
- assert item is not None, goal
- item["quota"] = goal["quota"]
- item["agent_todos"] = {
- "source_section": "Agent Todo",
- "total_count": 1,
- "open_count": 1,
- "done_count": 0,
- "items": [{"index": 1, "done": False, "text": AGENT_TODO}],
- }
- item["project_asset"]["agent_todos"] = item["agent_todos"]
- item["project_asset"]["quota"] = goal["quota"]
-
- backlog = autonomous_backlog_candidates([item])
- direct_backlog = build_autonomous_todo_candidates(
- [item],
- task_class=TODO_TASK_CLASS_ADVANCEMENT,
- open_todo_items=open_todo_items,
- todo_item_is_actionable_open=todo_item_is_actionable_open,
- normalize_todo_text=normalize_todo_text,
- )
- assert direct_backlog == backlog, (direct_backlog, backlog)
- status_payload = {
- "ok": True,
- "registry": "./fixtures/registry.json",
- "runtime_root": "./fixtures/runtime",
- "goal_count": 1,
- "run_count": 2,
- "attention_queue": {
- "items": [item],
- "autonomous_backlog_candidates": backlog,
- },
- "run_history": {"goals": [goal]},
- "promotion_readiness_summary": {
- "available": True,
- "source": "run_history",
- "goal_id": GOAL_ID,
- "generated_at": "2026-06-10T09:00:00+00:00",
- "classification": "canary_promotion_readiness_smoke_group",
- "freshness_status": "fresh",
- "requires_readiness_run": False,
- "freshness_window_hours": 24,
- "age_hours": 1.0,
- "sample_run_count": 1,
- "json_exists": True,
- "markdown_exists": True,
- },
- }
-
- decision = build_quota_should_run(status_payload, goal_id=GOAL_ID)
- assert decision["should_run"] is True, decision
- assert decision["state"] == "eligible", decision
- assert decision["status"] == "state_refreshed", decision
- assert decision["recommended_action"] == AGENT_TODO, decision
- primary_action = decision["interaction_contract"]["agent_channel"]["primary_action"]
- assert READINESS_ACTION not in primary_action, decision
- assert WORK_ACTION not in primary_action, decision
- assert primary_action == "[P1] Benchmark e2e-first evidence lane", decision
- assert "protocol_action_packet" not in decision, decision
- assert "promotion_readiness_warning" not in decision, decision
-
- print("maintenance-latest-run-routing-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/manager-answer-contract-smoke.py b/examples/manager-answer-contract-smoke.py
deleted file mode 100644
index 42fe4f35c8..0000000000
--- a/examples/manager-answer-contract-smoke.py
+++ /dev/null
@@ -1,111 +0,0 @@
-#!/usr/bin/env python3
-"""Guard adaptive steward answers and the installed instruction refresh."""
-
-from __future__ import annotations
-
-from collections import Counter
-from pathlib import Path
-import re
-import sys
-from tempfile import TemporaryDirectory
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.capabilities.manager_context.answer_contract import ( # noqa: E402
- MANAGER_ANSWER_CONTRACT_SCHEMA_VERSION,
- classify_manager_answer_shape,
- manager_answer_contract_instruction,
-)
-from loopx.chat_agent import _turn_prompt # noqa: E402
-from loopx.chat_manager import ( # noqa: E402
- MANAGED_SKILL_CURRENT_MARKER,
- MANAGED_SKILL_MARKER_V2,
- MANAGER_AGENT_OBJECTIVE,
- MANAGER_CONTEXT_VERSION,
- manager_answer_readback,
- manager_skill_text,
- manager_workspace,
-)
-
-
-def check(condition: bool, message: str) -> None:
- if not condition:
- raise AssertionError(message)
-
-
-def repeated_segments(text: str) -> list[str]:
- segments = [
- segment.strip() for segment in re.split(r"(?<=[.;])\s+", text) if segment.strip()
- ]
- counts = Counter(segments)
- return sorted(segment for segment, count in counts.items() if count > 1)
-
-
-def main() -> int:
- instruction = manager_answer_contract_instruction()
- skill = manager_skill_text()
- check("A simple question needs no report template." in instruction
- and "Preserve requested substantive detail" in instruction,
- "the shared instruction must distinguish short and substantive answers")
- check("depth proportionate to the work" in instruction
- and "do not replace a complete answer" in instruction,
- "the new instruction must not recreate the four-section obligation")
- check(instruction in MANAGER_AGENT_OBJECTIVE,
- "the steward objective must use the contract owner")
- check("concise Chinese" not in MANAGER_AGENT_OBJECTIVE,
- "the old brevity instruction must not suppress a substantive answer")
- check("A short factual question" in skill and "An investigation or decision" in skill,
- "the installed skill must carry the same adaptive policy")
- check(MANAGED_SKILL_CURRENT_MARKER in skill,
- "the installed skill must carry the current marker")
- check("safe Markdown text" in _turn_prompt("question")
- and "complete answer must stay in this conversation" in _turn_prompt("question"),
- "the shared Codex/DSH/direct-model Turn prompt must preserve a full Markdown answer")
- for surface, text in (("objective", MANAGER_AGENT_OBJECTIVE), ("skill", skill)):
- check(not repeated_segments(text), f"{surface} must not duplicate whole sentences")
-
- with TemporaryDirectory() as root:
- workspace = manager_workspace(Path(root))
- skill_path = workspace / ".agents/skills/loopx-manager/SKILL.md"
- check(skill_path.exists(), "the manager workspace must install its skill")
- skill_path.write_text(f"{MANAGED_SKILL_MARKER_V2}\n\n# stale manager skill\n", encoding="utf-8")
- manager_workspace(Path(root))
- check(skill_path.read_text(encoding="utf-8") == skill,
- "a workspace holding the previous managed skill must refresh")
- instructions = (workspace / "AGENTS.md").read_text(encoding="utf-8")
- check(instruction in instructions,
- "an installed manager workspace must carry the adaptive instruction")
- check(MANAGER_CONTEXT_VERSION >= 16,
- "the changed answer contract must invalidate existing manager context")
-
- short = "可以,见[来源](https://example.org/source)。"
- detailed = (
- "建议先验证方案 A,再决定是否采用。\n\n"
- "## 比较\n\n| 方案 | 证据 |\n|---|---|\n| A | 已验收 |\n"
- "\n- 当前证据:[记录](https://example.org/report)\n"
- "- 待确认:外部部署状态尚未读回。"
- )
- short_readback = manager_answer_readback({"message": short}, channel="manager")
- long_readback = manager_answer_readback({"message": detailed}, channel="manager")
- check(short_readback["message"] == short and short_readback["answer_shape"]["state"] == "present",
- "a direct answer must be retained and never called incomplete for lacking headings")
- check(long_readback["message"] == detailed
- and long_readback["answer_shape"]["schema_version"] == MANAGER_ANSWER_CONTRACT_SCHEMA_VERSION
- and long_readback["answer_shape"]["state"] == "present"
- and long_readback["answer_shape"]["character_count"] == len(detailed),
- "a multi-block Markdown answer must remain complete with format and length readback")
- check("required_order" not in classify_manager_answer_shape(detailed),
- "presentation readback must not call a missing ceremonial section a failure")
- check("answer_shape" not in manager_answer_readback({"message": detailed}, channel="manager.external.fixture"),
- "an external audience keeps its own transcript and is not measured by owner readback")
- check("answer_shape" not in manager_answer_readback({"message": ""}, channel="manager"),
- "an empty answer has no presentation readback")
-
- print("manager-answer-contract-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/meta-source-registry-self-repair-smoke.py b/examples/meta-source-registry-self-repair-smoke.py
deleted file mode 100644
index 588921ad62..0000000000
--- a/examples/meta-source-registry-self-repair-smoke.py
+++ /dev/null
@@ -1,196 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test meta source-registry shadow handling without leaking policy."""
-
-from __future__ import annotations
-
-import json
-import os
-import sys
-import tempfile
-import time
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.paths import global_registry_path # noqa: E402
-from loopx.quota import build_quota_should_run # noqa: E402
-from loopx.status import collect_status # noqa: E402
-
-
-META_GOAL_ID = "loopx-meta"
-OTHER_GOAL_ID = "ordinary-control"
-
-
-def write_state(project: Path, goal_id: str) -> str:
- state_file = f".codex/goals/{goal_id}/ACTIVE_GOAL_STATE.md"
- state_path = project / state_file
- state_path.parent.mkdir(parents=True, exist_ok=True)
- state_path.write_text(
- "---\n"
- "status: active\n"
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- f"# {goal_id}\n\n"
- "## Agent Todo\n\n"
- "- [ ] Repair or verify the source-registry control-plane projection.\n",
- encoding="utf-8",
- )
- return state_file
-
-
-def goal_entry(
- *,
- goal_id: str,
- project: Path,
- runtime: Path,
- source_registry: Path,
- synced_at: str,
- meta_policy: bool,
-) -> dict:
- goal = {
- "id": goal_id,
- "domain": "meta-source-registry-fixture",
- "status": "active",
- "repo": str(project),
- "state_file": write_state(project, goal_id),
- "adapter": {
- "kind": "harness_self_improvement" if meta_policy else "fixture_connected_readonly_v0",
- "status": "connected-read-only",
- },
- "source_registry": str(source_registry),
- "synced_at": synced_at,
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- },
- "authority_sources": [],
- }
- if meta_policy:
- goal["control_plane"] = {
- "self_repair": {
- "enabled": True,
- "allow_health_blocker_repair": True,
- "allow_waiting_projection_repair": True,
- }
- }
- return goal
-
-
-def write_global_registry(
- root: Path,
- *,
- finding_kind: str,
-) -> tuple[Path, Path, Path]:
- runtime = root / "runtime"
- meta_project = root / "meta-project"
- other_project = root / "ordinary-project"
- meta_project.mkdir()
- other_project.mkdir()
- missing_source = meta_project / ".loopx" / "registry.json"
- stale_source = meta_project / ".loopx" / "stale-registry.json"
- source_registry = missing_source
- synced_at = "2026-01-01T00:00:00+00:00"
- if finding_kind == "stale_source_registry":
- stale_source.parent.mkdir(parents=True, exist_ok=True)
- stale_source.write_text('{"schema_version": 1, "goals": []}\n', encoding="utf-8")
- now = time.time()
- os.utime(stale_source, (now, now))
- source_registry = stale_source
-
- global_registry = global_registry_path(runtime)
- global_registry.parent.mkdir(parents=True, exist_ok=True)
- payload = {
- "schema_version": 1,
- "updated_at": "2026-01-01T00:00:00+00:00",
- "common_runtime_root": str(runtime),
- "goals": [
- goal_entry(
- goal_id=META_GOAL_ID,
- project=meta_project,
- runtime=runtime,
- source_registry=source_registry,
- synced_at=synced_at,
- meta_policy=True,
- ),
- goal_entry(
- goal_id=OTHER_GOAL_ID,
- project=other_project,
- runtime=runtime,
- source_registry=other_project / ".loopx" / "registry.json",
- synced_at=synced_at,
- meta_policy=False,
- ),
- ],
- }
- global_registry.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- return global_registry, runtime, meta_project
-
-
-def queue_item(status_payload: dict, goal_id: str) -> dict:
- items = status_payload.get("attention_queue", {}).get("items") or []
- matches = [item for item in items if isinstance(item, dict) and item.get("goal_id") == goal_id]
- matches = [item for item in matches if item.get("project_asset")]
- assert len(matches) == 1, items
- return matches[0]
-
-
-def assert_meta_source_shadow(finding_kind: str) -> None:
- with tempfile.TemporaryDirectory(prefix="loopx-meta-source-shadow-") as tmp:
- root = Path(tmp)
- registry_path, runtime, project = write_global_registry(root, finding_kind=finding_kind)
- from loopx.control_plane.testing.canary_harness import import_fixture_authority
- # Author canonical fixture data via its owned project registry, then
- # retain the deliberately broken shared source declaration for diagnostics.
- fixture_registry = root / "fixture-source.json"
- source = json.loads(registry_path.read_text())
- source.pop("registry_role", None)
- for record in source["goals"]:
- record.pop("source_registry", None)
- fixture_registry.write_text(json.dumps(source), encoding="utf-8")
- for record in source["goals"]:
- import_fixture_authority(fixture_registry, record["id"], provider="sqlite")
- status_payload = collect_status(
- registry_path=registry_path,
- runtime_root_override=str(runtime),
- limit=5,
- )
- findings_text = json.dumps(status_payload["global_registry"], ensure_ascii=False)
- assert finding_kind in findings_text, status_payload["global_registry"]
-
- meta_item = queue_item(status_payload, META_GOAL_ID)
- assert meta_item["status"] == "connected_without_run", meta_item
- assert not any(
- item.get("goal_id") == META_GOAL_ID and item.get("status") == finding_kind
- for item in status_payload["attention_queue"]["items"]
- if isinstance(item, dict)
- ), status_payload["attention_queue"]["items"]
- shadows = meta_item["global_registry_shadow_findings"]
- assert shadows[0]["kind"] == finding_kind, shadows
- asset_shadow = meta_item["project_asset"]["global_registry_shadow_findings"]
- assert asset_shadow["open"] == 1, asset_shadow
- assert finding_kind in asset_shadow["kinds"], asset_shadow
-
- meta_decision = build_quota_should_run(status_payload, goal_id=META_GOAL_ID)
- assert meta_decision["should_run"] is True, meta_decision
- assert meta_decision["effective_action"] == "normal_run", meta_decision
- assert meta_decision["plan_summary"]["health_blockers"] == 0, meta_decision
- assert meta_decision["control_plane"]["self_repair"]["enabled"] is True, meta_decision
-
- other_decision = build_quota_should_run(status_payload, goal_id=OTHER_GOAL_ID)
- assert other_decision["should_run"] is True, other_decision
- assert "control_plane" not in other_decision, other_decision
- assert other_decision["self_repair_allowed"] is False, other_decision
-
-
-def main() -> int:
- assert_meta_source_shadow("source_registry_missing")
- assert_meta_source_shadow("stale_source_registry")
- print("meta-source-registry-self-repair-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/operator-provider-credential-smoke.py b/examples/operator-provider-credential-smoke.py
deleted file mode 100644
index f6ff9082df..0000000000
--- a/examples/operator-provider-credential-smoke.py
+++ /dev/null
@@ -1,247 +0,0 @@
-#!/usr/bin/env python3
-"""Prove the operator credential is configurable, redacted, and effective.
-
-The machine's operator model credential is what the steward channel and the
-managed host authenticate with. This smoke exercises the two shipped entry
-points that now write it -- the personal-workspace API and
-``loopx machine-config credential`` -- and then proves the value actually
-reaches the existing executor resolution, while no readback and no
-machine-configuration document ever carries the key.
-"""
-
-from __future__ import annotations
-
-import argparse
-import json
-import sys
-import tempfile
-from pathlib import Path
-from types import SimpleNamespace
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.capabilities.machine_configuration.builtins import ( # noqa: E402
- build_builtin_machine_configuration_registry,
-)
-from loopx.capabilities.machine_configuration.cli import ( # noqa: E402
- handle_machine_configuration_command,
-)
-from loopx.capabilities.machine_configuration.store import ( # noqa: E402
- machine_configuration_store_path,
- read_machine_configuration,
-)
-from loopx.chat_operator_provider_api import ( # noqa: E402
- CHAT_OPERATOR_PROVIDER_PATH,
- OperatorProviderRequestMixin,
-)
-from loopx.control_plane.operator_provider import ( # noqa: E402
- SOURCE_MACHINE_STORE,
- STATUS_ABSENT,
- STATUS_CONFIGURED,
- operator_provider_environ,
- operator_provider_store_path,
-)
-from loopx.control_plane.turn_driver.host_binding import ( # noqa: E402
- OPERATOR_CREDENTIAL_UNCONFIGURED,
- managed_executor_binding,
- selected_turn_host,
-)
-
-
-KEY = "sk-operator-provider-smoke-key"
-BASE_URL = "https://endpoint.smoke.invalid/v1"
-
-
-def fail(message: str) -> None:
- raise SystemExit(f"operator provider credential smoke failed: {message}")
-
-
-def _runtime_installed(*_args: object, **_kwargs: object) -> bool:
- """Report the optional managed runtime as installed.
-
- This smoke is about which credential authenticates the managed host, not
- about whether this host happens to have that runtime on disk, so it must not
- read the machine it runs on. The typed ``dsh_runtime_unavailable`` refusal is
- covered by ``examples/loopx-turn-managed-executor-binding-smoke.py`` and
- ``tests/test_turn_managed_executor_binding.py``.
- """
-
- return True
-
-
-class _Handler(OperatorProviderRequestMixin):
- """Drive the real request mixin without opening a socket."""
-
- def __init__(self, runtime_root: Path, body: dict[str, Any] | None = None) -> None:
- self.server = SimpleNamespace(runtime_root=runtime_root)
- self.body = body or {}
- self.responses: list[dict[str, Any]] = []
-
- def _read_json(self) -> dict[str, Any]:
- return self.body
-
- def _send_json(self, payload: dict[str, Any], *, status: int = 200) -> None:
- self.responses.append({"status_code": status, **payload})
-
- def _send_error(
- self, message: str, *, status: int, error_code: str, **_kwargs: Any
- ) -> None:
- self.responses.append(
- {
- "status_code": status,
- "error_code": error_code,
- "error": message,
- }
- )
-
-
-def _cli_args(**overrides: Any) -> argparse.Namespace:
- values: dict[str, Any] = {
- "command": "machine-config",
- "machine_config_command": "credential",
- "machine_credential_command": "status",
- "config_json": None,
- "clear_api_key": False,
- "clear_base_url": False,
- }
- values.update(overrides)
- return argparse.Namespace(**values)
-
-
-def _run_cli(
- runtime_root: Path, registry_path: Path, **overrides: Any
-) -> tuple[int, dict[str, Any]]:
- captured: list[dict[str, Any]] = []
- code = handle_machine_configuration_command(
- _cli_args(**overrides),
- runtime_root_arg=str(runtime_root),
- registry_path=registry_path,
- output_format=lambda _args: "json",
- print_payload=lambda payload, _fmt, _render: captured.append(dict(payload)),
- )
- if code is None:
- fail("machine-config credential did not take the credential path")
- return code, captured[-1]
-
-
-def main() -> None:
- with tempfile.TemporaryDirectory() as directory:
- root = Path(directory)
- runtime_root = root / "runtime"
- registry_path = root / ".loopx" / "registry.json"
- registry_path.parent.mkdir(parents=True, exist_ok=True)
- registry_path.write_text("{}", encoding="utf-8")
-
- # 1. An unconfigured machine refuses the managed host instead of
- # spending a Turn on an endpoint nothing can authenticate.
- handler = _Handler(runtime_root)
- handler._operator_provider_status()
- status = handler.responses[-1]
- if status["status_code"] != 200 or status["status"] != STATUS_ABSENT:
- fail(f"an unconfigured machine must report absent: {status}")
- if selected_turn_host(operator_provider_environ(runtime_root))[0] != "codex-cli":
- fail("an unconfigured machine must keep the individual default host")
-
- refused = managed_executor_binding(
- "dsh",
- environ=operator_provider_environ(runtime_root),
- module_probe=_runtime_installed,
- )
- if refused.get("unavailable_reason") != OPERATOR_CREDENTIAL_UNCONFIGURED:
- fail(f"the managed host must name the missing credential: {refused}")
-
- # 2. The browser writes the pair through the real request mixin.
- writer = _Handler(
- runtime_root, {"provider_key": KEY, "base_url": BASE_URL}
- )
- writer._operator_provider_update()
- written = writer.responses[-1]
- if written["status_code"] != 200 or written["status"] != STATUS_CONFIGURED:
- fail(f"the write path must report the stored credential: {written}")
- if written["provider_key"]["source"] != SOURCE_MACHINE_STORE:
- fail(f"the readback must name the machine store: {written}")
- if KEY in json.dumps(written):
- fail("the write readback must never echo the key")
- if written["base_url"]["value"] != BASE_URL:
- fail(f"the endpoint is not a secret and must read back: {written}")
-
- # 3. The credential resolves into the existing executor decision, which
- # is what makes the stored key effective rather than decorative.
- resolved = operator_provider_environ(runtime_root)
- if resolved.get("DEEPSEEK_API_KEY") != KEY:
- fail("the stored key did not resolve into the host environment")
- if selected_turn_host(resolved)[0] != "dsh":
- fail("a stored credential must select the managed default host")
- if operator_provider_store_path(runtime_root).stat().st_mode & 0o777 != 0o600:
- fail("the credential file must be readable only by its owner")
-
- # 4. The CLI is the second entry point, and it is read-only for the key.
- code, cli_status = _run_cli(
- runtime_root, registry_path, machine_credential_command="status"
- )
- if code != 0 or cli_status["status"] != STATUS_CONFIGURED:
- fail(f"`machine-config credential status` must read the store: {cli_status}")
- if KEY in json.dumps(cli_status):
- fail("the status readback must never echo the key")
-
- code, cli_written = _run_cli(
- runtime_root,
- registry_path,
- machine_credential_command="set",
- config_json=None,
- clear_base_url=True,
- )
- if code != 0 or cli_written["base_url"]["configured"] is not False:
- fail(f"clearing one field must keep the other: {cli_written}")
- if cli_written["provider_key"]["configured"] is not True:
- fail("clearing the endpoint must not clear the key")
-
- code, cli_cleared = _run_cli(
- runtime_root,
- registry_path,
- machine_credential_command="clear",
- )
- if code != 0 or cli_cleared["status"] != STATUS_ABSENT:
- fail(f"`credential clear` must remove the whole record: {cli_cleared}")
- if operator_provider_store_path(runtime_root).exists():
- fail("a cleared credential must not leave a readable file behind")
-
- # 5. Nothing that is projected, inspected, or backed up carries it.
- _Handler(
- runtime_root, {"provider_key": KEY, "base_url": BASE_URL}
- )._operator_provider_update()
- document = machine_configuration_store_path(runtime_root)
- if document.exists() and KEY in document.read_text(encoding="utf-8"):
- fail("the machine-configuration document must never carry the key")
- projected = read_machine_configuration(
- runtime_root,
- registry=build_builtin_machine_configuration_registry(),
- )
- if KEY in json.dumps(projected or {}):
- fail("the machine-configuration projection must never carry the key")
-
- print(
- json.dumps(
- {
- "ok": True,
- "schema_version": "operator_provider_credential_smoke_v0",
- "api_path": CHAT_OPERATOR_PROVIDER_PATH,
- "checks": [
- "unconfigured_machine_refuses_the_managed_host",
- "browser_write_reports_machine_store_without_echoing_the_key",
- "stored_credential_selects_and_authenticates_the_managed_host",
- "credential_file_is_owner_only",
- "cli_status_reads_and_cli_clear_removes",
- "machine_configuration_never_carries_the_key",
- ],
- },
- indent=2,
- )
- )
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/periodic-report-runtime-producer-smoke.py b/examples/periodic-report-runtime-producer-smoke.py
deleted file mode 100644
index 3fce2d43e6..0000000000
--- a/examples/periodic-report-runtime-producer-smoke.py
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/env python3
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.capabilities.periodic_report import build_periodic_report_run # noqa: E402
-from loopx.capabilities.periodic_report.runtime_producer import ( # noqa: E402
- build_periodic_report_runtime_trigger_decision,
-)
-from loopx.rollout_event_log import build_rollout_event # noqa: E402
-
-
-def main() -> None:
- events = [
- build_rollout_event(
- goal_id="sample-long-goal",
- event_kind="refresh_state",
- recorded_at="2026-08-22T09:00:00Z",
- status="appended",
- details={
- "stage_completion_schema": (
- "periodic_report_stage_completion_receipt_v0"
- ),
- "stage_identity": "stage-sample-closed-vision",
- "closed_vision_revision": "2026-08-22T08:59:00Z",
- "frontier_identity": "frontier-sample-successor",
- "stage_transition": "successor_frontier_settled",
- "stage_acceptance": "validated",
- "stage_outcome_checkpoint_satisfied": True,
- "stage_durable_writeback_required": True,
- },
- )
- ]
- decision = build_periodic_report_runtime_trigger_decision(
- {
- "schema_version": "periodic_report_runtime_trigger_request_v0",
- "evaluated_at": "2026-08-24T12:00:00Z",
- "goal_id": "sample-long-goal",
- "profile": {"profile_id": "weekly_progress", "profile_version": "v1"},
- "trigger_policy": {
- "enabled_kinds": ["bounded_segment_milestone"],
- "minimum_interval_seconds": 0,
- "aggregation": {
- "window_seconds": 604800,
- "todo_completed_threshold": 3,
- "promote_replan": False,
- "stage_completion_required": True,
- },
- },
- "segment": {
- "segment_ref": "week-2026-w34",
- "start_at": "2026-08-18T12:00:00Z",
- "end_at": "2026-08-24T12:00:00Z",
- "remaining_todo_count": 8,
- },
- },
- rollout_events=events,
- )
- run = build_periodic_report_run(
- {
- "schema_version": "periodic_report_run_request_v0",
- "generated_at": "2026-08-24T12:05:00Z",
- "period_window": {
- "start_at": "2026-08-18T12:00:00Z",
- "end_at": "2026-08-24T12:00:00Z",
- },
- "profile": {"profile_id": "weekly_progress", "profile_version": "v1"},
- "trigger_receipt": decision,
- "source_snapshots": [
- {
- "source_id": "project_progress",
- "source_kind": "validated_project_progress",
- "status": "complete",
- "observed_at": "2026-08-24T12:00:00Z",
- "snapshot_digest": "sha256:sample-progress",
- }
- ],
- "artifact_receipt": {
- "artifact_id": "weekly_progress",
- "renderer_id": "markdown_v0",
- "renderer_kind": "markdown",
- "status": "pending",
- },
- "sink_receipts": [
- {
- "sink_id": "archive",
- "sink_kind": "resource_store",
- "sink_role": "archive",
- "status": "pending",
- },
- {
- "sink_id": "delivery",
- "sink_kind": "message_channel",
- "sink_role": "delivery",
- "status": "pending",
- },
- ],
- }
- )
- assert decision["producer_receipt"]["status"] == "promoted"
- assert decision["producer_receipt"]["reason"] == (
- "authoritative_stage_completion_observed"
- )
- assert run["trigger_receipt"]["report_kind"] == "milestone_update"
- assert run["boundary"]["external_writes_performed"] is False
- print("periodic-report-runtime-producer-smoke: ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/personal-workspace-browser-smoke.mjs b/examples/personal-workspace-browser-smoke.mjs
index 3bbfe65498..f15b4b49a9 100644
--- a/examples/personal-workspace-browser-smoke.mjs
+++ b/examples/personal-workspace-browser-smoke.mjs
@@ -107,6 +107,7 @@ import { goalShowcaseScenario } from "./personal-workspace-browser/goal-showcase
import { stewardGroupTriggerScenario } from "./personal-workspace-browser/steward-group-trigger.mjs";
import { goalDraftScenario } from "./personal-workspace-browser/goal-draft.mjs";
+import { goalDraftLiveScenario } from "./personal-workspace-browser/goal-draft-live.mjs";
import { larkCliMissingScenario } from "./personal-workspace-browser/lark-cli-missing.mjs";
import { executionServiceOfflineScenario } from "./personal-workspace-browser/execution-service-offline.mjs";
@@ -164,6 +165,7 @@ scenarioCatalog.push(runtimeReadinessLiveScenario);
scenarioCatalog.push(attentionNotificationsScenario);
scenarioCatalog.push(attentionNotificationsLiveScenario);
scenarioCatalog.push(firstGoalHomeLiveScenario);
+scenarioCatalog.push(goalDraftLiveScenario);
scenarioCatalog.push(goalSuggestionsScenario);
scenarioCatalog.push(goalSuggestionsLiveScenario);
scenarioCatalog.push(managedAgentSessionsScenario);
diff --git a/examples/personal-workspace-browser/attached-host-follow-up.mjs b/examples/personal-workspace-browser/attached-host-follow-up.mjs
index 2f70547ce1..7b9dcdffc5 100644
--- a/examples/personal-workspace-browser/attached-host-follow-up.mjs
+++ b/examples/personal-workspace-browser/attached-host-follow-up.mjs
@@ -100,10 +100,10 @@ export const attachedHostFollowUpScenario = {
if (posts.length !== 1 || posts[0].sessionId !== sessionIdFor(attachedGoal.id) || posts[0].message !== followUp) {
throw new Error(`The attached_host follow-up did not reach its Session queue: ${JSON.stringify(posts)}`);
}
- const queuedFollowUp = page.locator(".personal-conversation-queue li").filter({ hasText: followUp });
+ const queuedFollowUp = page.locator(".personal-conversation-queue > ol > li").filter({ hasText: followUp });
await queuedFollowUp.waitFor({ timeout: 10_000 });
await queuedFollowUp.locator("summary").click();
- const expandedMessage = queuedFollowUp.locator(".personal-queue-message > p");
+ const expandedMessage = queuedFollowUp.locator(".personal-queue-message > .personal-md > p");
await expandedMessage.waitFor();
const assertExpandedBodyTypography = async (viewport) => {
const typography = await expandedMessage.evaluate(element => {
diff --git a/examples/personal-workspace-browser/codex-attached.mjs b/examples/personal-workspace-browser/codex-attached.mjs
index 0ee5e6d1f4..c164ac5477 100644
--- a/examples/personal-workspace-browser/codex-attached.mjs
+++ b/examples/personal-workspace-browser/codex-attached.mjs
@@ -371,7 +371,13 @@ async function runConversation(browser, uncertain) {
await panel.getByText('来源:cursor。此宿主的工作记录与回复尚未接入。',{exact:true}).waitFor();
assert.equal(await live.count(),0,'Changing the Agent removes the old live records');
assert.equal(await recordedModel.count(),0,'Changing the Agent removes the old model observation');
- await page.waitForFunction(async () => (await (await fetch('/fixture/following')).json()).events.at(-1) === false);
+ const readFollowEvents = async () => (await (await page.request.get(new URL('/fixture/following',url).href)).json()).events;
+ // Await the backend read itself: an async waitForFunction predicate is a
+ // truthy Promise, so it can finish before the old follower has stopped.
+ for (let attempt = 0; attempt < 100 && (await readFollowEvents()).at(-1) !== false; attempt++) {
+ await page.waitForTimeout(50);
+ }
+ assert.equal((await readFollowEvents()).at(-1),false,'Changing the Agent stops the old native follower before measuring the new one');
await panel.getByRole('combobox',{name:'查看 Agent'}).selectOption('worker');
await live.getByText('原宿主实时草稿,已持续更新。',{exact:true}).waitFor();
assert.equal(await live.locator('article').count(),2,'A new baseline does not duplicate old live rows');
@@ -383,11 +389,10 @@ async function runConversation(browser, uncertain) {
await page.request.post(new URL('/fixture/live-update',url).href);
await panel.getByText('正在回看历史 · 有新活动',{exact:true}).waitFor();
assert.equal(await live.getByText('原宿主实时草稿,已持续更新 2。',{exact:true}).count(),0,'History reading freezes the newer live draft');
- const followEvents = async () => (await (await page.request.get(new URL('/fixture/following',url).href)).json()).events.length;
- const followsBefore = await followEvents();
+ const followsBefore = (await readFollowEvents()).length;
await scrollHistory(page, panel, 1);
await live.getByText('原宿主实时草稿,已持续更新 2。',{exact:true}).waitFor({timeout: 3000});
- assert.equal(await followEvents(),followsBefore,'Returning to the tail publishes the buffer instead of waiting for a new subscription');
+ assert.equal((await readFollowEvents()).length,followsBefore,'Returning to the tail publishes the buffer instead of waiting for a new subscription');
assert.equal(await live.getByText('原宿主实时草稿,已持续更新。',{exact:true}).count(),0,'Returning to the tail replaces the stale draft');
assert.equal(await inputCount(),0,'Observation never submits native input');
await page.request.post(new URL('/fixture/live-finish',url).href);
diff --git a/examples/personal-workspace-browser/fixture.mjs b/examples/personal-workspace-browser/fixture.mjs
index 1b84b840e8..54fb211d85 100644
--- a/examples/personal-workspace-browser/fixture.mjs
+++ b/examples/personal-workspace-browser/fixture.mjs
@@ -2113,6 +2113,7 @@ export async function installApi(page, { fixturePort = port, goalSubagentConfigu
const storedProposal = actionProposals.get(apply[1]);
const proposal = {
schema_version: "loopx_chat_action_proposal_v1", proposal_id: apply[1], action_kind: actionKind,
+ idempotency_key: storedProposal?.idempotency_key,
summary: actionKind === "team.plan" && storedProposal ? storedProposal.summary : "已应用",
normalized_parameters: actionKind === "team.plan" && storedProposal
? storedProposal.normalized_parameters : preview?.normalized_parameters ?? storedProposal?.normalized_parameters ?? {},
diff --git a/examples/personal-workspace-browser/goal-draft-live.mjs b/examples/personal-workspace-browser/goal-draft-live.mjs
new file mode 100644
index 0000000000..c43d728d17
--- /dev/null
+++ b/examples/personal-workspace-browser/goal-draft-live.mjs
@@ -0,0 +1,118 @@
+import assert from "node:assert/strict";
+import {spawn} from "node:child_process";
+import {once} from "node:events";
+import {mkdtemp, readFile, stat} from "node:fs/promises";
+import {tmpdir} from "node:os";
+import {join, resolve} from "node:path";
+import {createInterface} from "node:readline";
+import {resolveTestPython} from "../../scripts/test-python.mjs";
+import {waitForHttp} from "../dashboard-browser-smoke-support.mjs";
+import {outputDir, repoRoot} from "./fixture.mjs";
+import {fetchWorkspaceBackend, openWorkspacePage} from "./scenario-context.mjs";
+
+// Conversation delivery is synthetic. Discovery, preview, apply and recovery
+// use the real Chat owner on disposable state. The stub Agent's failed first
+// Turn must never be presented as completed work.
+export const goalDraftLiveScenario = {
+ id: "goal-draft-live", requiresBackendReadback: true,
+ async run({browser, collectCoverage, url}) {
+ const coverageEntries = [];
+ for (const available of [true, false]) {
+ const root = await mkdtemp(join(tmpdir(), "loopx-goal-draft-live-"));
+ const child = spawn(resolveTestPython({repoRoot}), ["-u",
+ resolve(repoRoot, "examples/personal-workspace-browser/fresh-install-backend.py"),
+ root, ...(available ? [] : ["--no-agent"])], {cwd: repoRoot,
+ env: {...process.env, PYTHONPATH: repoRoot, LOOPX_USAGE_PING: "0"}, stdio: ["ignore", "pipe", "pipe"]});
+ const closed = once(child, "close"), lines = createInterface({input: child.stdout});
+ let session, diagnostics = "", loseApplyResponse = available;
+ const previews = [], applies = [];
+ child.stderr.on("data", chunk => {diagnostics = (diagnostics + chunk).slice(-4000);});
+ try {
+ const ready = await Promise.race([once(lines, "line").then(([line]) => JSON.parse(line)),
+ closed.then(() => {throw new Error(`fresh backend exited: ${diagnostics}`);})]);
+ const backend = `http://127.0.0.1:${ready.port}`;
+ await waitForHttp(`${backend}/status.json?view=workspace-directory`);
+ const registry = join(ready.project, ".loopx/registry.json");
+ const draft = {objective: "Prepare the release checklist", completion_criteria: "A checklist with validation steps",
+ execution_boundary: "Read project files only", question: "", options: []};
+ session = await openWorkspacePage(browser, url, {collectCoverage, beforeGoto: async (api, page) => {
+ api.answerForMessage = () => ({message: "The goal is ready to review.", goal_draft: draft});
+ // Keep the synthetic conversation runtime distinct from the real
+ // action executor catalog (which preview validates independently).
+ const paths = new Set(["/status.json", "/api/chat/projects"]);
+ await page.route(target => paths.has(target.pathname) || target.pathname.startsWith("/api/actions"), async route => {
+ const request = route.request(), pathname = new URL(request.url()).pathname;
+ if (pathname === "/api/actions/preview") previews.push(request.postDataJSON());
+ if (pathname.endsWith("/apply")) applies.push(pathname);
+ try {
+ const response = await fetchWorkspaceBackend(route, backend);
+ if (pathname.endsWith("/apply") && loseApplyResponse) {loseApplyResponse = false; await route.abort("failed");}
+ else await route.fulfill({response});
+ } catch {await route.abort().catch(() => {});}
+ });
+ }});
+ const {page} = session;
+ await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: "对话", exact: true}).click();
+ await page.locator(".personal-channel-composer textarea").fill(draft.objective);
+ await page.getByRole("button", {name: "发送", exact: true}).click();
+ const card = page.getByRole("region", {name: "目标草稿"}).last();
+ await card.waitFor();
+ if (!available) {
+ await card.getByRole("alert").filter({hasText: /Agent 当前不可用/}).waitFor();
+ await assert.rejects(stat(registry), {code: "ENOENT"});
+ assert.equal(applies.length, 0, "An unavailable Agent never receives apply");
+ await card.getByRole("button", {name: "查看并处理", exact: true}).click();
+ await page.locator(".personal-context-drawer").waitFor({state: "visible"});
+ await assert.rejects(stat(registry), {code: "ENOENT"});
+ } else {
+ const create = card.getByRole("button", {name: "创建并开始", exact: true});
+ await create.waitFor();
+ assert.equal(await page.locator('.personal-proposal-row[data-action-kind="goal.create"]').count(), 0);
+ await card.getByText(/^默认:project/).waitFor();
+ assert.ok(!(await card.innerText()).includes(root), "The resolved scope is public safe");
+ await assert.rejects(stat(registry), {code: "ENOENT"});
+ assert.equal(applies.length, 0, "Preparation never applies a Goal");
+ await page.screenshot({path: resolve(outputDir, "goal-draft-live-ready.png"), animations: "disabled"});
+ await page.setViewportSize({width: 390, height: 844});
+ await card.scrollIntoViewIfNeeded();
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
+ await page.screenshot({path: resolve(outputDir, "goal-draft-live-ready-narrow.png"), animations: "disabled"});
+ await create.evaluate(button => {button.click(); button.click();});
+ await card.getByRole("button", {name: "重试创建", exact: true}).waitFor({timeout: 60_000});
+ const first = JSON.parse(await readFile(registry, "utf8"));
+ assert.equal(first.goals.length, 1);
+ const proposalId = applies[0].split("/").at(-2);
+ const original = (await (await fetch(`${backend}/api/actions/${proposalId}`)).json()).proposal;
+ assert.equal(original.normalized_parameters.goal_id, first.goals[0].id);
+ assert.equal(original.normalized_parameters.heartbeat.enabled, false);
+ assert.equal(original.normalized_parameters.permission, "read_only");
+ assert.notEqual(original.status, "applied", "A failed first Turn is not completed creation");
+ assert.equal(await card.getByRole("button", {name: "已创建", exact: true}).count(), 0);
+ assert.equal(applies.length, 1, "Repeated clicks apply once even when the response is lost");
+ await page.reload({waitUntil: "networkidle"});
+ await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: "对话", exact: true}).click();
+ await card.getByRole("button", {name: "重试创建", exact: true}).click();
+ await card.getByRole("button", {name: "重试创建", exact: true}).waitFor({timeout: 60_000});
+ assert.deepEqual(applies, [applies[0], applies[0]], "Recovery retries the original operation");
+ assert.equal(previews.length, 1, "Reload reads the original preview");
+ assert.deepEqual(JSON.parse(await readFile(registry, "utf8")).goals.map(goal => goal.id), [first.goals[0].id]);
+ await page.screenshot({path: resolve(outputDir, "goal-draft-live-recovery.png"), animations: "disabled"});
+ }
+ coverageEntries.push(...await session.close());
+ } catch (error) {
+ await session?.page.screenshot({path: resolve(outputDir, "goal-draft-live-failed.png")}).catch(() => {});
+ const body = await session?.page.locator("body").innerText().catch(() => "");
+ await session?.close().catch(() => {});
+ throw new Error(`${error.message}; body=${body?.slice(-6000)}; backend=${diagnostics}`);
+ } finally {
+ lines.close();
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill("SIGTERM");
+ const kill = setTimeout(() => child.kill("SIGKILL"), 5000);
+ try {await closed;} finally {clearTimeout(kill);}
+ }
+ }
+ }
+ return {coverageEntries, backendReadbackVerified: true, note: "Synthetic conversation, real discovery/actions: prepare without Goal writes, one confirmation, lost-response readback, original retry and one registry Goal; unavailable Agent writes nothing; stub first-Turn failure stays explicit."};
+ },
+};
diff --git a/examples/personal-workspace-browser/goal-draft.mjs b/examples/personal-workspace-browser/goal-draft.mjs
index 69402a06d6..e775b92f33 100644
--- a/examples/personal-workspace-browser/goal-draft.mjs
+++ b/examples/personal-workspace-browser/goal-draft.mjs
@@ -28,14 +28,35 @@ export const goalDraftScenario = {
const requests = api.turnRequests.length;
await card.getByRole("button", {name: "资本支出变化", exact: true}).click();
assert.equal(await composer.inputValue(), "资本支出变化");
+ await composer.fill("保留现金流的判断。");
+ await card.getByRole("button", {name: "资本支出变化", exact: true}).click();
+ assert.equal(await composer.inputValue(), "保留现金流的判断。\n资本支出变化",
+ "An existing suggestion appends to the current draft");
assert.equal(api.turnRequests.length, requests, "Suggestion auto-sent a request");
assert.equal(api.actionPreviews.length, 0);
assert.equal(api.durableWriteCount, writes);
+ api.failNextActionPreview = true;
await send("重点比较资本支出,列出来源");
await card.getByText("重点比较资本支出,列出来源", {exact: true}).waitFor();
+ await card.scrollIntoViewIfNeeded();
+ await card.getByRole("alert").waitFor();
+ assert.equal(api.durableWriteCount, writes, "Preparing a complete draft cannot create a Goal");
+ await card.getByRole("button", {name: "重新准备", exact: true}).click();
+ await card.getByRole("button", {name: "创建并开始", exact: true}).waitFor();
+ await card.locator(".personal-goal-creation-execution").getByText("只读", {exact: true}).waitFor();
+ await card.locator(".personal-goal-creation-execution").getByText("无", {exact: true}).waitFor();
+ assert.equal(api.actionPreviews.at(-1).normalized_parameters.start_execution, true,
+ "A fresh Codex Create and start explicitly requests execution");
+ assert.equal(await page.locator('.personal-proposal-row[data-action-kind="goal.create"]').count(), 0,
+ "The visible draft owns one confirmation instead of a duplicate action card");
+ await card.getByText("codex", {exact: true}).waitFor();
+ const requestKey = api.actionPreviews.at(-1).idempotency_key;
+ const preparedCount = api.actionPreviews.length;
await page.reload({waitUntil: "networkidle"});
await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click();
await card.getByText("重点比较资本支出,列出来源", {exact: true}).waitFor();
+ await card.getByRole("button", {name: "创建并开始", exact: true}).waitFor();
+ assert.equal(api.actionPreviews.length, preparedCount, "Reload reads the existing operation");
await card.getByRole("button", {name: "修改", exact: true}).click();
const form = page.getByRole("dialog", {name: "创建新 Goal"});
assert.equal(await form.getByLabel("目标", {exact: true}).inputValue(), draft.objective);
@@ -58,13 +79,17 @@ export const goalDraftScenario = {
await objective.fill(`\u0085${draft.objective}\u001c`);
await boundary.fill(draft.execution_boundary);
await form.getByLabel("完成标准", {exact: true}).fill("资本支出对照表与原始来源");
+ await form.getByLabel("执行权限", {exact: true}).selectOption("workspace_write_on_confirmation");
await form.getByRole("button", {name: "检查配置"}).click();
await page.getByText("确认执行", {exact: true}).waitFor();
const preview = api.actionPreviews.at(-1);
assert.equal(preview.action_kind, "goal.create");
assert.equal(preview.normalized_parameters.title, draft.objective);
assert.equal(preview.normalized_parameters.workspace_ref, "current");
- assert.equal(preview.normalized_parameters.permission, "read_only");
+ assert.equal(preview.normalized_parameters.permission, "workspace_write_on_confirmation");
+ assert.equal(preview.normalized_parameters.start_execution, true);
+ await page.locator(".personal-context-drawer .personal-goal-creation-execution")
+ .getByText("所选工作区的所有文件", {exact: true}).waitFor();
assert.equal(preview.normalized_parameters.heartbeat.enabled, false);
assert.equal(api.durableWriteCount, writes);
await page.getByRole("button", {name: "关闭", exact: true}).click();
@@ -76,25 +101,32 @@ export const goalDraftScenario = {
assert.equal(api.durableWriteCount, writes, "Cancelling the reviewed draft mutated state");
await page.setViewportSize({width: 1512, height: 982});
const beforePreview = api.actionPreviews.length;
- await card.getByRole("button", {name: "预览创建", exact: true}).click();
- await page.getByText("确认执行", {exact: true}).waitFor();
assert.equal(await form.count(), 0, "Complete draft should skip the redundant form");
- assert.equal(api.actionPreviews.length, beforePreview + 1);
- assert.equal(api.actionPreviews.at(-1).normalized_parameters.workspace_ref, "current");
- assert.equal(api.actionPreviews.at(-1).normalized_parameters.completion_criteria, "重点比较资本支出,列出来源");
- assert.equal(api.actionPreviews.at(-1).normalized_parameters.permission, "read_only");
- assert.equal(api.actionPreviews.at(-1).normalized_parameters.heartbeat.enabled, false);
- const requestKey = api.actionPreviews.at(-1).idempotency_key;
- await page.getByRole("button", {name: "关闭", exact: true}).click();
+ const preparedPreview = api.actionPreviews.find(item => item.idempotency_key === requestKey);
+ assert.equal(preparedPreview.normalized_parameters.workspace_ref, "current");
+ assert.equal(preparedPreview.normalized_parameters.completion_criteria, "重点比较资本支出,列出来源");
+ assert.equal(preparedPreview.normalized_parameters.permission, "read_only");
+ assert.equal(preparedPreview.normalized_parameters.heartbeat.enabled, false);
await page.reload({waitUntil: "networkidle"});
await page.getByRole("navigation", {name: "管家视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click();
- await card.getByRole("button", {name: "预览创建", exact: true}).click();
- await page.getByText("确认执行", {exact: true}).waitFor();
- assert.equal(api.actionPreviews.at(-1).idempotency_key, requestKey, "Reopening must preserve operation identity");
- await page.getByRole("button", {name: "创建 Goal 并开始首轮", exact: true}).last().click();
- await page.getByText("已应用,LoopX 状态将刷新。", {exact: true}).first().waitFor();
+ const create = card.getByRole("button", {name: "创建并开始", exact: true});
+ await create.waitFor();
+ await card.scrollIntoViewIfNeeded();
+ await page.screenshot({path: resolve(outputDir, "goal-draft-ready.png"), animations: "disabled"});
+ await create.evaluate(button => { button.click(); button.click(); });
+ await card.getByRole("button", {name: "已创建", exact: true}).waitFor();
+ assert.equal(api.actionPreviews.length, beforePreview, "Confirmation uses the prepared operation");
+ assert.equal(await page.locator(".personal-context-drawer").count(), 0, "Ordinary creation needs one inline confirmation");
assert.equal(api.durableWriteCount, writes + 1);
assert.equal(api.actionApplies.length, 1);
+ await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "en"));
+ await page.reload({waitUntil: "networkidle"});
+ await page.getByRole("navigation", {name: "Manager view"}).getByRole("button", {name: "Chat", exact: true}).click();
+ await page.getByRole("region", {name: "Goal draft"}).last().getByRole("button", {name: "Created", exact: true}).waitFor();
+ assert.equal(api.actionPreviews.length, beforePreview, "Language changes do not create another operation");
+ assert.equal(api.actionApplies.length, 1);
+ await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "zh-CN"));
+ await page.reload({waitUntil: "networkidle"});
await page.keyboard.press("Escape");
await page.locator(".personal-goal-link").first().click();
await page.getByRole("navigation", {name: "Goal 视图"}).getByRole("button", {name: /^(Chat|对话)$/}).click();
@@ -108,8 +140,8 @@ export const goalDraftScenario = {
await englishCard.getByRole("button", {name: "Refine goal"}).waitFor();
await englishCard.scrollIntoViewIfNeeded();
await page.screenshot({path: resolve(outputDir, "goal-draft-english.png"), animations: "disabled"});
- assert.deepEqual(errors, []);
- return {coverageEntries: await close(), note: "Goal draft suggestions require explicit send; corrections and reload preserve draft; existing Goal preview retains read-only and disabled heartbeat defaults."};
+ assert.deepEqual(errors, ["Failed to load resource: the server responded with a status of 503 (Service Unavailable)"]);
+ return {coverageEntries: await close(), note: "Suggestions require explicit send; complete drafts prepare without writes and offer one confirmation; preparation failure is retryable; reload and locale preserve identity; repeated clicks apply once; Edit, narrow view and read-only/disabled heartbeat defaults remain."};
} catch(error) {
await page.screenshot({path: resolve(outputDir, "goal-draft-failed.png")});
const text = await page.locator("body").innerText();
diff --git a/examples/personal-workspace-browser/goal-workspace-backend.py b/examples/personal-workspace-browser/goal-workspace-backend.py
index 8b4ba4d2e6..7406701a69 100644
--- a/examples/personal-workspace-browser/goal-workspace-backend.py
+++ b/examples/personal-workspace-browser/goal-workspace-backend.py
@@ -30,7 +30,23 @@
registry.write_text(json.dumps(data), encoding="utf-8")
runtime = Path(data["common_runtime_root"])
store, sessions = ChatActionStore(runtime / "chat/actions"), ChatSessionStore(runtime)
-controller = fixture["FakeRuntimeController"](sessions)
+
+
+class WorkspaceRuntimeController(fixture["FakeRuntimeController"]):
+ def __init__(self, store: ChatSessionStore, registry_path: Path, runtime_root: Path) -> None:
+ super().__init__(store)
+ self.store = store
+ self.registry_path = registry_path
+ self.coordination_runtime_root = runtime_root
+
+ def resume_session_queue(self, *, session_id: str, work_dir: Path, objective: str) -> None:
+ # Observe the queue target at the synthetic dispatch boundary.
+ session = self.store.load_session(session_id)
+ assert session is not None
+ assert Path(session["managed_workspace_path"]) == Path(work_dir)
+
+
+controller = WorkspaceRuntimeController(sessions, registry, runtime)
# One Dashboard-configured workspace that no Goal uses yet.
configured = root / "docs-site"
configured.mkdir()
diff --git a/examples/personal-workspace-browser/goal-workspace-create.mjs b/examples/personal-workspace-browser/goal-workspace-create.mjs
index 0d4d3b9e4b..790f90923a 100644
--- a/examples/personal-workspace-browser/goal-workspace-create.mjs
+++ b/examples/personal-workspace-browser/goal-workspace-create.mjs
@@ -23,13 +23,16 @@ export const goalWorkspaceCreateScenario = {
const ready=await Promise.race([once(lines,'line').then(([line])=>JSON.parse(line)),closed.then(()=>{throw new Error(diagnostics);}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`Todo backend startup: ${diagnostics}`)),30000);})]);
clearTimeout(timer);
const backend=`http://127.0.0.1:${ready.port}`, requests=[];
- let refuseApply=true;
+ let refuseApply=true, applyAttempts=0;
const target=new URL(url);target.searchParams.set('goalId','progress-projection');target.searchParams.set('view','overview');
context=await openWorkspacePage(browser,target.toString(),{gotoWaitUntil:"domcontentloaded",beforeGoto:async(_api,page)=>{
for(const pattern of ['**/status.json*','**/api/actions{,/**,?*}','**/api/chat/todo/detail?*']) await page.route(pattern,async route=>{
const request=route.request(),path=new URL(request.url());
if(path.pathname==='/api/actions/preview')requests.push(request.postDataJSON());
- if(path.pathname.endsWith('/apply')&&refuseApply){await route.fulfill({status:503,json:{ok:false,error:'Synthetic temporary transport refusal'}});return;}
+ if(path.pathname.endsWith('/apply')){
+ applyAttempts++;
+ if(refuseApply){await route.fulfill({status:503,json:{ok:false,error:'Synthetic temporary transport refusal'}});return;}
+ }
const response=await fetchWorkspaceBackend(route,backend);await route.fulfill({response});
});
}});
@@ -51,18 +54,18 @@ export const goalWorkspaceCreateScenario = {
assert.equal(requests.length,1);assert.equal(requests[0].normalized_parameters.text,text);
assert.equal(requests[0].normalized_parameters.priority,undefined,'Ordinary creation leaves priority to the Todo owner');
await drawer.locator('.personal-primary-action').click();
- await drawer.getByText(/失败/).first().waitFor();
+ await page.getByRole('status').filter({hasText:'Synthetic temporary transport refusal'}).waitFor();
+ assert.equal(applyAttempts,1,'The first apply was attempted exactly once');
+ assert.equal(await now.locator('.goal-work-row').filter({hasText:text}).count(),0,'The refused apply did not create a task');
await page.locator('.personal-drawer-close').click();assert.equal(await task.inputValue(),rawText);
refuseApply=false;
await now.getByRole('button',{name:'检查任务',exact:true}).click();
- // The action owner may require regenerating the preview after failure.
- await drawer.locator('.personal-primary-action').click();
- await drawer.getByRole('button',{name:'确认并应用',exact:true}).waitFor();
await drawer.getByRole('button',{name:'确认并应用',exact:true}).click();
await now.locator('.goal-work-row').filter({hasText:text}).waitFor();
assert.equal(await task.inputValue(),'');
const {stdout}=await promisify(execFile)(python,['-c','from loopx.entrypoint import main; main()','--format','json','--registry',ready.registry,'todo','list','--goal-id','progress-projection','--role','agent'],{cwd:repoRoot,env:{...process.env,PYTHONPATH:repoRoot,LOOPX_USAGE_PING:'0'},timeout:30000});
const result=JSON.parse(stdout),created=result.todos.filter(todo=>todo.title===text);
+ assert.equal(applyAttempts,2,'Recovery attempted only one new apply');
assert.equal(created.length,1,'CLI must read exactly one created task');
assert.equal(created[0].priority,'P1','The real Todo owner defaults omitted creation priority');
await page.screenshot({path:resolve(outputDir,'goal-workspace-created.png'),animations:'disabled'});
diff --git a/examples/personal-workspace-browser/goal-workspace-m2.mjs b/examples/personal-workspace-browser/goal-workspace-m2.mjs
index ef5b6bc191..dc1ef830e9 100644
--- a/examples/personal-workspace-browser/goal-workspace-m2.mjs
+++ b/examples/personal-workspace-browser/goal-workspace-m2.mjs
@@ -286,6 +286,7 @@ async function runM2Pass({browser, collectCoverage, url}) {
const renderBudget = {coverageEnabled:collectCoverage,initialMs,expandMs,switchMs,switchSamplesMs,...lensBudget,
longTaskSupported,switchLongTasks,nodeCount:200};
console.log(JSON.stringify({m2RenderBudget:renderBudget}));
+ await verifyFocusAfterReprioritization(page, now, many[4]);
assert.equal(writes.length,0,`Rendering created effects: ${writes}`);
assert.equal(session.errors.length,0,session.errors.join('\n'));
if (!collectCoverage) assert.ok(lensBudget.withinBudget, `Loaded lens switches exceeded repeated 1s target or 2s ceiling: ${JSON.stringify({switchSamplesMs,...lensBudget})}`);
@@ -295,6 +296,40 @@ async function runM2Pass({browser, collectCoverage, url}) {
finally {await session.close();}
}
+async function verifyFocusAfterReprioritization(page, now, todo) {
+ const byOwner = now.getByRole("button", {name:"按负责人", exact:true});
+ await byOwner.click();
+ const owner = now.locator('.goal-owner-group[data-owner-id="worker-0"]');
+ const remaining = owner.locator(".goal-work-more");
+ await remaining.locator(":scope > summary").press("Enter");
+ assert.equal(await remaining.evaluate(node => node.open), false);
+
+ const row = `[data-todo-id="${todo.todo_id}"]`;
+ const leading = owner.locator(`:scope > ${row}`);
+ const moved = remaining.locator(`${row}[data-work-class="blocked"]`);
+ const refresh = page.getByRole("button", {name:"刷新状态", exact:true});
+ // Simulate a status refresh while the keyboard user remains on the page.
+ const refreshWithoutMovingFocus = () => refresh.evaluate(button => button.click());
+
+ await byOwner.focus();
+ todo.status = "blocked";
+ await refreshWithoutMovingFocus();
+ await moved.waitFor({state:"attached"});
+ assert.equal(await moved.isVisible(), false, "An unfocused task does not open its disclosure on refresh");
+ assert.equal(await byOwner.evaluate(node => document.activeElement === node), true, "Refresh leaves focus outside the task list alone");
+
+ todo.status = "open";
+ await refreshWithoutMovingFocus();
+ await leading.focus();
+ todo.status = "blocked";
+ await refreshWithoutMovingFocus();
+ await moved.waitFor({state:"attached"});
+ assert.equal(await moved.evaluate(node => document.activeElement === node), true, "The same task keeps keyboard focus after it moves");
+ await page.keyboard.press("Enter");
+ await page.waitForURL(value => value.searchParams.get("todo") === todo.todo_id);
+ await page.locator(".personal-context-drawer").waitFor();
+}
+
async function verifyRemoteSelection(browser, url) {
const snapshot = JSON.parse(await readFile(resolve(repoRoot,"examples/status.example.json"),"utf8"));
diff --git a/examples/personal-workspace-browser/goal-workspace-selection.mjs b/examples/personal-workspace-browser/goal-workspace-selection.mjs
index 5b9a03f2a1..bfca50ca3a 100644
--- a/examples/personal-workspace-browser/goal-workspace-selection.mjs
+++ b/examples/personal-workspace-browser/goal-workspace-selection.mjs
@@ -91,10 +91,18 @@ runpy.run_path(sys.argv[0], run_name="__main__")
assert.equal(await page.getByText(backend.second, {exact: false}).count(), 0);
assert.equal(JSON.parse(await readFile(backend.registry, "utf8")).goals.length, 2, "Preview created a Goal");
const confirm = page.getByRole("button", {name: /创建 Goal.*开始首轮/});
+ const confirmation = page.waitForResponse((response) =>
+ response.request().method() === "POST" && new URL(response.url()).pathname.endsWith("/apply"));
await confirm.click();
- await page.waitForFunction(() => document.body.innerText.includes("进入新 Goal"));
+ assert.ok((await confirmation).ok(), JSON.stringify(applied[0]));
assert.equal(applied.length, 1);
- assert.equal(applied[0].proposal.receipt.projection_verified, true);
+ const receipt = applied[0].proposal.receipt;
+ assert.equal(receipt.projection_verified, true);
+ assert.equal(receipt.original_task_request.todo_id, receipt.resource_ids.todo_ids[0]);
+ assert.equal(receipt.original_task_request.session_id, receipt.resource_ids.session_id);
+ assert.equal(receipt.original_task_request.permission, "read_only");
+ assert.deepEqual(receipt.original_task_request.write_scope, []);
+ await page.getByRole("button", {name: "进入新 Goal", exact: true}).waitFor();
const goalId = requests.at(-1).normalized_parameters.goal_id;
const registry = JSON.parse(await readFile(backend.registry, "utf8"));
const created = registry.goals.find(goal => goal.id === goalId);
diff --git a/examples/personal-workspace-browser/private-steward-scope.mjs b/examples/personal-workspace-browser/private-steward-scope.mjs
index fe5a85e44b..2a725c9d47 100644
--- a/examples/personal-workspace-browser/private-steward-scope.mjs
+++ b/examples/personal-workspace-browser/private-steward-scope.mjs
@@ -15,7 +15,7 @@ export const privateStewardScopeScenario = {
beforeGoto: async (_api, page) => {
await page.route("**/api/chat/projects", route => route.fulfill({json: projectsAvailable ? {ok: true,
projects: [{project_ref: row.project_ref, title: row.project_title, grant: "workspace_write"}]} : {ok: true}}));
- await page.route("**/api/chat/lark/private-conversations", async route => {
+ await page.route(url => url.pathname === "/api/chat/lark/private-conversations", async route => {
if (route.request().method() === "POST") {
const body = route.request().postDataJSON();
if (body.app_ref !== row.app_ref || body.project_ref !== row.project_ref
@@ -29,7 +29,19 @@ export const privateStewardScopeScenario = {
}
Object.assign(row, {goal_scope: "all_registered", goal_count: 150});
}
- await route.fulfill({json: {ok: true, revision: writes.length + 1, connections: hasConnection ? [row, ...extraRows] : []}});
+ const revision = writes.length + 1;
+ const connections = hasConnection ? [row, ...extraRows] : [];
+ const query = new URL(route.request().url()).searchParams;
+ if (query.get("view") === "diagnostics") {
+ if (query.get("revision") !== String(revision)) {
+ throw new Error("Diagnostics did not use the displayed authorization revision");
+ }
+ const diagnostics = connections.map(({binding_id, listener_status, pending_count, recovery_count, ingress, owner_attention}) =>
+ ({binding_id, listener_status, pending_count, recovery_count, ingress, owner_attention}));
+ await route.fulfill({json: {ok: true, revision, connections: diagnostics, stop_recoveries: []}});
+ return;
+ }
+ await route.fulfill({json: {ok: true, revision, connections}});
});
},
});
diff --git a/examples/personal-workspace-browser/research-history.md b/examples/personal-workspace-browser/research-history.md
index 4152f3172c..e4b032f086 100644
--- a/examples/personal-workspace-browser/research-history.md
+++ b/examples/personal-workspace-browser/research-history.md
@@ -408,7 +408,7 @@ receipt. Downloads do not launch research or change source state. While history
loading or no records match, downloading is unavailable; retry after a download
failure or refresh the history after a read failure.
-The synthetic packaged regression exercises native paged history, an old negative
+The synthetic browser regression exercises native paged history, an old negative
revision after 75 other findings, status filtering, full/filtered JSON and Markdown downloads,
original-version comparison (including unmeasured versus zero), partial/stale
coverage, interrupted reads/downloads and retry, Goal isolation and
@@ -418,8 +418,13 @@ desktop/narrow layouts without dispatching an Agent:
node --experimental-strip-types --test apps/presentation/dashboard/src/features/personal-workspace/research-record-search.test.mjs apps/presentation/dashboard/src/features/personal-workspace/research-record-versions.test.mjs
node --experimental-strip-types --test apps/presentation/dashboard/src/features/personal-workspace/research-record-export.test.mjs apps/presentation/dashboard/src/features/personal-workspace/research-record-report.test.mjs
LOOPX_PERSONAL_WORKSPACE_PACKAGED=1 LOOPX_PERSONAL_WORKSPACE_SCENARIO=research-record-search node examples/personal-workspace-browser-smoke.mjs
+LOOPX_DASHBOARD_COVERAGE=1 LOOPX_PERSONAL_WORKSPACE_SCENARIO=research-record-search node examples/personal-workspace-browser-smoke.mjs
```
+Both browser modes use the same disposable history owner and require readback
+with no source mutation. The coverage command uses Vite and must map executed
+code from the research-record browser module into the Dashboard source report.
+
From the worktree root:
```sh
diff --git a/examples/personal-workspace-browser/research-history.mjs b/examples/personal-workspace-browser/research-history.mjs
index 7923aa7192..5a1d21abf3 100644
--- a/examples/personal-workspace-browser/research-history.mjs
+++ b/examples/personal-workspace-browser/research-history.mjs
@@ -299,6 +299,9 @@ for question in range(4):
finding_id=f'decision-{question}-{record}', title=f'Comparison {question}, decision {record}',
summary=summary, status=['confirmed', 'refuted', 'tentative'][record % 3],
recorded_at=f'2025-12-31T0{record}:00:00Z' if question == 3 else f'2026-01-0{question + 1}T0{record}:00:00Z'))
+events.append(build_explore_finding_event(goal_id=goal, node_id='question-3',
+ finding_id='undated-decision', title='Undated decision', status='tentative', recorded_at='unknown',
+ summary='Input revision: synthetic-v1 Applicability: current Observation: Time unavailable. Interpretation: Outcome: wait'))
Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synthetic decision reading', 'events': events}, ensure_ascii=False))
`, fixture], {cwd: repoRoot});
let owner, page;
@@ -308,12 +311,14 @@ Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synth
await page.addInitScript(() => {if (!localStorage.getItem('loopx-pw-locale')) localStorage.setItem('loopx-pw-locale', 'zh-CN');});
await page.goto(`${owner.base}/chat/?goalId=${owner.goal_id}&view=research&statusUrl=%2Fstatus.json`, {waitUntil: 'domcontentloaded'});
const history = page.locator('.research-history');
- await history.getByRole('status').filter({hasText: '24 / 24'}).waitFor();
+ await history.getByRole('status').filter({hasText: '25 / 25'}).waitFor();
const readLatePhase = async (locale, size) => {
const late = history.getByRole('button', {name: locale === 'zh-CN' ? /^后段 ·/ : /^Late ·/});
await late.focus();
await late.press('Enter');
assert.equal(await late.getAttribute('aria-pressed'), 'true');
+ assert.equal(await history.locator('.research-decision-key .is-replan').evaluate(key => key.parentElement.textContent.trim()),
+ locale === 'zh-CN' ? '转向 19' : 'Replan 19', 'Selecting a period keeps the whole-history decision count');
await page.screenshot({path: resolve(outputDir, 'recorded-phase-' + size + '-' + locale + '.png'), animations: 'disabled'});
assert.equal(await history.locator('[data-research-nodes~="question-2"]:not(.is-dimmed)').count(), 1,
'A question with a late record stays highlighted at its earlier first record');
@@ -322,6 +327,22 @@ Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synth
assert.match(await late.getAttribute('aria-label'), locale === 'zh-CN' ? /2 个有记录的研究项/ : /2 research items with records/);
await late.press('Enter');
};
+ const key = history.locator('.research-decision-key');
+ assert.equal(await key.locator('span').count(), 3, 'Dated outcomes and unknown times are accounted for separately');
+ assert.equal(await key.locator('.is-no_change').evaluate(mark => mark.parentElement.textContent.trim()), '无变化 1');
+ assert.match(await key.innerText(), /时间未知 1/);
+ assert.equal(await key.locator('.is-wait').count(), 0, 'An undated decision is not placed on the elapsed axis');
+ const marks = await history.locator('.research-decision-ticks span').evaluateAll(elements => elements.map(element => {
+ const style = getComputedStyle(element);
+ return {type: element.className, fill: style.backgroundColor, rotate: style.rotate};
+ }));
+ assert.equal(marks.length, 20);
+ assert.equal(marks.filter(mark => mark.type === 'is-replan').length, 19);
+ const replan = marks.find(mark => mark.type === 'is-replan');
+ assert.notEqual(replan.fill, 'rgba(0, 0, 0, 0)', 'Recorded changes of direction must be visible on the plot');
+ assert.notEqual(replan.rotate, marks.find(mark => mark.type === 'is-no_change').rotate);
+ assert.equal(await key.locator('.is-replan').evaluate(mark => getComputedStyle(mark).backgroundColor), replan.fill,
+ 'The legend uses the same visible mark as the plot');
await readLatePhase('zh-CN', 'desktop');
const middle = history.getByRole('button', {name: /^中段 ·/});
await middle.press('Enter');
@@ -365,7 +386,7 @@ Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synth
for (const locale of ['zh-CN', 'en']) {
await page.evaluate(value => localStorage.setItem('loopx-pw-locale', value), locale);
await page.reload({waitUntil: 'domcontentloaded'});
- await history.getByRole('status').filter({hasText: '24 / 24'}).waitFor();
+ await history.getByRole('status').filter({hasText: '25 / 25'}).waitFor();
await readLatePhase(locale, 'phone');
const row = group.locator('[data-research-decision]').first();
assert.match(await row.innerText(), locale === 'zh-CN' ? /停止 2.*保留 3/s : /Stopped 2.*Retained 3/s);
@@ -398,7 +419,7 @@ Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synth
await oldest.click();
assert.equal(new URL(page.url()).searchParams.get('research_finding'), 'decision-2-0');
await page.reload({waitUntil: 'domcontentloaded'});
- await history.getByRole('status').filter({hasText: '24 / 24'}).waitFor();
+ await history.getByRole('status').filter({hasText: '25 / 25'}).waitFor();
await detail.waitFor();
assert.equal(new URL(page.url()).searchParams.get('research_finding'), 'decision-2-0', 'Reload keeps the exact historical finding');
await page.screenshot({path: resolve(outputDir, `decision-return-reader-${locale}.png`), animations: 'disabled'});
@@ -430,10 +451,10 @@ Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synth
await assertReturn(oldest);
await trail.getByRole('button', {name: locale === 'zh-CN' ? '显示更多问题 · 1' : 'Show more questions · 1', exact: true}).click();
const earlierQuestion = trail.locator('.research-trail-question').last();
- await earlierQuestion.getByRole('button', {name: locale === 'zh-CN' ? '显示更早记录 · 2' : 'Show earlier records · 2', exact: true}).click();
- const earlierDecision = earlierQuestion.locator('[data-research-decision]').last();
+ await earlierQuestion.getByRole('button', {name: locale === 'zh-CN' ? '显示更早记录 · 3' : 'Show earlier records · 3', exact: true}).click();
+ const earlierDecision = earlierQuestion.getByRole('button', {name: /Comparison 3, decision 0/});
await earlierDecision.click(); await page.reload({waitUntil: 'domcontentloaded'});
- await history.getByRole('status').filter({hasText: '24 / 24'}).waitFor();
+ await history.getByRole('status').filter({hasText: '25 / 25'}).waitFor();
await detail.waitFor();
assert.equal(new URL(page.url()).searchParams.get('research_finding'), 'decision-3-0');
await detail.press('Escape');
@@ -448,9 +469,9 @@ Path(sys.argv[1]).write_text(json.dumps({'goal_id': goal, 'display_name': 'Synth
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
}
await page.setViewportSize({width: 1280, height: 900});
- const desktopOrigin = trail.locator('.research-trail-question').last().locator('[data-research-decision]').last();
+ const desktopOrigin = trail.locator('.research-trail-question').last().getByRole('button', {name: /Comparison 3, decision 0/});
await desktopOrigin.click(); await page.reload({waitUntil: 'domcontentloaded'});
- await history.getByRole('status').filter({hasText: '24 / 24'}).waitFor();
+ await history.getByRole('status').filter({hasText: '25 / 25'}).waitFor();
const desktopReader = history.locator('.research-history-detail');
await desktopReader.waitFor();
assert.equal(new URL(page.url()).searchParams.get('research_finding'), 'decision-3-0');
diff --git a/examples/personal-workspace-browser/research-record-search.mjs b/examples/personal-workspace-browser/research-record-search.mjs
index dc3c221db7..252e4480e4 100644
--- a/examples/personal-workspace-browser/research-record-search.mjs
+++ b/examples/personal-workspace-browser/research-record-search.mjs
@@ -4,8 +4,9 @@ import {mkdtemp, readFile, rm} from "node:fs/promises";
import {tmpdir} from "node:os";
import {resolve} from "node:path";
import {resolveTestPython} from "../../scripts/test-python.mjs";
-import {outputDir, repoRoot} from "./fixture.mjs";
+import {outputDir, packaged, repoRoot} from "./fixture.mjs";
import {startHistoryOwner} from "./research-history.mjs";
+import {fetchWorkspaceBackend} from "./scenario-context.mjs";
async function readEmptyScope(page, results, message) {
const search = results.getByRole('searchbox');
@@ -25,7 +26,8 @@ async function readEmptyScope(page, results, message) {
export const researchRecordSearchScenario = {
id: "research-record-search",
- async run({browser, collectCoverage}) {
+ requiresBackendReadback: true,
+ async run({browser, collectCoverage, url}) {
const temporary = await mkdtemp(resolve(tmpdir(), "loopx-record-search-"));
let owner, page;
try {
@@ -67,8 +69,18 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
page = await browser.newPage({viewport: {width: 1440, height: 900}});
if (collectCoverage) await page.coverage.startJSCoverage({resetOnNavigation: false});
await page.addInitScript(() => {if (!localStorage.getItem("loopx-pw-locale")) localStorage.setItem("loopx-pw-locale", "en");});
- const url = `${owner.base}/chat/?goalId=synthetic-record-search&view=research&statusUrl=%2Fstatus.json`;
- await page.goto(url);
+ const entry = packaged ? new URL("/chat/", owner.base) : new URL(url);
+ entry.searchParams.set("goalId", "synthetic-record-search");
+ entry.searchParams.set("view", "research");
+ entry.searchParams.set("statusUrl", "/status.json");
+ if (!packaged) {
+ // Keep Vite modules and their source maps while using the same history owner.
+ await page.route(target => target.origin === entry.origin && (target.pathname === "/status.json"
+ || target.pathname.startsWith("/api/") || target.pathname.startsWith("/extension-")), async route => {
+ await route.fulfill({response: await fetchWorkspaceBackend(route, owner.base)});
+ });
+ }
+ await page.goto(entry.href);
const history = page.locator(".research-history");
await page.waitForFunction(() => document.querySelector('.research-history')?.getAttribute('aria-busy') === 'false');
await page.screenshot({path: resolve(outputDir, "research-record-first-1440.png"), animations: "disabled"});
@@ -263,7 +275,7 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
assert.equal(await results.locator("li").count(), 50, "A changed query resets display paging");
// Fresh interrupted load searches only the explicitly partial snapshot.
await page.route("**/api/chat/explore-results?*", route => new URL(route.request().url()).searchParams.has("cursor")
- ? route.fulfill({status: 503, json: {error: "Synthetic page interruption"}}) : route.continue());
+ ? route.fulfill({status: 503, json: {error: "Synthetic page interruption"}}) : route.fallback());
const periodBookmark = new URL(page.url());
periodBookmark.searchParams.set("research_goal", "synthetic-record-search");
periodBookmark.searchParams.set("research_phase", "2");
@@ -304,7 +316,9 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
const phases = history.locator(".research-phase");
assert.equal(await phases.count(), 3);
assert.equal(await phases.nth(2).getAttribute("aria-pressed"), "true", "Recovery applies the original period bookmark");
- await page.goto(url.replace("synthetic-record-search", "synthetic-other-research"));
+ const otherGoal = new URL(entry);
+ otherGoal.searchParams.set("goalId", "synthetic-other-research");
+ await page.goto(otherGoal.href);
const openOtherSearch = history.getByRole("button", {name: "Search research records", exact: true});
await openOtherSearch.evaluate(button => {
// Hold the frame from this one search activation until the reader moves focus.
@@ -354,13 +368,13 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
assert(other.records.every(record => record.goal_id === other.goal_id));
await search.fill("amber-v1");
await readEmptyScope(page, results, "No matching records. Try another term or clear the filters.");
- await page.goto(url);
+ await page.goto(entry.href);
await history.getByRole("button", {name: "Search research records", exact: true}).click();
await search.fill("amber-v1");
await results.getByRole("status", {name: /^1 matches in 79 loaded records/}).waitFor();
let firstRecord, pageMode = "replay";
await page.route("**/api/chat/explore-results?*", async route => {
- const response = await route.fetch();
+ const response = await fetchWorkspaceBackend(route, owner.base);
const historyPage = await response.json();
if (new URL(route.request().url()).searchParams.has("cursor")) {
if (pageMode === "short") historyPage.items.pop();
@@ -391,7 +405,7 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
let release, observed;
const hold = new Promise(resolve => {release = resolve;});
const seen = new Promise(resolve => {observed = resolve;});
- await page.route("**/api/chat/explore-results?*", async route => {observed(); await hold; await route.continue();});
+ await page.route("**/api/chat/explore-results?*", async route => {observed(); await hold; await route.fallback();});
await history.getByRole("button", {name: "Refresh history", exact: true}).click();
await seen;
await page.waitForFunction(() => [...document.querySelectorAll(".research-record-filters button")].some(button => button.textContent.includes("Download matches") && button.disabled));
@@ -400,8 +414,6 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
await page.waitForFunction(() => document.querySelector('.research-history')?.getAttribute('aria-busy') === 'false');
await page.unroute("**/api/chat/explore-results?*");
assert.equal(await downloadButton.isEnabled(), true);
- const readback = await (await page.request.get(`${owner.base}/fixture/readback`)).json();
- assert(readback.source_unchanged && readback.mutation_attempts === 0);
await page.evaluate(() => localStorage.setItem("loopx-pw-locale", "zh-CN"));
await page.reload();
await history.getByRole("button", {name: "搜索研究记录", exact: true}).click();
@@ -432,10 +444,24 @@ Path(sys.argv[2]).write_text(json.dumps({'goal_id':other,'display_name':'Other s
assert.match(reportText, /\*\*数值:\*\* 未知/);
assert.match(reportText, /\*\*数值:\*\* 0/);
assert.match(reportText, /质量下降 — original negative evidence/);
- return {coverageEntries: collectCoverage ? await page.coverage.stopJSCoverage() : [], note: "packaged evidence search/export through native paged history; full and filtered downloads, original revisions, coverage/staleness, original revision comparison, download/read recovery, Goal isolation and narrow viewport"};
+ const readback = await (await page.request.get(`${owner.base}/fixture/readback`)).json();
+ assert.ok(readback.ok && readback.history_reads >= 2, "Search uses the real paged history owner");
+ assert.ok(readback.source_unchanged && readback.mutation_attempts === 0, "Search leaves the source untouched");
+ const coverageEntries = collectCoverage ? await page.coverage.stopJSCoverage() : [];
+ if (collectCoverage) {
+ assert.ok(coverageEntries.some(entry => new URL(entry.url).pathname === "/src/features/personal-workspace/research-record-browser.tsx"
+ && entry.source && entry.functions.some(fn => fn.ranges.some(range => range.count > 0))),
+ "Research-record search must execute instrumented Dashboard source in the coverage lane");
+ }
+ return {coverageEntries, backendReadbackVerified: true, note: "evidence search/export through native paged history; full and filtered downloads, original revisions, coverage/staleness, original revision comparison, download/read recovery, Goal isolation and narrow viewport"};
} catch (error) {
if (page && !page.isClosed()) await page.screenshot({path: resolve(outputDir, "research-record-search-failed.png")});
throw error;
- } finally {await page?.close(); await owner?.close(); await rm(temporary, {recursive: true, force: true});}
+ } finally {
+ await page?.unrouteAll({behavior: "ignoreErrors"}).catch(() => {});
+ await page?.close();
+ await owner?.close();
+ await rm(temporary, {recursive: true, force: true});
+ }
},
};
diff --git a/examples/personal-workspace-browser/server-startup.test.mjs b/examples/personal-workspace-browser/server-startup.test.mjs
index d13ce4506e..25a6ce469c 100644
--- a/examples/personal-workspace-browser/server-startup.test.mjs
+++ b/examples/personal-workspace-browser/server-startup.test.mjs
@@ -1,24 +1,44 @@
import assert from "node:assert/strict";
+import {execFile} from "node:child_process";
import {createServer} from "node:http";
import {once} from "node:events";
+import {resolve} from "node:path";
+import {promisify} from "node:util";
-// A healthy foreign page must never certify the candidate bundle.
-const foreign = createServer((_request, response) => response.end("unrelated page"));
+// A healthy foreign page must never certify the candidate source or bundle.
+let foreignRequests = 0;
+const foreign = createServer((_request, response) => {
+ foreignRequests++;
+ response.end("unrelated page");
+});
foreign.listen(0, "127.0.0.1");
await once(foreign, "listening");
try {
+ const {port} = foreign.address();
process.env.LOOPX_PERSONAL_WORKSPACE_PACKAGED = "1";
- process.env.LOOPX_PERSONAL_WORKSPACE_PORT = String(foreign.address().port);
- const {startServer} = await import("./fixture.mjs");
+ process.env.LOOPX_PERSONAL_WORKSPACE_PORT = String(port);
+ const {repoRoot, startServer} = await import("./fixture.mjs");
+ const source = promisify(execFile)(process.execPath, [resolve(repoRoot, "examples/personal-workspace-browser-smoke.mjs")], {
+ cwd: repoRoot, timeout: 30_000,
+ env: {...process.env, LOOPX_PERSONAL_WORKSPACE_PACKAGED: "0", LOOPX_DASHBOARD_COVERAGE: "1",
+ LOOPX_PERSONAL_WORKSPACE_SCENARIO: "research-results"},
+ });
+ await assert.rejects(source, error => {
+ assert.equal(error.code, 1);
+ assert.match(error.stderr, /Dashboard Vite server exited/);
+ assert.match(error.stderr, new RegExp(`Port ${port} is already in use`));
+ return true;
+ });
await assert.rejects(startServer(), error => {
assert.match(error.message, /Packaged workspace server exited/);
const finalError = error.message.trimEnd().split("\n").at(-1);
assert.match(finalError, /^OSError: \[(?:Errno (?:48|98)|WinError 10048)\]/);
return true;
});
- assert.equal(await (await fetch(`http://127.0.0.1:${foreign.address().port}/chat/`)).text(), "unrelated page");
+ assert.equal(foreignRequests, 0, "Neither launcher probes the foreign listener for readiness");
+ assert.equal(await (await fetch(`http://127.0.0.1:${port}/chat/`)).text(), "unrelated page");
} finally {
foreign.closeAllConnections();
await new Promise((resolveClose, rejectClose) => foreign.close((error) => error ? rejectClose(error) : resolveClose()));
}
-console.log("Packaged workspace rejects occupied-port readiness without touching the other server");
+console.log("Dashboard source and packaged launchers reject an occupied port without touching the other server");
diff --git a/examples/personal-workspace-browser/typed-actions.mjs b/examples/personal-workspace-browser/typed-actions.mjs
index a4dc8fb3cf..fe06151219 100644
--- a/examples/personal-workspace-browser/typed-actions.mjs
+++ b/examples/personal-workspace-browser/typed-actions.mjs
@@ -325,13 +325,17 @@ export const typedActionsScenario = {
}
const writesBeforeSelection = api.durableWriteCount;
await drawer.getByRole("button", { name: /Workspace 1/ }).click();
- await page.getByRole("button", { name: "创建 Goal 并开始首轮", exact: true }).waitFor({ state: "visible" });
+ const create = drawer.getByRole("button", { name: "创建 Goal", exact: true });
+ await create.waitFor({ state: "visible" });
const regenerated = api.actionPreviews.at(-1);
if (regenerated?.normalized_parameters.workspace_ref !== "workspace-fixture") {
throw new Error(`Stored workspace selection did not regenerate the Goal preview: ${JSON.stringify(regenerated)}`);
}
+ if (regenerated.normalized_parameters.start_execution !== storedWorkspaceGate.normalized_parameters.start_execution) {
+ throw new Error("Workspace selection changed the saved execution intent");
+ }
if (api.durableWriteCount !== writesBeforeSelection) throw new Error("Selecting a workspace applied without confirmation");
- await page.getByRole("button", { name: "创建 Goal 并开始首轮", exact: true }).click();
+ await create.click();
await page.getByText("已应用,LoopX 状态将刷新。", { exact: true }).waitFor({ state: "visible" });
if (!api.actionApplies.includes(regenerated.proposalId)) throw new Error("Confirmation did not apply the regenerated preview");
if (api.durableWriteCount !== writesBeforeSelection + 1) throw new Error("Confirmation did not write exactly one Goal");
diff --git a/examples/pr-program-snapshot-walkthrough-smoke.py b/examples/pr-program-snapshot-walkthrough-smoke.py
deleted file mode 100644
index 69aad9f4ce..0000000000
--- a/examples/pr-program-snapshot-walkthrough-smoke.py
+++ /dev/null
@@ -1,127 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test public PR-program snapshot reconciliation."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-SCRIPT = REPO_ROOT / "skills" / "loopx-pr-program" / "scripts" / "diff_snapshot.py"
-FIXTURES = REPO_ROOT / "examples" / "fixtures"
-BASELINE = FIXTURES / "pr-program-snapshot-baseline.public.json"
-CURRENT = FIXTURES / "pr-program-snapshot-current.public.json"
-
-
-def load(path: Path) -> dict[str, Any]:
- return json.loads(path.read_text(encoding="utf-8"))
-
-
-def write(path: Path, payload: dict[str, Any]) -> None:
- path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
-
-
-def diff(previous: Path, current: Path) -> dict[str, Any]:
- result = subprocess.run(
- [sys.executable, str(SCRIPT), "--previous", str(previous), "--current", str(current)],
- cwd=REPO_ROOT,
- check=True,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- return json.loads(result.stdout)
-
-
-def assert_public_safe(payload: dict[str, Any]) -> None:
- text = json.dumps(payload, sort_keys=True)
- for forbidden in (
- "/Users/",
- "/private/",
- "Bearer ",
- "api_key",
- "review_body",
- "provider_payload",
- ):
- assert forbidden not in text, forbidden
-
-
-def main() -> int:
- baseline = load(BASELINE)
- current = load(CURRENT)
- assert baseline["program_id"] == current["program_id"]
- assert_public_safe(baseline)
- assert_public_safe(current)
-
- with tempfile.TemporaryDirectory() as temp_dir:
- root = Path(temp_dir)
- baseline_path = root / "baseline.json"
- current_path = root / "current.json"
- write(baseline_path, baseline)
- write(current_path, current)
-
- delta = diff(baseline_path, current_path)
- assert delta["program_id"] == "example-runtime-reliability", delta
- assert delta["baseline_advance_allowed"] is True, delta
- assert delta["scope_matches_previous"] is True, delta
- assert delta["changed"] == [
- {
- "ref": "example/runtime#42",
- "changed_fields": [
- "draft",
- "head_sha",
- "checks",
- "review",
- "work_item",
- ],
- "before": {
- "draft": True,
- "head_sha": "a" * 40,
- "checks": "pending",
- "review": "pending",
- "work_item": "action_required",
- },
- "after": {
- "draft": False,
- "head_sha": "b" * 40,
- "checks": "passed",
- "review": "approved",
- "work_item": "passed",
- },
- }
- ], delta
- assert_public_safe(delta)
-
- incomplete = json.loads(json.dumps(current))
- incomplete["result_completeness"]["complete"] = False
- incomplete["change_requests"][0]["checks"] = "unknown"
- incomplete["change_requests"][0]["review"] = "unknown"
- incomplete["change_requests"][0]["work_item"] = "unknown"
- incomplete_path = root / "incomplete.json"
- write(incomplete_path, incomplete)
- incomplete_delta = diff(baseline_path, incomplete_path)
- assert incomplete_delta["baseline_advance_allowed"] is False, incomplete_delta
- assert incomplete_delta["baseline_block_reason"] == "incomplete_result", incomplete_delta
- assert incomplete_delta["result_hash"] is None, incomplete_delta
-
- mismatched = json.loads(json.dumps(current))
- mismatched["result_completeness"]["scope"]["repositories"] = ["example/other"]
- mismatched_path = root / "scope-mismatch.json"
- write(mismatched_path, mismatched)
- mismatch_delta = diff(baseline_path, mismatched_path)
- assert mismatch_delta["baseline_advance_allowed"] is False, mismatch_delta
- assert mismatch_delta["baseline_block_reason"] == "scope_mismatch", mismatch_delta
- assert mismatch_delta["result_hash"] is None, mismatch_delta
-
- print("pr-program-snapshot-walkthrough-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/project/goal-vision-path-delta-smoke.py b/examples/project/goal-vision-path-delta-smoke.py
deleted file mode 100644
index 3243d8d1f7..0000000000
--- a/examples/project/goal-vision-path-delta-smoke.py
+++ /dev/null
@@ -1,123 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-check compact path deltas survive the goal-vision read path."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
-
-from loopx.control_plane.goals.goal_frontier import ( # noqa: E402
- latest_agent_vision_from_runs,
-)
-from loopx.control_plane.goals.goal_vision import ( # noqa: E402
- compact_goal_vision_packet,
- normalize_goal_vision_packet,
-)
-from loopx.control_plane.runtime.shared_runtime_refresh_projection import ( # noqa: E402
- build_shared_runtime_projection,
-)
-
-
-GOAL_ID = "fixture-goal"
-AGENT_ID = "fixture-agent"
-
-
-def packet() -> dict[str, object]:
- return {
- "agent_id": AGENT_ID,
- "state": "vision_drift_detected",
- "vision_patch": {
- "vision_summary": "Route one bounded successor from verified evidence.",
- "acceptance_summary": "The successor falsifies or confirms the new path.",
- "replan_trigger_summary": "The prior monitor-only path made no progress.",
- },
- "path_delta": {
- "outcome": "replan",
- "prior_assumption": "The monitor lane would produce acceptance evidence.",
- "observed_reality": "Two bounded polls produced no material transition.",
- "retained": ["Keep the verified monitor target."],
- "changed": ["Create one runnable advancement successor."],
- "stopped": ["Stop treating future polling as completion evidence."],
- "unresolved_questions": ["Can the successor falsify the new path?"],
- "reentry_condition": "Resume waiting after successor evidence lands.",
- "evidence_refs": ["evidence:monitor-poll-02", "todo:successor-01"],
- },
- }
-
-
-def main() -> int:
- normalized = normalize_goal_vision_packet(
- packet(), goal_id=GOAL_ID, agent_id=AGENT_ID
- )
- path_delta = normalized["path_delta"]
- assert path_delta["schema_version"] == "goal_path_delta_v0", path_delta
- assert path_delta["outcome"] == "replan", path_delta
- assert normalized["vision_budget"]["total_usage"] <= 1200, normalized
-
- compact = compact_goal_vision_packet(normalized)
- assert compact is not None, normalized
- assert compact["path_delta"] == path_delta, compact
-
- record = {
- "generated_at": "2026-07-20T00:00:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "autonomous_replan_recorded",
- "agent_id": AGENT_ID,
- "agent_vision": normalized,
- "state": {"sha256_16": "0123456789abcdef", "frontmatter": {}},
- }
- shared, _ = build_shared_runtime_projection(record=record)
- assert shared["agent_vision"]["path_delta"] == path_delta, shared
-
- latest = latest_agent_vision_from_runs(
- [shared], goal_id=GOAL_ID, agent_id=AGENT_ID
- )
- assert latest is not None, shared
- assert latest["path_delta"] == path_delta, latest
-
- invalid = packet()
- invalid["path_delta"] = {"outcome": "replan"}
- try:
- normalize_goal_vision_packet(invalid, goal_id=GOAL_ID, agent_id=AGENT_ID)
- except ValueError as exc:
- assert "requires prior_assumption and observed_reality" in str(exc), exc
- else:
- raise AssertionError("incomplete path delta should fail")
-
- missing_disposition = packet()
- missing_disposition["path_delta"] = {
- "outcome": "wait",
- "prior_assumption": "A dependency would become available.",
- "observed_reality": "The dependency remains unavailable.",
- }
- try:
- normalize_goal_vision_packet(
- missing_disposition, goal_id=GOAL_ID, agent_id=AGENT_ID
- )
- except ValueError as exc:
- assert "requires at least one retained, changed, or stopped item" in str(exc), exc
- else:
- raise AssertionError("path delta without a disposition should fail")
-
- over_item_limit = packet()
- over_item_limit["path_delta"]["retained"] = ["item"] * 4
- try:
- normalize_goal_vision_packet(
- over_item_limit, goal_id=GOAL_ID, agent_id=AGENT_ID
- )
- except ValueError as exc:
- assert "path_delta.retained has 4 items; limit is 3" in str(exc), exc
- else:
- raise AssertionError("over-item path delta should fail")
-
- print("goal-vision-path-delta-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/project/project-asset-next-eye-smoke.py b/examples/project/project-asset-next-eye-smoke.py
deleted file mode 100644
index d0e60c82f0..0000000000
--- a/examples/project/project-asset-next-eye-smoke.py
+++ /dev/null
@@ -1,283 +0,0 @@
-#!/usr/bin/env python3
-"""Guard the project-asset "next eye" operator contract.
-
-The first screen should let an operator decide where to look next without
-reading old threads: project identity, waiting owner/gate, next action, stop
-condition, todo ownership, quota, and latest validation must stay visible from
-the shared project_asset contract.
-"""
-
-from __future__ import annotations
-
-import copy
-from pathlib import Path
-import sys
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.status import ( # noqa: E402
- MONITOR_DISPLAY_STOP_CONDITION,
- MONITOR_SIGNAL_WAITING_ON,
- build_project_asset,
- build_long_task_cadence_hint,
- compact_execution_profile,
- compact_orchestration_policy,
- enrich_project_asset,
- project_asset_handoff_readiness,
- project_asset_quota_summary,
- project_asset_summary_is_public_safe,
- project_asset_todo_projection_gap,
- project_asset_todo_summary,
-)
-from loopx.control_plane.work_items import project_asset as project_asset_read_model # noqa: E402
-from loopx.control_plane.work_items.project_asset import ( # noqa: E402
- project_asset_quota_state,
- project_asset_user_todo_open_count,
-)
-
-
-USER_TODO = "Review the owner decision before approving delivery."
-AGENT_TODO = "Run the read-only map after the owner decision is recorded."
-NEXT_ACTION = "Use the current project asset to choose one bounded delivery step."
-STOP_CONDITION = "stop until the user or controller decision is recorded"
-VALIDATION_SUMMARY = "fixture validation passed; authority_sources 1"
-SAFE_AGENT_COMMAND = "loopx read-only-map --goal-id next-eye-fixture --dry-run"
-
-
-def _enrich_with_projection(
- item: dict,
- *,
- user_todos: dict | None,
- agent_todos: dict | None,
- quota: dict | None,
- latest_validation: dict | None,
- latest_runs: list[dict] | None,
- execution_profile: dict | None,
- orchestration: dict | None,
-) -> None:
- project_asset_read_model.enrich_project_asset(
- item,
- user_todos=user_todos,
- agent_todos=agent_todos,
- quota=quota,
- latest_validation=latest_validation,
- latest_runs=latest_runs,
- execution_profile=execution_profile,
- orchestration=orchestration,
- subagent_activity=None,
- interface_budget_cadence=None,
- project_asset_todo_summary=project_asset_todo_summary,
- project_asset_todo_projection_gap=project_asset_todo_projection_gap,
- project_asset_quota_summary=project_asset_quota_summary,
- compact_execution_profile=compact_execution_profile,
- compact_orchestration_policy=compact_orchestration_policy,
- project_asset_handoff_readiness=project_asset_handoff_readiness,
- project_asset_quota_state=project_asset_quota_state,
- project_asset_user_todo_open_count=project_asset_user_todo_open_count,
- build_long_task_cadence_hint=build_long_task_cadence_hint,
- )
-
-
-def assert_status_project_asset_next_eye() -> None:
- item = {
- "goal_id": "next-eye-fixture",
- "recommended_action": NEXT_ACTION,
- "project_asset": build_project_asset(
- status="operator_gate",
- waiting_on="user_or_controller",
- recommended_action=NEXT_ACTION,
- operator_question="Should this project proceed?",
- agent_command=None,
- missing_gates=None,
- next_handoff_condition=None,
- ),
- }
- user_todos = {
- "open_count": 1,
- "done_count": 0,
- "total_count": 1,
- "items": [{"index": 1, "done": False, "text": USER_TODO}],
- }
- agent_todos = {
- "open_count": 1,
- "done_count": 0,
- "total_count": 1,
- "items": [{"index": 1, "done": False, "text": AGENT_TODO}],
- }
- quota = {
- "compute": 0.5,
- "state": "operator_gate",
- "spent_slots": 2,
- "allowed_slots": 10,
- "reason": "waiting for owner decision",
- }
- latest_validation = {
- "generated_at": "2026-01-01T00:00:00+00:00",
- "classification": "next_eye_fixture",
- "summary": VALIDATION_SUMMARY,
- }
-
- projection_item = copy.deepcopy(item)
- enrich_project_asset(
- item,
- user_todos=user_todos,
- agent_todos=agent_todos,
- quota=quota,
- latest_validation=latest_validation,
- execution_profile={"minimum_scale": "implementation"},
- orchestration={"mode": "default", "allowed": False, "max_children": 3},
- )
- _enrich_with_projection(
- projection_item,
- user_todos=user_todos,
- agent_todos=agent_todos,
- quota=quota,
- latest_validation=latest_validation,
- latest_runs=None,
- execution_profile={"minimum_scale": "implementation"},
- orchestration={"mode": "default", "allowed": False, "max_children": 3},
- )
- assert item == projection_item, projection_item
-
- asset = item["project_asset"]
- for field in ("owner", "gate", "support_mode", "next_action", "stop_condition"):
- assert asset.get(field), asset
- assert asset["owner"] == "user_or_controller", asset
- assert asset["gate"] == "operator_question", asset
- assert asset["support_mode"] == "decision_support", asset
- assert asset["next_action"] == NEXT_ACTION, asset
- assert asset["stop_condition"] == STOP_CONDITION, asset
- assert "next_safe_command" not in asset, asset
- assert asset["user_todos"]["open"] == 1, asset
- assert asset["user_todos"]["next"] == USER_TODO, asset
- assert asset["agent_todos"]["open"] == 1, asset
- assert asset["agent_todos"]["next"] == AGENT_TODO, asset
- assert asset["quota"]["state"] == "operator_gate", asset
- assert asset["latest_validation"]["classification"] == "next_eye_fixture", asset
- assert asset["latest_validation"]["summary"] == VALIDATION_SUMMARY, asset
- assert project_asset_summary_is_public_safe(asset), asset
-
-
-def assert_project_asset_cadence_input_fallbacks() -> None:
- project_asset = {
- "quota": {"state": "eligible"},
- "user_todos": {"open_count": "2"},
- }
- assert project_asset_quota_state(quota=None, project_asset=project_asset) == "eligible"
- assert (
- project_asset_quota_state(
- quota={"state": "operator_gate"},
- project_asset=project_asset,
- )
- == "operator_gate"
- )
- assert (
- project_asset_user_todo_open_count(user_todos=None, project_asset=project_asset)
- == 2
- )
- assert (
- project_asset_user_todo_open_count(
- user_todos={"open_count": 0},
- project_asset=project_asset,
- )
- == 0
- )
- assert (
- project_asset_user_todo_open_count(
- user_todos={"open_count": "not-an-int"},
- project_asset=project_asset,
- )
- is None
- )
-
-
-def assert_status_project_asset_safe_command_contract() -> None:
- item = {
- "goal_id": "next-eye-command-fixture",
- "recommended_action": "Run the approved read-only map command.",
- "project_asset": build_project_asset(
- status="operator_gate_approved",
- waiting_on="codex",
- recommended_action="Run the approved read-only map command.",
- operator_question=None,
- agent_command=SAFE_AGENT_COMMAND,
- missing_gates=None,
- next_handoff_condition=None,
- ),
- "agent_command": SAFE_AGENT_COMMAND,
- }
- asset = item["project_asset"]
- assert asset["owner"] == "codex", asset
- assert asset["gate"] == "none", asset
- assert asset["support_mode"] == "selective_assist", asset
- assert asset["next_safe_command"] == SAFE_AGENT_COMMAND, asset
- assert asset["stop_condition"] == "stop if the command fails or needs write, production, or additional approval", asset
- assert project_asset_summary_is_public_safe(asset), asset
-
-
-def assert_status_project_asset_monitor_display_contract() -> None:
- asset = build_project_asset(
- status="monitor_quiet_skip",
- waiting_on=MONITOR_SIGNAL_WAITING_ON,
- recommended_action="No immediate agent work; keep monitoring quietly.",
- operator_question=None,
- agent_command=None,
- missing_gates=None,
- next_handoff_condition=None,
- )
- assert asset["owner"] == MONITOR_SIGNAL_WAITING_ON, asset
- assert asset["gate"] == "none", asset
- assert asset["support_mode"] == "read_only_observer", asset
- assert asset["stop_condition"] == MONITOR_DISPLAY_STOP_CONDITION, asset
- assert project_asset_summary_is_public_safe(asset), asset
-
-
-def assert_dashboard_first_screen_render_contract() -> None:
- dashboard = (REPO_ROOT / "apps/presentation/dashboard/src/views/dashboard-page.tsx").read_text(
- encoding="utf-8"
- )
- workspace = (
- REPO_ROOT
- / "apps/presentation/dashboard/src/features/personal-workspace/personal-workspace-page.tsx"
- ).read_text(encoding="utf-8")
- tasks = (
- REPO_ROOT
- / "apps/presentation/dashboard/src/features/personal-workspace/goal-tasks-view.tsx"
- ).read_text(encoding="utf-8")
- for marker in (
- "todosFromProjectAssetSummary(projectAsset?.user_todos",
- "todosFromProjectAssetSummary(projectAsset?.agent_todos",
- "row.queueItem?.project_asset?.latest_validation",
- "row.queueItem?.recommended_action",
- "hasRunObservation: Boolean(row.queueItem?.project_asset?.latest_validation",
- ):
- assert marker in dashboard, marker
- for marker in (
- "goal.needsYou ?? goal.nextSentence",
- "goal.agentTodos",
- "goal.latestActivity",
- ):
- assert marker in workspace, marker
- for marker in (
- "attentionItems",
- "openAgentTodos",
- "scheduleItems",
- "doneAgentTodos",
- ):
- assert marker in tasks, marker
-
-
-def main() -> int:
- assert_status_project_asset_next_eye()
- assert_project_asset_cadence_input_fallbacks()
- assert_status_project_asset_safe_command_contract()
- assert_status_project_asset_monitor_display_contract()
- assert_dashboard_first_screen_render_contract()
- print("project-asset-next-eye-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/project/subagent-status-projection-smoke.py b/examples/project/subagent-status-projection-smoke.py
deleted file mode 100644
index 0a34a87b0a..0000000000
--- a/examples/project/subagent-status-projection-smoke.py
+++ /dev/null
@@ -1,187 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-test compact sub-agent run-history/status projection."""
-
-from __future__ import annotations
-
-import json
-import sys
-import tempfile
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.presentation.renderers.status_markdown import render_status_markdown # noqa: E402
-from loopx.status import ( # noqa: E402
- collect_status,
- project_asset_summary_is_public_safe,
-)
-
-
-GOAL_ID = "multi-subagent-controller"
-PRIVATE_LOCAL_PATH = "/" + "Users/example/private.txt"
-
-
-def write_fixture(root: Path) -> tuple[Path, Path]:
- project = root / "project"
- runtime = root / "runtime"
- state_file = f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md"
- registry_path = project / ".loopx" / "registry.json"
- run_dir = runtime / "goals" / GOAL_ID / "runs"
-
- (project / Path(state_file).parent).mkdir(parents=True, exist_ok=True)
- (project / state_file).write_text(
- "---\n"
- "status: active-read-only\n"
- "updated_at: 2026-01-01T00:00:00+00:00\n"
- "---\n\n"
- "# Multi Subagent Controller\n\n"
- "## Agent Todo\n\n"
- "- [ ] Observe child run projection before launching more children.\n",
- encoding="utf-8",
- )
- registry_path.parent.mkdir(parents=True, exist_ok=True)
- registry_path.write_text(
- json.dumps(
- {
- "schema_version": 1,
- "updated_at": "2026-01-01T00:00:00+00:00",
- "common_runtime_root": str(runtime),
- "goals": [
- {
- "id": GOAL_ID,
- "domain": "subagent-smoke",
- "status": "active-read-only",
- "repo": str(project),
- "state_file": state_file,
- "adapter": {
- "kind": "harness_self_improvement",
- "status": "connected-read-only",
- },
- "spawn_policy": {
- "mode": "multi_subagent",
- "allowed": True,
- "max_children": 3,
- "allowed_domains": ["docs", "validation", "implementation"],
- },
- "quota": {"compute": 1.0},
- "authority_sources": [],
- }
- ],
- },
- indent=2,
- sort_keys=True,
- )
- + "\n",
- encoding="utf-8",
- )
-
- run_dir.mkdir(parents=True, exist_ok=True)
- runs = [
- {
- "generated_at": "2026-01-01T00:02:00+00:00",
- "run_id": "controller-run-001",
- "goal_id": GOAL_ID,
- "classification": "ready_for_parallel_probe",
- "recommended_action": "merge child evidence, then choose one bounded implementation slice",
- "subagents": [
- {
- "run_id": "docs-map-001",
- "goal_id": "docs-map-subagent",
- "parent_run_id": "controller-run-001",
- "spawned_by_goal_id": GOAL_ID,
- "agent_role": "explorer",
- "work_scope": ["docs/**"],
- "touched_paths": ["docs/status-data-contract.md", PRIVATE_LOCAL_PATH],
- "result_status": "completed",
- "quota_slots": 1,
- "handoff_summary": "Mapped status docs and found the projection surface.",
- },
- {
- "run_id": "validation-001",
- "goal_id": "validation-subagent",
- "parent_run_id": "controller-run-001",
- "spawned_by_goal_id": GOAL_ID,
- "agent_role": "validator",
- "work_scope": ["examples/**"],
- "result_status": "running",
- "quota_event": {"slots": 1},
- "handoff_summary": "Running focused smoke coverage.",
- },
- ],
- "merge_decision": "accepted docs-map evidence; validator still running",
- },
- {
- "generated_at": "2026-01-01T00:01:00+00:00",
- "run_id": "implementation-001",
- "goal_id": GOAL_ID,
- "parent_run_id": "controller-run-001",
- "spawned_by_goal_id": GOAL_ID,
- "agent_role": "implementation",
- "classification": "subagent_progress",
- "result_status": "queued",
- "work_scope": ["loopx/status.py"],
- "quota_spend": 2,
- "handoff_summary": "Waiting for controller merge decision before writing.",
- },
- ]
- with (run_dir / "index.jsonl").open("w", encoding="utf-8") as f:
- for run in runs:
- f.write(json.dumps(run, ensure_ascii=False, sort_keys=True) + "\n")
- from loopx.control_plane.testing.canary_harness import import_fixture_authority
-
- for record in json.loads(registry_path.read_text())["goals"]:
- import_fixture_authority(registry_path, record["id"], provider="sqlite")
- return registry_path, runtime
-
-
-def main() -> int:
- with tempfile.TemporaryDirectory(prefix="loopx-subagent-status-") as tmp:
- registry_path, runtime = write_fixture(Path(tmp))
- payload = collect_status(
- registry_path=registry_path,
- runtime_root_override=str(runtime),
- limit=5,
- include_goal_subagent_configuration=True,
- )
- markdown = render_status_markdown(payload)
- goal = payload["run_history"]["goals"][0]
- activity = goal["subagent_activity"]
- queue_item = payload["attention_queue"]["items"][0]
- project_asset = queue_item["project_asset"]
- asset_activity = project_asset["subagent_activity"]
- latest = goal["latest_runs"][0]
-
- assert payload["ok"] is True, payload
- assert goal["spawn_policy"] == {
- "mode": "multi_subagent",
- "spawn_allowed": True,
- "max_children": 3,
- "allowed_domains": ["docs", "validation", "implementation"],
- }, goal
- assert activity["source"] == "run_history", activity
- assert activity["parent_goal_id"] == GOAL_ID, activity
- assert activity["child_count"] == 3, activity
- assert activity["visible_child_count"] == 3, activity
- assert activity["completed_count"] == 1, activity
- assert activity["active_count"] == 2, activity
- assert activity["quota_spend_slots"] == 4, activity
- assert asset_activity == activity, (asset_activity, activity)
- assert project_asset_summary_is_public_safe(project_asset), project_asset
- assert latest["subagent_count"] == 2, latest
- assert latest["subagents"][0]["run_id"] == "docs-map-001", latest
- assert latest["subagents"][0]["parent_run_id"] == "controller-run-001", latest
- assert latest["subagents"][0]["touched_paths"] == ["docs/status-data-contract.md"], latest
- assert PRIVATE_LOCAL_PATH not in json.dumps(activity, ensure_ascii=False), activity
- assert "subagent_activity: children=3 visible=3 active=2 completed=1 quota_slots=4" in markdown, markdown
- assert "child_run: role=explorer state=completed run_id=docs-map-001 parent_run_id=controller-run-001" in markdown, markdown
- assert "child_run: role=implementation state=queued run_id=implementation-001 parent_run_id=controller-run-001" in markdown, markdown
-
- print("subagent-status-projection-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/public-adoption-loop-doc-smoke.py b/examples/public-adoption-loop-doc-smoke.py
deleted file mode 100644
index f837e4b934..0000000000
--- a/examples/public-adoption-loop-doc-smoke.py
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/usr/bin/env python3
-"""Validate the docs-first public adoption loop contract."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-DOC = ROOT / "docs" / "product" / "public-adoption-loop.md"
-DOCS_INDEX = ROOT / "docs" / "README.md"
-PRODUCT_INDEX = ROOT / "docs" / "product" / "README.md"
-
-FORBIDDEN_PUBLIC_STRINGS = [
- "/Users/",
- "/private/tmp/",
- "OPENAI_API_KEY",
- "ANTHROPIC_API_KEY",
- "raw_thread",
- "session_history",
- "verifier_output_tail",
- "ACTIVE_GOAL_STATE.md:",
-]
-
-
-def read(path: Path) -> str:
- if not path.exists():
- raise AssertionError(f"missing expected file: {path.relative_to(ROOT)}")
- return path.read_text(encoding="utf-8")
-
-
-def compact(text: str) -> str:
- return " ".join(text.split())
-
-
-def assert_contains(text: str, needle: str, label: str) -> None:
- if needle not in text:
- raise AssertionError(f"{label} missing {needle!r}")
-
-
-def validate_boundary(path: Path) -> None:
- text = read(path)
- label = str(path.relative_to(ROOT))
- for forbidden in FORBIDDEN_PUBLIC_STRINGS:
- if forbidden in text:
- raise AssertionError(f"{label} contains forbidden string {forbidden!r}")
-
-
-def main() -> None:
- for path in [DOC, DOCS_INDEX, PRODUCT_INDEX]:
- validate_boundary(path)
-
- doc = compact(read(DOC))
- for required in [
- "Status: docs-first product contract.",
- "## Issue Template Copy",
- "## Discussion Template Copy",
- "## Triage Labels",
- "adoption:try-loopx",
- "workflow:issue-fix",
- "privacy:needs-redaction",
- "## Lightweight Metrics",
- "workflow_type",
- "attention_cost",
- "would_repeat",
- "## Promotion To GitHub Templates",
- "owner-approved boundary decision",
- ]:
- assert_contains(doc, required, "public adoption loop doc")
-
- docs_index = read(DOCS_INDEX)
- product_index = read(PRODUCT_INDEX)
- assert_contains(docs_index, "product/README.md", "docs index")
- assert_contains(product_index, "public-adoption-loop.md", "product index")
-
- print("public-adoption-loop-doc-smoke ok")
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/readme-star-history-smoke.py b/examples/readme-star-history-smoke.py
index f74ed31703..de3d782f0a 100644
--- a/examples/readme-star-history-smoke.py
+++ b/examples/readme-star-history-smoke.py
@@ -101,6 +101,7 @@ def main() -> int:
readme_sections = {
ROOT / "README.md": ("## Current Status", "## Star History", "## License"),
ROOT / "README.zh-CN.md": ("## 当前状态", "## Star 趋势", "## License"),
+ ROOT / "README.ja.md": ("## 現在のステータス", "## Star の推移", "## ライセンス"),
}
for readme, sections in readme_sections.items():
text = readme.read_text(encoding="utf-8")
diff --git a/examples/release-artifacts-smoke.py b/examples/release-artifacts-smoke.py
index 937fe4a11d..0cda949886 100644
--- a/examples/release-artifacts-smoke.py
+++ b/examples/release-artifacts-smoke.py
@@ -121,6 +121,9 @@ def commit(message: str) -> str:
shutil.copyfile(ROOT / "pyproject.toml", root / "pyproject.toml")
(root / "loopx").mkdir()
shutil.copyfile(ROOT / "loopx/__init__.py", root / "loopx/__init__.py")
+ shutil.copyfile(ROOT / "loopx/release_metadata.py", root / "loopx/release_metadata.py")
+ with (root / "loopx/__init__.py").open("a") as initializer:
+ initializer.write('\nraise RuntimeError("artifact inspection executed the candidate")\n')
artifacts = [*packages.iterdir(), root / "dist/SHA256SUMS"]
before = {path.name: digest(path) for path in artifacts}
env = {**os.environ, "RELEASE_TAG": identity.tag, "GITHUB_SHA": correction,
diff --git a/examples/release/codex-cli-no-clone-release-verification-smoke.py b/examples/release/codex-cli-no-clone-release-verification-smoke.py
index 20671572b6..80ff455646 100644
--- a/examples/release/codex-cli-no-clone-release-verification-smoke.py
+++ b/examples/release/codex-cli-no-clone-release-verification-smoke.py
@@ -24,8 +24,6 @@
AGENT_ID = "codex-side-bypass"
FIRST_RUN_COMMANDS = (
"codex-cli-bootstrap-message",
- "codex-cli-tui-bootstrap-smoke-bundle",
- "codex-cli-visible-attach-acceptance",
)
@@ -85,8 +83,6 @@ def assert_docs() -> None:
"Codex CLI No-Clone Release Verification",
"scripts/install-from-github.sh",
"codex-cli-bootstrap-message",
- "codex-cli-tui-bootstrap-smoke-bundle",
- "codex-cli-visible-attach-acceptance",
"Current archive route: **qualified as the recovery fallback, with one boundary**.",
"network access to GitHub archive endpoints",
"same-TUI automation is not the default path",
@@ -138,8 +134,6 @@ def assert_installed_release(
assert (release_dir / "docs" / "product" / "runtimes" / "codex-cli" / "codex-cli-first-run-rehearsal.md").exists()
assert (release_dir / "docs" / "product" / "runtimes" / "codex-cli" / "codex-cli-no-clone-release-verification.md").exists()
- fixture_dir = release_dir / "examples" / "fixtures" / "codex-cli-visible-proof"
- assert fixture_dir.exists(), fixture_dir
message = run(
[
@@ -176,61 +170,6 @@ def assert_installed_release(
assert "settlement_plan.ordered_steps" in normalized_message, message
assert "raw Codex transcripts" in normalized_message, message
- bundle = json.loads(
- run(
- [
- str(installed),
- "--format",
- "json",
- "codex-cli-tui-bootstrap-smoke-bundle",
- "--project",
- str(fresh_repo),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- ],
- env=runtime_env,
- cwd=fresh_repo,
- ).stdout
- )
- assert bundle["schema_version"] == "codex_cli_tui_bootstrap_smoke_bundle_v0", bundle
- assert bundle["boundary"]["runs_codex"] is False, bundle
- assert bundle["boundary"]["requires_loopx_repo_clone"] is False, bundle
- assert bundle["boundary"]["spends_loopx_quota"] is False, bundle
- assert str(fresh_repo) in bundle["message_only_command"], bundle
-
- acceptance = json.loads(
- run(
- [
- str(installed),
- "--format",
- "json",
- "codex-cli-visible-attach-acceptance",
- "--project",
- str(fresh_repo),
- "--goal-id",
- GOAL_ID,
- "--agent-id",
- AGENT_ID,
- "--fixture",
- str(fixture_dir / "codex-visible-resume-help.public.json"),
- "--proof-fixture",
- str(fixture_dir / "visible-resume-proof.public.json"),
- "--idle-fixture",
- str(fixture_dir / "runtime-idle-visible-resume.public.json"),
- ],
- env=runtime_env,
- cwd=fresh_repo,
- ).stdout
- )
- assert acceptance["decision"] == "visible_surface_spike_passed_not_same_tui", acceptance
- assert acceptance["accepted_for_visible_later_turn"] is True, acceptance
- assert acceptance["accepted_for_same_tui_automation"] is False, acceptance
- assert acceptance["boundary"]["runs_codex"] is False, acceptance
- assert acceptance["boundary"]["reads_raw_transcripts"] is False, acceptance
- assert acceptance["boundary"]["reads_session_files"] is False, acceptance
-
assert not codex_called_marker.exists(), codex_called_marker
diff --git a/examples/reward-lesson-projection-smoke.py b/examples/reward-lesson-projection-smoke.py
deleted file mode 100644
index 7493df9acc..0000000000
--- a/examples/reward-lesson-projection-smoke.py
+++ /dev/null
@@ -1,147 +0,0 @@
-#!/usr/bin/env python3
-"""Validate human_reward lesson projection into status/quota warnings."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.feedback import compact_reward
-from loopx.quota import build_quota_should_run, render_quota_should_run_markdown
-from loopx.status import compact_human_reward
-
-
-GOAL_ID = "reward-lesson-projection-smoke"
-
-
-def status_payload(reward: dict) -> dict:
- action = "[P1] Run SkillsBench before fixing the reward lesson projection."
- agent_todos = {
- "schema_version": "todo_summary_v0",
- "source_section": "Agent Todo",
- "total_count": 1,
- "open_count": 1,
- "done_count": 0,
- "first_open_items": [
- {
- "index": 1,
- "text": action,
- "role": "agent",
- "status": "open",
- "priority": "P1",
- "task_class": "advancement_task",
- "action_kind": "run_skillsbench",
- "todo_id": "todo_reward_lesson_projection",
- }
- ],
- }
- item = {
- "goal_id": GOAL_ID,
- "status": "reward_lesson_projection_smoke",
- "waiting_on": "codex",
- "severity": "info",
- "source": "project_asset",
- "recommended_action": action,
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- "slot_minutes": 1,
- "allowed_slots": 10,
- "spent_slots": 0,
- "state": "eligible",
- "reason": "eligible fixture",
- },
- "project_asset": {
- "next_action": action,
- "stop_condition": "stop on private material",
- "agent_todos": agent_todos,
- },
- }
- return {
- "ok": True,
- "attention_queue": {"items": [item]},
- "run_history": {
- "goals": [
- {
- "id": GOAL_ID,
- "registry_member": True,
- "status": "reward_lesson_projection_smoke",
- "adapter_kind": "harness_self_improvement",
- "adapter_status": "connected-read-only",
- "quota": {
- "compute": 1.0,
- "window_hours": 24,
- "slot_minutes": 1,
- "allowed_slots": 10,
- },
- "latest_runs": [
- {
- "generated_at": "2026-06-24T00:00:00+00:00",
- "goal_id": GOAL_ID,
- "classification": "human_reward_recorded",
- "recommended_action": "Run SkillsBench before fixing the route.",
- "human_reward": reward,
- }
- ],
- }
- ]
- },
- }
-
-
-def main() -> int:
- reward = compact_reward(
- recorded_at="2026-06-24T00:00:00+00:00",
- decision="route_correction",
- reward="mixed",
- reason_summary="User corrected the route: fix durable lesson projection before running more cases.",
- follow_up="Update the affected todo and next action before benchmark expansion.",
- lesson={
- "kind": "route",
- "summary": "Do not expand benchmark cases before the lesson projection route is fixed.",
- "avoid": ["Run SkillsBench before fixing"],
- "prefer": ["fix reward lesson projection"],
- },
- )
- compact = compact_human_reward(reward)
- assert compact is not None, reward
- assert compact["lesson"]["schema_version"] == "human_reward_lesson_v0", compact
- assert compact["lesson"]["kind"] == "route", compact
- assert compact["lesson"]["avoid"] == ["Run SkillsBench before fixing"], compact
-
- guard = build_quota_should_run(status_payload(compact), goal_id=GOAL_ID)
- warning = guard.get("reward_lesson_projection_warning")
- assert isinstance(warning, dict), guard
- assert warning["schema_version"] == "reward_lesson_projection_warning_v0", warning
- assert warning["match_count"] == 1, warning
- assert "Run SkillsBench" in warning["matches"][0]["avoid"], warning
- markdown = render_quota_should_run_markdown(guard)
- assert "reward_lesson_projection_warning" in markdown, markdown
- assert "reward_lesson_action" in markdown, markdown
-
- zero_token_reward = compact_reward(
- recorded_at="2026-06-24T00:00:00+00:00",
- decision="route_correction",
- reward="mixed",
- reason_summary="User correction phrase should not warn when it has no scope tokens.",
- follow_up=None,
- lesson={
- "kind": "route",
- "summary": "A tokenless avoid phrase should not match every recommended action.",
- "avoid": ["P0"],
- },
- )
- zero_token_compact = compact_human_reward(zero_token_reward)
- assert zero_token_compact is not None, zero_token_reward
- zero_token_guard = build_quota_should_run(status_payload(zero_token_compact), goal_id=GOAL_ID)
- assert "reward_lesson_projection_warning" not in zero_token_guard, zero_token_guard
- print("reward-lesson-projection smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/reward-memory-walkthrough-smoke.py b/examples/reward-memory-walkthrough-smoke.py
deleted file mode 100644
index 693f80cc6d..0000000000
--- a/examples/reward-memory-walkthrough-smoke.py
+++ /dev/null
@@ -1,599 +0,0 @@
-#!/usr/bin/env python3
-"""Contributor-safe walkthrough: corpus health → candidate → ATR → apply → feedback.
-
-Synthetic quota/todo packets only. Guidance stays advisory. Without explicit
-Reward Memory activation, Agent Turn Recall fails closed. No external sinks and
-no retained provider payloads.
-"""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import re
-import sys
-import tempfile
-from pathlib import Path
-from typing import Any
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-if str(REPO_ROOT) not in sys.path:
- sys.path.insert(0, str(REPO_ROOT))
-
-from loopx.capabilities.agent_turn_recall import ( # noqa: E402
- build_agent_turn_recall_preview,
- build_agent_turn_situation,
- run_agent_turn_recall,
-)
-from loopx.capabilities.context_providers.base import ( # noqa: E402
- ContextProviderItem,
- ContextProviderRetrieval,
- ContextProviderSync,
-)
-from loopx.capabilities.reward_memory import ( # noqa: E402
- apply_reward_memory_recall,
- build_active_reward_memory_record,
- build_reward_memory_candidate,
- build_reward_memory_corpus_health_packet,
- build_reward_memory_recall_request,
- execute_reward_memory_recall,
- review_reward_memory_candidate,
- reward_memory_health_case,
-)
-from loopx.capabilities.reward_memory.experiment import ( # noqa: E402
- load_reward_memory_experiment_config,
- resolve_reward_memory_surface_config,
-)
-from loopx.capabilities.reward_memory.scoped_feedback import ( # noqa: E402
- ingest_scoped_feedback_reward_memory_event,
-)
-
-
-OBSERVED_AT = "2026-08-26T07:00:00+00:00"
-WORKSPACE = "workspace:rm-walkthrough"
-PROJECT = "repository:loopx"
-USER = "user:example"
-PEER = "agent:pilot"
-SESSION = "session:walkthrough-turn"
-SURFACE = "agent_workflow.turn_admission"
-SCOPE_REF = "viking://user/example/memories/agent-turn"
-GOAL_ID = "goal:rm-walkthrough"
-
-_PRIVATE_RE = (
- re.compile(r"/Users/[A-Za-z0-9._-]+/"),
- re.compile(r"/home/[A-Za-z0-9._-]+/"),
- re.compile(r"\bBearer\s+[A-Za-z0-9._-]+"),
- re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
- re.compile(r"\bghp_[A-Za-z0-9]{36}\b"),
- re.compile(r"\bsk-[A-Za-z0-9]{32,}\b"),
-)
-
-
-class FakeProvider:
- provider_id = "fake_provider"
-
- def __init__(self, content: str | None = None) -> None:
- self.content = content
- self.calls = 0
-
- def retrieve(self, **kwargs: Any) -> ContextProviderRetrieval:
- self.calls += 1
- content = self.content
- if content is None:
- items: tuple[ContextProviderItem, ...] = ()
- else:
- items = (
- ContextProviderItem(
- resource_ref=f"{SCOPE_REF}/guidance.json",
- summary="Scoped turn guidance.",
- content=content,
- score=0.97,
- ),
- )
- return ContextProviderRetrieval(
- provider=self.provider_id,
- namespace=str(kwargs["namespace"]),
- status="completed",
- query_summary=str(kwargs["query_summary"]),
- observed_at=str(kwargs["observed_at"]),
- search_performed=True,
- read_performed=bool(items),
- items=items,
- requested_limit=int(kwargs["max_results"]),
- )
-
- def sync(self, **kwargs: Any) -> ContextProviderSync:
- assert kwargs["execute"] is False
- self.calls += 1
- return ContextProviderSync(
- provider=self.provider_id,
- namespace=str(kwargs["namespace"]),
- status="preflight_ready",
- observed_at=str(kwargs["observed_at"]),
- requested_count=1,
- completed_count=0,
- reason_code="execute_required_for_verified_write",
- retry_disposition="execute_required",
- provider_preflight_performed=True,
- target_access_preflight_verified=True,
- writability_verified=False,
- )
-
-
-def assert_public_safe(payload: object) -> None:
- text = json.dumps(payload, sort_keys=True) if not isinstance(payload, str) else payload
- for pattern in _PRIVATE_RE:
- assert pattern.search(text) is None, pattern.pattern
- assert '"provider_payload":' not in text
- assert "raw chat" not in text.lower()
-
-
-def quota_decision() -> dict[str, Any]:
- return {
- "ok": True,
- "status_health_ok": True,
- "decision": "run",
- "lifecycle_phase": "reviewing",
- "recommended_action": "Review and refine the selected work.",
- "selected_todo": {
- "todo_id": "todo:walkthrough-001",
- "text": "Advance one synthetic review todo.",
- "action_kind": "review_refine_merge",
- "target_key": "pr:walkthrough",
- "claimed_by": "pilot",
- },
- }
-
-
-def corpus() -> dict[str, Any]:
- return {
- "corpus_id": "agent_turn_prefs",
- "class_id": "soft_preference",
- "provider_id": "fake_provider",
- "owner_ref": "owner:example",
- "source_of_truth": "reviewed_owner_feedback",
- "read_authority": "module_scoped",
- "write_authority": "provider_managed",
- "scope": {
- "workspace_ref": WORKSPACE,
- "project_ref": PROJECT,
- "user_ref": USER,
- "peer_ref": PEER,
- "session_ref": SESSION,
- "surface_ids": [SURFACE],
- },
- "freshness": {"mode": "source_truth_bound"},
- "lifecycle": {"state": "active", "supersedes": []},
- "retrieval": {
- "index_required": True,
- "readback_required": True,
- "application_receipt_required": True,
- },
- "maintenance": {
- "writeback_triggers": ["reviewed_candidate"],
- "closure_policy": "provider_write_then_revision_verified_read",
- "retirement_authority": "owner:example",
- },
- "privacy": {"visibility": "private", "raw_content_in_registry": False},
- "provider_scope_ref_digest": hashlib.sha256(
- SCOPE_REF.encode("utf-8")
- ).hexdigest()[:16],
- }
-
-
-def checkpoint() -> dict[str, Any]:
- return {
- "verified": True,
- "corpus_id": "agent_turn_prefs",
- "workspace_ref": WORKSPACE,
- "project_ref": PROJECT,
- "user_ref": USER,
- "peer_ref": PEER,
- "session_ref": SESSION,
- "surface_id": SURFACE,
- "read_authority": "module_scoped",
- "source_ref": "repository:authority-map",
- }
-
-
-def binding() -> dict[str, Any]:
- return {
- "corpus_id": "agent_turn_prefs",
- "provider_id": "fake_provider",
- "namespace": "reward_memory",
- "scope_ref": SCOPE_REF,
- "timeout_seconds": 5,
- }
-
-
-def standing_policy() -> dict[str, Any]:
- return {
- "schema_version": "reward_memory_standing_policy_v0",
- "policy_id": "policy:walkthrough:agent-turn",
- "enabled": True,
- "auto_activate": True,
- "owner_ref": "owner:example",
- "reviewer_ref": "github:user:maintainer",
- "authority_source_ref": "policy:walkthrough:agent-turn",
- "scope": dict(corpus()["scope"]),
- "allowed_target_classes": ["soft_preference"],
- "allowed_source_kinds": ["explicit_feedback", "explicit_user_instruction"],
- "allowed_actor_roles": ["verified_project_owner_or_operator"],
- "allowed_action_scopes": [],
- "raw_content_captured": False,
- }
-
-
-def candidate_scope() -> dict[str, Any]:
- scope = dict(corpus()["scope"])
- scope["revision_ref"] = "revision:abc123"
- return scope
-
-
-def build_candidate() -> dict[str, Any]:
- return build_reward_memory_candidate(
- {
- "target_class": "soft_preference",
- "content_summary": "Prefer small reversible turn refinements.",
- "source": {
- "source_kind": "explicit_feedback",
- "source_ref": "fb:walkthrough-1",
- "actor_ref": USER,
- "actor_role": "verified_project_owner_or_operator",
- },
- "scope": candidate_scope(),
- "reasoning": {
- "summary": "Owner preference for bounded turn changes.",
- "confidence": "high",
- },
- "guard_context": {
- "source_freshness": "current",
- "conflict_state": "clear",
- "current_artifact_verified": True,
- },
- "requested_action_scopes": [],
- "raw_content_captured": False,
- }
- )
-
-
-def feedback_event(*, peer_ref: str = PEER, project_ref: str = PROJECT) -> dict[str, Any]:
- return {
- "schema_version": "scoped_feedback_reward_memory_event_v0",
- "feedback_ref": "feedback:walkthrough:turn-preference",
- "workspace_ref": WORKSPACE,
- "project_ref": project_ref,
- "user_ref": USER,
- "peer_ref": peer_ref,
- "session_ref": SESSION,
- "surface_id": SURFACE,
- "revision_ref": "revision:abc123",
- "target_class": "soft_preference",
- "content_summary": "Prefer small reversible turn refinements.",
- "source": {
- "source_kind": "explicit_user_instruction",
- "source_ref": "user:instruction:walkthrough",
- "actor_ref": USER,
- "actor_role": "verified_project_owner_or_operator",
- },
- "reasoning": {
- "summary": "Scoped feedback for one agent session.",
- "confidence": "high",
- },
- "guard_context": {
- "source_freshness": "current",
- "conflict_state": "clear",
- "current_artifact_verified": True,
- },
- "requested_action_scopes": [],
- "raw_content_captured": False,
- }
-
-
-def recall_payload(**overrides: Any) -> dict[str, Any]:
- """Function-boundary recall payload; scope fields are overridable for fail-closed cases."""
- payload: dict[str, Any] = {
- "workspace_ref": WORKSPACE,
- "project_ref": PROJECT,
- "user_ref": USER,
- "peer_ref": PEER,
- "session_ref": SESSION,
- "surface_id": SURFACE,
- "revision_ref": "revision:abc123",
- "mode": "function_boundary",
- "queries": [
- {"query": "turn guidance", "query_summary": "turn admission"},
- ],
- "limit": 3,
- "observed_at": OBSERVED_AT,
- "freshness_context": {
- "source_truth_current": True,
- "source_revision": "revision:abc123",
- },
- "conflict_state": "clear",
- "raw_content_captured": False,
- }
- payload.update(overrides)
- return payload
-
-
-def experiment_raw(*, automatic_recall: bool) -> dict[str, Any]:
- selected = corpus()
- return {
- "schema_version": "reward_memory_experiment_config_v1",
- "project_provider_binding": {
- "provider_id": "fake_provider",
- "namespace": "reward_memory",
- "timeout_seconds": 5,
- "corpus_scopes": [
- {"corpus_id": selected["corpus_id"], "scope_ref": SCOPE_REF}
- ],
- },
- "corpora": [{"corpus": selected, "standing_policy": standing_policy()}],
- "surfaces": [
- {
- "surface_id": SURFACE,
- "adapter": "scoped_feedback",
- "corpus_ids": [selected["corpus_id"]],
- "ingest_corpus_id": selected["corpus_id"],
- "recall_profile": {
- "profile_id": "agent_turn_v1",
- "mode": "bounded_agentic_search",
- "max_queries": 1,
- "limit": 4,
- },
- }
- ],
- "automation": {
- "automatic_recall": automatic_recall,
- "automatic_ingest": False,
- "fail_open": True,
- },
- }
-
-
-def load_config(*, automatic_recall: bool) -> dict[str, Any]:
- with tempfile.TemporaryDirectory(prefix="loopx-rm-walkthrough-") as root:
- project = Path(root)
- path = project / "experiment.json"
- path.write_text(
- json.dumps(experiment_raw(automatic_recall=automatic_recall)),
- encoding="utf-8",
- )
- return load_reward_memory_experiment_config(
- project=project,
- config_path="experiment.json",
- )
-
-
-def situation() -> dict[str, Any]:
- return build_agent_turn_situation(
- quota_decision(),
- goal_id=GOAL_ID,
- agent_id="pilot",
- turn_instance_id=OBSERVED_AT,
- workspace_ref=WORKSPACE,
- project_ref=PROJECT,
- user_ref=USER,
- session_ref=SESSION,
- )
-
-
-def main() -> int:
- # 1) Corpus health: empty fails closed for apply; retrieval-verified may apply.
- empty_corpus, empty_obs = reward_memory_health_case("empty")
- empty_health = build_reward_memory_corpus_health_packet(empty_corpus, empty_obs)
- assert empty_health["health_state"] == "empty"
- assert empty_health["may_apply_memory"] is False
- assert empty_health["memory_patch_authority"] is False
-
- ready_corpus, ready_obs = reward_memory_health_case("retrieval-verified")
- ready_health = build_reward_memory_corpus_health_packet(ready_corpus, ready_obs)
- assert ready_health["health_state"] == "retrieval_verified"
- assert ready_health["may_apply_memory"] is True
- assert_public_safe(empty_health)
- assert_public_safe(ready_health)
-
- # 2) Candidate review stays advisory and does not write providers.
- candidate = build_candidate()
- assert candidate["status"] == "review_ready"
- assert candidate["raw_content_captured"] is False
- assert candidate["provider_write_performed"] is False
- accepted = review_reward_memory_candidate(
- candidate,
- {
- "decision": "accept",
- "reviewer_ref": "github:user:maintainer",
- "review_ref": "review:walkthrough-accept",
- "reasoning_summary": "Scoped preference is review-ready.",
- },
- )
- assert accepted["effective_decision"] == "accept"
- assert accepted["status"] == "active"
- assert accepted["grants_new_action_authority"] is False
- assert accepted["provider_write_performed"] is False
- active = build_active_reward_memory_record(
- accepted, corpus(), activated_at=OBSERVED_AT
- )
- assert active["schema_version"] == "reward_memory_active_record_v0"
- assert active["provider_write_performed"] is False
- assert_public_safe(active)
-
- # 3) Agent Turn Recall: preview, fail closed without activation, then apply.
- turn = situation()
- assert turn["user_prompt_included"] is False
- assert turn["session_ref"] == SESSION
- preview = build_agent_turn_recall_preview(turn)
- assert preview["status"] == "preview"
- assert preview["provider_call_count"] == 0
- assert preview["context"]["guidance"] == []
- assert preview["grants_new_action_authority"] is False
- assert preview["suppress_external_sinks"] is True
-
- disabled_config = load_config(automatic_recall=False)
- disabled_provider = FakeProvider(json.dumps(active, ensure_ascii=False))
- disabled = run_agent_turn_recall(
- disabled_config,
- turn,
- observed_at=OBSERVED_AT,
- read_authority_checkpoints={
- "agent_turn_prefs": checkpoint(),
- },
- provider=disabled_provider,
- )
- assert disabled["status"] == "disabled"
- assert disabled["provider_call_count"] == 0
- assert disabled_provider.calls == 0
- assert disabled["grants_new_action_authority"] is False
- assert disabled["suppress_external_sinks"] is True
- assert disabled["raw_provider_payload_captured"] is False
-
- enabled_config = load_config(automatic_recall=True)
- route = resolve_reward_memory_surface_config(enabled_config, SURFACE)
- enabled_provider = FakeProvider(json.dumps(active, ensure_ascii=False))
- recalled = run_agent_turn_recall(
- enabled_config,
- turn,
- observed_at=OBSERVED_AT,
- read_authority_checkpoints={
- route["corpus"]["corpus_id"]: checkpoint(),
- },
- provider=enabled_provider,
- )
- assert recalled["status"] == "applied"
- assert recalled["provider_call_count"] == 1
- assert len(recalled["context"]["guidance"]) == 1
- assert recalled["grants_new_action_authority"] is False
- assert recalled["quota_spend_performed"] is False
- assert recalled["suppress_external_sinks"] is True
- assert recalled["raw_provider_payload_captured"] is False
- assert_public_safe(recalled)
-
- # 4) Explicit Reward Memory recall/application remains advisory; wrong
- # project/session scope fails closed before any provider call.
- request = build_reward_memory_recall_request(
- corpus(),
- recall_payload(),
- read_authority_checkpoint=checkpoint(),
- )
- assert request["status"] == "ready"
- apply_provider = FakeProvider(json.dumps(active, ensure_ascii=False))
- session = execute_reward_memory_recall(
- request,
- provider_binding=binding(),
- provider=apply_provider,
- )
- assert session.public_packet["status"] == "completed"
- applied = apply_reward_memory_recall(
- {"guidance": []},
- session,
- application_id="recall:walkthrough",
- apply_memory=lambda base, items: {
- "outcome": "applied",
- "output": dict(base)
- | {
- "guidance": [
- {
- "candidate_ref": item.candidate_ref,
- "target_class": item.target_class,
- "content_summary": item.content_summary,
- }
- for item in items
- ]
- },
- "memory_refs": [item.memory_ref for item in items],
- "reasoning_summary": "Advisory guidance injected for the exact turn.",
- "current_artifact_verified": True,
- },
- )
- assert applied["status"] == "applied"
- assert applied["receipt"]["grants_new_action_authority"] is False
- assert_public_safe(applied)
-
- # Mirrors tests/capabilities/test_reward_memory_agent_scoped_recall.py:
- # wrong and missing agent/task scope must both fail closed at the guard.
- scope_negatives = [
- ("project_ref", {"project_ref": "repository:other"}, "project_scope_mismatch"),
- ("session_ref", {"session_ref": "task:other"}, "session_ref_scope_mismatch"),
- ("missing session_ref", {"session_ref": None}, "session_ref_scope_mismatch"),
- ]
- scope_blocked: dict[str, str] = {}
- for label, overrides, reason_code in scope_negatives:
- blocked = build_reward_memory_recall_request(
- corpus(),
- recall_payload(**overrides),
- read_authority_checkpoint=checkpoint(),
- )
- assert blocked["status"] == "guard_blocked", label
- assert reason_code in blocked["guard"]["reason_codes"], label
- scope_blocked[label] = blocked["status"]
-
- # 5) Scoped feedback: plan without provider write; wrong peer fails closed.
- provider = FakeProvider()
- planned = ingest_scoped_feedback_reward_memory_event(
- feedback_event(),
- corpus=corpus(),
- standing_policy=standing_policy(),
- provider_binding=binding(),
- observed_at=OBSERVED_AT,
- execute=False,
- provider=provider,
- )
- assert planned["status"] == "preflight_ready"
- assert planned["external_writes_performed"] is False
- assert planned["raw_provider_payload_captured"] is False
- assert planned["grants_new_action_authority"] is False
- assert planned["next_reward_memory_call"] == "explicit_function_boundary_recall"
- assert provider.calls == 1
-
- blocked_peer = ingest_scoped_feedback_reward_memory_event(
- feedback_event(peer_ref="agent:other"),
- corpus=corpus(),
- standing_policy=standing_policy(),
- provider_binding=binding(),
- observed_at=OBSERVED_AT,
- execute=False,
- )
- assert blocked_peer["status"] == "guard_blocked"
- assert "candidate_peer_ref_corpus_mismatch" in blocked_peer["guard"]["reason_codes"]
-
- walkthrough = {
- "empty_health": empty_health["health_state"],
- "ready_health": ready_health["health_state"],
- "candidate_status": accepted["status"],
- "atr_disabled_status": disabled["status"],
- "atr_applied_status": recalled["status"],
- "application_status": applied["status"],
- "feedback_status": planned["status"],
- "scope": {
- "agent": PEER,
- "project": PROJECT,
- "session": SESSION,
- },
- }
- assert_public_safe(walkthrough)
-
- print(
- json.dumps(
- {
- "ok": True,
- "walkthrough": "corpus_health→candidate→atr→apply→scoped_feedback",
- "may_apply_when_empty": empty_health["may_apply_memory"],
- "may_apply_when_verified": ready_health["may_apply_memory"],
- "atr_without_activation": disabled["status"],
- "atr_with_activation": recalled["status"],
- "guidance_advisory": recalled["grants_new_action_authority"] is False,
- "external_sinks_suppressed": recalled["suppress_external_sinks"],
- "scoped_feedback": planned["status"],
- "wrong_peer_blocked": blocked_peer["status"],
- "scope_negatives_blocked": scope_blocked,
- },
- sort_keys=True,
- )
- )
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/self-repair-upstream-issue-escalation-smoke.py b/examples/self-repair-upstream-issue-escalation-smoke.py
deleted file mode 100644
index b3461239a7..0000000000
--- a/examples/self-repair-upstream-issue-escalation-smoke.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke-check guarded self-repair issue escalation stays safe and bounded."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[1]
-SKILL = ROOT / "skills" / "loopx-self-repair" / "SKILL.md"
-REFERENCE = (
- ROOT
- / "skills"
- / "loopx-self-repair"
- / "references"
- / "upstream-issue-escalation.md"
-)
-
-
-def require(text: str, snippets: list[str], *, source: Path) -> None:
- missing = [snippet for snippet in snippets if snippet not in text]
- assert not missing, f"{source}: missing {missing}"
-
-
-def main() -> int:
- skill = SKILL.read_text(encoding="utf-8")
- reference = REFERENCE.read_text(encoding="utf-8")
-
- require(
- skill,
- [
- "## Upstream Issue Escalation",
- "references/upstream-issue-escalation.md",
- "Invoking this skill never grants publication permission",
- "search open and closed issues",
- "create at most one issue per repair turn",
- ],
- source=SKILL,
- )
- require(
- reference,
- [
- "Self-repair invocation is diagnosis consent, not publication consent.",
- "LOOPX_SELF_REPAIR_AUTO_ISSUE=1",
- "credentials, suspected vulnerabilities",
- "loopx check --scan-path",
- "",
- "gh issue list",
- "--state all",
- "gh auth status",
- "gh issue create",
- "Create at most one issue per repair turn",
- "upstream_issue_deduplicated",
- "upstream_issue_opened",
- ],
- source=REFERENCE,
- )
-
- search_position = reference.index("gh issue list")
- auth_position = reference.index("gh auth status")
- create_position = reference.index("gh issue create")
- assert search_position < auth_position < create_position, (
- "duplicate search and auth must precede issue creation"
- )
-
- print("self-repair-upstream-issue-escalation-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/showcase-animation-source-boundary-smoke.py b/examples/showcase-animation-source-boundary-smoke.py
deleted file mode 100644
index c498003146..0000000000
--- a/examples/showcase-animation-source-boundary-smoke.py
+++ /dev/null
@@ -1,117 +0,0 @@
-#!/usr/bin/env python3
-"""Guard the public showcase animation path against private/live sources."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-
-
-REPO_ROOT = Path(__file__).resolve().parents[1]
-SHOWCASE_INDEX = REPO_ROOT / "docs" / "showcases" / "README.md"
-CATALOG = REPO_ROOT / "docs" / "showcases" / "showcase-catalog.json"
-STORYBOARD = REPO_ROOT / "docs" / "showcases" / "showcase-animation-storyboard.json"
-
-FORBIDDEN_SOURCE_PROMOTIONS = (
- "status.frontstage-share.json",
- "status.local.json",
- "registry.global.json",
- ".loopx/registry.json",
- ".codex/goals/",
- ".loopx/goals/",
- "ACTIVE_GOAL_STATE.md",
-)
-
-
-def read(path: Path) -> str:
- return path.read_text(encoding="utf-8")
-
-
-def assert_required_content() -> None:
- showcase_index = read(SHOWCASE_INDEX)
- assert "showcase-animation-storyboard.json" in showcase_index, SHOWCASE_INDEX
- assert "showcase-catalog.json` as the only case data source" in showcase_index, SHOWCASE_INDEX
- assert "showcase-animation-prototype-smoke.py" in showcase_index, SHOWCASE_INDEX
-
-
-def assert_no_live_source_promotion() -> None:
- showcase_index = read(SHOWCASE_INDEX)
- storyboard = read(STORYBOARD)
- for marker in FORBIDDEN_SOURCE_PROMOTIONS:
- assert marker not in showcase_index, (
- f"{SHOWCASE_INDEX}: live/private source marker {marker!r}"
- )
- assert marker not in storyboard, f"{STORYBOARD}: live/private source marker {marker!r}"
-
-
-def assert_catalog_is_frontstage_ready() -> None:
- catalog = json.loads(read(CATALOG))
- assert catalog.get("schema_version") in {
- "loopx_showcase_catalog_v0",
- "loopx_showcase_catalog_v1",
- }, catalog
- cases = catalog.get("cases")
- assert isinstance(cases, list) and len(cases) >= 4, catalog
- for case in cases:
- assert case.get("id"), case
- assert case.get("headline"), case
- assert case.get("evidence_boundary"), case
- frontend = case.get("frontend_card")
- appendix = case.get("appendix_surface")
- assert isinstance(frontend, dict) or isinstance(appendix, dict), case
- if isinstance(frontend, dict):
- beats = frontend.get("story_beats")
- assert isinstance(beats, list) and len(beats) >= 3, case
- else:
- assert appendix.get("public_surface") == "appendix_only", case
-
-
-def assert_storyboard_uses_public_catalog() -> None:
- catalog = json.loads(read(CATALOG))
- catalog_ids = {case["id"] for case in catalog["cases"]}
-
- storyboard = json.loads(read(STORYBOARD))
- assert storyboard.get("schema_version") == "loopx_showcase_animation_storyboard_v0", storyboard
- assert storyboard.get("source_catalog") == "docs/showcases/showcase-catalog.json", storyboard
- assert storyboard.get("duration_seconds_target") == {"min": 20, "max": 30}, storyboard
-
- boundary = storyboard.get("public_boundary")
- assert isinstance(boundary, dict), storyboard
- for key in (
- "live_registry_state",
- "local_status_exports",
- "user_specific_active_state",
- "private_docs_or_chats",
- "raw_benchmark_traces",
- "internal_project_names",
- ):
- assert boundary.get(key) is False, (key, boundary)
-
- scenes = storyboard.get("scenes")
- assert isinstance(scenes, list) and len(scenes) >= 5, storyboard
- referenced_ids: set[str] = set()
- for scene in scenes:
- assert scene.get("id"), scene
- assert scene.get("copy"), scene
- assert scene.get("visual"), scene
- source_case_ids = scene.get("source_case_ids")
- assert isinstance(source_case_ids, list), scene
- for case_id in source_case_ids:
- assert case_id in catalog_ids, (case_id, scene)
- referenced_ids.add(case_id)
-
- assert referenced_ids, referenced_ids
- assert referenced_ids <= catalog_ids, (referenced_ids, catalog_ids)
-
-
-def main() -> int:
- assert_required_content()
- assert_no_live_source_promotion()
- assert_catalog_is_frontstage_ready()
- assert_storyboard_uses_public_catalog()
- print("showcase-animation-source-boundary-smoke ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/showcase-catalog-smoke.py b/examples/showcase-catalog-smoke.py
index 37fbedcc50..1dd0a1e5fb 100644
--- a/examples/showcase-catalog-smoke.py
+++ b/examples/showcase-catalog-smoke.py
@@ -280,7 +280,6 @@ def main() -> int:
for phrase in (
"https://loopx-project.github.io/loopx/",
"docs/assets/long-running-loop-openviking-trajectory.png",
- "docs/assets/long-running-loop-ml-experiment-trajectory.png",
"### Review Agent Work",
"## Evidence",
"### Used In Real Projects",
diff --git a/examples/status-source-switch-browser-smoke.mjs b/examples/status-source-switch-browser-smoke.mjs
index d454868df1..815aea4330 100644
--- a/examples/status-source-switch-browser-smoke.mjs
+++ b/examples/status-source-switch-browser-smoke.mjs
@@ -22,7 +22,7 @@ const outputDir = resolve(repoRoot, "output/playwright/status-source-switch");
const port = Number(process.env.LOOPX_STATUS_SOURCE_SWITCH_PORT ?? "5197");
const packaged = process.env.LOOPX_STATUS_SOURCE_SWITCH_PACKAGED === "1";
-function startServer() {
+async function startServer() {
if (packaged) {
return spawn(resolveTestPython(), [
"-m", "http.server", String(port), "--bind", "127.0.0.1", "--directory", resolve(repoRoot, "loopx/web"),
@@ -66,7 +66,7 @@ async function selectSource(page, select, label) {
async function main() {
const { chromium } = loadPlaywright();
await mkdir(outputDir, { recursive: true });
- const server = startServer();
+ const server = await startServer();
let browser;
try {
const appUrl = `http://127.0.0.1:${port}/${packaged ? "chat/" : ""}`;
diff --git a/examples/value-connectors-finance-probe-doc-smoke.py b/examples/value-connectors-finance-probe-doc-smoke.py
deleted file mode 100644
index e5bf0f992e..0000000000
--- a/examples/value-connectors-finance-probe-doc-smoke.py
+++ /dev/null
@@ -1,85 +0,0 @@
-#!/usr/bin/env python3
-"""Prove the retired Finance connector returns extension migration guidance."""
-
-from __future__ import annotations
-
-import json
-from pathlib import Path
-import subprocess
-import sys
-
-
-ROOT = Path(__file__).resolve().parents[1]
-DOC = (
- ROOT
- / "loopx"
- / "capabilities"
- / "value_connectors"
- / "docs"
- / "finance-market-snapshot-probe.md"
-)
-
-
-def _run(*args: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [sys.executable, "-m", "loopx.cli", "--format", "json", *args],
- cwd=ROOT,
- capture_output=True,
- check=False,
- text=True,
- )
-
-
-def main() -> int:
- cases = (
- ("source-map", "--connector"),
- ("install-check", "--connector"),
- ("plan", "--connector-id"),
- )
- for command, selector in cases:
- completed = _run(
- "value-connectors",
- command,
- selector,
- "finance_market_snapshot",
- )
- assert completed.returncode == 0, completed.stderr
- packet = json.loads(completed.stdout)
- assert packet["ok"] is True, packet
- if command == "source-map":
- profiles = packet["source_profiles"]
- elif command == "install-check":
- profiles = packet["checks"]
- else:
- profiles = None
- if profiles is not None:
- assert len(profiles) == 1, profiles
- profile = profiles[0]
- assert profile["connector_id"] == "finance_market_snapshot", profile
- assert profile["status"] == "migrated_to_extension", profile
- migration = profile["migration"]
- else:
- migration = packet
- assert migration["schema_version"] == "value_connector_extension_migration_v0", migration
- assert migration["status"] == "migrated_to_extension", migration
- assert migration["replacement_extension_id"] == "loopx-finance-value-discovery", migration
- assert migration["replacement_capability_id"] is None, migration
- truth = migration["truth_contract"]
- assert truth["legacy_connector_executes_finance"] is False, truth
- assert truth["external_reads_performed"] is False, truth
- assert truth["external_writes_performed"] is False, truth
-
- doc = " ".join(DOC.read_text(encoding="utf-8").lower().split())
- for marker in (
- "value_connector_extension_migration_v0",
- "provider source required",
- "must not recreate the old connector",
- ):
- assert marker in doc, marker
-
- print("value-connectors-finance-probe-doc-smoke: ok")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/examples/worker-lifecycle-state-smoke.py b/examples/worker-lifecycle-state-smoke.py
deleted file mode 100644
index 7cc48d28be..0000000000
--- a/examples/worker-lifecycle-state-smoke.py
+++ /dev/null
@@ -1,171 +0,0 @@
-#!/usr/bin/env python3
-"""Smoke test for worker lifecycle state projection.
-
-Verifies that the agent management projection correctly derives lifecycle
-states from existing facts (registry, todo, session binding, execution facts).
-
-Run from the repository root:
- uv run --extra test python examples/worker-lifecycle-state-smoke.py
-"""
-
-from __future__ import annotations
-
-import sys
-from datetime import datetime, timedelta, timezone
-from pathlib import Path
-
-# Add the repository root to the path for direct execution
-sys.path.insert(0, str(Path(__file__).parent.parent))
-
-
-def _recent_activity() -> str:
- """A fresh Todo update: activity, which on its own never means execution."""
- return (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
-
-
-# Execution facts are what make a worker `executing`: here the worker's Turn
-# lane is live. The projection reads them; it never infers them from age.
-EXECUTION_FACTS = {"worker-executing": {"lane": "live"}}
-
-from loopx.control_plane.agents.management_projection import ( # noqa: E402
- WORKER_LIFECYCLE_STATE_ADDRESSABLE,
- WORKER_LIFECYCLE_STATE_BLOCKED,
- WORKER_LIFECYCLE_STATE_BOUND,
- WORKER_LIFECYCLE_STATE_EXECUTING,
- WORKER_LIFECYCLE_STATE_LAUNCHABLE,
- WORKER_LIFECYCLE_STATE_REGISTERED,
- build_agent_management_projection,
-)
-
-
-def build_status_payload() -> dict:
- """Build a minimal status payload with known facts."""
- return {
- "goal_filter": "smoke-goal",
- "run_history": {
- "goals": [
- {
- "id": "smoke-goal",
- "coordination": {
- "registered_agents": [
- "worker-registered",
- "worker-addressable",
- "worker-bound",
- "worker-launchable",
- "worker-executing",
- "worker-blocked",
- ],
- "thread_agent_bindings": [
- {
- "agent_id": "worker-addressable",
- "thread_id": "thread-1",
- "host_surface": "codex-app",
- },
- {
- "agent_id": "worker-bound",
- "thread_id": "thread-2",
- "host_surface": "codex-app",
- },
- {
- "agent_id": "worker-executing",
- "thread_id": "thread-3",
- "host_surface": "codex-app",
- },
- ],
- },
- }
- ]
- },
- "attention_queue": {
- "items": [
- {
- "goal_id": "smoke-goal",
- "agent_todos": {
- "items": [
- {
- "todo_id": "todo-bound",
- "claimed_by": "worker-bound",
- "status": "open",
- "updated_at": "2026-09-15T12:00:00+00:00",
- },
- {
- "todo_id": "todo-launchable",
- "claimed_by": "worker-launchable",
- "status": "open",
- "updated_at": "2026-09-15T12:00:00+00:00",
- },
- {
- "todo_id": "todo-executing",
- "claimed_by": "worker-executing",
- "status": "open",
- "updated_at": _recent_activity(),
- },
- {
- "todo_id": "todo-blocked",
- "claimed_by": "worker-blocked",
- "status": "blocked",
- "task_class": "blocker",
- "updated_at": "2026-09-17T12:00:00+00:00",
- },
- ]
- },
- }
- ]
- },
- }
-
-
-def main() -> int:
- payload = build_status_payload()
- projection = build_agent_management_projection(
- payload, execution_facts=EXECUTION_FACTS
- )
- without_facts = build_agent_management_projection(payload)
- timestamp_only = {
- a["agent_id"]: a["state"] for a in without_facts.get("agents", [])
- }.get("worker-executing")
- if timestamp_only == WORKER_LIFECYCLE_STATE_EXECUTING:
- print(
- "FAIL: a fresh Todo timestamp without execution facts must not "
- "read as executing"
- )
- return 1
-
- agents = {a["agent_id"]: a for a in projection.get("agents", [])}
-
- # Verify each worker's lifecycle state
- expected = {
- "worker-registered": WORKER_LIFECYCLE_STATE_REGISTERED,
- "worker-addressable": WORKER_LIFECYCLE_STATE_ADDRESSABLE,
- "worker-bound": WORKER_LIFECYCLE_STATE_BOUND,
- "worker-launchable": WORKER_LIFECYCLE_STATE_LAUNCHABLE,
- "worker-executing": WORKER_LIFECYCLE_STATE_EXECUTING,
- "worker-blocked": WORKER_LIFECYCLE_STATE_BLOCKED,
- }
-
- failures = []
- for agent_id, expected_state in expected.items():
- agent = agents.get(agent_id)
- if agent is None:
- failures.append(f"{agent_id}: missing from projection")
- continue
- actual_state = agent.get("state")
- if actual_state != expected_state:
- failures.append(
- f"{agent_id}: expected {expected_state}, got {actual_state}"
- )
- else:
- print(f" {agent_id}: {actual_state} ✓")
-
- if failures:
- print("\nFAILURES:")
- for failure in failures:
- print(f" {failure}")
- return 1
-
- print(f"\nAll {len(expected)} lifecycle states verified.")
- return 0
-
-
-if __name__ == "__main__":
- raise SystemExit(main())
diff --git a/loopx/__init__.py b/loopx/__init__.py
index 2f01aed637..46099679c6 100644
--- a/loopx/__init__.py
+++ b/loopx/__init__.py
@@ -2,4 +2,4 @@
__all__ = ["__version__"]
-__version__ = "2.3.0"
+__version__ = "2.4.0"
diff --git a/loopx/agent_onboarding.py b/loopx/agent_onboarding.py
index 7bacb923ab..bee609f34b 100644
--- a/loopx/agent_onboarding.py
+++ b/loopx/agent_onboarding.py
@@ -482,10 +482,12 @@ def build_agent_onboarding_packet(
registry_path,
resolved_goal_id,
)
+ activation_registry = str(registry_path) if canonical_agent_type == "antigravity-app" else None
host_loop_activation = build_host_loop_activation_packet(
agent_type=canonical_agent_type,
goal_id=resolved_goal_id,
cli_bin=cli_bin,
+ registry=activation_registry,
agent_id=agent_id,
registered_agents=registered_agents,
available_capabilities=available_capabilities,
@@ -516,6 +518,7 @@ def build_agent_onboarding_packet(
render_quota_guard_command(
resolved_goal_id,
cli_bin=cli_bin,
+ registry_path=activation_registry,
agent_id=str(selected_agent_id) if selected_agent_id else None,
available_capabilities=normalized_available_capabilities,
**scheduler_command_binding_for_agent_type(canonical_agent_type),
diff --git a/loopx/agy_goal_mode/__init__.py b/loopx/agy_goal_mode/__init__.py
index bb2c73536d..da60243cca 100644
--- a/loopx/agy_goal_mode/__init__.py
+++ b/loopx/agy_goal_mode/__init__.py
@@ -14,6 +14,8 @@
from pathlib import Path
from typing import Any
+from ..command_invocation import loopx_cli_argv
+
AGY_INSTALL_SURFACE = "agy"
ANTIGRAVITY_APP_INSTALL_SURFACE = "antigravity-app"
ANTIGRAVITY_APP_AGENT_TYPE = "antigravity-app"
@@ -111,38 +113,21 @@ def build_antigravity_sidecar_template(
goal_id: str = "",
agent_id: str | None = None,
runtime_root: str | None = None,
+ registry: str | None = None,
cli_bin: str = "loopx",
interval_seconds: int = 180,
) -> dict[str, Any]:
"""Build a public-safe Antigravity 2.0 ``sidecar.json`` periodic heartbeat template."""
- quota_args = [cli_bin, "--format", "json"]
+ cli_args = [*loopx_cli_argv(cli_bin), "--format", "json"]
if runtime_root:
- quota_args.extend(["--runtime-root", runtime_root])
- quota_args.extend(
- [
- "quota",
- "should-run",
- "--goal-id",
- goal_id,
- "--runtime-profile",
- "antigravity_app",
- ]
- )
+ cli_args.extend(["--runtime-root", runtime_root])
+ if registry:
+ cli_args.extend(["--registry", registry])
+ profile_args = ["--goal-id", goal_id, "--runtime-profile", "antigravity_app"]
+ quota_args = [*cli_args, "quota", "should-run", *profile_args]
if agent_id:
quota_args.extend(["--agent-id", agent_id])
- heartbeat_args = [cli_bin, "--format", "json"]
- if runtime_root:
- heartbeat_args.extend(["--runtime-root", runtime_root])
- heartbeat_args.extend(
- [
- "heartbeat-prompt",
- "--thin",
- "--goal-id",
- goal_id,
- "--runtime-profile",
- "antigravity_app",
- ]
- )
+ heartbeat_args = [*cli_args, "heartbeat-prompt", "--thin", *profile_args]
if agent_id:
heartbeat_args.extend(["--agent-id", agent_id])
bootstrap_prompt = (
@@ -364,6 +349,7 @@ def antigravity_app_activation_extras(
goal_id: str = "",
agent_id: str | None = None,
runtime_root: str | None = None,
+ registry: str | None = None,
cli_bin: str = "loopx",
) -> dict[str, Any]:
"""Keyword overrides for ``antigravity_app_activation``'s facade call."""
@@ -371,6 +357,7 @@ def antigravity_app_activation_extras(
goal_id=goal_id,
agent_id=agent_id,
runtime_root=runtime_root,
+ registry=registry,
cli_bin=cli_bin,
)
hooks_template = build_antigravity_hooks_template(
@@ -378,6 +365,7 @@ def antigravity_app_activation_extras(
goal_id=goal_id,
agent_id=agent_id,
runtime_root=runtime_root,
+ registry=registry,
resolve_local_executable=False,
)
wake_prompt = sidecar_template["sidecar"]["loopx-heartbeat"]["bootstrap_prompt"]
diff --git a/loopx/agy_goal_mode/host_runtime.py b/loopx/agy_goal_mode/host_runtime.py
index e0be7b1078..96e207b865 100644
--- a/loopx/agy_goal_mode/host_runtime.py
+++ b/loopx/agy_goal_mode/host_runtime.py
@@ -17,6 +17,7 @@
import time
from typing import Any
+from ..command_invocation import loopx_cli_argv
from ..entrypoint import pin_utf8_stdio
from ..file_lock import exclusive_file_lock
@@ -41,7 +42,7 @@ def retryable_native_error(error: Any) -> bool:
def _core_args(args: argparse.Namespace, command: list[str]) -> list[str]:
- result = [args.cli_bin, "--format", "json"]
+ result = [*loopx_cli_argv(args.cli_bin), "--format", "json"]
for flag, value in (
("--registry", args.registry),
("--runtime-root", args.runtime_root),
@@ -63,18 +64,15 @@ def _core_args(args: argparse.Namespace, command: list[str]) -> list[str]:
def _admitted(args: argparse.Namespace) -> bool:
+ # The retry gate observes Core. The resumed heartbeat reads its own work.
read = subprocess.run(
- _core_args(args, ["quota", "should-run"]),
+ _core_args(args, ["quota", "should-run", "--scheduler-observation"]),
capture_output=True,
text=True,
encoding="utf-8",
timeout=10,
check=True,
- env={
- **{key: value for key, value in os.environ.items() if key != "PYTHONPATH"},
- # This machine read needs Core's decision, not model context navigation.
- "LOOPX_CONTEXT_DELIVERY": "off",
- },
+ env={key: value for key, value in os.environ.items() if key != "PYTHONPATH"},
)
return json.loads(read.stdout).get("should_run") is True
diff --git a/loopx/attached_session.py b/loopx/attached_session.py
index 6ba0bdeeff..7c0f7ba627 100644
--- a/loopx/attached_session.py
+++ b/loopx/attached_session.py
@@ -767,7 +767,10 @@ def _enqueue_attached_agent_turn_under_grant(
def enqueue_attached_agent_turn(*, store: ChatSessionStore, registry_path: Path | None,
session_id: str, client_turn_id: str, message: str, origin: str,
- external_agent_target: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]:
+ external_agent_target: dict[str, Any] | None = None,
+ attachments: object = None) -> tuple[dict[str, Any], bool]:
+ if attachments:
+ raise ValueError("attached host session queue does not yet accept attachments")
kwargs = dict(store=store, registry_path=registry_path, session_id=session_id,
client_turn_id=client_turn_id, message=message, origin=origin,
external_agent_target=external_agent_target)
diff --git a/loopx/bootstrap_command_pack.py b/loopx/bootstrap_command_pack.py
index 1c92b1409a..8451873ba5 100644
--- a/loopx/bootstrap_command_pack.py
+++ b/loopx/bootstrap_command_pack.py
@@ -846,6 +846,7 @@ def build_loopx_bootstrap_command_pack(
registry_path=registry_path,
runtime_root_arg=runtime_root_arg,
)
+ activation_registry = str(registry_path) if agent_type == "antigravity-app" else None
thread_binding = resolve_thread_agent_binding(
registry_goal,
host_surface=host_surface,
@@ -890,6 +891,7 @@ def build_loopx_bootstrap_command_pack(
goal_id=resolved_goal_id,
cli_bin=cli_bin,
runtime_root=command_runtime_root,
+ registry=activation_registry,
identity_runtime_root=identity_runtime_root,
agent_id=effective_agent_id,
registered_agents=registered_agents,
@@ -923,6 +925,7 @@ def build_loopx_bootstrap_command_pack(
resolved_goal_id,
cli_bin=cli_bin,
runtime_root=command_runtime_root,
+ registry_path=activation_registry,
agent_id=str(selected_agent_id) if selected_agent_id else None,
available_capabilities=available_capabilities,
begin_turn=guided_start_begins_turn,
diff --git a/loopx/canary/maintainability_ratchet.py b/loopx/canary/maintainability_ratchet.py
index ebad2d40c4..498b4dbe44 100644
--- a/loopx/canary/maintainability_ratchet.py
+++ b/loopx/canary/maintainability_ratchet.py
@@ -6,10 +6,13 @@
from collections import Counter
from importlib.util import resolve_name
import json
+import os
from pathlib import Path
import subprocess
from typing import Any, Mapping, Sequence
+from ..paths import display_path_text
+
MAINTAINABILITY_REPORT_SCHEMA_VERSION = "control_plane_maintainability_report_v0"
MODULE_METRIC_BASELINE_SCHEMA_VERSION = "control_plane_module_metric_baseline_v0"
@@ -209,18 +212,24 @@ def tracked_python_paths(repository_root: Path) -> set[Path]:
# `-z` frames each pathname on NUL, so a path carrying U+0085/U+2028/U+2029
# stays one record even in a repository that sets `core.quotePath=false`,
# where `git ls-files` emits it raw and `str.splitlines()` would tear it.
+ # The read stays in bytes so the record's own identity survives: a text
+ # read turns a CR inside a legal name into LF and an undecodable record
+ # into U+FFFD, and the rebuilt path would not name the tracked file, so
+ # that module would silently leave the ratchet.
completed = subprocess.run(
["git", "ls-files", "-z", "*.py"],
cwd=repository_root,
check=True,
- text=True, encoding="utf-8", errors="replace",
stdout=subprocess.PIPE,
)
- return {
- repository_root / relative_path
- for relative_path in completed.stdout.split("\0")
- if relative_path and (repository_root / relative_path).is_file()
- }
+ paths: set[Path] = set()
+ for record in completed.stdout.split(b"\0"):
+ if not record:
+ continue
+ path = repository_root / os.fsdecode(record)
+ if path.is_file():
+ paths.add(path)
+ return paths
def _dependency_finding(
@@ -236,12 +245,14 @@ def _dependency_finding(
if imported_name:
identity += f":{imported_name}"
return {
- "id": _finding_id("dependency_debt", identity),
+ "id": _finding_id("dependency_debt", display_path_text(identity)),
"category": "dependency_debt",
"rule": rule,
- "path": path.relative_to(repository_root).as_posix(),
- "source": source,
- "target": target,
+ # A name Git can hold but UTF-8 cannot encode would otherwise write
+ # bytes no JSON reader can parse; the label keeps the record locatable.
+ "path": display_path_text(path.relative_to(repository_root).as_posix()),
+ "source": display_path_text(source),
+ "target": display_path_text(target),
**({"imported_name": imported_name} if imported_name else {}),
}
@@ -459,10 +470,14 @@ def collect_oversized_decision_functions(
identity = f"{module}:{qualified_name}"
findings.append(
{
- "id": _finding_id("oversized_decision_function", identity),
+ "id": _finding_id(
+ "oversized_decision_function", display_path_text(identity)
+ ),
"category": "oversized_decision_function",
- "path": path.relative_to(repository_root).as_posix(),
- "module": module,
+ "path": display_path_text(
+ path.relative_to(repository_root).as_posix()
+ ),
+ "module": display_path_text(module),
"symbol": qualified_name,
"line": function.lineno,
"metrics": {
@@ -615,10 +630,10 @@ def collect_module_metric_findings(
continue
findings.append(
{
- "id": _finding_id("module_metric_budget", relative),
+ "id": _finding_id("module_metric_budget", display_path_text(relative)),
"category": "module_metric_budget",
- "path": relative,
- "module": _module_name(path, package_root),
+ "path": display_path_text(relative),
+ "module": display_path_text(_module_name(path, package_root)),
"metrics": metrics,
"metric_ceilings": ceilings,
"regressions": regressions,
@@ -692,9 +707,11 @@ def diff_scoped_module_ceiling_violations(
if crossed_inherited_ceiling and head_ceiling < head_lines:
violations.append(
{
- "id": _finding_id("module_metric_budget", relative),
+ "id": _finding_id(
+ "module_metric_budget", display_path_text(relative)
+ ),
"category": "module_metric_budget",
- "path": relative,
+ "path": display_path_text(relative),
"base_lines": 0 if base_lines is None else len(base_lines.splitlines()),
"base_ceiling": base_ceiling,
"head_lines": head_lines,
@@ -825,7 +842,7 @@ def build_control_plane_maintainability_report(
)
return {
"schema_version": MAINTAINABILITY_REPORT_SCHEMA_VERSION,
- "repository_root": str(repository_root),
+ "repository_root": display_path_text(repository_root),
"policy": {
"decision_statement_limit": DECISION_STATEMENT_LIMIT,
"decision_point_limit": DECISION_POINT_LIMIT,
diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json
index ca1d08c0f0..e6a6fe67b9 100644
--- a/loopx/canary/module_metric_baseline.json
+++ b/loopx/canary/module_metric_baseline.json
@@ -29,6 +29,9 @@
"loopx/capabilities/issue_fix/pr_lifecycle.py": {
"lines": 2056
},
+ "loopx/capabilities/native_chat/external_conversations.py": {
+ "lines": 2111
+ },
"loopx/chat_actions.py": {
"any_count": 52,
"dict_any_count": 0
@@ -39,20 +42,13 @@
"loopx/chat_runtime.py": {
"any_count": 38,
"dict_any_count": 0,
- "lines": 2503
+ "lines": 2524
},
"loopx/chat_server.py": {
"any_count": 25,
"dict_any_count": 0,
"lines": 2058
},
- "loopx/chat_store.py": {
- "lines": 2146
- },
- "loopx/codex_cli_probe.py": {
- "any_count": 37,
- "dict_any_count": 0
- },
"loopx/control_plane/agents/agent_scope.py": {
"any_count": 107,
"dict_any_count": 0
@@ -84,7 +80,7 @@
"lines": 2760
},
"loopx/extensions/lark/private_conversations.py": {
- "lines": 2191
+ "lines": 2654
},
"loopx/heartbeat_prompt.py": {
"any_count": 17,
diff --git a/loopx/canary/planner.py b/loopx/canary/planner.py
index 29af2a36eb..2f904be580 100644
--- a/loopx/canary/planner.py
+++ b/loopx/canary/planner.py
@@ -1000,9 +1000,9 @@
"reason": "guards Codex App heartbeat identity, scheduler hints, and no-spend cadence behavior",
},
{
- "command": "python3 examples/codex-cli-tui-bootstrap-smoke-bundle-smoke.py",
+ "command": "python3 examples/codex-cli-bootstrap-message-smoke.py",
"tier": "default",
- "reason": "checks Codex CLI TUI bootstrap bundle and scoped LoopX command contract",
+ "reason": "checks Codex CLI TUI bootstrap message and scoped LoopX command contract",
},
{
"command": "python3 examples/claude-goalmode-lifecycle-smoke.py",
diff --git a/loopx/capabilities/agent_turn_recall/core.py b/loopx/capabilities/agent_turn_recall/core.py
index 7bf8c42742..631c99a262 100644
--- a/loopx/capabilities/agent_turn_recall/core.py
+++ b/loopx/capabilities/agent_turn_recall/core.py
@@ -7,7 +7,6 @@
from ...control_plane.digest_envelope import sha256_envelope
from ...control_plane.runtime.public_safety import public_safe_compact_text
from ..context_providers.base import ContextProvider
-from ..reward_memory.runtime_hooks import run_reward_memory_automatic_recall_hook
AGENT_TURN_SITUATION_SCHEMA_VERSION = "agent_turn_situation_v0"
@@ -215,6 +214,8 @@ def run_agent_turn_recall(
) -> dict[str, Any]:
"""Recall guidance and inject it into this turn's private reasoning context."""
+ from ..reward_memory.runtime_hooks import run_reward_memory_automatic_recall_hook
+
query = _turn_query(situation)
context = {
"schema_version": AGENT_TURN_RECALL_CONTEXT_SCHEMA_VERSION,
diff --git a/loopx/capabilities/agent_turn_recall/runtime.py b/loopx/capabilities/agent_turn_recall/runtime.py
index 441519e71b..5eaca95d6f 100644
--- a/loopx/capabilities/agent_turn_recall/runtime.py
+++ b/loopx/capabilities/agent_turn_recall/runtime.py
@@ -17,7 +17,6 @@
resolve_reward_memory_experiment,
resolve_reward_memory_surface_config,
)
-from ..reward_memory.read_authority import build_reward_memory_surface_read_authority_checkpoints
from .core import (
AGENT_TURN_RECALL_SCHEMA_VERSION,
AGENT_TURN_RECALL_SURFACE_ID,
@@ -150,6 +149,8 @@ def resolve_reward_memory_turn_session_ref(
def reward_memory_turn_read_authority_checkpoints(
config: Mapping[str, Any], goal_id: str
) -> dict[str, dict[str, Any]]:
+ from ..reward_memory.read_authority import build_reward_memory_surface_read_authority_checkpoints
+
return build_reward_memory_surface_read_authority_checkpoints(
config, AGENT_TURN_RECALL_SURFACE_ID,
verified=True, source_ref=f"registry:{goal_id}:reward-memory",
diff --git a/loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py b/loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py
index 45e7219808..d018bd9ad7 100644
--- a/loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py
+++ b/loopx/capabilities/benchmark_toolkit/trajectory_assessment_store.py
@@ -55,6 +55,8 @@ def _pack_id(owner_goal_id: str, record: dict) -> str:
identity["solver_usage"] = record["solver_usage"]
if "native_outcomes" in record:
identity["native_outcomes"] = record["native_outcomes"]
+ if "human_attention" in record:
+ identity["human_attention"] = record["human_attention"]
if "base_pack_id" in record:
identity["base_pack_id"] = record["base_pack_id"]
if "case_study" in record:
@@ -365,6 +367,9 @@ def _summary(record: dict, reason: str | None, prepared: dict | None = None) ->
"config": analysis["config"],
"availability": "unavailable" if reason else "available",
"reason_code": reason,
+ **({"human_attention": {"projection": analysis["human_attention"],
+ "applicability": "historical" if reason else "current"}}
+ if "human_attention" in analysis else {}),
**({"case_study_summary": {"title": record["case_study"]["title"],
"language": record["case_study"]["language"]}}
if "case_study" in record else {}),
@@ -413,6 +418,8 @@ def register_pack(
},
}
_verify_sources(record)
+ if "human_attention" in prepared:
+ record["human_attention"] = prepared["human_attention"]
if "case_study" in prepared:
record["case_study"] = prepared["case_study"]
if base_pack_id is not None:
@@ -737,6 +744,8 @@ def read_citation(
citations = [c for a in (result or {}).get("assessments", []) for c in a["citations"]]
citations.extend(c for field in ((result or {}).get("display") or {}).get("fields", [])
for c in field.get("context_citations", []))
+ attention = (view.get("human_attention") or {}).get("projection") or {}
+ citations.extend(event["citation"] for event in attention.get("events", []))
synthesis = (result or {}).get("synthesis")
case_study = view.get("case_study")
if case_study:
diff --git a/loopx/capabilities/benchmark_toolkit/trajectory_tool_context.py b/loopx/capabilities/benchmark_toolkit/trajectory_tool_context.py
index 398a925989..489c82e7a9 100644
--- a/loopx/capabilities/benchmark_toolkit/trajectory_tool_context.py
+++ b/loopx/capabilities/benchmark_toolkit/trajectory_tool_context.py
@@ -14,7 +14,9 @@
_TURN_ASSIGNMENT = re.compile(
- r"LOOPX_TURN=([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,9})?Z)"
+ r"LOOPX_TURN=("
+ r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]{1,9})?Z"
+ r"|wake-[0-9]+-[a-f0-9]{12})"
)
_TURN_PLACEHOLDER = "${LOOPX_TURN:?}"
_TURN_ARGUMENT = re.compile(r'(? list[str] | None:
return None
bound_turn = None
if "\n" in command:
- # The managed heartbeat assigns one literal UTC Turn ID before the
- # quota guard. Resolve only its quoted argument, without running shell.
+ # Codex App and the benchmark worker assign one literal Turn ID before
+ # the quota guard. Resolve only its quoted argument, without running shell.
assignment, _, command = command.partition("\n")
command = command.removesuffix("\n")
match = _TURN_ASSIGNMENT.fullmatch(assignment)
@@ -48,7 +50,9 @@ def _argv(command: str, depth: int = 0) -> list[str] | None:
if not words or any(word and set(word) <= set(";&|()<>") for word in words):
return None
if bound_turn is not None:
- if words.count("--turn-instance-id") != 1:
+ # Both CLI spellings name the same option; an equals-form override
+ # must not hide behind the single quoted placeholder binding.
+ if sum(word.partition("=")[0] == "--turn-instance-id" for word in words) != 1:
return None
index = words.index("--turn-instance-id") + 1
if words[index:index + 1] != [_TURN_PLACEHOLDER]:
diff --git a/loopx/capabilities/configuration_ui.py b/loopx/capabilities/configuration_ui.py
index 9be1689c3d..e991c2d0e9 100644
--- a/loopx/capabilities/configuration_ui.py
+++ b/loopx/capabilities/configuration_ui.py
@@ -83,8 +83,15 @@ def capability_configuration_editor(
# The steward namespace owns its closed vocabulary, so the editor offers the
# same values instead of restating them: a form cannot submit an executor or
# effort the owning namespace would reject.
- steward_endpoints, steward_efforts = _steward_executor_editor_options()
- from .native_chat.machine_defaults import codex_profile_options
+ steward_endpoints, steward_efforts = (
+ _steward_executor_editor_options()
+ if capability_id in ("codex_chat", "steward_executor") else ([], [])
+ )
+ codex_profiles: list[str] = []
+ if capability_id == "codex_chat":
+ from .native_chat.machine_defaults import codex_profile_options
+
+ codex_profiles = codex_profile_options()
definitions: dict[str, dict[str, Any]] = {
"context_delivery": {
"supported_scopes": ["machine"], "writable_scopes": ["machine"],
@@ -100,7 +107,7 @@ def capability_configuration_editor(
"supported_scopes": ["machine"], "writable_scopes": ["machine"],
"fields": [
_field("codex_profile", "Codex configuration profile", "select", nullable=True,
- options=codex_profile_options(), description="Existing native account/configuration home; credentials are not copied."),
+ options=codex_profiles, description="Existing native account/configuration home; credentials are not copied."),
_field("model", "Conversation model", "text", nullable=True,
description="For example gpt-6.1-sol. Blank inherits this Codex profile's default."),
_field("reasoning_effort", "Reasoning effort", "select", nullable=True,
diff --git a/loopx/capabilities/content_ops/reference.py b/loopx/capabilities/content_ops/reference.py
index 3a25ebcef2..d9650bb331 100644
--- a/loopx/capabilities/content_ops/reference.py
+++ b/loopx/capabilities/content_ops/reference.py
@@ -9,7 +9,6 @@
from typing import Any
from ...control_plane.effect_runtime import EffectRuntimeRejected, EffectRuntimeStartupError, effect_runtime_result
-from ..material_lifecycle.inventory import build_material_store_inventory
def content_reference_operation(operation: str, request: Mapping[str, Any]) -> dict[str, Any]:
@@ -28,6 +27,8 @@ def content_reference_operation(operation: str, request: Mapping[str, Any]) -> d
def inspect_reference_materials(*, library_path: Path, goal_id: str, store_id: str, observed_at: str) -> dict[str, Any]:
"""Inventory the original bytes; never infer lifecycle state or claim a backup."""
+ from ..material_lifecycle.inventory import build_material_store_inventory
+
source = library_path.read_bytes()
library = json.loads(source)
projection = content_reference_operation("search", {"library": library})
diff --git a/loopx/capabilities/explore/README.md b/loopx/capabilities/explore/README.md
index 1178b80e93..5aa566c70a 100644
--- a/loopx/capabilities/explore/README.md
+++ b/loopx/capabilities/explore/README.md
@@ -192,6 +192,35 @@ original server commit is provably later than that decision and their canonical
log position follows its original prefix. A delayed old delivery, tied time or
unknown time does not become new work evidence. Original results and explicitly
cited, verified prefix history remain available.
+The detail read also connects confirmed `execution_observation` records to the
+current or explicitly preceding decision through `previous_decision_followthrough`.
+An ordinary result can omit `work_yardstick_decision`, including when it has no
+quantitative measurements; the existing choice remains current. A later choice
+keeps the preceding execution's original finding reference. Attribution requires
+the same Goal/Agent/Todo, question and tested input, plus the original commit and
+visible work window. Foreign, tentative, stale and late-visible records cannot
+become that choice's execution. This reuses existing findings and readback;
+the association does not independently verify method adoption or benefit.
+A verified successor history prefix determines whether prior execution was
+already visible even when the successor clock moves backward. Captures without
+that prefix retain the strict timestamp bound; later delivery stays excluded.
+Ordinary `turn run-once` accepts the same inline `explore_result` inside the
+Host's existing `agent_vision_json`. It retains one decoded Vision packet,
+then uses the original attachment parser and delivery owner. A failed delivery
+leaves quota unspent and recovers from the original Run on the same Turn;
+completed replay repeats neither Host work, finding ingestion nor quota spend.
+Off mode with an omitted attachment creates no finding; supplied invalid or
+disabled attachments reject before Todo completion and primary writeback. The
+completion path uses the same capability preflight before lifecycle effects;
+the primary writer still checks it again at commit. An omitted attachment adds
+no capability preflight, and recovery retains already committed completion.
+The quota writeback receipt is published only after requested attachment delivery
+finishes in both `turn run-once` and `refresh-state`. The public quota CLI rejects
+a debit while that receipt is missing. Ordinary refresh and
+`refresh-state --settle-turn` recovery deliver the verified original Run before
+repairing its receipt; a failed attachment leaves the same recovery pending without a debit.
+Receipt repair preserves the original committed replay after Yardstick is disabled.
+Finish that delivery and settlement before starting the next Turn.
The comparison is advisory and carries no retention or execution obligation.
On an admitted work turn, the progressive starting read includes the enabled
Yardstick's decision guidance and any compact cue for the selected Todo. Use
diff --git a/loopx/capabilities/explore/README.zh-CN.md b/loopx/capabilities/explore/README.zh-CN.md
index ecf9fa3ee7..bdce7feb8d 100644
--- a/loopx/capabilities/explore/README.zh-CN.md
+++ b/loopx/capabilities/explore/README.zh-CN.md
@@ -99,6 +99,28 @@
`selected_candidate`,仍核对来源修订、Todo 关联和后续实际工作。未带测量的手动笔记
保持既有摘要/审计路径。读取或选择某条成绩不认证实际采用或执行。
+开启 work Yardstick 后,详情读取通过既有 `previous_decision_followthrough`,
+把 confirmed 的 `execution_observation` 关联到当前或显式前驱决策。普通结果可以
+省略 `work_yardstick_decision`,也可以没有量化测量;原选择继续有效。后续选择
+保留此前执行的原始 finding 引用。关联要求相同 Goal/Agent/Todo、问题和测试输入,
+并核对原始提交时间及证据可见的工作窗口;其他归属、tentative、过时或迟到的
+记录不能成为该选择的执行。复用现有 finding 与回读入口;关联本身不独立认证
+方法采用或收益。已验证的后继历史前缀决定此前执行是否已可见,后继时钟回拨
+不再否决前缀内的结果;缺少此前缀的旧 capture 保留严格时间上界,迟到投递仍被排除。
+
+普通 `turn run-once` 接受 Host 既有 `agent_vision_json` 内的同一
+`explore_result`,保留一个解码后的 Vision packet,再复用原附件解析及交付 owner。
+交付失败时不扣额,在同一 Turn 从原 Run 恢复;已提交重放不重复 Host 工作、
+finding 写入或扣额。关闭且省略附件时不产生 finding;非法或未启用的附件在
+Todo 完成及主写回前被拒绝。完成路径在生命周期效果前复用原能力预检,主写回
+提交时仍再次检查;省略附件时不增加能力预检,恢复保留已提交的完成记录。
+`turn run-once` 和 `refresh-state` 都在请求的附件交付完成后才发布 quota 所需的
+写回回执。该回执缺失时,公开 quota CLI 拒绝扣额。普通 refresh 与
+`refresh-state --settle-turn` 恢复先交付已验证的原 Run,再修复回执;附件失败时
+保留同一恢复状态,不扣额。
+关闭 Yardstick 后,回执修复仍保留原已提交捕获的重放语义。
+先完成该交付和结算,再开始下一 Turn。
+
## 概览
LoopX Explore 是面向长程探索目标(软件研究、安全攻击面测绘、领域调研)的受支持、默认关闭的可选能力。它把“到处看看”变成有界、可观测、有门控的流程,包含三根支柱:
diff --git a/loopx/capabilities/explore/result_log.py b/loopx/capabilities/explore/result_log.py
index ae6bc61bbb..7b98b51ad9 100644
--- a/loopx/capabilities/explore/result_log.py
+++ b/loopx/capabilities/explore/result_log.py
@@ -933,7 +933,9 @@ def _materialized_parent_edges(
return derived
-def _finding_view(event: Mapping[str, Any]) -> dict[str, Any]:
+def _finding_view(
+ event: Mapping[str, Any], *, include_internal_order: bool = False
+) -> dict[str, Any]:
measured: dict[str, Any] = {}
if "measurements" in event:
try:
@@ -943,11 +945,13 @@ def _finding_view(event: Mapping[str, Any]) -> dict[str, Any]:
# view, not the append-only history. Runtime failure propagates.
measured["measurement_error"] = str(error)
else:
- measured.update(measurements=event["measurements"], recorded_order=event["_recorded_order"])
+ measured["measurements"] = event["measurements"]
return {
**({"work_binding": event["work_binding"]} if "work_binding" in event else {}),
- **({"work_yardstick": event["work_yardstick"], "recorded_order": event["_recorded_order"]} if "work_yardstick" in event else {}),
+ **({"work_yardstick": event["work_yardstick"]} if "work_yardstick" in event else {}),
**({"execution_observation": event["execution_observation"]} if "execution_observation" in event else {}),
+ **({"recorded_order": event["_recorded_order"]} if include_internal_order
+ or "measurements" in event or "work_yardstick" in event else {}),
**measured,
"finding_id": str(event.get("result_id") or ""),
"finding": str(event.get("title") or ""),
@@ -1171,6 +1175,7 @@ def build_explore_result_projection(
goal_id: str,
finding_limit: int = DEFAULT_FINDING_LIMIT,
mermaid_node_limit: int = DEFAULT_MERMAID_NODE_LIMIT,
+ include_internal_finding_order: bool = False,
) -> dict[str, Any]:
"""Fold result events into the bounded projection display sinks render."""
@@ -1202,7 +1207,9 @@ def build_explore_result_projection(
# Whole-second source clocks can tie. Folding retains creation order, so
# break equal chronology keys with the existing latest-append ordinal
# before bounding any consumer; do not rewrite the stored evidence clock.
- findings = [_finding_view(event) for event in sorted(
+ findings = [_finding_view(
+ event, include_internal_order=include_internal_finding_order,
+ ) for event in sorted(
folded_findings,
key=lambda item: (chronology_key(item["last_updated_at"]), item["_recorded_order"]),
reverse=True,
diff --git a/loopx/capabilities/explore/turn_context.py b/loopx/capabilities/explore/turn_context.py
index 639f9981f3..d8942ae27e 100644
--- a/loopx/capabilities/explore/turn_context.py
+++ b/loopx/capabilities/explore/turn_context.py
@@ -133,6 +133,9 @@ def explore_turn_context(
# applied. New unrelated findings must not hide an older refutation.
events, goal_id=goal_id, finding_limit=len(events),
mermaid_node_limit=3,
+ # Yardstick's typed owner needs the canonical append ordinal for
+ # execution feedback. Presentation callers keep their v0 wire.
+ include_internal_finding_order=yardstick,
)
if gate["enabled"] or graph and (todo_id is not None or page_tasks or yardstick):
todos = list_goal_todos(
diff --git a/loopx/capabilities/issue_fix/README.md b/loopx/capabilities/issue_fix/README.md
index 22b2d4525f..c8b4d3c8de 100644
--- a/loopx/capabilities/issue_fix/README.md
+++ b/loopx/capabilities/issue_fix/README.md
@@ -345,14 +345,11 @@ candidate so a maintainer can audit why that person was selected.
`CODEOWNERS` remains the strongest repository-native signal. Commit volume is
only evidence of familiarity; it is not proof of maintainership, availability,
-or review authority. See the [reviewer recommendation
-contract](protocols/issue-fix-reviewer-recommendation-v0.md) for scoring,
-identity, and future-signal details, and the [reviewer request
-contract](protocols/issue-fix-reviewer-request-v0.md) for the external-write,
+or review authority. See the [reviewer recommendation contract](docs/protocols/issue-fix-reviewer-recommendation-v0.md) for scoring,
+identity, and future-signal details, and the [reviewer request contract](docs/protocols/issue-fix-reviewer-request-v0.md) for the external-write,
idempotency, and verification rules. Secondary delivery, dedicated-bot
isolation, local-private identity mapping, and readback are defined by the
-[reviewer notification sink
-contract](protocols/issue-fix-reviewer-notification-sinks-v0.md).
+[reviewer notification sink contract](docs/protocols/issue-fix-reviewer-notification-sinks-v0.md).
### 6. PR publication and public-write boundary
diff --git a/loopx/capabilities/issue_fix/pr_wait_hook.py b/loopx/capabilities/issue_fix/pr_wait_hook.py
index 74689d73dc..5eb7569006 100644
--- a/loopx/capabilities/issue_fix/pr_wait_hook.py
+++ b/loopx/capabilities/issue_fix/pr_wait_hook.py
@@ -13,7 +13,6 @@
TURN_START_HOOK_RESULT_SCHEMA_VERSION,
TurnStartHookRegistration,
)
-from .pr_wait_reconcile import reconcile_pr_wait_dependencies
PR_WAIT_OBSERVATION_HOOK_ID = "issue_fix.pr_wait_observation"
@@ -91,6 +90,9 @@ def produce() -> dict[str, Any]:
"external_read_count": 0, "state_written": False,
"summary_lines": ["Observation permission source is unavailable; provider not contacted."]}}
try:
+ # Optional provider loading follows the invocation-time permission recheck.
+ from .pr_wait_reconcile import reconcile_pr_wait_dependencies
+
readback = reconcile_pr_wait_dependencies(registry_path=registry_path,
runtime_root_arg=str(runtime_root), goal_id=goal_id, agent_id=agent_id,
fetch_timeout_seconds=fetch_timeout_seconds)
diff --git a/loopx/capabilities/issue_fix/reviewer_recommendation.py b/loopx/capabilities/issue_fix/reviewer_recommendation.py
index 1db50658ac..df2e7cf395 100644
--- a/loopx/capabilities/issue_fix/reviewer_recommendation.py
+++ b/loopx/capabilities/issue_fix/reviewer_recommendation.py
@@ -13,6 +13,10 @@
from ...control_plane.runtime.public_safety import public_safe_compact_text
from ...public_safe_text import COMPACT_LABEL_PATTERN as REVIEWER_SOURCE_ID_PATTERN
+from .repository_context import (
+ FRESHNESS_STATES as REVIEWER_SOURCE_FRESHNESS_STATES,
+ TRUST_LEVELS as REVIEWER_SOURCE_TRUST_LEVELS,
+)
ISSUE_FIX_REVIEWER_RECOMMENDATION_SCHEMA_VERSION = (
@@ -37,8 +41,6 @@
re.IGNORECASE,
)
REVIEWER_SOURCE_KINDS = {"maintainer_map"}
-REVIEWER_SOURCE_TRUST_LEVELS = {"authoritative", "verified", "advisory"}
-REVIEWER_SOURCE_FRESHNESS_STATES = {"current", "stale", "unknown"}
REVIEWER_SOURCE_MATCH_KINDS = {
"path_prefix",
"path_glob",
diff --git a/loopx/capabilities/machine_configuration/builtins.py b/loopx/capabilities/machine_configuration/builtins.py
index 0d782857fd..8e26aab087 100644
--- a/loopx/capabilities/machine_configuration/builtins.py
+++ b/loopx/capabilities/machine_configuration/builtins.py
@@ -75,7 +75,10 @@ def load() -> MachineConfigurationNamespace:
def build_builtin_machine_configuration_registry() -> MachineConfigurationRegistry:
+ from .compaction_memory import normalize_compaction_memory
+
registry = MachineConfigurationRegistry()
+ registry.register_retired("compaction_memory", normalize_compaction_memory)
for namespace, module, factory in _BUILTIN_NAMESPACES:
registry.register_deferred(namespace, _owner(module, factory))
return registry
diff --git a/loopx/capabilities/machine_configuration/compaction_memory.py b/loopx/capabilities/machine_configuration/compaction_memory.py
new file mode 100644
index 0000000000..781db3d5a2
--- /dev/null
+++ b/loopx/capabilities/machine_configuration/compaction_memory.py
@@ -0,0 +1,15 @@
+"""Strict decoder for a retired experiment; no activation or runtime owner."""
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any
+
+COMPACTION_MEMORY_MACHINE_SCHEMA = "compaction_memory_machine_defaults_v0"
+
+
+def normalize_compaction_memory(raw: Mapping[str, Any]) -> dict[str, Any]:
+ if (set(raw) != {"schema_version", "enabled"}
+ or raw.get("schema_version") != COMPACTION_MEMORY_MACHINE_SCHEMA
+ or type(raw.get("enabled")) is not bool):
+ raise ValueError("compaction_memory requires its schema_version and boolean enabled")
+ return {"schema_version": COMPACTION_MEMORY_MACHINE_SCHEMA, "enabled": raw["enabled"]}
diff --git a/loopx/capabilities/machine_configuration/contract.py b/loopx/capabilities/machine_configuration/contract.py
index 8e0ac56957..6ee32708a9 100644
--- a/loopx/capabilities/machine_configuration/contract.py
+++ b/loopx/capabilities/machine_configuration/contract.py
@@ -90,9 +90,10 @@ class MachineConfigurationRegistry:
def __init__(self) -> None:
self._namespaces: dict[str, MachineConfigurationNamespace] = {}
self._deferred: dict[str, Callable[[], MachineConfigurationNamespace]] = {}
+ self._retired: dict[str, Normalizer] = {}
def _reserve(self, namespace: str) -> None:
- if namespace in self._namespaces or namespace in self._deferred:
+ if namespace in self._namespaces or namespace in self._deferred or namespace in self._retired:
raise ValueError(
"machine-configuration namespace is already registered: " + namespace
)
@@ -143,6 +144,39 @@ def resolve(self, namespace: str) -> MachineConfigurationNamespace:
self._namespaces[namespace] = contract
return contract
+ def register_retired(
+ self, namespace: str, normalize: Normalizer
+ ) -> MachineConfigurationRegistry:
+ """Decode saved settings without advertising or reviving their owner.
+
+ Retired values remain in the normalized storage document so revisions,
+ sibling updates and exact rollback retain their existing meaning.
+ They have no editor, public projection or namespace update operation.
+ """
+ if not _NAMESPACE_RE.fullmatch(namespace):
+ raise ValueError("machine-configuration namespace is invalid")
+ self._reserve(namespace)
+ self._retired[namespace] = normalize
+ return self
+
+ def normalize_namespace(self, namespace: str, candidate: dict[str, Any]) -> dict[str, Any]:
+ retired = self._retired.get(namespace)
+ if retired is not None:
+ return retired(candidate)
+ contract = self.resolve(namespace)
+ schema_version = str(candidate.get("schema_version") or "").strip()
+ if schema_version not in contract.schema_versions:
+ raise ValueError(
+ f"machine_configuration namespace {namespace} has unsupported "
+ f"schema_version: {schema_version or 'missing'}"
+ )
+ value = contract.normalize(candidate)
+ if value.get("schema_version") != schema_version:
+ raise ValueError(
+ f"machine-configuration normalizer changed {namespace} schema_version"
+ )
+ return value
+
@property
def namespace_ids(self) -> tuple[str, ...]:
return tuple(sorted({*self._namespaces, *self._deferred}))
@@ -248,22 +282,10 @@ def normalize_machine_configuration(
selected.intersection_update(namespace_ids)
normalized: dict[str, Any] = {}
for namespace in sorted(selected):
- contract = registry.resolve(namespace)
candidate = _mapping(
namespaces[namespace], f"machine_configuration.namespaces.{namespace}"
)
- schema_version = str(candidate.get("schema_version") or "").strip()
- if schema_version not in contract.schema_versions:
- raise ValueError(
- f"machine_configuration namespace {namespace} has unsupported "
- f"schema_version: {schema_version or 'missing'}"
- )
- value = contract.normalize(candidate)
- if value.get("schema_version") != schema_version:
- raise ValueError(
- f"machine-configuration normalizer changed {namespace} schema_version"
- )
- normalized[namespace] = value
+ normalized[namespace] = registry.normalize_namespace(namespace, candidate)
return {
"schema_version": MACHINE_CONFIGURATION_SCHEMA,
"namespaces": normalized,
@@ -283,6 +305,8 @@ def project_machine_configuration(
normalized = normalize_machine_configuration(configuration, registry=registry)
projected: dict[str, Any] = {}
for namespace, value in normalized["namespaces"].items():
+ if namespace not in registry.namespace_ids:
+ continue
contract = registry.resolve(namespace)
public_value = contract.project_public(value)
if public_value.get("schema_version") != value.get("schema_version"):
diff --git a/loopx/capabilities/manager_context/README.md b/loopx/capabilities/manager_context/README.md
index 4b196cd1dc..cf7a77a8a9 100644
--- a/loopx/capabilities/manager_context/README.md
+++ b/loopx/capabilities/manager_context/README.md
@@ -358,18 +358,30 @@ that path are outside this integration. Frontend/Lark conversations retain their
existing request and return views; no new screen or setting is introduced.
The progressive quota hook's required command requests the Inbox Markdown view.
-When every item on a page has the same `instruction` or `next_action`, apply
-that exact value from `shared_item_guidance` to each item on that page. Differing
-values and all request bodies, current state, read receipts, warnings, and
-cursors are delivered in full. Use the same command with the returned
-`--cursor` or `--operation-cursor` as appropriate. Plain or JSON CLI reads retain the per-item fields.
-The command on an explicit context-delivery-off guard retains the JSON view.
-
-渐进 quota 的必读命令使用 Inbox Markdown 视图。当前页每条的 `instruction` 或
-`next_action` 完全相同时,从 `shared_item_guidance` 读取原值并应用到本页每条。
-不同指引、请求全文、当前状态、读回执、警告和游标均完整交付。用相同命令和
-对应的 `--cursor` 或 `--operation-cursor` 读完后续页。普通或 JSON CLI 读保留逐条字段。显式关闭上下文交付时,
-必读命令继续使用 JSON 视图。
+When every item on a page has the same `instruction`, `next_action` or
+`receiver_followthrough`, apply that exact field from `shared_item_guidance`
+to each item on that page. Differing values and all request bodies, current state, read receipts, warnings, and
+cursors are delivered in full. If a Markdown page exceeds the 12,000-byte tool
+output budget, the command returns a private, digest-checked reader for that
+exact Inbox result. Compare each page's digest with the opening and use its
+direct recovery command if the reference is unavailable. Read the captured
+bytes to EOF, then use the Inbox `--cursor` or `--operation-cursor` for the next
+Inbox page. A transport
+failure is not an empty Inbox. Reading the saved result does not record a
+second Inbox read, consume a return, or qualify context retention. Plain or JSON
+CLI reads retain the per-item fields, including the required read when context
+delivery is explicitly off.
+
+渐进 quota 的必读命令使用 Inbox Markdown 视图。当前页每条的 `instruction`、
+`next_action` 或 `receiver_followthrough` 完全相同时,从 `shared_item_guidance`
+读取原值并应用到本页每条。
+不同指引、请求全文、当前状态、读回执、警告和游标均完整交付。Markdown 页超出
+12,000 字节工具输出预算时,命令给出绑定原 Inbox 结果摘要的私有 reader。逐页与开场
+摘要核对,引用不可用时使用直接恢复命令。先按字节偏移
+读到 EOF,再按 Inbox 的 `--cursor` 或 `--operation-cursor` 读后续请求;这两类分页
+不能混用。交付失败不表示 Inbox 为空。读回保存结果不会再次记 Inbox 读取回执、消费
+返回结果或证明模型保留了上下文。普通或 JSON CLI 读保留逐条字段;显式关闭上下文
+交付时,必读命令仍使用 JSON 视图。
The local Inbox read transaction now lives in
`loopx/control_plane/collaboration/inbox_read.ts`. It reuses the typed receipt,
@@ -924,7 +936,9 @@ coordination runtime; neither root is moved and path containment stays enforced.
When the provider returned a trustworthy message locator before readback failed,
the same background pump persists that private attempt and later performs a
read-only verification. A matching message advances the original delivery to
-`delivered` without sending again. Provider outages retain
+`delivered` without sending again. When the project registry cannot be read,
+the pump retries without changing delivery receipts. A legacy transaction may
+not modify a receipt bound to an exact Goal instance. Provider outages retain
`verification_required`; a missing legacy locator, changed intent, missing
message, or verified mismatch becomes `explicit_unverified`. CLI, Manager read,
and Chat expose the same public-safe state and reason without returning the
diff --git a/loopx/capabilities/manager_context/__init__.py b/loopx/capabilities/manager_context/__init__.py
index 82a3d41d5f..3442c14bf1 100644
--- a/loopx/capabilities/manager_context/__init__.py
+++ b/loopx/capabilities/manager_context/__init__.py
@@ -5,10 +5,10 @@
from contextlib import nullcontext
from pathlib import Path
import re
-import shlex
from ...command_invocation import loopx_cli_argv
from ...file_lock import exclusive_file_lock
+from ...install_contract import render_host_cli_command
from ...control_plane.collaboration import conversation_scope
from ...control_plane.collaboration.source_grant_observation import (
POLICY_SCHEMA as POLICY_SCHEMA,
@@ -257,6 +257,9 @@ def produce():
count = (
max(len(inbox["items"]), agenda["incoming_count"])
+ max(len(inbox.get("peer_returns", {}).get("items", [])), agenda["outgoing_count"])
+ + len(inbox.get("native_child_results", {}).get("items", []))
+ + int(inbox.get("native_child_results", {}).get("unavailable_count", 0))
+ + int(inbox.get("native_child_results", {}).get("scan_complete") is False)
+ len(inbox.get("operation_handoffs", []))
)
incomplete = not agenda["scan_complete"]
@@ -280,7 +283,7 @@ def produce():
"error_code": error,
}
- command = shlex.join(
+ command = render_host_cli_command(
[
*loopx_cli_argv(),
"--registry",
diff --git a/loopx/capabilities/manager_context/inspection.py b/loopx/capabilities/manager_context/inspection.py
index 31e2a4fbba..4d6916dea8 100644
--- a/loopx/capabilities/manager_context/inspection.py
+++ b/loopx/capabilities/manager_context/inspection.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import hashlib
import json
import re
from copy import deepcopy
@@ -15,6 +16,11 @@
TOOL_NAME = "loopx_manager_read"
+_TODO_DETAIL_GUIDANCE = (
+ "For an oversized exact local Todo, follow its read_reference. Concatenate "
+ "detail_page.text from offset zero through EOF with the same source_revision, "
+ "then parse the complete JSON record before deciding; a fragment is not the full task. "
+)
READ_TOOL = {
"type": "function",
"name": TOOL_NAME,
@@ -32,6 +38,9 @@
"or a typed unavailable gap naming why it could not be derived. Use that to state where "
"the Goal stands before listing detail. Use concrete evidence "
"to answer progress and priority questions. Paginate with next_offset. "
+ "An oversized portfolio row is incomplete; resolve attention read_reference "
+ "to recover complete decision terms before deciding or acting. "
+ + _TODO_DETAIL_GUIDANCE +
"Use view=report_source with a closed window_start/window_end for a frozen periodic-report "
"source over all authorized local Goals including stopped ones, current tasks, window deliveries "
"and their associated tasks, and handoff receipts. Copy source.source_revision when paging. "
@@ -51,7 +60,7 @@
"include_outcome_gaps": {"type": "boolean", "description": "Local deliveries: include recorded outcome_gap counterevidence alongside progress. Default false for ordinary delivery queries; report_source always includes it. Observations and untyped host failures are not delivery outcomes."},
"window_start": {"type": "string", "description": "Local deliveries/report_source: exact inclusive ISO-8601 timestamp with offset. Pair with window_end instead of days, e.g. a frozen report window."},
"window_end": {"type": "string", "description": "Local deliveries/report_source: exact exclusive ISO-8601 timestamp with offset. Boundaries do not move while paging; report_source requires a closed window."},
- "expected_source_revision": {"type": "string", "pattern": "^sha256:[a-f0-9]{64}$", "description": "Local deliveries/report_source: copy source.source_revision from the first page onto subsequent pages. A conflicting response requires restarting this read, not merging pages from different snapshots."},
+ "expected_source_revision": {"type": "string", "pattern": "^sha256:[a-f0-9]{64}$", "description": "Local deliveries/report_source: copy source.source_revision when paging. Exact local Todo: copy its read_reference; this revision selects bounded JSON detail pages, where offset counts Unicode characters. Follow detail_page.next_read. On conflict restart the exact read; never merge revisions."},
"delivery_ref": {"type": "string", "pattern": "^sha256:[a-f0-9]{64}$", "description": "Local deliveries only: use an observed row's source_ref to recover its full permitted recorded_details and evidence references within the same read window/revision. Does not read referenced artifacts or prove the recorded claims."},
"goal_id": {"type": "string"},
"agent_id": {"type": "string", "minLength": 1,
@@ -87,7 +96,8 @@
"The Goal row carries its lifecycle readback: reached milestones with evidence refs and the phase "
"(starting/qualifying/waiting_owner/closing/closed), or a typed unavailable gap naming why. "
"Use view=agents to find registered peers, then view=agent_route with exact goal_id and agent_id to observe an existing local host binding. A route is not execution readiness. "
- "Paginate with next_offset. No cross-Goal access, shell, writes or execution authority."}
+ "Paginate with next_offset. " + _TODO_DETAIL_GUIDANCE +
+ "No cross-Goal access, shell, writes or execution authority."}
# The published tool schema is the contract the caller sees, so the reader takes
@@ -184,7 +194,15 @@ def rejected_read_arguments(arguments: dict[str, Any]) -> list[str]:
rejected.append("include_outcome_gaps:must_be_a_boolean")
if not isinstance(arguments.get("source_id", "local"), str):
rejected.append("source_id:must_be_a_string")
- exact_arguments = {"window_start", "window_end", "expected_source_revision", "delivery_ref"} & arguments.keys()
+ detail_read = view == "todos" and "expected_source_revision" in arguments
+ if detail_read:
+ if not arguments.get("goal_id") or not arguments.get("todo_id"):
+ rejected.append("expected_source_revision:requires_exact_todo")
+ if arguments.get("source_id", "local") != "local":
+ rejected.append("expected_source_revision:only_for_source_local")
+ exact_arguments = {"window_start", "window_end", "delivery_ref"} & arguments.keys()
+ if "expected_source_revision" in arguments and not detail_read:
+ exact_arguments.add("expected_source_revision")
for name in sorted(exact_arguments):
if view not in {"deliveries", "report_source"} or name == "delivery_ref" and view != "deliveries":
rejected.append(f"{name}:only_for_view_deliveries" if name == "delivery_ref" else f"{name}:only_for_view_deliveries_or_report_source")
@@ -216,6 +234,41 @@ def rejected_read_arguments(arguments: dict[str, Any]) -> list[str]:
return rejected
+def _todo_detail_revision(row: dict[str, Any], source: dict[str, Any]) -> str:
+ # Bind both native source and permitted projection, so an old owner-only
+ # cursor cannot continue into a different redaction/presentation scope.
+ encoded = json.dumps([source["source_revision"], row], ensure_ascii=False, sort_keys=True)
+ return "sha256:" + hashlib.sha256(encoded.encode()).hexdigest()
+
+
+def _todo_detail_page(row: dict[str, Any], arguments: dict[str, Any], revision: str) -> dict[str, Any]:
+ """Page transport encoding only; canonical selection and redaction stay in Core."""
+ text = json.dumps(row, ensure_ascii=False, sort_keys=True)
+ offset = arguments.get("offset", 0)
+ if offset >= len(text):
+ return {"ok": False, "error": "todo_detail_offset_out_of_range"}
+ reference = {**arguments, "source_id": "local"}
+
+ def page(end: int) -> dict[str, Any]:
+ return {"offset": offset, "next_offset": end if end < len(text) else None,
+ "total_characters": len(text), "source_revision": revision,
+ "text": text[offset:end], "eof": end == len(text),
+ "next_read": {**reference, "offset": end} if end < len(text) else None}
+
+ # The JSON string escapes quotes/control characters again. Budget the
+ # encoded page, not just the original text, without splitting Unicode.
+ low, high = offset, min(len(text), offset + 24000)
+ while low < high:
+ end = (low + high + 1) // 2
+ if len(json.dumps(page(end), ensure_ascii=False)) <= 24000:
+ low = end
+ else:
+ high = end - 1
+ if low == offset:
+ return {"ok": False, "error": "todo_detail_page_unavailable"}
+ return {"ok": True, "detail_page": page(low)}
+
+
def agent_work_summary(agent: dict[str, Any]) -> dict[str, Any]:
"""Keep the existing quota projection small; never infer live presence."""
verified = agent.get("source_verified") is True
@@ -381,6 +434,40 @@ def safe(value):
return page
+def _oversized_portfolio_index(row: dict[str, Any], gap: dict[str, Any]) -> dict[str, Any]:
+ """Keep recoverable decision references without lifting the row budget.
+
+ These are already scoped, public-safe portfolio fields. The existing typed
+ attention owner makes directory excerpts; exact Todo reads retain the full
+ terms, current authority check and original source. Other views keep their
+ existing oversized-record response.
+ """
+ reference = {"view": "todos", "goal_id": row["goal_id"]}
+ preview = effect_runtime_result("presentation.goal_attention.bound", {
+ "goals": [{"goal_id": row["goal_id"], "attention": row.get("attention")}],
+ "preview": True,
+ })["goals"][0]
+ index = {
+ **gap,
+ **{key: row[key] for key in (
+ "goal_instance_id", "description", "activation_state", "quality",
+ "progress", "source", "warnings", "goal_lifecycle",
+ ) if key in row},
+ "attention": preview.get("attention"),
+ "details_omitted": True,
+ "read_reference": reference,
+ }
+ if len(json.dumps(index, ensure_ascii=False)) <= 24000:
+ return index
+ # Even metadata can exceed the budget. Keep an explicit unknown gap and
+ # the existing scoped read route, never malformed JSON or a partial term.
+ from ...goal_portfolio import lifecycle_readback_unavailable
+
+ return {**gap, "details_omitted": True, "read_reference": reference,
+ "goal_lifecycle": lifecycle_readback_unavailable(row["goal_id"], "omitted_due_to_size"),
+ "attention": {"status": "unavailable", "items": [], "reason": "omitted_due_to_size"}}
+
+
class ManagerInspection:
def __init__(
self,
@@ -470,9 +557,12 @@ def collect(source):
return result
def _goal_scope(self) -> list[str] | None:
- ids = (self.discovery_scope() if self.discovery_scope else
- None if self.owner_scope and self.context.get("scope") == "owner_global" else
- [r["goal_id"] for r in self.context.get("goals", [])])
+ try:
+ ids = (self.discovery_scope() if self.discovery_scope else
+ None if self.owner_scope and self.context.get("scope") == "owner_global" else
+ [r["goal_id"] for r in self.context.get("goals", [])])
+ except (OSError, KeyError, TypeError) as error:
+ raise ValueError("current audience scope unavailable") from error
if ids is None:
if not (self.owner_scope and self.context.get("scope") == "owner_global"):
raise ValueError("current audience scope unavailable")
@@ -484,6 +574,7 @@ def _portfolio(self, ids, goal_id, include_stopped, offset, limit):
from ...control_plane.goals.activation import goal_activation_state
from ...chat_manager_context import manager_turn_context
try:
+ inventory_bytes = self.registry_path.read_bytes()
inventory = self._registered_goals()
permitted = sorted({g["id"] for g in inventory if ids is None or g["id"] in ids})
if goal_id is not None:
@@ -500,22 +591,51 @@ def _portfolio(self, ids, goal_id, include_stopped, offset, limit):
pass # Unknown activation stays visible as a source gap.
permitted = [gid for gid in permitted if gid not in stopped]
selected = permitted[offset:offset + limit]
- context = manager_turn_context(
- self.registry_path,
- {"channel_id": self.channel_id or ("manager" if self.owner_scope else "manager.external.inspection")},
- self.runtime_root, authorized_goal_ids=ids, requested_goal_ids=selected,
- include_stopped=include_stopped or goal_id is not None, include_details=False,
- ) if selected else {"goals": [], "coverage": {"complete": True}}
+ page, contexts, collected = [], [], []
+ for selected_id in selected:
+ context = manager_turn_context(
+ self.registry_path,
+ {"channel_id": self.channel_id or ("manager" if self.owner_scope else "manager.external.inspection")},
+ self.runtime_root, authorized_goal_ids=ids, requested_goal_ids=[selected_id],
+ include_stopped=include_stopped or goal_id is not None, include_details=False,
+ )
+ if not self.scope_valid():
+ return {"ok": False, "error": "authorization_changed"}
+ rows = context.get("goals", [])
+ if len(rows) != 1 or rows[0].get("goal_id") != selected_id:
+ raise ValueError("requested portfolio row is unavailable")
+ contexts.append(context)
+ collected.extend(rows)
+ bounded = effect_runtime_result("presentation.goal_attention.bound", {"goals": collected})["goals"]
+ # Apply the existing encoded-row budget while collecting. At
+ # most one lookahead row is read again on the next page; do not
+ # collect every later Goal only to discard it in read(). A lone
+ # oversized row keeps the existing explicit gap/continuation.
+ if len(json.dumps(bounded, ensure_ascii=False)) > 24000 and page:
+ break
+ page = bounded
+ if len(json.dumps(page, ensure_ascii=False)) > 24000:
+ break
+ if self.registry_path.read_bytes() != inventory_bytes:
+ raise ValueError("Goal inventory changed during collection")
+ coverages = [context.get("coverage", {}) for context in contexts]
+ coverage = {"complete": all(c.get("complete") is True for c in coverages)}
+ for key in set().union(*(c.keys() for c in coverages)) - {"complete"}:
+ values = [c.get(key, 0) for c in coverages]
+ coverage[key] = ((max(values) if key == "invalid_registry_entries" else sum(values))
+ if all(type(v) is int for v in values) else None)
+ snapshot_id = ("sha256:" + hashlib.sha256(json.dumps(
+ contexts, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
+ if contexts else None)
except (OSError, ValueError, KeyError, TypeError, RuntimeError):
return {"ok": False, "view": "portfolio", "error": "goal_inventory_unavailable"}
- page = context.get("goals", [])
- end = offset + len(selected)
+ end = offset + len(page)
return {"ok": True, "view": "portfolio", "goal_id": goal_id, "rows": page,
"offset": offset, "included": len(page), "matched": len(permitted),
"next_offset": end if end < len(permitted) else None,
- "source": {"source": "goal_portfolio", "snapshot_id": context.get("snapshot_id"),
- "coverage": context.get("coverage")},
- "unknown": bool(context.get("warnings")) or len(page) != len(selected),
+ "source": {"source": "goal_portfolio", "snapshot_id": snapshot_id,
+ "coverage": coverage},
+ "unknown": any(context.get("warnings") for context in contexts),
"initial_snapshot_id": self.context.get("snapshot_id"),
"source_id": "local", "source_host": "local"}
@@ -639,7 +759,7 @@ def read(self, tool: str, arguments: Any) -> dict[str, Any]:
goal_id,
owner_scope=self.owner_scope,
limit=limit,
- offset=offset,
+ offset=0 if "expected_source_revision" in arguments else offset,
todo_id=arguments.get("todo_id"),
query=arguments.get("query", ""),
)
@@ -679,6 +799,24 @@ def read(self, tool: str, arguments: Any) -> dict[str, Any]:
page = [{**r, "todo_title": titles.get(r.get("todo_id"))} for r in page]
if not self.scope_valid():
return {"ok": False, "error": "authorization_changed"}
+ if view == "todos" and "expected_source_revision" in arguments:
+ if source.get("status") != "read":
+ return {"ok": False, "error": "todo_detail_unavailable"}
+ if len(page) != 1:
+ return {"ok": False, "error": "todo_detail_unavailable"}
+ revision = _todo_detail_revision(page[0], source)
+ if revision != arguments["expected_source_revision"]:
+ return {"ok": False, "error": "todo_detail_revision_mismatch"}
+ result = _todo_detail_page(page[0], arguments, revision)
+ if not result["ok"]:
+ return result
+ if not self.scope_valid():
+ return {"ok": False, "error": "authorization_changed"}
+ result.update({"view": view, "goal_id": goal_id, "source": source,
+ "rows": [], "matched": matched, "unknown": True, "source_id": "local",
+ "source_host": "local", "note": _TODO_DETAIL_GUIDANCE})
+ self.record(result)
+ return result
# Trim whole rows, never malformed JSON or undisclosed byte truncation.
while len(page) > 1 and len(json.dumps(page, ensure_ascii=False)) > 24000:
page.pop()
@@ -686,13 +824,25 @@ def read(self, tool: str, arguments: Any) -> dict[str, Any]:
for i, row in enumerate(page):
if len(json.dumps(row, ensure_ascii=False)) > 24000:
oversized.append(offset + i)
- page[i] = {
+ gap = {
"status": "oversized_record",
"row_index": offset + i,
"goal_id": row.get("goal_id"),
"todo_id": row.get("todo_id"),
"details": "omitted_due_to_size",
}
+ page[i] = _oversized_portfolio_index(row, gap) if view == "portfolio" else gap
+ if view == "todos" and arguments.get("todo_id") and source.get("source_revision"):
+ page[i]["read_reference"] = {
+ "view": "todos", "source_id": "local", "goal_id": goal_id,
+ "todo_id": arguments["todo_id"], "offset": 0,
+ "expected_source_revision": _todo_detail_revision(row, source),
+ }
+ page[i]["read_instruction"] = _TODO_DETAIL_GUIDANCE
+ # Building an oversized index crosses the typed presentation owner;
+ # a grant revoked during that read must suppress the entire response.
+ if view == "portfolio" and oversized and not self.scope_valid():
+ return {"ok": False, "error": "authorization_changed"}
end = offset + len(page)
result = {
"ok": True,
@@ -706,12 +856,13 @@ def read(self, tool: str, arguments: Any) -> dict[str, Any]:
"next_offset": end
if isinstance(matched, int) and page and end < matched
else None,
- "unknown": matched is None or portfolio_unknown
+ # An omitted record is incomplete evidence in every view, even
+ # when an exact Todo has no further row page to read.
+ "unknown": matched is None or portfolio_unknown or bool(oversized)
or ("window_start" in arguments and (
source.get("window_complete") is False
or bool(source.get("coverage", {}).get("invalid_delivery_records"))
- or bool(source.get("coverage", {}).get("invalid_index_records"))
- or bool(oversized)))
+ or bool(source.get("coverage", {}).get("invalid_index_records"))))
or (
view == "handoffs"
and (
diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py
index 6c07c6c43e..8359b41340 100644
--- a/loopx/capabilities/manager_context/roundtrip.py
+++ b/loopx/capabilities/manager_context/roundtrip.py
@@ -50,6 +50,7 @@
from ...control_plane.content_digest import BARE_SHA256_PATTERN
from ...control_plane.collaboration.source_chat_observation import original_delivery_facts
from ...chat import ChatMessagePayloadConflictError
+from ...chat_store import TERMINAL_TURN_STATES
class ReturnResolutionBlocked(ValueError, RuntimeError):
"""A return cannot be resolved; ``reason`` is the provider-neutral code.
@@ -426,20 +427,53 @@ def observe_result(result_path, reply):
]
+def _saved_answer_rows(messages, message_id, expected_turn_id):
+ matches = [row for row in messages if row.get("message_id") == message_id]
+ if len(matches) > 1:
+ raise ValueError("saved answer has conflicting message identities")
+ if not matches or matches[0].get("role") not in {"agent", "assistant"}:
+ return [], []
+ answer = matches[0]
+ turn_id = answer.get("turn_id")
+ if expected_turn_id is not None and turn_id != expected_turn_id:
+ return [], []
+ if not turn_id:
+ return [answer], [answer]
+ original = [row for row in messages if row.get("turn_id") == turn_id]
+ question = next((row for row in original if row.get("role") == "user"), None)
+ return ([question, answer] if question else [answer]), original
+
+
def project_chat_session_snapshot(root, store, session_id, *, registry,
- message_limit=None, message_cursor=None, turn_id=None,
- resume_from=None, project_history_messages=None):
+ message_limit=None, message_cursor=None, turn_id=None, report_message_id=None,
+ resume_from=None, project_history_messages=None, include_turn_error=False):
"""Project return delivery state into one existing Chat snapshot."""
- strict = message_limit is not None or resume_from is not None
- snapshot = (store.session_snapshot(session_id, strict_messages=True) if strict
- else store.session_snapshot(session_id))
- if turn_id is not None:
+ turn = None
+ if turn_id is not None and report_message_id is None:
if message_limit is None:
raise ValueError("a selected original Turn requires paged history")
turn = store.load_turn(session_id, turn_id)
if not turn or turn.get("session_id") != session_id or turn.get("turn_id") != turn_id:
raise ValueError("original Turn is unavailable from this Session")
+ strict = message_limit is not None or resume_from is not None or report_message_id is not None
+ # Read the status first: terminal completion persists its answer before
+ # publishing completed. An older message prefix must not appear final.
+ snapshot = (store.session_snapshot(session_id, strict_messages=True) if strict
+ else store.session_snapshot(session_id))
+ report_context = None
+ if report_message_id is not None:
+ snapshot["messages"], report_context = _saved_answer_rows(snapshot["messages"], report_message_id, turn_id)
+ snapshot["report_message_id"] = report_message_id
+ snapshot["active_turn"] = None
+ elif turn is not None:
+ status = turn["status"]
+ snapshot["selected_turn"] = {"turn_id": turn_id, "status": status, "terminal": status in TERMINAL_TURN_STATES}
+ # Failure records persist the reason with the status, before appending the message.
+ error = turn.get("error")
+ if include_turn_error and status in {"failed", "timed_out"} and isinstance(error, str) and error.strip():
+ snapshot["selected_turn"]["error"] = error
+ snapshot["active_turn"] = None
# OriginalRequest already displays only this Turn. Select it before
# paging/projection, retaining every message and the strict journal read.
snapshot["messages"] = [row for row in snapshot["messages"] if row.get("turn_id") == turn_id]
@@ -452,7 +486,7 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
from .chat_history import page_chat_messages
page = (page_chat_messages(session_id, snapshot["messages"], limit=message_limit,
cursor=message_cursor, turn_id=turn_id) if message_limit is not None else None)
- context_messages = snapshot["messages"]
+ context_messages = snapshot["messages"] if report_context is None else report_context
if page is not None:
context_messages = context_messages[:page["message_page"]["total"]]
snapshot["messages"] = page["messages"]
@@ -463,8 +497,14 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
# Use the frozen context to choose the carrier, projecting only this page.
# A question and answer can straddle pages without duplicating a commitment
# or re-reading every off-page Turn for each page.
- snapshot["messages"] = project_collaboration(store, root, session_id, snapshot["messages"],
+ projected = project_collaboration(store, root, session_id, snapshot["messages"],
registry=registry, context_messages=context_messages)
+ if report_message_id is not None:
+ # Collaboration may include the original receipt carrier. The saved
+ # answer only exposes its precise answer and the question it displays.
+ visible_ids = {row.get("message_id") for row in snapshot["messages"]}
+ projected = [row for row in projected if row.get("message_id") in visible_ids]
+ snapshot["messages"] = projected
# Provider-owned history joins the selected page at the composition root.
# Core capabilities never import an extension projection sink.
if page is not None:
@@ -475,13 +515,22 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
def parse_chat_history_selection(query):
"""Validate one HTTP history selection before any recovery observation."""
- if (set(query) - {"message_limit", "message_cursor", "turn_id", "known_history"}
+ keys = set(query)
+ report = "report_message_id" in keys
+ if (keys - {"message_limit", "message_cursor", "turn_id", "known_history",
+ "task_goal_id", "task_todo_id", "report_message_id"}
or any(len(values) != 1 or not values[0] for values in query.values())
- or ("message_limit" not in query and set(query) & {"message_cursor", "turn_id", "known_history"})):
+ or (report and keys - {"report_message_id", "turn_id"})
+ or (not report and "message_limit" not in keys and keys & {"message_cursor", "turn_id", "known_history"})):
raise ValueError("invalid history page arguments")
limit = int(query["message_limit"][0]) if "message_limit" in query else None
if limit is not None and not 1 <= limit <= 200:
raise ValueError("message_limit must be between 1 and 200")
+ task_scope = None
+ if "task_goal_id" in query or "task_todo_id" in query:
+ if not {"turn_id", "message_limit", "task_goal_id", "task_todo_id"} <= query.keys():
+ raise ValueError("a Task receipt requires its Goal, Task and original Turn")
+ task_scope = (query["task_goal_id"][0], query["task_todo_id"][0])
basis = query.get("known_history", [None])[0]
parsed_basis = None
if basis is not None:
@@ -495,7 +544,31 @@ def parse_chat_history_selection(query):
raise ValueError("invalid known history proof")
parsed_basis = (basis, count, proof)
return {"message_limit": limit, "message_cursor": query.get("message_cursor", [None])[0],
- "turn_id": query.get("turn_id", [None])[0], "known_history": parsed_basis}
+ "turn_id": query.get("turn_id", [None])[0], "known_history": parsed_basis, "task_scope": task_scope,
+ "report_message_id": query.get("report_message_id", [None])[0]}
+
+
+def prepare_chat_history_session(store, session_id, selection, *, recover_turn):
+ """Use the existing lifecycle owner only for the execution this read owns."""
+ task_scope = selection["task_scope"]
+ turn_id = selection["turn_id"]
+ if task_scope is None:
+ if turn_id is None and selection["report_message_id"] is None:
+ recover_turn(session_id)
+ return store.load_session(session_id) or {}
+
+ session = store.load_session(session_id) or {}
+ goal_id, todo_id = task_scope
+ if session.get("goal_id") != goal_id or session.get("channel_id") != f"task.{todo_id}":
+ raise ValueError("the original Task Session could not be verified")
+ if selection["message_cursor"] is not None or session.get("active_turn_id") != turn_id:
+ return session
+
+ turn = store.load_turn(session_id, turn_id)
+ if not turn or turn.get("session_id") != session_id or turn.get("turn_id") != turn_id:
+ raise ValueError("the original Task Turn could not be verified")
+ recover_turn(session_id, turn_id)
+ return store.load_session(session_id) or {}
def _visible_history_page_digest(session_id, offset, messages):
@@ -511,8 +584,10 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection,
basis = selection["known_history"]
if basis is None:
snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry,
- project_history_messages=project_history_messages,
- **{key: value for key, value in selection.items() if key != "known_history"})
+ message_limit=selection["message_limit"], message_cursor=selection["message_cursor"],
+ turn_id=selection["turn_id"], project_history_messages=project_history_messages,
+ report_message_id=selection["report_message_id"],
+ include_turn_error=selection["task_scope"] is not None)
snapshot["messages"] = project_provider(snapshot["messages"])
if selection["message_limit"] == 200 and selection["turn_id"] is None:
page = snapshot["message_page"]
@@ -753,10 +828,9 @@ def clock() -> datetime:
# Keep one eligibility instant for the scan. The per-return transaction
# observes its own time after acquiring the route and source guards.
scan_at = clock()
- try:
- exact = load_project_registry(registry).get("profile_id") == SOURCE_SESSION_PROFILE_ID
- except (OSError, ValueError, TypeError):
- exact = False
+ # An unreadable registry cannot authorize legacy delivery. Let the hosted
+ # worker retry the scan without advancing any of its receipts.
+ exact = load_project_registry(registry).get("profile_id") == SOURCE_SESSION_PROFILE_ID
processed = 0
host = {
"root": root, "registry": registry, "store": store,
diff --git a/loopx/capabilities/multi_subagent/cli.py b/loopx/capabilities/multi_subagent/cli.py
index 420a2005ce..5e4fceadec 100644
--- a/loopx/capabilities/multi_subagent/cli.py
+++ b/loopx/capabilities/multi_subagent/cli.py
@@ -11,6 +11,7 @@
from ...control_plane.goals.source_session_registry_state import exact_goal_ref
from ...orchestration import compact_orchestration_policy
from .native_child_receipts import load_native_child_activity, record_native_child
+from .native_child_result_inbox import acknowledge_native_child_result
def register_native_child_commands(subparsers, add_format):
@@ -18,7 +19,7 @@ def register_native_child_commands(subparsers, add_format):
"native-child", help="Record or read typed host-native child activity for an admitted Turn."
)
add_format(parser)
- parser.add_argument("native_child_action", choices=("record", "read"))
+ parser.add_argument("native_child_action", choices=("record", "read", "acknowledge-result"))
parser.add_argument("--goal-id", required=True)
parser.add_argument("--agent-id", required=True)
parser.add_argument("--turn-instance-id", required=True)
@@ -35,6 +36,9 @@ def register_native_child_commands(subparsers, add_format):
"for result/deferred/rejected. Accepted reviews use evidence/validation refs instead.")
parser.add_argument("--evidence-ref", help="Public-safe opaque reference for accepted evidence.")
parser.add_argument("--validation-ref", help="Public-safe opaque reference for parent validation.")
+ parser.add_argument("--result-id", help="Stable native child result identity returned by manager-inbox read.")
+ parser.add_argument("--disposition", choices=("accepted", "deferred", "rejected"),
+ help="Parent disposition after the result was delivered and reviewed.")
parser.add_argument("--execute", action="store_true", help="Append the receipt; otherwise preview only.")
@@ -56,27 +60,46 @@ def handle_native_child_command(args, registry_path, runtime_root, print_payload
goal = load_goal_from_registry(registry_path, args.goal_id)
if goal is None or args.agent_id not in registered_agent_ids_for_goal(goal):
raise ValueError("coordinator is not registered for this Goal")
- orchestration = compact_orchestration_policy(goal.get("spawn_policy"))
- if not (
- orchestration.get("mode") == "multi_subagent"
- and orchestration.get("spawn_allowed") is True
- and int(orchestration.get("max_children") or 0) > 0
- ):
- raise ValueError("native child receipts require enabled multi_subagent policy")
- configured_limit = int(orchestration["max_children"])
+ configured_limit = None
+ if args.native_child_action != "acknowledge-result":
+ orchestration = compact_orchestration_policy(goal.get("spawn_policy"))
+ if not (
+ orchestration.get("mode") == "multi_subagent"
+ and orchestration.get("spawn_allowed") is True
+ and int(orchestration.get("max_children") or 0) > 0
+ ):
+ raise ValueError("native child receipts require enabled multi_subagent policy")
+ configured_limit = int(orchestration["max_children"])
if args.native_child_action == "read":
if any((args.operation_id, args.stage, args.operation, args.outcome,
args.entrypoint_id, args.reason_code, args.evidence_ref,
- args.validation_ref, args.execute)):
+ args.validation_ref, args.result_id, args.disposition, args.execute)):
raise ValueError("read accepts only goal, agent and Turn identity")
payload = {"ok": True, "native_child_activity": load_native_child_activity(
runtime_root, goal_id=args.goal_id, agent_id=args.agent_id,
turn_instance_id=args.turn_instance_id, configured_limit=configured_limit,
registry_path=registry_path, goal_ref=goal_ref,
)}
+ elif args.native_child_action == "acknowledge-result":
+ if any((args.operation_id, args.stage, args.operation, args.outcome,
+ args.entrypoint_id, args.reason_code, args.evidence_ref,
+ args.validation_ref)) or not args.result_id or not args.disposition:
+ raise ValueError("acknowledge-result requires only result-id and disposition")
+ if not args.execute:
+ payload = {"ok": True, "preview": True, "result_id": args.result_id,
+ "disposition": args.disposition}
+ else:
+ payload = acknowledge_native_child_result(
+ runtime_root=runtime_root, goal_id=args.goal_id,
+ agent_id=args.agent_id, turn_instance_id=args.turn_instance_id,
+ result_id=args.result_id,
+ disposition=args.disposition, goal_ref=goal_ref,
+ )
else:
if not args.operation_id or not args.stage or not args.outcome:
raise ValueError("record requires operation-id, stage and outcome")
+ if args.result_id or args.disposition:
+ raise ValueError("record does not accept result acknowledgement fields")
payload = record_native_child(
runtime_root=runtime_root, goal_id=args.goal_id, agent_id=args.agent_id,
turn_instance_id=args.turn_instance_id, operation_id=args.operation_id,
@@ -96,6 +119,11 @@ def handle_native_child_command(args, registry_path, runtime_root, print_payload
def render_native_child(payload):
if not payload["ok"]:
return str(payload["error"])
+ if "native_child_activity" not in payload:
+ return (
+ f"Native child result {payload['result_id']} "
+ f"{'would be ' if payload.get('preview') else ''}{payload['disposition']}."
+ )
activity = payload["native_child_activity"]
return (
f"Native child activity for {activity['turn_instance_id']}: "
diff --git a/loopx/capabilities/multi_subagent/native_child_receipts.py b/loopx/capabilities/multi_subagent/native_child_receipts.py
index 4281a32db4..f7e2f7563f 100644
--- a/loopx/capabilities/multi_subagent/native_child_receipts.py
+++ b/loopx/capabilities/multi_subagent/native_child_receipts.py
@@ -307,6 +307,7 @@ def _record_native_child(
_host_observed: bool = False,
_host_child_refs: Sequence[str] | None = None,
_host_wait_ref: str | None = None,
+ _host_result_text: str | None = None,
) -> dict[str, Any]:
"""Preview or append a typed report; never launch a child or spend quota."""
goal_id = _id(goal_id, field="goal_id")
@@ -335,6 +336,8 @@ def _record_native_child(
if not _host_observed or stage != "result":
raise ValueError("wait correlation requires a host-observed result")
fields["host_wait_ref"] = _id(_host_wait_ref, field="host_wait_ref")
+ if _host_result_text is not None and (not _host_observed or stage != "result" or not execute):
+ raise ValueError("result text requires an executed host-observed result")
log_path = rollout_event_log_path(runtime_root, goal_id)
events = load_rollout_events(log_path)
prior = _events_for_turn(
@@ -442,6 +445,22 @@ def validate_transition(observed: Sequence[Mapping[str, Any]]) -> None:
if fields["outcome"] == "accepted" and _details(result).get("outcome") != "completed":
raise ValueError("accepted parent review requires a completed native child result")
+ def stage_private_result(receipt: Mapping[str, Any]) -> None:
+ if _host_result_text is None:
+ return
+ from .native_child_result_inbox import ingest_native_child_result
+
+ ingest_native_child_result(
+ runtime_root=runtime_root, goal_id=goal_id, agent_id=agent_id,
+ turn_instance_id=turn_instance_id, operation_id=operation_id,
+ outcome=outcome, text=_host_result_text, goal_ref=goal_ref,
+ terminal_event_id=str(receipt["event_id"]),
+ )
+
+ def validate_and_stage() -> None:
+ validate_transition(load_rollout_events(log_path))
+ stage_private_result(event)
+
if not execute:
if existing is None:
validate_transition(prior)
@@ -466,7 +485,7 @@ def validate_transition(observed: Sequence[Mapping[str, Any]]) -> None:
*(("goal_ref",) if goal_ref is not None else ()),
*(("details",) if _host_wait_ref is not None else ()),
),
- precondition=lambda: validate_transition(load_rollout_events(log_path)),
+ precondition=validate_and_stage,
)
if _details(stored) != fields:
raise ValueError("operation identity already has a conflicting native child report")
@@ -474,6 +493,7 @@ def validate_transition(observed: Sequence[Mapping[str, Any]]) -> None:
# Append-once skips its precondition for an exact duplicate. Verify
# the original identity without re-authorizing work or appending.
report_admission()
+ stage_private_result(stored)
events = load_rollout_events(log_path)
else:
stored = existing or event
@@ -501,6 +521,7 @@ def record_native_child(
_host_observed: bool = False,
_host_child_refs: Sequence[str] | None = None,
_host_wait_ref: str | None = None,
+ _host_result_text: str | None = None,
) -> dict[str, Any]:
"""Preview or append one report under its exact quota owner."""
@@ -533,4 +554,5 @@ def record_native_child(
_host_observed=_host_observed,
_host_child_refs=_host_child_refs,
_host_wait_ref=_host_wait_ref,
+ _host_result_text=_host_result_text,
)
diff --git a/loopx/capabilities/multi_subagent/native_child_result_inbox.py b/loopx/capabilities/multi_subagent/native_child_result_inbox.py
new file mode 100644
index 0000000000..1993cc1cb6
--- /dev/null
+++ b/loopx/capabilities/multi_subagent/native_child_result_inbox.py
@@ -0,0 +1,50 @@
+"""Thin Python adapter for the TypeScript native-child result inbox owner."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from ...control_plane.effect_runtime import EffectRuntimeRejected, effect_runtime_result
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def ingest_native_child_result(
+ *, runtime_root: Path, goal_id: str, agent_id: str,
+ turn_instance_id: str, operation_id: str, outcome: str, text: str,
+ goal_ref: Mapping[str, Any] | None = None,
+ terminal_event_id: str,
+) -> dict[str, Any]:
+ try:
+ return effect_runtime_result("multi_subagent.native_result_inbox", {
+ "operation": "ingest", "runtime_root": str(runtime_root.resolve()),
+ "goal_id": goal_id, "agent_id": agent_id,
+ "goal_ref": dict(goal_ref) if goal_ref is not None else None,
+ "turn_instance_id": turn_instance_id, "operation_id": operation_id,
+ "outcome": outcome, "text": text, "terminal_event_id": terminal_event_id, "observed_at": _now(),
+ })
+ except EffectRuntimeRejected as exc:
+ raise ValueError(str(exc)) from exc
+
+
+def acknowledge_native_child_result(
+ *, runtime_root: Path, goal_id: str, agent_id: str,
+ turn_instance_id: str, result_id: str, disposition: str,
+ goal_ref: Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ try:
+ return effect_runtime_result("multi_subagent.native_result_inbox", {
+ "operation": "acknowledge", "runtime_root": str(runtime_root.resolve()),
+ "goal_id": goal_id, "agent_id": agent_id,
+ "goal_ref": dict(goal_ref) if goal_ref is not None else None,
+ "turn_instance_id": turn_instance_id,
+ "result_id": result_id, "disposition": disposition,
+ "observed_at": _now(),
+ })
+ except EffectRuntimeRejected as exc:
+ raise ValueError(str(exc)) from exc
diff --git a/loopx/capabilities/native_chat/codex_adapter.py b/loopx/capabilities/native_chat/codex_adapter.py
index ca62c0f7b1..7fd5dd5d58 100644
--- a/loopx/capabilities/native_chat/codex_adapter.py
+++ b/loopx/capabilities/native_chat/codex_adapter.py
@@ -5,7 +5,9 @@
"""
from __future__ import annotations
-from dataclasses import dataclass, replace
+from contextlib import contextmanager
+from copy import deepcopy
+from dataclasses import dataclass, field, replace
import hashlib
import json
import logging
@@ -737,6 +739,7 @@ def turns() -> list[dict[str, Any]]:
class CodexAppServerAdapter:
session: CodexChatAgentSession
goal_driver: CodexGoalDriver | None = None
+ _managed_read_turn_guard: Callable[[], None] | None = field(default=None, repr=False)
def completed_work_observation(self, *, thread_ids: list[str], turn_id: str,
known_turn_ids: set[str] | None = None) -> dict[str, Any] | None:
@@ -1004,7 +1007,32 @@ def capabilities(self) -> dict[str, Any]:
}
def start_turn(self, message: str, event_sink: Callable[[str, dict[str, Any]], None]) -> dict[str, Any]:
- return self.session.send(message, on_event=event_sink)
+ return self.session.send(message, on_event=event_sink, **self._ordinary_turn_arguments())
+
+ def _ordinary_turn_arguments(self):
+ check = self._managed_read_turn_guard
+ if check is None:
+ return {}
+ previous_guard = self.session._launch_guard
+ @contextmanager
+ def read_turn():
+ check()
+ if previous_guard is None:
+ yield
+ else:
+ with previous_guard():
+ check()
+ yield
+ # Native sandboxPolicy is sticky across subsequent Turns. Reassert the
+ # current managed Chat read boundary without changing Session defaults.
+ return {"sandbox_policy": {"type": "readOnly", "networkAccess": False},
+ "turn_start_guard": read_turn}
+
+ def start_native_task_turn(self, message: str,
+ event_sink: Callable[[str, dict[str, Any]], None], policy: dict[str, object]) -> dict[str, Any]:
+ """Transport one Core-admitted Task through its existing launch fence."""
+ return self.session.send(message, on_event=event_sink, _native_task=True,
+ sandbox_policy=deepcopy(policy), turn_start_guard=self.session._launch_guard)
def steer_turn(self, message: str, expected_turn_id: str, client_message_id: str | None = None) -> str:
return self.session.steer(message, expected_turn_id=expected_turn_id,
@@ -1021,7 +1049,8 @@ def start_turn_with_attachments(
event_sink: Callable[[str, dict[str, Any]], None],
attachments: list[dict[str, Any]],
) -> dict[str, Any]:
- return self.session.send(message, attachments=attachments, on_event=event_sink)
+ return self.session.send(message, attachments=attachments, on_event=event_sink,
+ **self._ordinary_turn_arguments())
def interrupt_turn(self, turn_id: str | None = None) -> None:
driver = self.goal_driver
@@ -1053,6 +1082,60 @@ def start_attachment_turn(adapter: Any, session: dict[str, Any], turn: dict[str,
return adapter.start_turn_with_attachments(message, event_sink, attachments)
+def prepare_native_turn_text(session: CodexChatAgentSession, user_message: str, *,
+ output_schema, project_collaboration: bool, native_task: bool,
+ sandbox_policy, turn_start_guard):
+ """Preserve Chat input validation; adapt only the fenced Task invocation.
+
+ The Core caller owns Task/lease/permission admission. This transport cannot
+ manufacture that grant from a policy dictionary or a model/browser payload.
+ """
+ text = str(user_message or "")
+ if not text.strip():
+ raise ValueError("user message is required")
+ if native_task:
+ workspace_policy = {"type": "workspaceWrite", "writableRoots": [str(session.work_dir.resolve())],
+ "networkAccess": False, "excludeTmpdirEnvVar": True, "excludeSlashTmp": True}
+ if (turn_start_guard is None or session._launch_guard is None
+ or turn_start_guard is not session._launch_guard
+ or sandbox_policy not in ({"type": "readOnly", "networkAccess": False}, workspace_policy)
+ or session.execution_mode or session.read_only_review or session.project_context is not None
+ or session.permissions_profile is not None or session.sandbox != "read-only"):
+ raise ValueError("native Task transport requires the original read-only Session, bound workspace policy and current host launch guard")
+ elif sandbox_policy is not None and sandbox_policy != {"type": "readOnly", "networkAccess": False}:
+ raise ValueError("an ordinary Chat Turn cannot install a native execution policy")
+ if sandbox_policy is not None and session.permissions_profile is not None:
+ raise ValueError("a native sandbox policy cannot replace an existing named permissions profile")
+ if session.read_only_review and not session.metadata_review and not session.answer_review:
+ text = (
+ "Review the existing results of the interrupted original request below. "
+ "Its earlier execution may have already changed files or external systems. "
+ "Use the original native history and current local artifacts to verify what actually happened. "
+ "This Turn is read-only: do not re-execute the business request, write, send, delegate or start background work. "
+ "Return a clear answer to the original user, distinguishing verified results from remaining gaps. "
+ "If verification is incomplete, report the concrete limitation; do not claim completion. "
+ "Original request: " + text
+ )
+ if project_collaboration:
+ if (session.execution_mode or session.read_only_review or output_schema is not None
+ or not session.project_context or session.project_context.get("audience") != "bound_owner"):
+ raise ValueError("original project collaboration requires its existing bound project session")
+ from ...control_plane.effect_runtime import effect_runtime_result
+ output_schema = effect_runtime_result("collaboration.project.response_schema", {})
+ if output_schema is not None and not session.execution_mode and not project_collaboration and not native_task:
+ raise ValueError("structured Turn output requires an execution session")
+ return text, output_schema
+
+
+def native_runtime_context(controller: ChatRuntimeController, *, goal_id: str | None,
+ objective: str, manager_profile: Mapping[str, object] | None,
+ project_coordination: bool, execution_mode: bool) -> dict[str, str]:
+ """Compose the shared native adapter inputs in their construction owner."""
+ return {"objective": controller._session_objective(goal_id=goal_id, objective=objective,
+ project_coordination=project_coordination and not execution_mode),
+ "runtime_profile": str(manager_profile["runtime_profile"]) if manager_profile else "restricted"}
+
+
def start_runtime_adapter(controller: ChatRuntimeController, *, work_dir: Path, goal_id: str | None,
native_context: Mapping[str, str], manager_profile: Mapping[str, object] | None,
model_config: Mapping[str, str | None], history: list[dict[str, str]] | None,
@@ -1061,13 +1144,16 @@ def start_runtime_adapter(controller: ChatRuntimeController, *, work_dir: Path,
read_only_review: bool, metadata_review_context: dict[str, object] | None,
answer_review_context: dict[str, object] | None,
history_check: Callable[[], None] | None = None,
- working_continuation: NativeWorkingContinuation | None = None) -> CodexAppServerAdapter:
+ working_continuation: NativeWorkingContinuation | None = None,
+ check_preparation: bool = False,
+ managed_read_default: bool = False) -> CodexAppServerAdapter:
"""Build the native adapter from already-authorized runtime arguments."""
from ...chat_manager import MANAGER_AGENT_GOAL_ID
from ..manager_context.inspection import READ_TOOL, CONTEXT_READ_TOOL
from ...chat_loopx_mode import TOOL as COLLABORATION_TOOL
+ from ...chat.coordination import check_preparation_tool
review_context = metadata_review_context or answer_review_context
- return CodexAppServerAdapter.start(
+ adapter = CodexAppServerAdapter.start(
codex_bin=controller.codex_bin,
account_runtime_root=controller.coordination_runtime_root,
account_consumer="steward" if manager_profile is not None or review_context is not None else "worker",
@@ -1101,8 +1187,13 @@ def start_runtime_adapter(controller: ChatRuntimeController, *, work_dir: Path,
service_tier=model_config.get("service_tier"),
dynamic_tools=[READ_TOOL] if answer_review_context else (
[READ_TOOL] if goal_id == MANAGER_AGENT_GOAL_ID
- else [CONTEXT_READ_TOOL, *([COLLABORATION_TOOL] if loopx_tools else [])]
+ else [CONTEXT_READ_TOOL, *([COLLABORATION_TOOL] if loopx_tools else
+ [check_preparation_tool()] if check_preparation and resume_thread_id is None
+ and working_continuation is None else [])]
) if not execution_mode and not read_only_review and (
goal_id == MANAGER_AGENT_GOAL_ID or project_coordination
) else None,
)
+ if managed_read_default:
+ adapter.session._managed_goal_read_default = True
+ return adapter
diff --git a/loopx/capabilities/native_chat/conversation_bindings.py b/loopx/capabilities/native_chat/conversation_bindings.py
index db9821d0ea..a38ac0d472 100644
--- a/loopx/capabilities/native_chat/conversation_bindings.py
+++ b/loopx/capabilities/native_chat/conversation_bindings.py
@@ -270,7 +270,13 @@ def _reconcile_steward_executor(self, row: dict[str, Any], defaults: Mapping[str
raise OSError("steward executor binding publication did not verify")
def app_steward_target(self) -> dict[str, Any]:
- """Discover within the selected source; opening creates no execution."""
+ session = self.app_steward_session()
+ if session is None:
+ return {"binding_id": None, "session_id": None}
+ return {"binding_id": session["steward_context"]["binding_id"], "session_id": session["session_id"]}
+
+ def app_steward_session(self) -> dict[str, Any] | None:
+ """Read the Session within the selected source without starting work."""
current = self.read()
selected = current.get("app_steward_binding_id")
if selected is None:
@@ -278,14 +284,23 @@ def app_steward_target(self) -> dict[str, Any]:
# unreadable grant must not masquerade as an unselected entry.
self._core("collaboration.conversation.binding", {"current": current,
"expected_revision": current.get("revision"), "operation": "select_app_steward", "binding_id": None})
- return {"binding_id": None, "session_id": None}
- sessions = self.local_sessions(selected, app_steward_entry=True)
+ return None
+ current, sessions, _ = self._observe_local_sessions(selected, app_steward_entry=True)
if not sessions:
raise ValueError("the original steward Session is unavailable")
session = max(sessions, key=lambda item: (item.get("last_activity_at") or "", item["session_id"]))
- if self.read().get("app_steward_binding_id") != selected:
- raise ValueError("App steward selection changed during discovery")
- return {"binding_id": selected, "session_id": session["session_id"]}
+ # Close uses the same Session fences. Keep it from committing between
+ # this read and the final grant decision; grant revocation still races
+ # freely and is detected by the version check. All provider/Core IO has
+ # already completed, and background grant inspection remains nonblocking.
+ with self.controller.store.read_session_fenced(session["session_id"]) as fresh:
+ if fresh is None or fresh.get("status") == "closed":
+ raise ValueError("the original steward Session is unavailable")
+ expected = {**self._session_observation(session), "status": fresh.get("status")}
+ if self._session_observation(fresh) != expected:
+ raise ValueError("the original steward Session is unavailable")
+ self._recheck_local_bindings(current)
+ return fresh
def _revoke_delivery_sources(self, binding_id: str) -> None:
if self.controller is not None:
@@ -410,6 +425,19 @@ def local_sessions(self, binding_id: str, *, app_steward_entry: bool = False) ->
return self.local_session_snapshot(binding_id, app_steward_entry=app_steward_entry)["sessions"]
def local_session_snapshot(self, binding_id: str, *, app_steward_entry: bool = False) -> dict[str, Any]:
+ current, sessions, source = self._observe_local_sessions(binding_id, app_steward_entry=app_steward_entry)
+ payload = {"sessions": [self.controller.store.public_session(session) for session in sessions],
+ "conversation_source": source}
+ self._recheck_local_bindings(current)
+ return payload
+
+ def _recheck_local_bindings(self, observed: dict[str, Any]) -> None:
+ if self.read() != observed:
+ raise ValueError("conversation binding changed during discovery")
+
+ def _observe_local_sessions(
+ self, binding_id: str, *, app_steward_entry: bool,
+ ) -> tuple[dict[str, Any], list[dict[str, Any]], dict[str, Any]]:
"""Read original targets; metadata hints never replace Core's grant.
This read-only snapshot does not wait for a mutation fence. Core checks
@@ -453,16 +481,13 @@ def mentions_binding(session: dict[str, Any]) -> bool:
# an IO dictionary must not silently turn ambiguity into one target.
by_id = {session["session_id"]: session for session in sessions}
project = next(project for project in projects if project["project_ref"] == row["project_ref"])
- payload = {"sessions": [store.public_session(by_id[sid]) for sid in result["session_ids"]],
- "conversation_source": {"binding_id": binding_id, "app_ref": row["transport_ref"],
- "context_kind": row["context_kind"], "audience": row.get("audience", "owner"),
- "project_title": Path(project["workspace_path"]).name, "context_available": True,
- "executor_endpoint_id": row["executor_endpoint_id"]}}
+ source = {"binding_id": binding_id, "app_ref": row["transport_ref"],
+ "context_kind": row["context_kind"], "audience": row.get("audience", "owner"),
+ "project_title": Path(project["workspace_path"]).name, "context_available": True,
+ "executor_endpoint_id": row["executor_endpoint_id"]}
# Bind the projection to the exact atomic configuration Core checked.
# This is not an execution grant or a cached provider observation.
- if self.read() != current:
- raise ValueError("conversation binding changed during discovery")
- return payload
+ return current, [by_id[sid] for sid in result["session_ids"]], source
def goal_scope_ids(self, binding: dict[str, Any]) -> list[str]:
if binding.get("goal_scope") != "all_registered":
diff --git a/loopx/capabilities/native_chat/creation_queue.py b/loopx/capabilities/native_chat/creation_queue.py
new file mode 100644
index 0000000000..ff7753938d
--- /dev/null
+++ b/loopx/capabilities/native_chat/creation_queue.py
@@ -0,0 +1,131 @@
+"""IO for the original creation request; the existing Session queue executes it."""
+from pathlib import Path
+from typing import Any
+import logging
+
+def creation_request_facts(controller: Any, session_id: str, *, proposal_id: str | None = None,
+ basis: dict[str, Any] | None = None) -> dict[str, Any] | None:
+ actions = getattr(controller, "original_task_action_store", None)
+ if actions is None:
+ return None
+ session = controller.store.load_session(session_id)
+ if not session or not session.get("managed_agent_id"):
+ return None
+ candidates = [actions.load(proposal_id)] if proposal_id is not None else actions.list()
+ candidates = [row for row in candidates if isinstance(row, dict)
+ and row.get("action_kind") == "goal.create"
+ and (row.get("normalized_parameters") or {}).get("start_execution") is True
+ and (row.get("normalized_parameters") or {}).get("goal_id") == session.get("goal_id")
+ and (((row.get("checkpoint") or {}).get("steps") or {}).get("first_session_opened") or {}).get(
+ "session_id") == session_id]
+ if not candidates:
+ return None
+ # Candidate filtering is IO narrowing, not authorization. Only explicit
+ # same-Session source candidates load native/canonical owners below.
+ from .steward_managed_mode import StewardManagedMode
+ from ...control_plane.effect_runtime import effect_runtime_result, EffectRuntimeRejected
+ from ...control_plane.goals.acceptance import inspect_goal_acceptance
+
+ goal = StewardManagedMode(controller, None)._goal(session.get("goal_id"))
+ if goal is None:
+ return None
+ # This registered creation identity is the action owner's proposal key,
+ # not a label or a parsed operation prefix.
+ source = proposal_id if proposal_id is not None else goal.get("creation_operation_id")
+ if not isinstance(source, str) or not source:
+ return None
+ proposal = next((row for row in candidates if row["proposal_id"] == source), None)
+ if (proposal is None or proposal.get("action_kind") != "goal.create"
+ or (proposal.get("normalized_parameters") or {}).get("start_execution") is not True):
+ return None
+ if basis is None:
+ basis = inspect_goal_acceptance(registry_path=controller.registry_path,
+ runtime_root=str(controller.coordination_runtime_root), goal_id=goal["goal_id"],
+ agent_id=session["managed_agent_id"], validation_workspace_path=Path(goal["workspace_path"]))
+ try:
+ selected = effect_runtime_result("goal.task.creation_selection", {"basis": basis})
+ except EffectRuntimeRejected as exc:
+ raise ValueError(str(exc)) from exc
+ return {"proposal": proposal, "session": session, "goal": goal, "current_original_task": selected}
+
+
+def project_creation_request(facts: dict[str, Any] | None) -> dict[str, Any] | None:
+ if facts is None:
+ return None
+ from ...control_plane.effect_runtime import effect_runtime_result, EffectRuntimeRejected
+ try:
+ request = effect_runtime_result("goal.creation.execution_request", facts)
+ except EffectRuntimeRejected as exc:
+ raise ValueError(str(exc)) from exc
+ if request is not None and not isinstance(request, dict):
+ raise ValueError("original creation request projection returned an invalid result")
+ return request
+
+
+def consume_creation_request(controller: Any, session_id: str) -> bool:
+ """Return whether this creation needs attention, never replaying its Turn."""
+ facts = creation_request_facts(controller, session_id)
+ if facts is None or facts["proposal"].get("status") not in ("applying", "applied"):
+ return False
+ if not isinstance(((facts["proposal"].get("checkpoint") or {}).get("steps") or {}).get(
+ "original_task_requested"), dict):
+ return False
+ try:
+ request = project_creation_request(facts)
+ if request is None:
+ return True # The same creation has not committed its request yet.
+ from .steward_managed_mode import ManagedSessionTurn
+ return ManagedSessionTurn(controller).consume_creation_request(request)
+ except (ValueError, RuntimeError) as exc:
+ # Missing/changed checks or source authority leave the saved request
+ # open. A content-free action/Turn signal or restart rechecks it.
+ logging.getLogger(__name__).debug("Original creation request retained: %s", exc)
+ return True
+
+
+def queued_turn_unstarted(turn: dict[str, Any]) -> bool:
+ """Unknown native publication facts cannot authorize a queue dispatch."""
+ return (turn.get("status") == "queued" and "_acceptance" not in turn
+ and "started_at" in turn and turn["started_at"] is None
+ and "upstream_turn_id" in turn and turn["upstream_turn_id"] is None
+ and type(turn.get("delta_count")) is int and turn["delta_count"] == 0)
+
+
+def resume_creation_requests(controller: Any) -> None:
+ """Discover only saved requests at service setup; hints grant no execution."""
+ actions = getattr(controller, "original_task_action_store", None)
+ if actions is None or controller.closed.is_set():
+ return
+ for proposal in actions.list():
+ if (proposal.get("action_kind") != "goal.create"
+ or (proposal.get("normalized_parameters") or {}).get("start_execution") is not True):
+ continue
+ request = (proposal.get("receipt") or {}).get("original_task_request")
+ if not isinstance(request, dict):
+ continue
+ session_id = request.get("session_id")
+ if not isinstance(session_id, str):
+ continue
+ try:
+ facts = creation_request_facts(controller, session_id, proposal_id=proposal["proposal_id"])
+ qualified = project_creation_request(facts)
+ if qualified is None or qualified != request:
+ continue
+ existing = controller.store.turn_for_client(session_id, "managed." + qualified["operation_id"])
+ if existing is not None:
+ if not queued_turn_unstarted(existing):
+ continue
+ from .steward_managed_mode import ManagedSessionTurn
+ expected = ManagedSessionTurn(controller)._request(session_id, qualified["agent_id"],
+ qualified["operation_id"], qualified["todo_id"])
+ expected["creation_request"] = qualified
+ if existing.get("loopx_request") != expected:
+ continue
+ session = facts["session"]
+ except (KeyError, OSError, ValueError, RuntimeError):
+ # A malformed candidate cannot wake another Session's queue. Its
+ # current-source refusal remains available through the Task GET.
+ continue
+ controller.resume_session_queue(session_id=session_id,
+ work_dir=Path(session["managed_workspace_path"]),
+ objective="Continue the original Goal's requested Task.")
diff --git a/loopx/capabilities/native_chat/external_conversations.py b/loopx/capabilities/native_chat/external_conversations.py
index 8e08e0f06e..afa5d25983 100644
--- a/loopx/capabilities/native_chat/external_conversations.py
+++ b/loopx/capabilities/native_chat/external_conversations.py
@@ -6,8 +6,9 @@
"""
from __future__ import annotations
-from collections.abc import Callable, Mapping, Sequence
+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from copy import deepcopy
+from functools import cache
from pathlib import Path
import hashlib
import json
@@ -26,7 +27,7 @@
from ...file_lock import exclusive_file_lock, try_exclusive_file_lock
from . import result_review_evidence
from .codex_context import checked_session_home
-from .file_discovery import FileChatDiscovery
+from .file_discovery import FileChatDiscovery, external_source_route_path, later_equivalent_source_input, source_control_fields
# Request journals are named by their 24-hex request_ref; lock metadata and
# other siblings in this directory are not requests.
@@ -105,6 +106,7 @@ def __init__(self, controller: Any) -> None:
self.bindings.controller = controller
self.root = controller.store.root / "external-requests"
self._source_control_discovery = FileChatDiscovery()
+ self._backlog_request_discovery = FileChatDiscovery()
self.actions: Any | None = None
def _retained_result_review(self, row: dict[str, Any]) -> dict[str, Any] | None:
@@ -187,6 +189,8 @@ def _context_recovery_plan(self, row: dict[str, Any], *,
_, open_literal, _ = _review_openings(str((turn.get("response") or {}).get("message") or ""), 0)
preparation = None
later_equivalent = None
+ read_source_controls = (discovery_reads.source_controls if discovery_reads is not None
+ else cache(self.source_controls))
image_failure = turn.get("error_code") == "runtime_error" and bool(row.get("attachments"))
runtime_failure = turn.get("error_code") in {"model_auth_unavailable", "resume_failed"}
if turn.get("error_code") == "manager_authorization_unavailable" or image_failure or runtime_failure:
@@ -207,6 +211,10 @@ def _context_recovery_plan(self, row: dict[str, Any], *,
and datetime.fromisoformat(item["created_at"]) > created
for item in (discovery_reads.user_messages(session["session_id"])
if discovery_reads is not None else store.messages(session["session_id"])))
+ elif turn.get("status") == "failed" and session.get("agent_id") == "codex":
+ # Native history cannot see a newer request that is still in the FIFO.
+ # Read the Core receipt when the source journal has not settled yet.
+ later_equivalent = later_equivalent_source_input(row, read_source_controls, store.turn_for_client)
from ...chat_manager import steward_machine_defaults
recovery_row = {key: value for key, value in row.items() if key != "attachments"}
review_preparation = None
@@ -239,15 +247,14 @@ def _context_recovery_plan(self, row: dict[str, Any], *,
"attachments_present": bool(row.get("attachments")),
"steering_observed": any(event.get("kind") == "turn.steered" for event in events),
"stop_observed": self._source_stop_observed(row, turn, events,
- source_controls=discovery_reads.source_controls if discovery_reads is not None else None),
+ source_controls=read_source_controls),
"preparation_observation": preparation,
"later_equivalent_input_present": later_equivalent,
"preparation_scope_available": preparation_scope_available,
"later_source_input_present": any(item.get("binding_id") == row["binding_id"]
and item.get("source") == row["source"] and item.get("command") is None
and datetime.fromisoformat(item["created_at"]) > datetime.fromisoformat(row["created_at"])
- for item in (discovery_reads.source_controls() if discovery_reads is not None
- else self.source_controls())) if turn.get("error_code") == "antigravity_step_error" else None,
+ for item in read_source_controls()) if turn.get("error_code") == "antigravity_step_error" else None,
"native_input": anchors[0] if len(anchors) == 1 else None,
**({"retained_result_review": retained_review} if retained_review is not None else {}),
**({"live_work_owner": live_work_owner} if unfinished or related_review is not None else {}),
@@ -283,20 +290,25 @@ def _source_stop_observed(self, row: dict[str, Any], turn: dict[str, Any],
and datetime.fromisoformat(item["created_at"]) >= datetime.fromisoformat(row["created_at"])
for item in (source_controls or self.source_controls)())))
- def quota_backlog_observer(self) -> Callable[[Sequence[dict[str, Any]]], list[bool]]:
- """Batch the existing typed projection; share controls only within this read."""
- controls: list[dict[str, Any]] | None = None
-
- def read_controls() -> list[dict[str, Any]]:
- nonlocal controls
- if controls is None:
- controls = self.source_controls()
- return controls
+ def quota_backlog_observer(
+ self, *, source_controls: Callable[[], list[dict[str, Any]]] | None = None,
+ ) -> Callable[[Sequence[dict[str, Any]]], list[bool]]:
+ """Read Session state after each batch's Turns and share source controls across batches."""
+ read_controls = cache(source_controls or self.source_controls)
def observe(rows: Sequence[dict[str, Any]]) -> list[bool]:
if len(rows) > QUOTA_BACKLOG_BATCH_SIZE:
raise ValueError("select at most 64 pending requests per observation")
params = [self._quota_pending_inputs(row) for row in rows]
+ load_session = self.controller.store.load_session
+ sessions = {}
+ for session_id in dict.fromkeys(row["session_id"] for row in rows):
+ # A transient read failure must not mask a closed Session.
+ session = load_session(session_id) or load_session(session_id)
+ sessions[session_id] = ({key: session[key] for key in ("session_id", "status") if key in session}
+ if session is not None else None)
+ for row, values in zip(rows, params, strict=True):
+ values["current_session"] = sessions[row["session_id"]]
flags = self._quota_pending_flags(params)
stopped = []
for index, (row, values, pending) in enumerate(zip(rows, params, flags, strict=True)):
@@ -351,15 +363,9 @@ def flush() -> None:
return flags
def _quota_pending_inputs(self, row: dict[str, Any]) -> dict[str, Any]:
- store = self.controller.store
- turn = store.load_turn(row["session_id"], row["turn_id"])
- session = store.load_session(row["session_id"])
- # Keep the full request/response evidence. The related Session and
- # Turn need only identity, lifecycle and result for this read.
+ turn = self.controller.store.load_turn(row["session_id"], row["turn_id"])
return {
"request": {key: value for key, value in row.items() if key != "attachments"},
- "current_session": ({key: session[key] for key in ("session_id", "status") if key in session}
- if session is not None else None),
"pending_observation": {
"turn": ({key: turn[key] for key in ("session_id", "turn_id", "client_turn_id", "status",
"error_code", "response") if key in turn} if turn is not None else None),
@@ -370,22 +376,7 @@ def _quota_pending_inputs(self, row: dict[str, Any]) -> dict[str, Any]:
def quota_backlog_pending(self, row: dict[str, Any], *,
source_controls: Callable[[], list[dict[str, Any]]] | None = None) -> bool:
"""Retain quota and declared unfinished work without admitting recovery."""
- from ...control_plane.effect_runtime import effect_runtime_result
-
- params = self._quota_pending_inputs(row)
- observation = params["pending_observation"]
- turn = observation["turn"]
- # The typed owner first excludes work that has no retained obligation even
- # without a stop. Stop evidence can only remove a pending request;
- # never expose a positive result before reading those native facts.
- if effect_runtime_result("collaboration.conversation.request", params).get("pending") is not True:
- return False
- assert turn is not None # Required by the typed pending projection.
- events = self.controller.store.events_after(row["session_id"], row["turn_id"], None)
- if self._source_stop_observed(row, turn, events, source_controls=source_controls):
- observation["stop_observed"] = True
- return effect_runtime_result("collaboration.conversation.request", params).get("pending") is True
- return True
+ return self.quota_backlog_observer(source_controls=source_controls)([row])[0]
def context_recovery_observer(self) -> Callable[[str], bool]:
"""Reuse scan-local hints; reread each request, Turn and binding."""
@@ -557,7 +548,7 @@ def source_requests() -> list[dict[str, Any]]:
# route already owns the fence, leave this request unchanged for
# the existing worker's next fresh visit, rather than admitting
# from an observation that waited behind that route.
- with try_exclusive_file_lock(self.root / "source-fences" / f"{row['binding_id']}.{row['source']['source_ref']}.json", operation="route_external_chat_request") as acquired:
+ with try_exclusive_file_lock(external_source_route_path(self.root, row["binding_id"], row["source"]["source_ref"]), operation="route_external_chat_request") as acquired:
if acquired is None:
return row
current = self.bindings.read()
@@ -749,7 +740,7 @@ def _recover_native_result(self, path: Path, row: dict[str, Any], session: dict[
proof = recovered.get("native_observation")
selected = self.bindings.resolve(binding_id=row["binding_id"], **row["source"], include_observation=True)
source = source_observation(selected)
- with try_exclusive_file_lock(self.root / "source-fences" / f"{row['binding_id']}.{row['source']['source_ref']}.json",
+ with try_exclusive_file_lock(external_source_route_path(self.root, row["binding_id"], row["source"]["source_ref"]),
operation="route_external_chat_request") as acquired:
if acquired is None:
return row
@@ -835,8 +826,7 @@ def admit_history_answer(self, *, binding_id: str, source: dict[str, Any], reque
raise ValueError("invalid historical answer source")
path = self.root / f"{request_ref}.json"
with exclusive_file_lock(path, operation="admit_external_chat_request"):
- with exclusive_file_lock(self.root / "source-fences" / f"{binding_id}.{source['source_ref']}.json",
- operation="route_external_chat_request"):
+ with exclusive_file_lock(external_source_route_path(self.root, binding_id, source["source_ref"]), operation="route_external_chat_request"):
selected = self.bindings.resolve(binding_id=binding_id, **source, include_observation=True)
if source_preflight(deepcopy(selected)) is not None:
raise ValueError("source preflight must verify or raise")
@@ -1376,11 +1366,70 @@ def _automation_cadence_observation(
reason="owner_read_failed",
)
+ def _source_session(self, selected: dict[str, Any], target: dict[str, Any] | None):
+ controller = self.controller
+ steward_candidate = authority = None
+ if target:
+ authority = self.bindings.resolve_agent_target(selected, target)
+ # Observation must retain failed or closed originals, so read the
+ # exact frozen target Session without lifecycle filtering.
+ current = next((candidate for candidate in controller.store.session_candidates(
+ goal_id=None, agent_id=selected["binding"]["executor_endpoint_id"],
+ channel_id=selected["channel_id"])
+ if candidate.get("session_id") == target["session_id"]),
+ controller.store.load_session(target["session_id"]))
+ else:
+ current = controller.store.latest_session(goal_id=None,
+ agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"])
+ if selected["binding"]["context_kind"] == "steward":
+ # A quota fallback keeps the original channel, source and Core
+ # Session. Agent filtering must not create another consumer or
+ # fork the conversation when its actual endpoint changed.
+ candidates = [item for item in controller.store.list_sessions(channel_id=selected["channel_id"])
+ if item.get("status") in RESUMABLE_SESSION_STATES]
+ if candidates:
+ latest = max(candidates, key=lambda item: str(item.get("created_at") or ""))
+ steward_candidate = controller.store.load_session(latest["session_id"])
+ allocation = (steward_candidate or {}).get("manager_executor_allocation")
+ if isinstance(allocation, dict) and allocation.get("selection_policy") == "flexible":
+ self.bindings.session_context(steward_candidate["steward_context"], session=steward_candidate)
+ current = steward_candidate
+ return current, steward_candidate, authority
+
+ def capture_native_mention(self, binding: dict[str, Any], source: dict[str, Any]) -> dict[str, Any]:
+ """Observe local identities before provider IO, without granting input.
+
+ Do not wait behind an in-flight source admission. Current routing and
+ grants are checked again before the frozen target can receive anything.
+ """
+ choices = [item for item in self.pending() if item.get("binding_id") == binding["binding_id"]
+ and item["source"]["source_ref"] == source["source_ref"] and item.get("selection_recorded")]
+ previous = max(choices, key=lambda item: item.get("selection_order", 0)) if choices else None
+ target = previous.get("selection_target") if previous else None
+ current = self.controller.store.load_session(target["session_id"]) if target else None
+ if not target:
+ candidates = []
+ for _, session in self.controller.store.iter_session_metadata():
+ saved = session.get("steward_context") or session.get("project_context") or {}
+ allocation = session.get("manager_executor_allocation") or {}
+ if (saved.get("binding_id") == binding["binding_id"]
+ and saved.get("source_ref") == source["source_ref"]
+ and session.get("status") in RESUMABLE_SESSION_STATES
+ and (session.get("agent_id") == binding["executor_endpoint_id"]
+ or binding["context_kind"] == "steward" and allocation.get("selection_policy") == "flexible")):
+ candidates.append(session)
+ current = max(candidates, key=lambda item: str(item.get("created_at") or ""), default=None)
+ return {"session_id": (current or {}).get("session_id"),
+ "target_turn_id": (current or {}).get("active_turn_id") or None,
+ "channel_id": (current or {}).get("channel_id")}
+
def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str,
message: str, command: str | None = None,
attachments: list[dict[str, Any]] | None = None,
origin: str = "lark", defer_background_stop: bool = False,
- source_preflight: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]:
+ source_preflight: Callable[[dict[str, Any]], None] | None = None,
+ native_mention: bool = False,
+ native_mention_capture: dict[str, Any] | None = None) -> dict[str, Any]:
import re
if origin not in {"lark", "external"}:
raise ValueError("unsupported external conversation origin")
@@ -1390,6 +1439,8 @@ def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str,
raise ValueError("unsupported external conversation command")
if source_preflight is not None and not callable(source_preflight):
raise ValueError("source preflight must be an in-process verifier")
+ if type(native_mention) is not bool or native_mention and (source_preflight is None or command is not None):
+ raise ValueError("native mentions require their original provider preflight")
# These references enter the lock path before authority is resolved.
# Check path-safe shape here; the typed owner checks current grants
# and provider identity after both fences are acquired.
@@ -1400,12 +1451,17 @@ def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str,
# A duplicate waits on its own request before taking the route fence;
# it must not hold up other messages while native cancellation runs.
with exclusive_file_lock(path, operation="admit_external_chat_request"):
- with exclusive_file_lock(self.root / "source-fences" / f"{binding_id}.{source['source_ref']}.json", operation="route_external_chat_request"):
+ with exclusive_file_lock(external_source_route_path(self.root, binding_id, source["source_ref"]),
+ operation="route_external_chat_request"):
# Resolve and verify the source inside both fences before
# creating or replaying any canonical request.
- selected = resolve_external_admission_source(self.bindings, binding_id, source, source_preflight)
+ # Freeze a mention's original Session/Turn before its fenced
+ # source IO. A slow verifier cannot retarget a later Turn.
+ selected = resolve_external_admission_source(self.bindings, binding_id, source,
+ None if native_mention else source_preflight)
expected = {"binding_id": binding_id, "source": source, "message": message, "command": command,
- "attachments": normalize_chat_image_attachments(attachments) or None, "origin": origin}
+ "attachments": normalize_chat_image_attachments(attachments) or None, "origin": origin,
+ **({"native_mention": True, "mention_capture": deepcopy(native_mention_capture)} if native_mention else {})}
recovering_request = path.exists()
if recovering_request:
row = _read_json(path)
@@ -1451,7 +1507,8 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A
*, recovering_request: bool = False,
source_preflight: Callable[[dict[str, Any]], None] | None = None) -> dict[str, Any]:
controller = self.controller
- selected = ensure_external_admission_scope(self.bindings, selected, path, row, source_preflight=source_preflight)
+ selected = ensure_external_admission_scope(self.bindings, selected, path, row,
+ source_preflight=None if row.get("native_mention") else source_preflight)
held_for_binding = row.get("response_code") == STEWARD_BINDING_ADOPTION_PENDING
if held_for_binding:
row.pop("response_code")
@@ -1466,32 +1523,9 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A
row["agent_target"] = None
target = row.get("agent_target")
steward_candidate = None
- if target:
- authority = self.bindings.resolve_agent_target(selected, target)
+ current, steward_candidate, authority = self._source_session(selected, target)
+ if authority:
row["agent_audience"] = authority["audience"]
- # Observation must retain failed or closed originals, so read the
- # exact frozen target Session without lifecycle filtering.
- current = next((candidate for candidate in controller.store.session_candidates(
- goal_id=None, agent_id=selected["binding"]["executor_endpoint_id"],
- channel_id=selected["channel_id"])
- if candidate.get("session_id") == target["session_id"]),
- controller.store.load_session(target["session_id"]))
- else:
- current = controller.store.latest_session(goal_id=None,
- agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"])
- if selected["binding"]["context_kind"] == "steward":
- # A quota fallback keeps the original channel, source and Core
- # Session. Agent filtering must not create another consumer or
- # fork the conversation when its actual endpoint changed.
- candidates = [item for item in controller.store.list_sessions(channel_id=selected["channel_id"])
- if item.get("status") in RESUMABLE_SESSION_STATES]
- if candidates:
- latest = max(candidates, key=lambda item: str(item.get("created_at") or ""))
- steward_candidate = controller.store.load_session(latest["session_id"])
- allocation = (steward_candidate or {}).get("manager_executor_allocation")
- if isinstance(allocation, dict) and allocation.get("selection_policy") == "flexible":
- self.bindings.session_context(steward_candidate["steward_context"], session=steward_candidate)
- current = steward_candidate
if row["command"] in {"status", "help"} and not target:
# Observation must retain failed/closed originals. Admission still
# uses the resumable selector and never resumes from this snapshot.
@@ -1500,6 +1534,8 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A
agent_id=selected["binding"]["executor_endpoint_id"], channel_id=selected["channel_id"]))
snapshot = max(candidates, key=lambda candidate: str(candidate.get("updated_at") or ""), default=None)
current = controller.store.load_session(snapshot["session_id"]) if snapshot else None
+ if row.get("native_mention") and (row.get("mention_capture") or {}).get("session_id"):
+ row["session_id"] = row["mention_capture"]["session_id"]
if row.get("session_id") and row["command"] is None:
current = controller.store.load_session(row["session_id"])
if current is None:
@@ -1621,6 +1657,73 @@ def _admit_prepared(self, path: Path, row: dict[str, Any], selected: dict[str, A
mode="resume_latest", conversation_binding_id=row["binding_id"], source_context=row["source"])
row["session_id"] = current["session_id"]
_atomic_write_json(path, row)
+ if row.get("native_mention"):
+ from types import SimpleNamespace
+ from .queued_admission import deliver_native_mention
+
+ capture = row.get("mention_capture") or {}
+ if source_preflight is None:
+ raise ValueError("native mentions require fresh original provider verification")
+ source_preflight(deepcopy(selected))
+ fresh_source = resolve_external_admission_source(self.bindings, row["binding_id"], row["source"], None)
+ if any(fresh_source.get(key) != selected.get(key) for key in ("binding", "context", "channel_id")):
+ raise ValueError("native mention authority changed during source verification")
+ selected = fresh_source
+ selected = ensure_external_admission_scope(self.bindings, selected, path, row,
+ source_preflight=source_preflight)
+
+ def steer_admitted(**kwargs):
+ # The public steering endpoint intentionally rejects bound
+ # conversations. Only this existing source-fenced admission
+ # can reach the native IO with its current binding grant.
+ saved = current.get("steward_context") or current.get("project_context")
+ if not saved or saved.get("audience") not in {"bound_owner", "bound_group"}:
+ return controller.steer_active_turn(**kwargs)
+ with self.bindings.input_context(saved, origin=row["origin"], session=current,
+ store=controller.store) as authorized:
+ fresh = controller.store.load_session(current["session_id"])
+ if (fresh is None or fresh.get("status") == "closed"
+ or authorized["binding"] != selected["binding"]
+ or any(fresh.get(key) != current.get(key) for key in
+ ("channel_id", "goal_id", "agent_id", "project_context", "steward_context"))):
+ raise ValueError("original bound Session changed")
+ controller.project_contexts.runtime_context(fresh, authorized)
+ if fresh.get("project_context") is not None:
+ from .project_context import validate_project_executor_scope
+ validate_project_executor_scope(str(fresh["agent_id"]),
+ fresh["project_context"], controller.capabilities)
+ with controller.store.steering_delivery_lock(kwargs["session_id"], kwargs["client_ingress_id"]):
+ return controller._steer_active_turn(session=fresh, _queued_turn_id=None, **kwargs)
+
+ scope_current = True
+ if current.get("steward_context") and capture.get("target_turn_id"):
+ from ...chat_manager_context import manager_authorization_scope_is_current
+ scope_current = manager_authorization_scope_is_current(
+ controller.registry_path, controller.manager_scope_resolver, current,
+ current.get("manager_authorization_scope_id"), runtime_root=controller.coordination_runtime_root)
+ decision = deliver_native_mention(
+ SimpleNamespace(store=controller.store, steer_active_turn=steer_admitted),
+ session_id=current["session_id"], ingress_id=plan["client_turn_id"],
+ target_turn_id=capture.get("target_turn_id"),
+ binding_matches=(scope_current and (capture.get("channel_id") == selected["channel_id"]
+ or capture.get("channel_id") is None and capture.get("session_id") is None
+ and capture.get("target_turn_id") is None and bool(capture))
+ and current.get("status") != "closed"
+ and (capture.get("session_id") == current["session_id"]
+ or capture.get("session_id") is None and capture.get("target_turn_id") is None)
+ and current.get("channel_id") == selected["channel_id"]),
+ text_only=not row.get("attachments"), may_deliver_new=not recovering_request,
+ steering_text=row["message"], queued_text=row["message"], origin=row["origin"])
+ row["mention_delivery"] = decision
+ if decision["action"] != "enqueue":
+ row.update(status="prepared" if decision["action"] == "unresolved" else "command_completed",
+ turn_id=decision.get("target_turn_id") or capture.get("target_turn_id"),
+ response=("已送达当前回合。" if decision["action"] == "delivered" else
+ "已收到,送达状态待核实。原消息已保留,不会自动改投下一回合。" if decision["action"] == "unresolved" else
+ "本轮调整仅支持文字,原消息和附件已保留。" if decision.get("error_code") == "queue_steering_attachments_unavailable" else
+ "未送达接收时的回合;原回合、授权或宿主能力已变化。原消息已保留。"))
+ _atomic_write_json(path, row)
+ return row
self._record_steward_ingress(row, selected, current, plan["client_turn_id"])
try:
turn, _ = controller.enqueue_turn(session_id=current["session_id"],
@@ -1687,7 +1790,7 @@ def pending(self) -> list[dict[str, Any]]:
if _REQUEST_JOURNAL_STEM.fullmatch(path.stem)]
def source_controls(self) -> list[dict[str, Any]]:
- """Observe exact source-control fields without reparsing unchanged bodies.
+ """Observe source controls and private text digests without reparsing unchanged bodies.
Recovery/stop rules remain with their original typed owner and callers.
A new, replaced or modified journal is read again; pending() and exact
@@ -1696,18 +1799,27 @@ def source_controls(self) -> list[dict[str, Any]]:
paths = (path for path in sorted(self.root.glob("*.json"))
if _REQUEST_JOURNAL_STEM.fullmatch(path.stem))
- def project(_path, row):
- fields = ("binding_id", "source", "command", "created_at")
- # The tolerant reader can return {} after transient IO failure.
- # An incomplete read must not seed an unchanged-file observation.
- return {key: row[key] for key in fields} if all(key in row for key in fields) else None
-
return [row for _path, row in self._source_control_discovery.rows(self.root, paths,
- read=_read_json, project=project)]
+ read=_read_json, project=source_control_fields)]
def read_request(self, request_ref: str) -> dict[str, Any]:
return _read_json(self.root / f"{request_ref}.json")
+ def read_backlog_requests(self, request_refs: Iterable[str]) -> Iterator[dict[str, Any]]:
+ """Observe settings correlation, without retaining ordinary request bodies."""
+ fields = ("request_ref", "binding_id", "source", "session_id", "turn_id",
+ "status", "command", "created_at")
+
+ def project(_path: Path, row: dict[str, Any]) -> dict[str, Any] | None:
+ # Recovery evidence is consumed by the typed pending rule.
+ if any(row.get(k) is not None for k in ("context_recovery", "native_result_recovery")):
+ return None
+ return {key: row[key] for key in fields} if all(key in row for key in fields) else None
+
+ paths = (self.root / f"{ref}.json" for ref in request_refs)
+ for _, row in self._backlog_request_discovery.rows(self.root, paths, read=_read_json, project=project):
+ yield row
+
def commission_evidence(self, session: dict[str, Any]) -> list[dict[str, Any]]:
"""Read original Core execution facts for this exact bound audience.
@@ -1973,7 +2085,7 @@ def recover(self, *, request_ref: str | None = None) -> None:
# queue preparation. The transport checks its source.
continue
if row["status"] == "prepared":
- if row.get("capture_origin") == "provider_history":
+ if row.get("capture_origin") == "provider_history" or row.get("native_mention"):
continue # Only the original provider can reverify this source.
# Admission resolves current authority after both request
# and route fences. A separate pre-fence network probe
diff --git a/loopx/capabilities/native_chat/file_discovery.py b/loopx/capabilities/native_chat/file_discovery.py
index 625ee8ad6b..1454dde4b8 100644
--- a/loopx/capabilities/native_chat/file_discovery.py
+++ b/loopx/capabilities/native_chat/file_discovery.py
@@ -3,12 +3,84 @@
from collections.abc import Callable, Iterable, Iterator
from copy import deepcopy
+from datetime import datetime
+import hashlib
from pathlib import Path
import sys
from threading import Lock
from typing import Any
+def external_source_route_path(root: Path, binding_id: str, source_ref: str) -> Path:
+ """Locate the original source's cross-process admission fence."""
+ return root / "source-fences" / f"{binding_id}.{source_ref}.json"
+
+
+def _ordinary_request_text_digest(row: dict[str, Any]) -> str | None:
+ """Match ordinary private text without retaining its body in discovery."""
+ message = row.get("message")
+ source = row.get("source")
+ status = row.get("status")
+ if (status not in ("accepted", "prepared") or row.get("command") is not None
+ or row.get("capture_origin") is not None or row.get("agent_target") is not None
+ or row.get("attachments") not in (None, []) or not isinstance(message, str) or not message
+ or not row.get("session_id")
+ or not isinstance(source, dict) or source.get("private_human_message") is not True):
+ return None
+ return hashlib.sha256(message.encode("utf-8", errors="surrogatepass")).hexdigest()
+
+
+def source_control_fields(path: Path, row: dict[str, Any]) -> dict[str, Any] | None:
+ """Keep exact source controls and the metadata needed to prove admission."""
+ fields = ("binding_id", "source", "command", "created_at")
+ # A tolerant reader can return an incomplete journal after a transient
+ # failure. Do not cache that read as an unchanged-file observation.
+ if not all(key in row for key in fields):
+ return None
+ result = {key: row[key] for key in fields}
+ digest = _ordinary_request_text_digest(row)
+ if digest is None:
+ return result
+ if row["status"] == "accepted" and row.get("turn_id"):
+ result.update(text_sha256=digest, session_id=row["session_id"])
+ elif (row["status"] == "prepared" and row.get("turn_id") is None
+ and row.get("request_ref") == path.stem):
+ result.update(text_sha256=digest, session_id=row["session_id"],
+ prepared_client_turn_id=f"external-{path.stem}", origin=row.get("origin", "lark"))
+ return result
+
+
+def later_equivalent_source_input(
+ row: dict[str, Any],
+ read_controls: Callable[[], list[dict[str, Any]]],
+ read_turn_for_client: Callable[[str, str], dict[str, Any] | None],
+) -> bool | None:
+ """Check canonical acceptance in the same source and Session, even before dispatch."""
+ if row.get("status") != "accepted" or not row.get("turn_id"):
+ return None
+ digest = _ordinary_request_text_digest(row)
+ if digest is None:
+ return None
+ created = datetime.fromisoformat(row["created_at"])
+ for item in read_controls():
+ if (item.get("text_sha256") != digest or item["binding_id"] != row["binding_id"]
+ or item["source"] != row["source"] or item["session_id"] != row["session_id"]
+ or datetime.fromisoformat(item["created_at"]) <= created):
+ continue
+ client_turn_id = item.get("prepared_client_turn_id")
+ if client_turn_id is None:
+ return True
+ # Core owns the durable queue receipt even if the outer journal has
+ # not finished its write. Never treat preparation alone as admission.
+ turn = read_turn_for_client(item["session_id"], client_turn_id)
+ if (turn is not None and turn.get("origin") == item["origin"]
+ and turn.get("_queue_original_message", turn.get("message")) == row["message"]
+ and turn.get("attachments") in (None, [])
+ and turn.get("external_agent_target") is None and turn.get("collaboration_request") is None):
+ return True
+ return False
+
+
def file_change_fingerprint(path: Path) -> tuple[int, ...] | None:
"""A local mutation token, or no reuse when the platform lacks one."""
# Windows stat ctime can be creation time, not a mutation stamp. Keep
diff --git a/loopx/capabilities/native_chat/queue_api.py b/loopx/capabilities/native_chat/queue_api.py
index 17be78f6d3..a06118a3ec 100644
--- a/loopx/capabilities/native_chat/queue_api.py
+++ b/loopx/capabilities/native_chat/queue_api.py
@@ -1,11 +1,49 @@
-"""HTTP projection and explicit steering of the existing persisted queue."""
+"""HTTP transport for original Session Tasks and the existing persisted queue."""
from typing import Any
+from urllib.parse import parse_qs, urlparse
from ...chat_store import CHAT_STORE_SCHEMA_VERSION
class ChatQueueRequestMixin:
+ def _project_queue_reply_history(
+ self,
+ store: Any,
+ session: dict[str, Any],
+ rows: list[dict[str, Any]],
+ ) -> list[dict[str, Any]]:
+ return rows
+ def _managed_native_turn(self, session_id: str, *, execute: bool = False) -> None:
+ from .steward_managed_mode import ManagedSessionTurn
+ service = ManagedSessionTurn(self.server.runtime_controller)
+ try:
+ if execute:
+ body = self._read_json()
+ if set(body) - {"agent_id", "operation_id", "todo_id"}:
+ raise ValueError("unsupported managed Turn arguments")
+ turn, created = service.submit(session_id, **body)
+ return self._send_json({"ok": True, "session_id": session_id, "turn": turn, "created": created}, status=202)
+ query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
+ sources = query.get("calendar_task_sources", ["false"])
+ if sources not in (["true"], ["false"]):
+ raise ValueError("calendar_task_sources must be one true or false value")
+ include_sources = sources == ["true"]
+ original_task = query.get("original_task", ["false"])
+ if original_task not in (["true"], ["false"]):
+ raise ValueError("original_task must be one true or false value")
+ include_original_task = original_task == ["true"]
+ if (include_sources or include_original_task) and (set(query) - {"calendar_task_sources", "original_task", "agent_id", "operation_id"}
+ or any(len(values) != 1 for values in query.values())):
+ raise ValueError("select one original managed Session and Agent for Task sources")
+ self._send_json(service.inspect(session_id, agent_id=query.get("agent_id", [None])[0],
+ operation_id=query.get("operation_id", [None])[0], include_calendar_task_sources=include_sources,
+ include_original_task=include_original_task))
+ except KeyError:
+ self._send_error("chat session was not found", status=404)
+ except (TypeError, ValueError, RuntimeError) as exc:
+ self._send_error(str(exc), status=409, error_code="managed_turn_unavailable")
+
def _dispatch_chat_queue(self, path: str, *, apply: bool) -> bool:
parts = path.strip("/").split("/")
if parts[:3] != ["api", "chat", "sessions"] or len(parts) < 5 or parts[4] != "queue":
@@ -32,7 +70,12 @@ def _session_queue(self, session_id: str) -> None:
self._session_context(session)
rows: list[dict[str, Any]] = []
for turn in store.queued_turns(session_id, strict=True, include_reserved=True):
- text = str(turn.get("message") or "")
+ # Reuse history's exact admission/source checks before truncating;
+ # a preview cannot decode a partial context envelope.
+ original = {"role": "user", "origin": turn.get("origin"),
+ "turn_id": turn["turn_id"], "text": str(turn.get("message") or "")}
+ visible = self._project_queue_reply_history(store, session, [original])[0]
+ text = visible.get("reply_context", {}).get("source_text", original["text"])
rows.append({
"turn_id": turn["turn_id"],
"created_at": turn["created_at"],
diff --git a/loopx/capabilities/native_chat/session_queue.py b/loopx/capabilities/native_chat/session_queue.py
new file mode 100644
index 0000000000..217e882154
--- /dev/null
+++ b/loopx/capabilities/native_chat/session_queue.py
@@ -0,0 +1,170 @@
+"""The existing same-Session FIFO, preparation and recovery consumer."""
+from pathlib import Path
+from typing import Any
+import threading
+
+from ...chat_store import CHAT_SESSION_MODE_ATTACHED, TERMINAL_TURN_STATES
+
+
+def drain_session_queue(controller: Any, *, session_id: str, work_dir: Path, objective: str) -> None:
+ wakeup = threading.Event()
+ with controller.turn_release_wakeup(wakeup):
+ _drain_session_queue_events(controller, session_id=session_id, work_dir=work_dir,
+ objective=objective, wakeup=wakeup)
+
+
+def _drain_session_queue_events(controller: Any, *, session_id: str, work_dir: Path,
+ objective: str, wakeup: threading.Event) -> None:
+ try:
+ while not controller.closed.is_set():
+ # Register and clear before reading durable state. A signal
+ # during this read remains visible when a pending request waits.
+ wakeup.clear()
+ session = controller.store.load_session(session_id)
+ if (
+ controller.closed.is_set()
+ or session is None
+ or session.get("status") == "closed"
+ or session.get("session_mode") == CHAT_SESSION_MODE_ATTACHED
+ ):
+ return
+ turn = None
+ active_turn_id = str(session.get("active_turn_id") or "")
+ if active_turn_id:
+ try:
+ controller.recover_exited_turn(session_id, active_turn_id)
+ except OSError:
+ # Storage can still be unavailable. Retry only the
+ # non-executing lifecycle repair, never the old input.
+ controller.closed.wait(0.25)
+ continue
+ active = controller.store.load_turn(session_id, active_turn_id)
+ if active and isinstance((active.get("loopx_request") or {}).get("creation_request"), dict):
+ if active.get("status") == "queued":
+ from .creation_queue import consume_creation_request
+ try:
+ pending = consume_creation_request(controller, session_id)
+ except (OSError, ValueError, RuntimeError):
+ pending = True
+ if not pending:
+ # The native worker can terminalize after this
+ # queue cached its queued state. Reconcile the
+ # current FIFO instead of retiring with ordinary
+ # messages stranded behind the released operation.
+ current = controller.store.load_session(session_id)
+ latest = controller.store.load_turn(session_id, active_turn_id)
+ if current is None:
+ return
+ if (current.get("active_turn_id") != active_turn_id
+ or latest and latest.get("status") in TERMINAL_TURN_STATES):
+ continue
+ # A still-active unknown operation grants no
+ # dispatch. Keep its worker until a state signal.
+ wakeup.wait()
+ continue
+ if active.get("status") not in TERMINAL_TURN_STATES:
+ # An admitted or unknown native operation retains
+ # its original worker/result; never restore it as an
+ # ordinary queued message or start another model.
+ wakeup.wait()
+ continue
+ if (active and active.get("status") == "queued" and "_acceptance" not in active
+ and active.get("started_at") is None and active.get("upstream_turn_id") is None
+ and active.get("delta_count") == 0):
+ # A crash can leave the queue claim before native
+ # dispatch. Keep that exact claim and pass through the
+ # normal preparation and execution fences below.
+ turn = active
+ else:
+ with controller.lock:
+ attached = controller.adapters.get(session_id)
+ if attached is None or not attached.healthcheck():
+ try:
+ controller._ensure_adapter(
+ session,
+ work_dir=work_dir,
+ objective=objective,
+ )
+ except Exception as exc:
+ controller._fail_queue_preparation(session_id, active_turn_id, exc)
+ else:
+ continue
+ active = controller.store.load_turn(session_id, active_turn_id)
+ if active and active.get("status") not in TERMINAL_TURN_STATES:
+ controller.closed.wait(0.05)
+ continue
+ controller.store.release_active_turn(session_id, active_turn_id)
+ refreshed = controller.store.load_session(session_id)
+ if refreshed is None:
+ return
+ with controller.lock:
+ controller.session_queue_wakeups.discard(session_id)
+ if turn is None:
+ turn = controller.store.claim_next_queued_turn(session_id)
+ if turn is None:
+ from .creation_queue import consume_creation_request
+ try:
+ pending = consume_creation_request(controller, session_id)
+ except (OSError, ValueError, RuntimeError):
+ pending = True
+ if pending:
+ # The request lives in its creation receipt. Existing
+ # action/Turn signals and startup discovery re-read it;
+ # pending checks do not create a failed native Turn.
+ wakeup.wait()
+ continue
+ with controller.lock:
+ if session_id in controller.session_queue_wakeups:
+ continue
+ worker = controller.session_queue_threads.get(session_id)
+ if worker is threading.current_thread():
+ controller.session_queue_workers.discard(session_id)
+ controller.session_queue_threads.pop(session_id, None)
+ return
+ turn_id = str(turn["turn_id"])
+ try:
+ if turn.get("origin") == "peer" or "collaboration_request" in turn:
+ from .conversation_bindings import OriginalConversationRequests
+ OriginalConversationRequests(controller).validate_turn(session_id, turn)
+ # An empty queue needs no provider preparation. Claim real
+ # work first, keeping the existing enqueue/retirement fence
+ # above and the Turn's execution/stop checks below.
+ current = controller.store.load_session(session_id)
+ if current is None or current.get("active_turn_id") != turn_id:
+ return
+ adapter = controller._ensure_adapter(
+ current,
+ work_dir=work_dir,
+ objective=objective,
+ )
+ if (controller.store.load_session(session_id) or {}).get("active_turn_id") != turn_id:
+ return
+ except Exception as exc:
+ # The claimed request still owns a terminal outcome when
+ # workspace preparation or adapter restoration fails.
+ controller._fail_queue_preparation(session_id, turn_id, exc)
+ continue
+ done_event = threading.Event()
+ with controller.lock:
+ controller.turn_done_events[(session_id, turn_id)] = done_event
+ try:
+ controller._run_turn(
+ session_id=session_id,
+ turn_id=turn_id,
+ message=str(turn.get("message") or ""),
+ attachments=turn.get("attachments") or [],
+ adapter=adapter,
+ done_event=done_event,
+ )
+ except OSError:
+ # _run_turn has released its execution fence/done event.
+ # A failed error checkpoint must not kill this queue worker;
+ # the next iteration reconciles the original durable state.
+ controller.closed.wait(0.25)
+ finally:
+ with controller.lock:
+ worker = controller.session_queue_threads.get(session_id)
+ if worker is threading.current_thread():
+ controller.session_queue_workers.discard(session_id)
+ controller.session_queue_threads.pop(session_id, None)
+ controller.session_queue_wakeups.discard(session_id)
diff --git a/loopx/capabilities/native_chat/steward_commands.py b/loopx/capabilities/native_chat/steward_commands.py
index 102d6623ca..5e1c8aae77 100644
--- a/loopx/capabilities/native_chat/steward_commands.py
+++ b/loopx/capabilities/native_chat/steward_commands.py
@@ -5,8 +5,17 @@
"""
from __future__ import annotations
+import argparse
from typing import Any
+from .steward_triage import (
+ StewardFastPathError,
+ build_portfolio_triage_projection,
+ execute_steward_fast_path,
+ parse_steward_fast_path_intent,
+ resolve_all_registered_goal_ids,
+)
+
class NativeStewardCommandError(ValueError):
def __init__(self, payload: dict[str, Any]) -> None:
@@ -16,7 +25,76 @@ def __init__(self, payload: dict[str, Any]) -> None:
payload.get("error") or payload.get("reason") or payload.get("message") or "inspect the native receipt"))
+def _triage_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(prog="steward-triage", add_help=False)
+ parser.add_argument("--goal-id", action="append", default=[])
+ parser.add_argument("--all-goals", action="store_true")
+ parser.add_argument("--focus", default="all")
+ parser.add_argument("--max-gates", type=int, default=8)
+ parser.add_argument("--max-todos", type=int, default=8)
+ parser.add_argument("--max-progress", type=int, default=5)
+ return parser
+
+
+def native_fast_path_triage(
+ controller: Any,
+ *,
+ text: str,
+ binding_id: str,
+ source_ref: str,
+ sender_ref: str,
+ bindings: Any = None,
+ private_human_message: bool = True,
+ origin: str | None = None,
+ session_context: dict[str, Any] | None = None,
+) -> dict[str, Any] | None:
+ """Execute a read-only Steward Fast-Path triage query without leases or Turns."""
+
+ active_bindings = bindings if bindings is not None else getattr(controller, "conversation_bindings", None)
+ if active_bindings is None:
+ raise StewardFastPathError(
+ "steward conversation bindings are unavailable",
+ code="steward_bindings_unavailable",
+ )
+ return execute_steward_fast_path(
+ text=text,
+ bindings=active_bindings,
+ binding_id=binding_id,
+ source_ref=source_ref,
+ sender_ref=sender_ref,
+ registry_path=controller.registry_path,
+ runtime_root_arg=str(controller.coordination_runtime_root),
+ private_human_message=private_human_message,
+ origin=origin,
+ session_context=session_context,
+ )
+
+
def native_command(controller: Any, argv: list[str]) -> dict[str, Any]:
+ if argv and argv[0] == "triage":
+ try:
+ parsed = _triage_parser().parse_args(argv[1:])
+ authorized = (
+ resolve_all_registered_goal_ids(controller.registry_path)
+ if parsed.all_goals
+ else list(parsed.goal_id)
+ )
+ return build_portfolio_triage_projection(
+ registry_path=controller.registry_path,
+ runtime_root_arg=str(controller.coordination_runtime_root),
+ authorized_goal_ids=authorized,
+ requested_goal_ids=list(parsed.goal_id) or None,
+ focus=parsed.focus,
+ max_gates=parsed.max_gates,
+ max_todos=parsed.max_todos,
+ max_progress=parsed.max_progress,
+ )
+ except (StewardFastPathError, SystemExit, ValueError) as exc:
+ error_code = getattr(exc, "code", "invalid_triage_command")
+ raise NativeStewardCommandError(
+ {"ok": False, "error_code": error_code, "error": str(exc)}
+ ) from exc
+
from ...cli import build_parser
from ...cli_rollout import append_cli_rollout_event
from ...cli_commands.quota import handle_quota_command
@@ -25,7 +103,7 @@ def native_command(controller: Any, argv: list[str]) -> dict[str, Any]:
args = build_parser().parse_args(["--format", "json", *argv])
result: dict[str, Any] = {}
- kwargs = {"registry_path": controller.registry_path,
+ kwargs: dict[str, Any] = {"registry_path": controller.registry_path,
"runtime_root_arg": str(controller.coordination_runtime_root),
"print_payload": lambda payload, *_args: result.update(payload)}
if args.command == "todo":
@@ -41,3 +119,12 @@ def native_command(controller: Any, argv: list[str]) -> dict[str, Any]:
if code or result.get("ok") is not True:
raise NativeStewardCommandError(result)
return result
+
+
+__all__ = [
+ "NativeStewardCommandError",
+ "execute_steward_fast_path",
+ "native_command",
+ "native_fast_path_triage",
+ "parse_steward_fast_path_intent",
+]
diff --git a/loopx/capabilities/native_chat/steward_managed_mode.py b/loopx/capabilities/native_chat/steward_managed_mode.py
index 1fe8028c5c..bc5cf51d86 100644
--- a/loopx/capabilities/native_chat/steward_managed_mode.py
+++ b/loopx/capabilities/native_chat/steward_managed_mode.py
@@ -180,7 +180,7 @@ def health(self, binding_id: str) -> dict[str, Any]:
class ManagedTaskValidationUnavailable(ValueError):
- """A native selection has no usable caller-declared independent validator."""
+ """A native selection has no usable owner-declared independent validator."""
def managed_session_identity(controller: Any, *, goal_id: str, agent_id: str, workspace: Path,
@@ -292,11 +292,23 @@ def admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None,
if request.get("work_kind") == "scheduled_task":
from .session_calendar_tasks import SessionCalendarTasks
report["scheduled_task"] = SessionCalendarTasks(self.controller).admission(request)
+ creation = {}
+ if "creation_request" in request:
+ from .creation_queue import creation_request_facts
+ retained = request["creation_request"]
+ if not isinstance(retained, dict) or not isinstance(retained.get("creation_operation_id"), str):
+ raise ValueError("the original creation request is unavailable")
+ facts = creation_request_facts(self.controller, actor["session_id"],
+ proposal_id=retained["creation_operation_id"])
+ if facts is None:
+ raise ValueError("the original creation request source is unavailable")
+ creation = {"creation_proposal": facts["proposal"],
+ "current_original_task": facts["current_original_task"]}
return ChatConversationBindings._core("collaboration.session.managed_turn.admit", {
"session": session, "request": request, "turn": turn,
"goal": StewardManagedMode(self.controller, None)._goal(actor["goal_id"]),
"goal_active": bool(goal and goal.get("status") == "active" and not goal_is_stopped(goal)),
- "monitor_todo": monitor, **report,
+ "monitor_todo": monitor, **report, **creation,
**({"report_settlement_recovery": settlement_recovery} if settlement_recovery is not None else {}),
**({"report_selection_recovery": selection_recovery} if selection_recovery is not None else {}),
**StewardTurnHost(self.controller).report_quota_basis(request),
@@ -304,7 +316,8 @@ def admit(self, request: dict[str, Any], *, turn: dict[str, Any] | None = None,
"queued_turn_count": len(self.store.queued_turns(actor["session_id"]))})
def inspect(self, session_id: str, *, agent_id: str | None = None,
- operation_id: str | None = None, include_calendar_task_sources: bool = False) -> dict[str, Any]:
+ operation_id: str | None = None, include_calendar_task_sources: bool = False,
+ include_original_task: bool = False) -> dict[str, Any]:
session = self.store.load_session(session_id)
if not session:
raise KeyError("chat session was not found")
@@ -322,6 +335,10 @@ def inspect(self, session_id: str, *, agent_id: str | None = None,
result["available"] = True
except ValueError as exc:
result["reason"] = str(exc)
+ if include_original_task:
+ if agent_id is not None and agent_id != session.get("managed_agent_id"):
+ raise ValueError("select the original registered Agent for Task entry")
+ result["task"] = self._original_task_entry(session_id)
if session.get("managed_agent_id"):
from .steward_reports import ManagedSessionReports
from .session_calendar_tasks import SessionCalendarTasks
@@ -336,14 +353,67 @@ def inspect(self, session_id: str, *, agent_id: str | None = None,
result["calendar_task_sources"] = SessionCalendarTasks(self.controller).source_options(session_id)
return result
+ def creation_request(self, session_id: str) -> dict[str, Any] | None:
+ from .creation_queue import creation_request_facts, project_creation_request
+ return project_creation_request(creation_request_facts(self.controller, session_id))
+
+ def _original_task_entry(self, session_id: str) -> dict[str, Any]:
+ """Observe the existing creation/validation owners without any effects.
+
+ The returned plan does not claim a Task or authorize a model. Native
+ submit still rechecks current admission and every validation source.
+ """
+ from ...control_plane.effect_runtime import effect_runtime_result
+ from ...control_plane.goals.acceptance import inspect_goal_acceptance
+
+ session = self.store.load_session(session_id) or {}
+ request = self._request(session_id, session.get("managed_agent_id") or "", "original-task-preview")
+ actor = request["actor"]
+ unavailable: dict[str, Any] = {"todo_id": None, "state": "unbound", "source": None,
+ "canonical_done": False}
+ try:
+ creation = self.creation_request(session_id)
+ if creation is not None:
+ request = self._request(session_id, creation["agent_id"], creation["operation_id"], creation["todo_id"])
+ request["creation_request"] = creation
+ retained_turn = self.store.turn_for_client(session_id, "managed." + creation["operation_id"])
+ unavailable.update(creation_request=creation, creation_turn=None)
+ if retained_turn is not None and retained_turn.get("loopx_request") != request:
+ raise ValueError("the original creation operation belongs to another managed request")
+ unavailable["creation_turn"] = retained_turn
+ self.admit(request)
+ basis = inspect_goal_acceptance(registry_path=self.controller.registry_path,
+ runtime_root=str(self.controller.coordination_runtime_root), goal_id=actor["goal_id"],
+ agent_id=actor["agent_id"], validation_workspace_path=Path(actor["workspace_path"]))
+ selected = effect_runtime_result("goal.task.creation_selection", {"basis": basis})
+ if selected["todo_id"] is None:
+ return {**unavailable, "reason": selected["reason"]}
+ todo_id = selected["todo_id"]
+ unavailable["todo_id"] = todo_id
+ request["todo_id"] = todo_id
+ self.admit(request)
+ plan = self._validation_source(request, todo_id)["plan"]
+ # Return only the display observation; commands, pins and private
+ # declarations stay with their existing owner.
+ self.admit(request)
+ return {**{key: plan[key] for key in ("todo_id", "state", "source", "observation", "canonical_done")},
+ **{key: unavailable[key] for key in ("creation_request", "creation_turn") if key in unavailable}}
+ except (OSError, ValueError, RuntimeError) as exc:
+ reason = ("the original task source is temporarily unavailable" if isinstance(exc, OSError)
+ else str(exc))
+ return {**unavailable, "reason": reason}
+
def submit(self, session_id: str, *, agent_id: str, operation_id: str,
todo_id: str | None = None, monitor_deadline: str | None = None,
report_window: dict[str, Any] | None = None,
- scheduled_window: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]:
+ scheduled_window: dict[str, Any] | None = None,
+ _creation_request: dict[str, Any] | None = None) -> tuple[dict[str, Any], bool]:
from ...attached_session import managed_session_goal_commit
controller = self.controller
with controller._session_adapter_lock(session_id):
request = self._request(session_id, agent_id, operation_id, todo_id)
+ if _creation_request is not None:
+ request["creation_request"] = _creation_request
if scheduled_window is not None:
if report_window is not None or monitor_deadline is not None or not todo_id:
raise ValueError("a calendar task requires its original finite Todo")
@@ -410,43 +480,145 @@ def submit(self, session_id: str, *, agent_id: str, operation_id: str,
registry_path=controller.registry_path, session_id=session_id)
with commit():
admitted = self.admit(request, selection_recovery=selection_recovery)
+ if _creation_request is not None:
+ self._validation_source(request, _creation_request["todo_id"])
+ if not self._creation_allowance(request):
+ raise ValueError("the original creation task has no current preparation admission")
accepted = self.store.accept_managed_turn(session_id, client_turn_id=client_id,
message="Advance the currently admitted native LoopX work.",
display_message="生成本期定时报告。" if report_window is not None else
"执行本期定时任务。" if scheduled_window is not None else
"检查当前 Goal 原生任务状态。" if monitor_deadline is not None else "推进一次 LoopX 任务。",
origin="native_loopx", loopx_execution=True, loopx_request=request)
- try:
- session = self.store.load_session(session_id)
- if admitted["observation_only"]:
- from .steward_monitor import StewardObservationAdapter
- adapter = StewardObservationAdapter(session.get("upstream_thread_id"))
- else:
- adapter = controller._ensure_adapter_locked(session, work_dir=Path(admitted["workspace_path"]),
- objective="Advance this Goal's authorized work.", accepted_turn_id=accepted.turn["turn_id"])
- if Path(adapter.session.work_dir).resolve() != Path(admitted["workspace_path"]).resolve():
- raise ValueError("the original managed conversation workspace changed")
- controller._start_accepted_turn_worker(session_id=session_id, turn_id=accepted.turn["turn_id"],
- message=accepted.turn["message"], attachments=[], adapter=adapter, loopx_execution=True)
- except Exception as exc:
- controller._fail_queue_preparation(session_id, accepted.turn["turn_id"], exc)
- raise
+ self._dispatch_accepted_turn(accepted.turn, admitted)
return accepted.turn, accepted.created
+ def _dispatch_accepted_turn(self, turn: dict[str, Any], admitted: dict[str, Any]) -> None:
+ session_id = turn["session_id"]
+ request = turn.get("loopx_request") or {}
+ if "creation_request" in request:
+ from ...attached_session import managed_session_goal_commit
+ with managed_session_goal_commit(store=self.store, registry_path=self.controller.registry_path,
+ session_id=session_id)():
+ admitted = self.admit(request, turn=turn)
+ self._validation_source(request, request["todo_id"])
+ if not self._creation_allowance(request):
+ return # Retain the accepted, unstarted operation for a fresh state signal.
+ try:
+ session = self.store.load_session(session_id)
+ if admitted["observation_only"]:
+ from .steward_monitor import StewardObservationAdapter
+ adapter = StewardObservationAdapter(session.get("upstream_thread_id"))
+ else:
+ adapter = self.controller._ensure_adapter_locked(session,
+ work_dir=Path(admitted["workspace_path"]), objective="Advance this Goal's authorized work.",
+ accepted_turn_id=turn["turn_id"])
+ if Path(adapter.session.work_dir).resolve() != Path(admitted["workspace_path"]).resolve():
+ raise ValueError("the original managed conversation workspace changed")
+ self.controller._start_accepted_turn_worker(session_id=session_id, turn_id=turn["turn_id"],
+ message=turn["message"], attachments=[], adapter=adapter, loopx_execution=True)
+ except Exception as exc:
+ self.controller._fail_queue_preparation(session_id, turn["turn_id"], exc)
+ raise
+
+ def consume_creation_request(self, creation: dict[str, Any]) -> bool:
+ """Consume one saved request through the existing managed acceptance owner."""
+ from ...attached_session import managed_session_goal_commit
+ from .creation_queue import queued_turn_unstarted
+ session_id = creation["session_id"]
+ request = self._request(session_id, creation["agent_id"], creation["operation_id"], creation["todo_id"])
+ request["creation_request"] = creation
+ with self.controller._session_adapter_lock(session_id):
+ existing = self.store.turn_for_client(session_id, "managed." + creation["operation_id"])
+ if existing is not None:
+ if existing.get("loopx_request") != request:
+ raise ValueError("the original creation operation belongs to another managed request")
+ if not queued_turn_unstarted(existing):
+ return False # Unknown, failed and completed operations are never re-executed.
+ with managed_session_goal_commit(store=self.store, registry_path=self.controller.registry_path,
+ session_id=session_id)():
+ admitted = self.admit(request, turn=existing)
+ self._validation_source(request, creation["todo_id"])
+ if not self._creation_allowance(request):
+ return True
+ self._dispatch_accepted_turn(existing, admitted)
+ return True
+ self.admit(request)
+ self._validation_source(request, creation["todo_id"])
+ if not self._creation_allowance(request):
+ return True
+ self.submit(session_id, agent_id=creation["agent_id"], operation_id=creation["operation_id"],
+ todo_id=creation["todo_id"], _creation_request=creation)
+ return True
+
+ def _creation_allowance(self, request: dict[str, Any]) -> bool:
+ """Read the existing typed selected-work admission, without binding or effects.
+
+ Preparation may require the native owner to claim a lease. Its final
+ admission and launch guards still own execution after this observation.
+ """
+ from ...status import collect_status, AUTONOMOUS_REPLAN_PERIODIC_LOOKBACK
+ from ...control_plane.quota.live_decision import build_live_quota_should_run_decision
+ from ...control_plane.scheduler.execution_context import scheduler_execution_context_for_turn
+ from ...control_plane.work_items.action_selection_contract import current_action_selection_admission
+ from ...control_plane.goals.first_party_host_admission import capture_first_party_host_goal_ref
+ actor = request["actor"]
+ root = self.controller.coordination_runtime_root
+ status = collect_status(registry_path=self.controller.registry_path,
+ runtime_root_override=str(root), limit=AUTONOMOUS_REPLAN_PERIODIC_LOOKBACK,
+ goal_id=actor["goal_id"], agent_lane_id=actor["agent_id"],
+ available_capabilities=None, include_presentation_projections=False)
+ decision = build_live_quota_should_run_decision(status,
+ goal_id=actor["goal_id"], agent_id=actor["agent_id"], available_capabilities=None,
+ include_scheduler_detail=False, codex_app_current_rrule=None,
+ registry_path=self.controller.registry_path, runtime_root=root,
+ requested_action_todo_id=request["todo_id"], turn_instance_id=request["turn_instance_id"],
+ workspace_path=Path(actor["workspace_path"]),
+ goal_ref=capture_first_party_host_goal_ref(registry_path=self.controller.registry_path,
+ goal_id=actor["goal_id"]),
+ scheduler_execution_context=scheduler_execution_context_for_turn(
+ host="codex-app-server", execution_mode="isolated-headless"))
+ agent = (decision.get("interaction_contract") or {}).get("agent_channel") or {}
+ _, admitted = current_action_selection_admission(decision,
+ requested_todo_id=request["todo_id"], agent_must_attempt=agent.get("must_attempt") is True,
+ agent_delivery_allowed=agent.get("delivery_allowed"))
+ return admitted
+
def _validation_source(self, request: dict[str, Any], todo_id: str) -> dict[str, Any]:
- from ...control_plane.todos.list_readback import list_goal_todos
- readback = list_goal_todos(registry_path=self.controller.registry_path, goal_id=request["actor"]["goal_id"],
- todo_id=todo_id, role="agent", runtime_root_arg=str(self.controller.coordination_runtime_root))
- rows = [readback["todo"]] if readback.get("todo") else []
- if len(rows) != 1 or rows[0].get("completion_validation_required") is not True:
+ from ...control_plane.effect_runtime import effect_runtime_result
+ from ...control_plane.goals.acceptance import inspect_goal_acceptance, validation_effect_files_current
+ from ...control_plane.todos.completion_validation import resolve_private_completion_validation_declaration
+ from ...materials import goal_state_path
+ actor = request["actor"]
+ workspace = Path(actor["workspace_path"])
+ basis = inspect_goal_acceptance(registry_path=self.controller.registry_path,
+ runtime_root=str(self.controller.coordination_runtime_root), goal_id=actor["goal_id"],
+ agent_id=actor["agent_id"], todo_id=todo_id, validation_workspace_path=workspace)
+ todo = basis.get("todo")
+ goal = load_goal_from_registry(self.controller.registry_path, actor["goal_id"])
+ if not isinstance(todo, dict) or goal is None:
+ raise ManagedTaskValidationUnavailable("the selected task's canonical validation source is unavailable")
+ declaration = resolve_private_completion_validation_declaration(canonical_todo=todo,
+ state_file=goal_state_path(goal), runtime_root=self.controller.coordination_runtime_root,
+ registry_path=self.controller.registry_path, goal_id=actor["goal_id"], todo_id=todo_id,
+ role=todo.get("role"), persist_if_resolved=False)
+ # Only the existing owner can resolve acceptance to explicit null.
+ # Applicable unbound/stale checks and failed reads must never fall back.
+ plan = effect_runtime_result("goal.task.validation_plan", {
+ "todo_id": todo_id, "basis": basis, "declaration": declaration})
+ if plan["state"] != "ready":
raise ManagedTaskValidationUnavailable("the selected task needs its existing independent argv validation declaration")
- return rows[0]
+ if not validation_effect_files_current(effects=plan["effects"],
+ registry_path=self.controller.registry_path, goal_id=actor["goal_id"],
+ validation_workspace_path=workspace):
+ raise ManagedTaskValidationUnavailable("the selected task's declared verifier files changed or are unavailable")
+ return {**todo, "plan": plan}
def prepare_validation(self, request: dict[str, Any], native_request: dict[str, Any], *,
_checked_work_identity: dict[str, str] | None = None) -> None:
from ...control_plane.turn_driver.driver import selected_turn_todo, turn_host_lineage
from ...control_plane.turn_driver.command_validation import build_loopx_turn_command_validator
- from ...control_plane.todos.completion_validation_store import read_completion_validation_declaration
+ from ...control_plane.goals.acceptance import run_goal_acceptance_validation_effect
# Dispatch can reuse its just-checked identity within this invocation;
# direct callers still check the complete source through the same owner.
if "work_contract" in native_request:
@@ -460,20 +632,47 @@ def prepare_validation(self, request: dict[str, Any], native_request: dict[str,
self.validation_basis = self._validation_source(request, selected["todo_id"])
if re.fullmatch(r"cadence_[a-f0-9]{64}", self.validation_basis.get("target_key") or "") and request.get("work_kind") != "scheduled_task":
raise ValueError("the original calendar Task must execute through its scheduled Session admission")
- declaration = read_completion_validation_declaration(runtime_root=self.controller.coordination_runtime_root,
- goal_id=request["actor"]["goal_id"], todo_id=selected["todo_id"],
- expected_digest=self.validation_basis["completion_validation_sha256"])
- if not declaration or not declaration.get("validation_command_argv"):
- raise ManagedTaskValidationUnavailable("the selected task requires its existing argv validation declaration")
- self.task_validator = build_loopx_turn_command_validator(declaration["validation_command_argv"],
- project=Path(request["actor"]["workspace_path"]), timeout_seconds=declaration.get("validation_timeout_seconds") or 20)
+ actor = request["actor"]
+ workspace = Path(actor["workspace_path"])
+ validators = []
+ for effect in self.validation_basis["plan"]["effects"]:
+ if "criterion_id" not in effect:
+ if not effect.get("validation_argv"):
+ raise ManagedTaskValidationUnavailable("the selected task requires its existing argv validation declaration")
+ # Preserve raw typed model-result JSON on the command's stdin,
+ # plus its existing receipt and optional reflection attestation.
+ validators.append(build_loopx_turn_command_validator(effect["validation_argv"],
+ project=workspace, timeout_seconds=effect["validation_timeout_seconds"] or 20))
+ else:
+ def goal_check(_plan, _result, effect=effect):
+ receipt = run_goal_acceptance_validation_effect(effect=effect,
+ registry_path=self.controller.registry_path, goal_id=actor["goal_id"],
+ validation_workspace_path=workspace)
+ return {"status": "passed" if receipt["passed"] else "failed",
+ "validator_kind": "command", "summary": receipt.get("summary") or
+ ("independent Goal acceptance check passed" if receipt["passed"] else
+ "independent Goal acceptance check failed"),
+ "exit_code": receipt["exit_code"],
+ **({"recovery_kind": "repair_required"} if not receipt["passed"] else {})}
+ validators.append(goal_check)
+
+ def validate_checks(plan, result):
+ receipts = [check(plan, result) for check in validators]
+ if len(receipts) == 1:
+ return receipts[0]
+ failed = next((row for row in receipts if row["status"] != "passed"), None)
+ # Keep the existing receipt contract and the caller's optional
+ # reflection attestation. Every required check has executed.
+ return failed or {**receipts[-1], "summary": f"{len(receipts)} independent task checks passed"}
+
+ self.task_validator = validate_checks
def validator(self, request: dict[str, Any], *, turn_id: str):
- """Resolve only the native selection's immutable, caller-declared argv.
+ """Execute the current owner-resolved Goal and required Todo checks.
No browser or model argument may install a host validation command.
- The captured canonical digest and fresh source must agree before and
- after the existing command validator reads the task's real artifact.
+ Definition, work, claim and lifecycle must agree before and after the
+ existing validators read the task's real artifact.
"""
from ...control_plane.turn_driver.driver import (
COMPLETE_TURN_PLAN_SCHEMA_VERSION, selected_turn_todo, turn_host_lineage,
@@ -486,15 +685,15 @@ def validate(plan, result):
selected = (turn_host_lineage(plan) if "work_contract" in plan or plan.get("schema_version") == COMPLETE_TURN_PLAN_SCHEMA_VERSION
else selected_turn_todo(plan.get("turn_envelope") or {}))
basis = self.validation_basis
- if not basis or not self.task_validator or basis["todo_id"] != selected["todo_id"]:
+ if not basis or not self.task_validator or basis["plan"]["todo_id"] != selected["todo_id"]:
raise ValueError("the original task validation source was not captured before model work")
def current():
self.admit(request, turn=self.store.load_turn(actor["session_id"], turn_id))
fresh = self._validation_source(request, selected["todo_id"])
- if any(fresh.get(key) != basis.get(key) for key in
- ("completion_validation_sha256", "completion_validation_revision")):
- raise ValueError("the selected task's validation declaration changed")
+ if (fresh["plan"]["task_basis_sha256"] != basis["plan"]["task_basis_sha256"]
+ or fresh["plan"]["observation"]["basis_sha256"] != basis["plan"]["observation"]["basis_sha256"]):
+ raise ValueError("the selected task's validation source or work changed")
current()
receipt = self.task_validator(plan, result)
diff --git a/loopx/capabilities/native_chat/steward_triage.py b/loopx/capabilities/native_chat/steward_triage.py
new file mode 100644
index 0000000000..8e431a4695
--- /dev/null
+++ b/loopx/capabilities/native_chat/steward_triage.py
@@ -0,0 +1,837 @@
+"""Read-only Steward Fast-Path portfolio triage.
+
+Fast-Path portfolio triage answers lightweight personal/Steward inspection
+intents directly from canonical Todo and run-index readback without:
+- acquiring or releasing Goal/Todo task leases,
+- opening or compacting upstream model session history,
+- mutating Chat Session/Turn state, or
+- spending Quota monitor/turn envelopes.
+
+Authorization remains fail-closed: Steward conversation bindings are re-verified
+through Core before reading portfolio state, and requested Goal IDs outside the
+authorized Steward scope are rejected with zero state reads or mutations.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from ...control_plane.coordination.local_authority import (
+ CanonicalAuthorityRequired,
+ LocalCoordinationAuthorityUnavailable,
+)
+from ...control_plane.projects.registry_codec import load_registry
+from ...control_plane.runtime.public_safety import public_safe_compact_text
+from ...control_plane.runtime.runtime_projection_route import resolve_goal_source_runtime_route
+from ...control_plane.runtime.time import chronology_key
+from ...control_plane.todos.contract import (
+ TODO_STATUS_BLOCKED,
+ TODO_STATUS_DONE,
+ TODO_STATUS_OPEN,
+ TODO_TASK_CLASS_USER_ACTION,
+ TODO_TASK_CLASS_USER_GATE,
+ decision_scope_metadata_value,
+)
+from ...control_plane.todos.list_readback import list_goal_todos
+from ...history import load_index_snapshot
+from ...registry import registry_goals
+
+PORTFOLIO_TRIAGE_SCHEMA_VERSION = "steward_portfolio_triage_v0"
+FAST_PATH_RESPONSE_SCHEMA_VERSION = "steward_fast_path_response_v0"
+
+VALID_TRIAGE_FOCUS = frozenset({"all", "gates", "todos"})
+ACTIONABLE_USER_TASK_CLASSES = frozenset(
+ {TODO_TASK_CLASS_USER_GATE, TODO_TASK_CLASS_USER_ACTION}
+)
+ACTIVE_TRIAGE_STATUSES = frozenset({TODO_STATUS_OPEN, TODO_STATUS_BLOCKED})
+HIGH_PRIORITIES = frozenset({"P0", "P1"})
+WITHHELD_TEXT = "(text withheld from digest; inspect the record)"
+
+_GOAL_ID_TOKEN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
+_PRIORITY_PREFIX = re.compile(r"^\s*\[(P[0-3])\]\s*", re.IGNORECASE)
+_SLASH_INTENT_MAP = {
+ "/triage": "all",
+ "/inbox": "all",
+ "/digest": "all",
+ "/gates": "gates",
+ "/decisions": "gates",
+ "/todos": "todos",
+ "/blockers": "todos",
+}
+_EXACT_TEXT_INTENT_MAP = {
+ "triage": "all",
+ "inbox": "all",
+ "open gates": "gates",
+ "pending gates": "gates",
+ "user gates": "gates",
+ "收件箱": "all",
+ "快车道": "all",
+ "待办速览": "todos",
+ "卡点速览": "gates",
+ "待确认门禁": "gates",
+}
+
+
+class StewardFastPathError(ValueError):
+ """Typed fail-closed error for Steward Fast-Path and gate settlement."""
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ code: str,
+ details: Mapping[str, Any] | None = None,
+ ) -> None:
+ super().__init__(message)
+ self.code = code
+ self.details = dict(details or {})
+
+
+@dataclass(frozen=True)
+class StewardFastPathIntent:
+ """Parsed lightweight read-only Steward triage intent."""
+
+ command: str
+ focus: str
+ requested_goal_ids: tuple[str, ...] = ()
+
+
+def parse_steward_fast_path_intent(text: str) -> StewardFastPathIntent | None:
+ """Classify explicit lightweight triage intents; return None for normal Turns."""
+
+ normalized = " ".join(str(text or "").strip().split())
+ if not normalized:
+ return None
+
+ lowered = normalized.lower()
+ if lowered in _EXACT_TEXT_INTENT_MAP:
+ return StewardFastPathIntent(
+ command=lowered,
+ focus=_EXACT_TEXT_INTENT_MAP[lowered],
+ )
+
+ if not normalized.startswith("/"):
+ return None
+
+ tokens = normalized.split(" ")
+ head = tokens[0].lower()
+ focus = _SLASH_INTENT_MAP.get(head)
+ if focus is None:
+ return None
+
+ requested_goals: list[str] = []
+ index = 1
+ while index < len(tokens):
+ token = tokens[index]
+ lower_token = token.lower()
+ if lower_token in {"all", "gates", "todos"} and head == "/triage":
+ focus = lower_token
+ index += 1
+ continue
+ if lower_token in {"--goal", "--goal-id"}:
+ if index + 1 >= len(tokens):
+ raise StewardFastPathError(
+ "fast-path --goal requires a Goal ID",
+ code="invalid_fast_path_arguments",
+ )
+ goal_token = tokens[index + 1].strip()
+ if not _GOAL_ID_TOKEN.fullmatch(goal_token):
+ raise StewardFastPathError(
+ "fast-path Goal ID must use public-safe identifier characters",
+ code="invalid_fast_path_arguments",
+ )
+ requested_goals.append(goal_token)
+ index += 2
+ continue
+ if lower_token.startswith("goal:"):
+ goal_token = token[5:].strip()
+ if not _GOAL_ID_TOKEN.fullmatch(goal_token):
+ raise StewardFastPathError(
+ "fast-path Goal ID must use public-safe identifier characters",
+ code="invalid_fast_path_arguments",
+ )
+ requested_goals.append(goal_token)
+ index += 1
+ continue
+ # Unknown trailing prose means the user wrote a richer instruction; hand
+ # off to the full Steward Turn instead of guessing or dropping context.
+ return None
+
+ deduped_goals = tuple(dict.fromkeys(requested_goals))
+ return StewardFastPathIntent(
+ command=head,
+ focus=focus,
+ requested_goal_ids=deduped_goals,
+ )
+
+
+def _effective_priority(todo: Mapping[str, Any]) -> str | None:
+ explicit = str(todo.get("priority") or "").strip().upper()
+ if explicit in {"P0", "P1", "P2", "P3"}:
+ return explicit
+ text = str(todo.get("text") or "")
+ match = _PRIORITY_PREFIX.match(text)
+ if match:
+ return match.group(1).upper()
+ return None
+
+
+def _strip_priority_prefix(text: object) -> str:
+ value = str(text or "")
+ while True:
+ stripped = _PRIORITY_PREFIX.sub("", value, count=1)
+ if stripped == value:
+ return value
+ value = stripped
+
+
+def _priority_rank(priority: str | None) -> int:
+ if priority == "P0":
+ return 0
+ if priority == "P1":
+ return 1
+ if priority == "P2":
+ return 2
+ if priority == "P3":
+ return 3
+ return 4
+
+
+def _compact_public(value: object, *, limit: int) -> str:
+ compact = public_safe_compact_text(str(value or ""), limit=limit)
+ return (compact or "").strip()
+
+
+def _decision_scope_summary(scope: object) -> str | None:
+ if not isinstance(scope, Mapping):
+ return None
+ kind = str(scope.get("kind") or "").strip()
+ granularity = str(scope.get("granularity") or "").strip()
+ key = str(scope.get("scope_key") or scope.get("key") or "").strip()
+ parts = [item for item in (kind, granularity, key) if item]
+ if not parts:
+ return None
+ return _compact_public(":".join(parts), limit=96) or None
+
+
+def compute_user_gate_state_fingerprint(
+ goal_id: str,
+ todo: Mapping[str, Any],
+) -> str:
+ """Compute a deterministic canonical fingerprint for callback drift checks."""
+
+ canonical_payload = {
+ "schema_version": "steward_user_gate_fingerprint_v0",
+ "goal_id": str(goal_id),
+ "todo_id": str(todo.get("todo_id") or ""),
+ "role": str(todo.get("role") or ""),
+ "status": str(todo.get("status") or ""),
+ "done": bool(todo.get("done")),
+ "superseded_by": str(todo.get("superseded_by") or ""),
+ "task_class": str(todo.get("task_class") or ""),
+ "text": str(todo.get("text") or ""),
+ "decision_scope": decision_scope_metadata_value(todo.get("decision_scope")),
+ "unblocks_todo_id": str(todo.get("unblocks_todo_id") or ""),
+ }
+ encoded = json.dumps(
+ canonical_payload,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ return "sha256:" + hashlib.sha256(encoded).hexdigest()
+
+
+def _select_scoped_goals(
+ *,
+ authorized_goal_ids: Sequence[str],
+ requested_goal_ids: Sequence[str] | None,
+) -> list[str]:
+ authorized = list(
+ dict.fromkeys(
+ str(goal_id).strip()
+ for goal_id in authorized_goal_ids
+ if str(goal_id).strip()
+ )
+ )
+ if not requested_goal_ids:
+ return authorized
+ authorized_set = set(authorized)
+ selected: list[str] = []
+ for raw in requested_goal_ids:
+ candidate = str(raw or "").strip()
+ if not candidate:
+ continue
+ if candidate not in authorized_set:
+ raise StewardFastPathError(
+ f"goal {candidate!r} is outside the authorized triage scope",
+ code="goal_outside_authorized_scope",
+ details={"goal_id": candidate},
+ )
+ if candidate not in selected:
+ selected.append(candidate)
+ return selected
+
+
+def resolve_all_registered_goal_ids(registry_path: Path) -> list[str]:
+ """Return active/registered non-internal portfolio Goal IDs from registry."""
+
+ registry = load_registry(registry_path)
+ result: list[str] = []
+ for goal in registry_goals(registry):
+ goal_id = str(goal.get("id") or "").strip()
+ if not goal_id or goal_id.startswith("steward-agent-"):
+ continue
+ if goal_id not in result:
+ result.append(goal_id)
+ return result
+
+
+def build_portfolio_triage_projection(
+ *,
+ registry_path: Path,
+ runtime_root_arg: str | None = None,
+ authorized_goal_ids: Sequence[str],
+ requested_goal_ids: Sequence[str] | None = None,
+ focus: str = "all",
+ max_gates: int = 8,
+ max_todos: int = 8,
+ max_progress: int = 5,
+ max_text_chars: int = 180,
+) -> dict[str, Any]:
+ """Build a bounded, public-safe, read-only triage digest over scoped Goals."""
+
+ if focus not in VALID_TRIAGE_FOCUS:
+ raise StewardFastPathError(
+ "triage focus must be one of: all, gates, todos",
+ code="invalid_triage_focus",
+ )
+ if max_gates < 1 or max_todos < 1 or max_progress < 1 or max_text_chars < 32:
+ raise StewardFastPathError(
+ "triage bounds must be positive integers (max_text_chars >= 32)",
+ code="invalid_triage_bounds",
+ )
+
+ scoped_goal_ids = _select_scoped_goals(
+ authorized_goal_ids=authorized_goal_ids,
+ requested_goal_ids=requested_goal_ids,
+ )
+ registry = load_registry(registry_path)
+ all_gates: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
+ all_attention_todos: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
+ all_progress: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
+ unavailable_goals: list[dict[str, str]] = []
+ unavailable_recent_progress: list[str] = []
+
+ for goal_id in scoped_goal_ids:
+ try:
+ route = resolve_goal_source_runtime_route(
+ registry_path=registry_path, registry=registry, goal_id=goal_id,
+ )
+ # The Chat host's root is only a local default. A declared Goal
+ # source owns both the authoritative Todo read and its history.
+ source_root = Path(route["source_runtime_root"])
+ if runtime_root_arg and not route["routed_to_source_registry"]:
+ source_root = Path(runtime_root_arg).expanduser().resolve()
+ todo_snapshot = list_goal_todos(
+ registry_path=Path(route["source_registry"]),
+ goal_id=goal_id,
+ runtime_root_arg=str(source_root),
+ )
+ todos = todo_snapshot.get("todos")
+ if (todo_snapshot.get("ok") is not True or not isinstance(todos, list)
+ or todo_snapshot.get("todo_count", len(todos)) != len(todos)
+ or any(not isinstance(row, Mapping) or not row.get("todo_id") for row in todos)):
+ raise ValueError("Goal Todo coverage is incomplete")
+ except (
+ CanonicalAuthorityRequired,
+ LocalCoordinationAuthorityUnavailable,
+ OSError,
+ ValueError,
+ ) as exc:
+ error_code = str(getattr(exc, "code", "") or "goal_readback_unavailable")
+ unavailable_goals.append({"goal_id": goal_id, "error_code": error_code})
+ continue
+
+ for index, raw_todo in enumerate(todos):
+ if not isinstance(raw_todo, Mapping):
+ continue
+ todo_id = str(raw_todo.get("todo_id") or "").strip()
+ if not todo_id or raw_todo.get("superseded_by"):
+ continue
+ role = str(raw_todo.get("role") or "").strip()
+ status = str(raw_todo.get("status") or TODO_STATUS_OPEN).strip()
+ done = bool(raw_todo.get("done")) or status == TODO_STATUS_DONE
+ task_class = str(raw_todo.get("task_class") or "").strip()
+ priority = _effective_priority(raw_todo)
+
+ if (
+ role == "user"
+ and not done
+ and status in ACTIVE_TRIAGE_STATUSES
+ and task_class in ACTIONABLE_USER_TASK_CLASSES
+ ):
+ has_decision_scope = isinstance(raw_todo.get("decision_scope"), Mapping)
+ scope_summary = _decision_scope_summary(raw_todo.get("decision_scope"))
+ unblocks_todo_id = (
+ str(raw_todo.get("unblocks_todo_id") or "").strip() or None
+ )
+ gate_entry: dict[str, Any] = {
+ "goal_id": goal_id,
+ "todo_id": todo_id,
+ "task_class": task_class,
+ "status": status,
+ "priority": priority,
+ "global_gate": bool(raw_todo.get("global_gate")),
+ "text": _compact_public(
+ _strip_priority_prefix(raw_todo.get("text")), limit=max_text_chars
+ )
+ or WITHHELD_TEXT,
+ "note": _compact_public(
+ raw_todo.get("note") or raw_todo.get("reason"),
+ limit=max_text_chars,
+ )
+ or None,
+ "unblocks_todo_id": unblocks_todo_id,
+ "has_decision_scope": has_decision_scope,
+ "decision_scope_summary": scope_summary,
+ "state_fingerprint": compute_user_gate_state_fingerprint(
+ goal_id, raw_todo
+ ),
+ }
+ gate_sort = (
+ 0 if gate_entry["global_gate"] else 1,
+ 0 if task_class == TODO_TASK_CLASS_USER_GATE else 1,
+ _priority_rank(priority),
+ goal_id,
+ index,
+ todo_id,
+ )
+ all_gates.append((gate_sort, gate_entry))
+ continue
+
+ if role == "agent" and not done and status in ACTIVE_TRIAGE_STATUSES:
+ is_blocked = status == TODO_STATUS_BLOCKED
+ is_high_priority = priority in HIGH_PRIORITIES
+ if is_blocked or is_high_priority:
+ todo_entry: dict[str, Any] = {
+ "goal_id": goal_id,
+ "todo_id": todo_id,
+ "status": status,
+ "priority": priority,
+ "task_class": task_class or None,
+ "claimed_by": (
+ str(raw_todo.get("claimed_by") or "").strip() or None
+ ),
+ "text": _compact_public(
+ _strip_priority_prefix(raw_todo.get("text")),
+ limit=max_text_chars,
+ )
+ or WITHHELD_TEXT,
+ "reason": _compact_public(
+ raw_todo.get("reason") or raw_todo.get("note"),
+ limit=max_text_chars,
+ )
+ or None,
+ }
+ todo_sort = (
+ _priority_rank(priority),
+ 0 if is_blocked else 1,
+ goal_id,
+ index,
+ todo_id,
+ )
+ all_attention_todos.append((todo_sort, todo_entry))
+ continue
+
+ if focus == "all" and role == "agent" and done:
+ completed_stamp = str(
+ raw_todo.get("completed_at") or raw_todo.get("updated_at") or ""
+ ).strip()
+ progress_entry: dict[str, Any] = {
+ "kind": "completed_todo",
+ "goal_id": goal_id,
+ "todo_id": todo_id,
+ "timestamp": completed_stamp or None,
+ "summary": _compact_public(
+ raw_todo.get("text"), limit=max_text_chars
+ ),
+ }
+ all_progress.append(
+ (
+ (*chronology_key(completed_stamp), index),
+ progress_entry,
+ )
+ )
+
+ runs_index = source_root / "goals" / goal_id / "runs" / "index.jsonl"
+ if focus == "all":
+ try:
+ index_snapshot = load_index_snapshot(
+ runs_index, include_artifact_status=False, skip_invalid_encoding=True,
+ )
+ except OSError:
+ unavailable_recent_progress.append(goal_id)
+ continue
+ if index_snapshot.invalid_count:
+ unavailable_recent_progress.append(goal_id)
+ for run_idx, run in enumerate(index_snapshot.records[-3:]):
+ if not isinstance(run, Mapping):
+ continue
+ summary = _compact_public(
+ run.get("summary") or run.get("headline") or "",
+ limit=max_text_chars,
+ )
+ if not summary:
+ continue
+ generated_at = str(run.get("generated_at") or "").strip()
+ all_progress.append(
+ (
+ (*chronology_key(generated_at), run_idx),
+ {
+ "kind": "run_summary",
+ "goal_id": goal_id,
+ "todo_id": (
+ str(run.get("todo_id") or "").strip() or None
+ ),
+ "timestamp": generated_at or None,
+ "summary": summary,
+ },
+ )
+ )
+
+ all_gates.sort(key=lambda item: item[0])
+ all_attention_todos.sort(key=lambda item: item[0])
+ all_progress.sort(key=lambda item: item[0], reverse=True)
+
+ sorted_gates = [item[1] for item in all_gates]
+ sorted_todos = [item[1] for item in all_attention_todos]
+ sorted_progress = [item[1] for item in all_progress]
+
+ visible_gates = (
+ sorted_gates[:max_gates] if focus in {"all", "gates"} else []
+ )
+ visible_todos = (
+ sorted_todos[:max_todos] if focus in {"all", "todos"} else []
+ )
+ visible_progress = (
+ sorted_progress[:max_progress] if focus == "all" else []
+ )
+
+ blocked_count = sum(
+ 1 for item in sorted_todos if item.get("status") == TODO_STATUS_BLOCKED
+ )
+ high_priority_count = sum(
+ 1 for item in sorted_todos if item.get("priority") in HIGH_PRIORITIES
+ )
+ quiet = bool(scoped_goal_ids) and not (
+ unavailable_goals or unavailable_recent_progress or sorted_gates or sorted_todos
+ )
+
+ return {
+ "ok": True,
+ "schema_version": PORTFOLIO_TRIAGE_SCHEMA_VERSION,
+ "focus": focus,
+ "quiet": quiet,
+ "scoped_goal_ids": scoped_goal_ids,
+ "counts": {
+ "scoped_goals": len(scoped_goal_ids),
+ "unavailable_goals": len(unavailable_goals),
+ "open_user_gates": len(sorted_gates),
+ "visible_user_gates": len(visible_gates),
+ "omitted_user_gates": (
+ max(0, len(sorted_gates) - len(visible_gates))
+ if focus in {"all", "gates"}
+ else len(sorted_gates)
+ ),
+ "attention_todos": len(sorted_todos),
+ "blocked_todos": blocked_count,
+ "high_priority_todos": high_priority_count,
+ "visible_attention_todos": len(visible_todos),
+ "omitted_attention_todos": (
+ max(0, len(sorted_todos) - len(visible_todos))
+ if focus in {"all", "todos"}
+ else len(sorted_todos)
+ ),
+ "visible_recent_progress": len(visible_progress),
+ "omitted_recent_progress": (
+ max(0, len(sorted_progress) - len(visible_progress))
+ if focus == "all"
+ else len(sorted_progress)
+ ),
+ },
+ "open_user_gates": visible_gates,
+ "attention_todos": visible_todos,
+ "recent_progress": visible_progress,
+ "unavailable_goals": unavailable_goals,
+ "unavailable_recent_progress": unavailable_recent_progress,
+ "bounds": {
+ "max_gates": max_gates,
+ "max_todos": max_todos,
+ "max_progress": max_progress,
+ "max_text_chars": max_text_chars,
+ },
+ "execution_profile": {
+ "fast_path": True,
+ "read_only": True,
+ "lease_acquired": False,
+ "model_invoked": False,
+ "history_compacted": False,
+ "quota_spent": False,
+ "external_writes_performed": False,
+ },
+ }
+
+
+def render_portfolio_triage_markdown(projection: Mapping[str, Any]) -> str:
+ """Render a concise mobile-friendly Markdown summary of portfolio triage."""
+
+ counts = (
+ projection.get("counts")
+ if isinstance(projection.get("counts"), Mapping)
+ else {}
+ )
+ gates = (
+ projection.get("open_user_gates")
+ if isinstance(projection.get("open_user_gates"), list)
+ else []
+ )
+ todos = (
+ projection.get("attention_todos")
+ if isinstance(projection.get("attention_todos"), list)
+ else []
+ )
+ progress = (
+ projection.get("recent_progress")
+ if isinstance(projection.get("recent_progress"), list)
+ else []
+ )
+ unavailable = (
+ projection.get("unavailable_goals")
+ if isinstance(projection.get("unavailable_goals"), list)
+ else []
+ )
+
+ lines = [
+ "# Steward Fast-Path Triage",
+ "",
+ (
+ f"- Scope: `{counts.get('scoped_goals', 0)}` goal(s) | "
+ f"Open gates: `{counts.get('open_user_gates', 0)}` | "
+ f"P0/P1 & blocked: `{counts.get('attention_todos', 0)}`"
+ ),
+ ]
+ progress_unavailable = projection.get("unavailable_recent_progress") or []
+ readable = counts.get("scoped_goals", 0) - len(unavailable)
+ if unavailable:
+ coverage = "Project status unavailable." if not readable else "Showing the projects whose status could be read."
+ lines.extend(["", coverage])
+ if progress_unavailable:
+ lines.extend(["", f"Recent progress is incomplete for {len(progress_unavailable)} project(s)."])
+ if projection.get("quiet") is True and readable and not unavailable and not progress_unavailable:
+ lines.extend(
+ [
+ "",
+ "All clear: no open user gates or P0/P1/blocked todos require attention.",
+ ]
+ )
+ if gates:
+ lines.extend(["", "## Open User Gates"])
+ for gate in gates:
+ if not isinstance(gate, Mapping):
+ continue
+ badge = f"[{gate['priority']}] " if gate.get("priority") else ""
+ unblocks = (
+ f" (unblocks `{gate['unblocks_todo_id']}`)"
+ if gate.get("unblocks_todo_id")
+ else ""
+ )
+ lines.append(
+ f"- `{gate.get('goal_id')}` · `{gate.get('todo_id')}`: "
+ f"{badge}{gate.get('text')}{unblocks}"
+ )
+ omitted_gates = int(counts.get("omitted_user_gates") or 0)
+ if omitted_gates > 0 and projection.get("focus") in {"all", "gates"}:
+ lines.append(f"- _+{omitted_gates} more open user gate(s) omitted_")
+
+ if todos:
+ lines.extend(["", "## P0/P1 & Blocked Todos"])
+ for item in todos:
+ if not isinstance(item, Mapping):
+ continue
+ tags = []
+ if item.get("priority"):
+ tags.append(str(item["priority"]))
+ if item.get("status") == TODO_STATUS_BLOCKED:
+ tags.append("blocked")
+ prefix = f"[{'/'.join(tags)}] " if tags else ""
+ lines.append(
+ f"- `{item.get('goal_id')}` · `{item.get('todo_id')}`: "
+ f"{prefix}{item.get('text')}"
+ )
+ omitted_todos = int(counts.get("omitted_attention_todos") or 0)
+ if omitted_todos > 0 and projection.get("focus") in {"all", "todos"}:
+ lines.append(f"- _+{omitted_todos} more attention todo(s) omitted_")
+
+ if progress:
+ lines.extend(["", "## Recent Progress"])
+ for entry in progress:
+ if not isinstance(entry, Mapping):
+ continue
+ todo_part = f" · `{entry['todo_id']}`" if entry.get("todo_id") else ""
+ lines.append(
+ f"- `{entry.get('goal_id')}`{todo_part}: {entry.get('summary')}"
+ )
+
+ if unavailable:
+ lines.extend(["", "## Unavailable Goals"])
+ for row in unavailable:
+ if isinstance(row, Mapping):
+ lines.append(
+ f"- `{row.get('goal_id')}`: `{row.get('error_code')}`"
+ )
+
+ return "\n".join(lines).rstrip() + "\n"
+
+
+def execute_steward_fast_path(
+ *,
+ text: str,
+ bindings: Any,
+ binding_id: str,
+ source_ref: str,
+ sender_ref: str,
+ registry_path: Path,
+ runtime_root_arg: str | None = None,
+ private_human_message: bool = True,
+ origin: str | None = None,
+ session_context: dict[str, Any] | None = None,
+ max_gates: int = 8,
+ max_todos: int = 8,
+ max_progress: int = 5,
+) -> dict[str, Any] | None:
+ """Execute a read-only Steward Fast-Path request if `text` matches a fast intent.
+
+ Returns `None` when `text` is not a fast-path triage command so the caller
+ can proceed through ordinary Steward Turn admission unchanged. Raises
+ `StewardFastPathError` fail-closed when `text` IS a fast-path command but
+ the conversation binding, sender observation, or requested Goal scope is
+ unauthorized.
+ """
+
+ intent = parse_steward_fast_path_intent(text)
+ if intent is None:
+ return None
+
+ try:
+ resolved = bindings.resolve(
+ binding_id=binding_id,
+ source_ref=source_ref,
+ sender_ref=sender_ref,
+ private_human_message=private_human_message,
+ origin=origin,
+ session_context=session_context,
+ )
+ except (KeyError, OSError, ValueError) as exc:
+ raise StewardFastPathError(
+ str(exc) or "steward conversation binding is not authorized",
+ code="steward_binding_unauthorized",
+ ) from exc
+
+ binding = resolved.get("binding") if isinstance(resolved, Mapping) else None
+ if (
+ not isinstance(binding, Mapping)
+ or binding.get("enabled") is not True
+ or binding.get("context_kind") != "steward"
+ ):
+ raise StewardFastPathError(
+ "fast-path triage requires an enabled Steward conversation binding",
+ code="steward_binding_required",
+ )
+
+ projection = project_steward_triage(
+ intent,
+ resolved,
+ registry_path=registry_path,
+ runtime_root_arg=runtime_root_arg,
+ max_gates=max_gates,
+ max_todos=max_todos,
+ max_progress=max_progress,
+ )
+ return {
+ "ok": True,
+ "schema_version": FAST_PATH_RESPONSE_SCHEMA_VERSION,
+ "handled": True,
+ "command": intent.command,
+ "focus": intent.focus,
+ "binding_id": str(binding.get("binding_id") or binding_id),
+ "triage": projection,
+ "markdown": render_portfolio_triage_markdown(projection),
+ }
+
+
+def project_steward_triage(
+ intent: StewardFastPathIntent,
+ resolved: Mapping[str, Any],
+ *,
+ registry_path: Path,
+ runtime_root_arg: str | None,
+ max_gates: int = 8,
+ max_todos: int = 8,
+ max_progress: int = 5,
+) -> dict[str, Any]:
+ """Read the portfolio using the result of a fresh Core binding resolution."""
+ binding = resolved["binding"]
+ context = resolved.get("context")
+ steward_scope = (
+ context.get("steward_scope") if isinstance(context, Mapping) else None
+ )
+ if isinstance(context, Mapping) and isinstance(context.get("goal_ids"), list):
+ authorized_goal_ids = list(context["goal_ids"])
+ elif isinstance(steward_scope, Mapping) and isinstance(
+ steward_scope.get("goal_ids"), list
+ ):
+ authorized_goal_ids = [
+ str(item) for item in steward_scope["goal_ids"] if str(item).strip()
+ ]
+ elif binding.get("goal_scope") == "all_registered":
+ authorized_goal_ids = resolve_all_registered_goal_ids(registry_path)
+ else:
+ raw_ids = binding.get("goal_ids")
+ authorized_goal_ids = (
+ [str(item) for item in raw_ids if str(item).strip()]
+ if isinstance(raw_ids, list)
+ else []
+ )
+
+ return build_portfolio_triage_projection(
+ registry_path=registry_path,
+ runtime_root_arg=runtime_root_arg,
+ authorized_goal_ids=authorized_goal_ids,
+ requested_goal_ids=intent.requested_goal_ids or None,
+ focus=intent.focus,
+ max_gates=max_gates,
+ max_todos=max_todos,
+ max_progress=max_progress,
+ )
+
+
+__all__ = [
+ "FAST_PATH_RESPONSE_SCHEMA_VERSION",
+ "PORTFOLIO_TRIAGE_SCHEMA_VERSION",
+ "StewardFastPathError",
+ "StewardFastPathIntent",
+ "build_portfolio_triage_projection",
+ "compute_user_gate_state_fingerprint",
+ "execute_steward_fast_path",
+ "parse_steward_fast_path_intent",
+ "project_steward_triage",
+ "render_portfolio_triage_markdown",
+ "resolve_all_registered_goal_ids",
+]
diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py
index b6f68efa18..96083a9160 100644
--- a/loopx/capabilities/native_chat/steward_turn.py
+++ b/loopx/capabilities/native_chat/steward_turn.py
@@ -819,7 +819,14 @@ def launch():
adapter.session._launch_guard = launch
try:
- response = adapter.start_turn(prompt, event_sink)
+ if managed_turn and not governance_work:
+ from ...control_plane.effect_runtime import effect_runtime_result
+ policy = effect_runtime_result("collaboration.session.managed_turn.sandbox_policy", {
+ "host": request["host"], "actor": actor, "authority": authority,
+ "validation": managed_turn.validation_basis["plan"], "task_lease": managed_lease})
+ response = adapter.start_native_task_turn(prompt, event_sink, policy)
+ else:
+ response = adapter.start_turn(prompt, event_sink)
finally:
adapter.session._launch_guard = previous_guard
current() # Revocation/stop/retarget after a long model call wins.
diff --git a/loopx/capabilities/periodic_report/adapters.py b/loopx/capabilities/periodic_report/adapters.py
index 5477b07360..17c6d04ab6 100644
--- a/loopx/capabilities/periodic_report/adapters.py
+++ b/loopx/capabilities/periodic_report/adapters.py
@@ -17,12 +17,16 @@
from ...control_plane.content_digest import ENVELOPED_SHA256_PATTERN
from ...control_plane.digest_envelope import sha256_envelope
from ...public_safe_text import PUBLIC_SAFE_SLUG_PATTERN
-from .field_shapes import REPORT_LANGUAGE_PATTERN, SUPPORTING_CONTENT_KINDS
+from .field_shapes import (
+ DOCUMENT_SCHEMA,
+ ITEM_VISIBILITIES,
+ REPORT_LANGUAGE_PATTERN,
+ SUPPORTING_CONTENT_KINDS,
+)
SOURCE_RESULT_SCHEMA = "periodic_report_source_result_v0"
SECTION_SCHEMA = "periodic_report_section_v0"
-DOCUMENT_SCHEMA = "periodic_report_document_v0"
EDITORIAL_ORCHESTRATION_SCHEMA = "periodic_report_editorial_orchestration_v0"
ARTIFACT_SCHEMA = "periodic_report_artifact_v0"
SINK_RESULT_SCHEMA = "periodic_report_sink_result_v0"
@@ -38,7 +42,6 @@
"risk",
"runtime",
}
-_ITEM_VISIBILITIES = {"primary", "supporting"}
_HIGHLIGHT_TONES = {"attention", "neutral", "positive"}
SourceCollector = Callable[[Mapping[str, Any]], Mapping[str, Any]]
ArtifactRenderer = Callable[[Mapping[str, Any]], Mapping[str, Any]]
@@ -221,7 +224,7 @@ def _normalize_item(raw: object, *, label: str) -> dict[str, Any]:
)
if visibility:
visibility = _token(visibility, f"{label}.visibility")
- if visibility not in _ITEM_VISIBILITIES:
+ if visibility not in ITEM_VISIBILITIES:
raise ValueError(f"{label}.visibility is invalid")
normalized["visibility"] = visibility
if content_kind in SUPPORTING_CONTENT_KINDS and visibility != "supporting":
diff --git a/loopx/capabilities/periodic_report/audience.py b/loopx/capabilities/periodic_report/audience.py
index d9b13e1ca9..ca6fe7213c 100644
--- a/loopx/capabilities/periodic_report/audience.py
+++ b/loopx/capabilities/periodic_report/audience.py
@@ -7,14 +7,13 @@
from .core import _reject_raw_keys
from ...control_plane.digest_envelope import sha256_envelope
from ...public_safe_text import PUBLIC_SAFE_SLUG_PATTERN
+from .field_shapes import DOCUMENT_SCHEMA, ITEM_VISIBILITIES
AUDIENCE_POLICY_SCHEMA = "periodic_report_audience_policy_v0"
AUDIENCE_RECIPIENT_SCHEMA = "periodic_report_audience_recipient_v0"
AUDIENCE_ROUTING_RULE_SCHEMA = "periodic_report_audience_routing_rule_v0"
ANNOUNCEMENT_PLAN_SCHEMA = "periodic_report_announcement_plan_v0"
-_DOCUMENT_SCHEMA = "periodic_report_document_v0"
-_VISIBILITIES = {"primary", "supporting"}
_RULE_SELECTORS = {
"source_ids",
"section_ids",
@@ -111,7 +110,7 @@ def normalize_periodic_report_audience_policy(
"audience_policy.eligible_visibilities",
maximum=2,
)
- if not visibilities or any(value not in _VISIBILITIES for value in visibilities):
+ if not visibilities or any(value not in ITEM_VISIBILITIES for value in visibilities):
raise ValueError(
"audience_policy.eligible_visibilities must contain primary or supporting"
)
@@ -180,8 +179,8 @@ def normalize_periodic_report_audience_policy(
def _normalized_document_items(document: Mapping[str, Any]) -> list[dict[str, Any]]:
- if document.get("schema_version") != _DOCUMENT_SCHEMA:
- raise ValueError(f"document must use {_DOCUMENT_SCHEMA}")
+ if document.get("schema_version") != DOCUMENT_SCHEMA:
+ raise ValueError(f"document must use {DOCUMENT_SCHEMA}")
items: list[dict[str, Any]] = []
for section_index, raw_section in enumerate(
_sequence(document.get("sections", []), "document.sections")
@@ -197,7 +196,7 @@ def _normalized_document_items(document: Mapping[str, Any]) -> list[dict[str, An
visibility = _token(
item.get("visibility", "primary"), f"{item_label}.visibility"
)
- if visibility not in _VISIBILITIES:
+ if visibility not in ITEM_VISIBILITIES:
raise ValueError(f"{item_label}.visibility is invalid")
items.append(
{
diff --git a/loopx/capabilities/periodic_report/field_shapes.py b/loopx/capabilities/periodic_report/field_shapes.py
index 4685b723e2..3a1610f504 100644
--- a/loopx/capabilities/periodic_report/field_shapes.py
+++ b/loopx/capabilities/periodic_report/field_shapes.py
@@ -17,6 +17,12 @@
case-insensitive and up to 160 characters versus lowercase-led 3..128 -- so it is
bounded-context reuse of one name, not a copy, and it is pinned as distinct here
rather than merged away by renaming.
+
+The document schema tag and the item-visibility pair joined the owner later:
+``adapters.py`` and ``audience.py`` each stated the schema string and each listed
+the two visibilities, so a schema bump or a new visibility had two places to land.
+``adapters.DOCUMENT_SCHEMA`` stays importable from ``adapters`` because the
+bindings, archive and renderer faces read it from there.
"""
from __future__ import annotations
@@ -26,3 +32,5 @@
SUPPORTING_CONTENT_KINDS = frozenset({"coverage", "delivery_receipt", "runtime"})
REPORT_IDENTITY_PATTERN = re.compile(r"^[a-z][a-z0-9_.:-]{2,127}$")
REPORT_LANGUAGE_PATTERN = re.compile(r"^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$")
+DOCUMENT_SCHEMA = "periodic_report_document_v0"
+ITEM_VISIBILITIES = frozenset({"primary", "supporting"})
diff --git a/loopx/capabilities/periodic_report/pending_intent.py b/loopx/capabilities/periodic_report/pending_intent.py
index c1164f0093..6c3e746d2a 100644
--- a/loopx/capabilities/periodic_report/pending_intent.py
+++ b/loopx/capabilities/periodic_report/pending_intent.py
@@ -19,7 +19,6 @@
from ...control_plane.digest_envelope import sha256_envelope
from ...history import load_registry
from .field_shapes import REPORT_IDENTITY_PATTERN
-from .todo_source import read_report_todo_source
from ...registry import (
atomic_write_json,
find_registry_goal,
@@ -37,11 +36,6 @@
request_entry_for_intent,
settle_periodic_report_request,
)
-from .project_progress_snapshot import build_project_progress_snapshot
-from .incremental import (
- build_periodic_report_publication_candidate,
- write_periodic_report_publication_candidate,
-)
from .machine_defaults import (
build_periodic_report_delivery_authority,
resolve_active_goal_periodic_report_subscription,
@@ -175,6 +169,8 @@ def _superseding_approval_revision(
approval_scope = str(receipt.get("approval_scope") or "")
if receipt.get("status") != "approval_pending" or not approval_scope:
return None
+ from .todo_source import read_report_todo_source
+
_, items = read_report_todo_source(
registry_path=registry_path, goal_id=goal_id, runtime_root=runtime_root
)
@@ -513,6 +509,8 @@ def _progress_facts(
available_capabilities: Any = None,
allow_empty: bool = False,
) -> list[dict[str, Any]]:
+ from .project_progress_snapshot import build_project_progress_snapshot
+
from ...control_plane.todos.todo_index import (
MAX_TODO_INDEX_ROLLOUT_EVENTS_PER_GOAL,
)
@@ -1317,6 +1315,11 @@ def _consume_pending_periodic_report_intent(
if not execute:
return result
+ from .incremental import (
+ build_periodic_report_publication_candidate,
+ write_periodic_report_publication_candidate,
+ )
+
receipt_path = _receipt_path(
runtime_root,
goal_id,
diff --git a/loopx/capabilities/reward_memory/README.md b/loopx/capabilities/reward_memory/README.md
index 6ca4517fef..fe741044d7 100644
--- a/loopx/capabilities/reward_memory/README.md
+++ b/loopx/capabilities/reward_memory/README.md
@@ -287,8 +287,20 @@ engineering source kind, and opaque evidence refs; an ordinary Turn summary is
not evidence. It also carries `procedural_experience_contract_v0` with
applicability, observed outcome, attribution, complete future behavior,
limitations, and the same evidence refs. Legacy v0 reflections remain
-audit-only and cannot become durable memory. Ambiguous provider commits and
-unverified readbacks remain in a
+audit-only and cannot become durable memory. When the same Turn delivers recall
+guidance and enables ingest, reflection instructions ask the agent to compare new independent evidence with
+comparable procedural experience guidance. Without a comparable experience, the
+ordinary eligibility rule remains in force. Mere confirmation leaves the
+reflection empty; a candidate is
+produced only for distinct reusable applicability or a material change to its
+trigger, action, validation, stop condition, or limitations. Distinct
+applicability remains separate rather than being blended. Reflection never
+merges, updates, retires, or supersedes a provider record; configured lifecycle
+owners retain those decisions. This qualifies instruction delivery, not model
+compliance or a measured deduplication rate. The joint instructions fit the
+existing 64 KiB turn-context envelope; recall-only and ingest-only keep their
+ordinary instructions. Ambiguous
+provider commits and unverified readbacks remain in a
mode-0600 Goal+Agent+event sidecar. The next executing Turn retries the same
deterministic event before recall, so the provider can deduplicate it and LoopX
can require exact readback. Explicit disable suppresses reconciliation and all
diff --git a/loopx/capabilities/reward_memory/README.zh-CN.md b/loopx/capabilities/reward_memory/README.zh-CN.md
index 74d04970c1..d964c04bd9 100644
--- a/loopx/capabilities/reward_memory/README.zh-CN.md
+++ b/loopx/capabilities/reward_memory/README.zh-CN.md
@@ -187,7 +187,15 @@ quota settlement 均完成后,才接受 outcome ingest。Reflection 必须使
research/simulation/real/engineering 来源类型和 opaque evidence refs;还必须携带
`procedural_experience_contract_v0`,分别写出适用情境、已观察结果、归因、未来行为(触发、动作、
验证、停止条件)、失效边界,并绑定相同 evidence refs。只有事实复述、没有未来行为改变的普通
-Turn summary 不算经验。旧的 v0 reflection 只保留审计兼容,不会写成可持久召回的记忆。
+Turn summary 不算经验。旧的 v0 reflection 只保留审计兼容,不会写成可持久召回的记忆。同一
+Turn 同时交付 recall guidance 并启用 ingest 时,reflection 指令要求 Agent 把新的独立证据与其中可比较的
+procedural experience 对照;没有可比较经验时,仍使用普通资格规则。若只是确认相同的未来行为
+与失效边界,就保持为空。只有触发、动作、验证、停止条件或
+失效边界发生实质变化,或者形成可复用的独立适用情境时才生成候选;适用情境不同的经验保持
+分开,不混成更宽泛的规则。
+Reflection 不合并、更新、退役或取代 Provider 记录,这些决定仍属于已配置的生命周期 owner。
+这里验证的是指令交付,不代表模型遵从或已测得去重率。组合指令沿用现有 64 KiB Turn context
+边界;仅启用 recall 或仅启用 ingest 时,保留各自原有指令。
Provider commit 含糊或精确读回失败时,会保留一份权限为 0600、按 Goal+Agent+事件隔离的
sidecar。下一个执行 Turn 会在 recall 前以同一 deterministic event 重试,使 Provider 可以去重,
LoopX 再要求精确读回。显式关闭会停止 reconciliation,并保持零 Provider 调用。
diff --git a/loopx/capabilities/reward_memory/turn_hooks.py b/loopx/capabilities/reward_memory/turn_hooks.py
index 836e3ae870..0ccea48af6 100644
--- a/loopx/capabilities/reward_memory/turn_hooks.py
+++ b/loopx/capabilities/reward_memory/turn_hooks.py
@@ -21,6 +21,12 @@
def _reward_memory_prompt_instructions(*, has_guidance: bool, ingest_enabled: bool) -> list[str]:
+ if has_guidance and ingest_enabled:
+ # Share the eligibility/schema text instead of appending a third
+ # instruction: comparison must not displace recall within 64 KiB.
+ return [
+ 'Recall: private, non-authoritative; apply only if current evidence fits; no new action authority. Before reflecting, compare independent task evidence to comparable delivered procedural_experience; else use ordinary eligibility. reward_memory_reflection_json stays empty unless evidence establishes distinct reusable applicability or material trigger/action/validation/stop_condition/limitations changes. Keep distinct applicability separate. Eligible compact JSON: schema_version=turn_reward_memory_reflection_v1,status=eligible,configured surface_id,outcome_kind=research|simulation|real|engineering,content_summary,reasoning_summary,confidence=low|medium|high,1-5 opaque evidence_refs; experience: schema_version=procedural_experience_contract_v0,nonempty applicability/limitations lists,observed_outcome,attribution,same evidence_refs,future_behavior:trigger/action/validation/stop_condition. Require future behavior change and non-generalization limits; never use own summary as evidence. Legacy v0 reflections:audit-only,never durable memory. Only settlement may ingest after caller-declared Todo validator attests exact reflection digest/evidence; ordinary success:awaiting,no provider write. Provider-record merge/update/retire/supersede: never claim; configured owners decide.'
+ ]
instructions: list[str] = []
if has_guidance:
instructions.append(
diff --git a/loopx/chat/coordination.py b/loopx/chat/coordination.py
index 1f47003fcd..f6f57f06eb 100644
--- a/loopx/chat/coordination.py
+++ b/loopx/chat/coordination.py
@@ -6,6 +6,14 @@
from __future__ import annotations
+from copy import deepcopy
+import hashlib
+import os
+from pathlib import Path
+import shutil
+import stat
+import sys
+
PROJECT_COORDINATION_GUIDANCE = (
"This conversation concerns only the selected LoopX Goal. Read its current work, "
"member commitments and evidence before suggesting changes. Use loopx_context_read "
@@ -32,6 +40,220 @@
PROJECT_CONTEXT_VERSION = 2
+def check_preparation_tool():
+ """Project the existing proposal action for a newly bound managed thread."""
+ from ..chat_loopx_mode import TOOL
+ tool = deepcopy(TOOL)
+ tool["description"] = (
+ "Prepare a reviewable delivery check for this original registered Goal and Agent. "
+ "Use action=prepare_check with a stable operation_id and the existing compact "
+ "acceptance document: outcome_id and criteria [{id, validation_argv, oracle}]. "
+ "Read retained requirements with loopx_context_read first. Select an existing "
+ "independent checker from this Goal workspace using [python3, relative.py] or "
+ "[relative/executable], without options or extra arguments. The host pins its "
+ "actual source bytes and verifies python3 resolves to the host interpreter. Each oracle "
+ "is {kind: owner_pinned_oracle, source_id, input_refs, output_refs}; name the "
+ "explicit delivery files in output_refs. Do not invent a checker or replace "
+ "owner intent. The host supplies Goal, Agent, workspace and runtime identity. "
+ "Preparation saves only a goal.acceptance.check proposal. Explain its purpose "
+ "and effects for local-owner review; it neither configures acceptance nor runs "
+ "checks, claims work or launches a Turn. The owner judges whether the checker "
+ "addresses the requested outcome before applying it."
+ )
+ properties = tool["inputSchema"]["properties"]
+ tool["inputSchema"]["properties"] = {
+ key: properties[key] for key in ("action", "operation_id", "document")
+ }
+ tool["inputSchema"]["properties"]["document"]["description"] = (
+ "Existing compact acceptance document with outcome_id, criteria and optional scope. "
+ "Each criterion selects an existing requirement id, supported validation_argv, "
+ "and owner_pinned_oracle with explicit source_id, input_refs and output_refs. "
+ "Optional validation_files must match actual host source pins."
+ )
+ tool["inputSchema"]["properties"]["action"]["enum"] = ["prepare_check"]
+ tool["inputSchema"]["required"] = ["action", "operation_id", "document"]
+ return tool
+
+
+def _workspace_file(workspace: Path, ref: str, *, required: bool) -> str | None:
+ """Observe a regular relative file without following any symlink component.
+
+ Missing delivery files are legal during preparation. Descriptor-relative
+ opens keep a replaced parent from redirecting a source read outside the
+ original workspace; source digests are host observations, not verdicts.
+ """
+ directory_only = getattr(os, "O_DIRECTORY", None)
+ no_follow = getattr(os, "O_NOFOLLOW", None)
+ nonblock = getattr(os, "O_NONBLOCK", None)
+ if (
+ os.open not in os.supports_dir_fd
+ or directory_only is None
+ or no_follow is None
+ or nonblock is None
+ ):
+ raise ValueError("this host cannot safely inspect workspace checker sources")
+ if (not isinstance(ref, str) or not ref or "\\" in ref or "\0" in ref
+ or ref.startswith("/") or any(part in {"", ".", ".."} for part in ref.split("/"))):
+ raise ValueError("checker files must remain relative to the original workspace")
+ descriptors = []
+ try:
+ directory_flags = os.O_RDONLY | directory_only | no_follow
+ parent = os.open(workspace, directory_flags)
+ descriptors.append(parent)
+ parts = ref.split("/")
+ for part in parts[:-1]:
+ parent = os.open(part, directory_flags, dir_fd=parent)
+ descriptors.append(parent)
+ source = os.open(parts[-1], os.O_RDONLY | no_follow | nonblock, dir_fd=parent)
+ descriptors.append(source)
+ if not stat.S_ISREG(os.fstat(source).st_mode):
+ raise ValueError("checker sources and present artifacts must be regular files")
+ if not required:
+ return None
+ digest = hashlib.sha256()
+ while chunk := os.read(source, 1024 * 1024):
+ digest.update(chunk)
+ return digest.hexdigest()
+ except FileNotFoundError:
+ if not required:
+ return None
+ raise ValueError("the selected independent checker source is unavailable") from None
+ except OSError:
+ raise ValueError("checker sources and present artifacts must be readable regular files without symlinks") from None
+ finally:
+ for descriptor in reversed(descriptors):
+ os.close(descriptor)
+
+
+class _GoalSessionCheckPreparation:
+ """Per-Turn source IO over the existing typed identity and acceptance owners."""
+ def __init__(self, controller, adapter, session, turn_id, read):
+ self.controller, self.adapter, self.read = controller, adapter, read
+ self.session_id, self.turn_id = session["session_id"], turn_id
+ self.workspace = Path(adapter.session.work_dir)
+ self.runtime_root = controller.coordination_runtime_root
+ self.registry_path = controller.registry_path
+ self.original = deepcopy(session)
+ self.identity = self._current_identity()
+
+ def _current_identity(self):
+ from ..capabilities.native_chat.steward_managed_mode import registered_managed_session_identity
+ from ..control_plane.collaboration import conversation_scope
+ controller = self.controller
+ session = controller.store.load_session(self.session_id) or {}
+ turn = controller.store.load_turn(self.session_id, self.turn_id) or {}
+ fields = ("session_id", "goal_id", "goal_instance_id", "managed_agent_id",
+ "managed_workspace_path", "agent_id", "executor_endpoint_id", "adapter_kind",
+ "session_mode", "upstream_mode", "upstream_thread_id", "channel_id",
+ "project_context", "steward_context", "codex_home", "loopx_tools", "loopx_mode")
+ if (controller.closed.is_set() or controller.registry_path != self.registry_path
+ or controller.coordination_runtime_root != self.runtime_root
+ or any(session.get(key) != self.original.get(key) for key in fields)
+ or session.get("active_turn_id") != self.turn_id
+ or turn.get("session_id") != self.session_id or turn.get("turn_id") != self.turn_id
+ or turn.get("status") not in {"starting", "running"} or turn.get("origin") != "web"
+ or turn.get("loopx_execution") or turn.get("loopx_request")
+ or "collaboration_request" in turn or session.get("upstream_mode") != "chat"
+ or session.get("loopx_tools") or (session.get("loopx_mode") or {}).get("enabled")
+ or self.adapter.session.thread_id != session.get("upstream_thread_id")
+ or self.adapter.session.execution_mode or self.adapter.session.read_only_review
+ or getattr(self.adapter, "goal_driver", None) is not None
+ or Path(self.adapter.session.work_dir) != self.workspace
+ or conversation_scope(session, origin="web")["kind"] != "owner_goal"):
+ raise ValueError("the original local-owner managed Session and active read-only Turn are unavailable")
+ return registered_managed_session_identity(registry_path=self.registry_path,
+ goal_id=session.get("goal_id"), agent_id=session.get("managed_agent_id"),
+ workspace=self.workspace, session=session)
+
+ def _current(self):
+ if self._current_identity() != self.identity:
+ raise ValueError("the original managed Goal lifetime or Agent scope changed")
+
+ @staticmethod
+ def _python_interpreter():
+ executable = shutil.which("python3")
+ if executable is None or Path(executable).resolve() != Path(sys.executable).resolve():
+ raise ValueError("the supported python3 token is unavailable for this host interpreter")
+
+ def _document(self, document):
+ # Accepted document syntax, requirements, scope and oracle semantics
+ # remain with the TS owner. Only invocation/source IO is narrowed here.
+ document = deepcopy(document)
+ criteria = document.get("criteria")
+ if not isinstance(criteria, list) or not 1 <= len(criteria) <= 64:
+ raise ValueError("select bounded existing acceptance criteria and independent checker sources")
+ sources = {}
+ for criterion in criteria:
+ if not isinstance(criterion, dict):
+ raise ValueError("a check requires its existing criterion and checker source")
+ argv = criterion.get("validation_argv")
+ if (not isinstance(argv, list) or not argv or any(not isinstance(arg, str) for arg in argv)):
+ raise ValueError("select an immediate Python script or direct pinned executable")
+ if len(argv) == 2 and argv[0] in {"python", "python3", sys.executable} and argv[1].endswith(".py"):
+ source = argv[1]
+ self._python_interpreter()
+ criterion["validation_argv"] = ["python3", source]
+ elif len(argv) == 1 and "/" in argv[0]:
+ source = argv[0]
+ else:
+ raise ValueError("checker invocation supports only an immediate Python script or direct source, without options or extra arguments")
+ oracle = criterion.get("oracle")
+ if not isinstance(oracle, dict) or oracle.get("kind") != "owner_pinned_oracle":
+ raise ValueError("select an existing owner-pinned independent checker with explicit oracle outputs")
+ inputs, outputs = oracle.get("input_refs"), oracle.get("output_refs")
+ if (not isinstance(inputs, list) or not isinstance(outputs, list)
+ or len(inputs) > 20 or not 1 <= len(outputs) <= 20):
+ raise ValueError("an independent checker requires bounded explicit input and output refs")
+ if source in inputs or source in outputs:
+ raise ValueError("the independent checker source cannot be a checked input or delivery output")
+ self._current()
+ digest = _workspace_file(self.workspace, source, required=True)
+ self._current()
+ if source in sources and sources[source] != digest:
+ raise ValueError("the checker source changed during preparation")
+ pins = [{"path": source, "sha256": digest}]
+ if "validation_files" in criterion and criterion["validation_files"] != pins:
+ raise ValueError("the claimed checker source pin does not match the original workspace")
+ criterion["validation_files"] = pins
+ sources[source] = digest
+ for ref in [*inputs, *outputs]:
+ self._current()
+ _workspace_file(self.workspace, ref, required=False)
+ self._current()
+ # Reobserve the sources before publishing an immutable proposal; never
+ # refresh saved intent when a checker changed after a lost reply.
+ for source, digest in sources.items():
+ self._current()
+ if _workspace_file(self.workspace, source, required=True) != digest:
+ raise ValueError("the checker source changed during preparation")
+ self._current()
+ if any(row["validation_argv"][0] == "python3" for row in criteria):
+ self._python_interpreter()
+ return document
+
+ def __call__(self, tool, arguments):
+ from ..chat_loopx_mode import TOOL
+ if tool != TOOL["name"]:
+ return self.read(tool, arguments)
+ from ..chat_action_store import ActionConflictError
+ from ..control_plane.goals.acceptance_actions import prepare_acceptance_check
+ try:
+ self._current()
+ if (not isinstance(arguments, dict) or set(arguments) != {"action", "operation_id", "document"}
+ or arguments["action"] != "prepare_check" or not isinstance(arguments["document"], dict)
+ or not isinstance(arguments["operation_id"], str) or not arguments["operation_id"].strip()):
+ raise ValueError("prepare_check accepts only its stable operation_id and acceptance document; the host supplies actor and source identity")
+ document = self._document(arguments["document"])
+ self._current()
+ return prepare_acceptance_check(registry_path=self.registry_path,
+ runtime_root=str(self.runtime_root), goal_id=self.original["goal_id"],
+ agent_id=self.original["managed_agent_id"], document=document,
+ operation_id=arguments["operation_id"], execute=True)
+ except (ActionConflictError, ValueError) as exc:
+ return {"ok": False, "error": "collaboration_request_rejected",
+ "next_action": f"Check preparation was refused ({exc}). Read the original Goal and saved proposal; retry an operation only with unchanged intent and sources. A new intent needs a new operation id. Preparation cannot change authority or run the check."}
+
+
def apply_context_handoff(
controller, scope, session, turn, response, context, *, execution_allowed
):
@@ -212,6 +434,16 @@ def scope_valid() -> bool:
),
)
adapter.session.read_tool_handler = inspection.read
+ adapter._managed_read_turn_guard = None
+ if (session.get("managed_agent_id") and turn.get("origin") == "web"
+ and not turn.get("loopx_request") and not turn.get("loopx_execution")
+ and not session.get("loopx_tools") and not (session.get("loopx_mode") or {}).get("enabled")
+ and not adapter.session.execution_mode and not adapter.session.read_only_review
+ and getattr(adapter, "goal_driver", None) is None
+ and scope["kind"] == "owner_goal" and session.get("upstream_mode") == "chat"):
+ adapter.session.read_tool_handler = _GoalSessionCheckPreparation(
+ controller, adapter, session, turn_id, inspection.read)
+ adapter._managed_read_turn_guard = adapter.session.read_tool_handler._current
context["evidence_sources"] = inspection.sources()
context = manager_index(context, status_on_demand=status_on_demand)
from ..capabilities.native_chat.external_conversations import ChatExternalConversations
diff --git a/loopx/chat/event_cache.py b/loopx/chat/event_cache.py
index 0e158e2dd2..a9ec95a1d0 100644
--- a/loopx/chat/event_cache.py
+++ b/loopx/chat/event_cache.py
@@ -1,8 +1,14 @@
-"""Revision-bound chat replay snapshots; file I/O and locking stay in the store."""
+"""Revision-bound chat replay snapshots and event stream mixin for ``ChatSessionStore``."""
from __future__ import annotations
+from bisect import bisect_right
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
import threading
-from typing import Any
+from typing import TYPE_CHECKING, Any
+import uuid
+
+from ..file_lock import exclusive_file_lock
EventKey = tuple[str, str]
EventRevision = tuple[int, int, int] | None
@@ -14,6 +20,14 @@
TERMINAL_CACHE_MAX_ENCODED_BYTES = 2 * 1024 * 1024
+def _durable_by_append_id(rows: EventRows) -> dict[str, dict[str, Any]]:
+ return {
+ row["_append_id"]: row
+ for row in rows
+ if isinstance(row.get("_append_id"), str)
+ }
+
+
class ChatEventCache:
def __init__(self, lock: threading.RLock) -> None:
self._lock = lock
@@ -50,3 +64,199 @@ def retain_terminal(self, key: EventKey, rows: EventRows) -> None:
or sum(weight[1] for weight in self._finished.values()) > TERMINAL_CACHE_MAX_ENCODED_BYTES
):
self.drop(next(iter(self._finished)))
+
+
+class ChatEventStreamMixin:
+ if TYPE_CHECKING:
+ sessions_root: Path
+ _event_lock: threading.RLock
+ _event_cache: ChatEventCache
+ _event_pending: dict[EventKey, list[tuple[dict[str, Any], str]]]
+
+ def _event_path(self, session_id: str, turn_id: str) -> Path: ...
+ def _event_flush_lock(self, key: EventKey) -> threading.Lock: ...
+
+ def _event_rows_locked(self, session_id: str, turn_id: str) -> EventRows:
+ from .. import chat_store as _store
+
+ key = (session_id, turn_id)
+ path = self._event_path(session_id, turn_id)
+ revision = self._event_revision(path)
+ rows = self._event_cache.get(key, revision)
+ if rows is None:
+ rows = _store._read_jsonl(path)
+ self._event_cache.put(key, revision, rows)
+ return rows
+
+ @staticmethod
+ def _event_revision(path: Path) -> EventRevision:
+ try:
+ stat = path.stat()
+ except OSError:
+ return None
+ return stat.st_ino, stat.st_size, stat.st_mtime_ns
+
+ def append_event(
+ self,
+ session_id: str,
+ turn_id: str,
+ *,
+ kind: str,
+ payload: dict[str, Any],
+ buffered: bool = False,
+ ) -> dict[str, Any]:
+ from .. import chat_store as _store
+
+ key = (session_id, turn_id)
+ event = {
+ "schema_version": _store.CHAT_EVENT_SCHEMA_VERSION,
+ "kind": str(kind),
+ "created_at": _store.utc_now(),
+ "payload": payload,
+ }
+ with self._event_lock:
+ self._event_pending.setdefault(key, []).append((event, uuid.uuid4().hex))
+ if not buffered:
+ self.flush_events(session_id, turn_id)
+ return event
+
+ def flush_events(self, session_id: str, turn_id: str) -> int:
+ """Persist queued events in one ordered append and one data fsync."""
+ from .. import chat_store as _store
+
+ key = (session_id, turn_id)
+ path = self._event_path(session_id, turn_id)
+ flush_lock = self._event_flush_lock(key)
+ flushed = 0
+ with flush_lock:
+ while True:
+ with self._event_lock:
+ pending = self._event_pending.pop(key, [])
+ if not pending:
+ return flushed
+ try:
+ with exclusive_file_lock(path, agent_id="loopx-chat", operation="append_chat_events"):
+ append_started = False
+ try:
+ uncertain = any("sequence" in event for event, _ in pending)
+ rows = (
+ _store._read_jsonl(path, raise_on_error=True)
+ if uncertain
+ else self._event_rows_locked(session_id, turn_id)
+ )
+ # A failed append may already have persisted all or part of
+ # its batch. Match only this store's stable append ids; two
+ # otherwise identical events are still separate writes.
+ durable = _durable_by_append_id(rows) if uncertain else {}
+ # Allocate after the last persisted sequence under the same
+ # file lock. Compaction may leave gaps; another writer may
+ # have appended after a partial failed batch.
+ sequence = int(rows[-1].get("sequence") or 0) if rows else 0
+ to_append: EventRows = []
+ for event, append_id in pending:
+ committed = durable.get(append_id)
+ if committed is not None:
+ event["event_id"] = committed["event_id"]
+ event["sequence"] = committed["sequence"]
+ continue
+ sequence += 1
+ event["event_id"] = str(sequence)
+ event["sequence"] = sequence
+ to_append.append({**event, "_append_id": append_id})
+ append_started = True
+ _store._append_jsonl_rows(path, to_append)
+ if any(event["kind"] in _store.TERMINAL_EVENT_KINDS for event, _ in pending):
+ self._event_cache.drop(key)
+ else:
+ self._event_cache.put(key, self._event_revision(path), [*rows, *to_append])
+ except Exception:
+ if not append_started:
+ raise
+ # Confirm visible writes before releasing the file lock:
+ # another store may compact old events before our retry.
+ try:
+ written = _durable_by_append_id(_store._read_jsonl(path, raise_on_error=True))
+ except OSError:
+ pass # Keep all uncertain events for a later retry.
+ else:
+ remaining = []
+ for event, append_id in pending:
+ committed = written.get(append_id)
+ if committed is None:
+ remaining.append((event, append_id))
+ else:
+ event["event_id"] = committed["event_id"]
+ event["sequence"] = committed["sequence"]
+ pending = remaining
+ raise
+ except Exception:
+ self._event_cache.drop(key)
+ with self._event_lock:
+ later = self._event_pending.get(key, [])
+ if pending or later:
+ self._event_pending[key] = [*pending, *later]
+ else:
+ self._event_pending.pop(key, None)
+ raise
+ flushed += len(pending)
+
+ def events_after(self, session_id: str, turn_id: str, event_id: str | None) -> EventRows:
+ from .. import chat_store as _store
+
+ try:
+ after = int(event_id or 0)
+ except ValueError:
+ after = 0
+ self.flush_events(session_id, turn_id)
+ key = (session_id, turn_id)
+ path = self._event_path(session_id, turn_id)
+ revision = self._event_revision(path)
+ rows = self._event_cache.get(key, revision)
+ if rows is None:
+ with exclusive_file_lock(path, agent_id="loopx-chat", operation="read_chat_events"):
+ rows = self._event_rows_locked(session_id, turn_id)
+ # Relies on the sequence ordering maintained by flush_events and compaction;
+ # gaps are valid, but inserting or rewriting rows must preserve that order.
+ start = bisect_right(rows, after, key=lambda row: int(row.get("sequence") or 0))
+ result = rows[start:]
+ if rows and rows[-1].get("kind") in _store.TERMINAL_EVENT_KINDS:
+ self._event_cache.retain_terminal(key, rows)
+ return [
+ {field: value for field, value in row.items() if field != "_append_id"}
+ for row in result
+ ]
+
+ def compact_completed_events(self, *, older_than_hours: float = 24.0) -> int:
+ """Drop replay-only deltas after the durable final message is old enough."""
+ from .. import chat_store as _store
+
+ cutoff = datetime.now(timezone.utc) - timedelta(hours=max(0.0, older_than_hours))
+ compacted = 0
+ for turn_path in self.sessions_root.glob("*/turns/*.json"):
+ turn = _store._read_json(turn_path)
+ if turn.get("status") not in _store.TERMINAL_TURN_STATES:
+ continue
+ completed = _store._instant(turn.get("completed_at"))
+ if completed is None or completed > cutoff:
+ continue
+ session_id = turn_path.parent.parent.name
+ turn_id = turn_path.stem
+ self.flush_events(session_id, turn_id)
+ event_path = turn_path.with_name(f"{turn_path.stem}.events.jsonl")
+ revision = self._event_revision(event_path)
+ if turn.get("event_compaction_revision") == list(revision or ()):
+ continue
+ with exclusive_file_lock(event_path, agent_id="loopx-chat", operation="compact_chat_events"):
+ rows = self._event_rows_locked(session_id, turn_id)
+ retained = [row for row in rows if row.get("kind") not in _store.REPLAY_ONLY_EVENT_KINDS]
+ if len(retained) != len(rows):
+ _store._replace_jsonl(event_path, retained)
+ compacted += 1
+ revision = self._event_revision(event_path)
+ self._event_cache.drop((session_id, turn_id))
+ with exclusive_file_lock(turn_path, agent_id="loopx-chat", operation="mark_chat_events_compacted"):
+ current = _store._read_json(turn_path)
+ if current.get("status") in _store.TERMINAL_TURN_STATES:
+ current["event_compaction_revision"] = list(revision or ())
+ _store._atomic_write_json(turn_path, current, preserve_mode=True)
+ return compacted
diff --git a/loopx/chat/goal_creation_execution.py b/loopx/chat/goal_creation_execution.py
new file mode 100644
index 0000000000..298332cbdb
--- /dev/null
+++ b/loopx/chat/goal_creation_execution.py
@@ -0,0 +1,99 @@
+"""IO in the existing confirmed Goal-creation saga, not a new execution owner."""
+from __future__ import annotations
+
+from typing import Any
+
+from ..agent_registry import load_goal_from_registry
+from ..boundary_authority import build_checkpointed_boundary_authority_entry
+from ..chat_action_store import ActionConflictError
+from ..configure_goal import configure_goal
+from ..control_plane.runtime.time import now_utc
+
+
+def retain_creation_write_approval(service: Any, proposal_id: str, review: dict[str, Any] | None) -> None:
+ """Publish an explicit reviewed grant once and recover its exact readback.
+
+ The typed creation review chooses scope. This IO adapter uses the existing
+ configuration/authority owners and never refreshes a lost or revoked grant.
+ """
+ if not review or not review["writeScope"]:
+ return
+ proposal = service.store.load(proposal_id)
+ goal_id = proposal["normalized_parameters"]["goal_id"]
+ goal = load_goal_from_registry(service.registry_path, goal_id)
+ if goal is None or goal.get("creation_operation_id") != proposal_id:
+ raise ActionConflictError("The write approval belongs to the original Goal creation")
+ steps = (proposal.get("checkpoint") or {}).get("steps", {})
+ prepared = steps.get("boundary_authority_prepared")
+ if prepared is None:
+ entry = build_checkpointed_boundary_authority_entry(
+ write_scopes=review["writeScope"], source="goal_creation_review",
+ decision_id=proposal_id, recorded_at=now_utc().isoformat(),
+ )
+ prepared = {"goal_id": goal_id, "goal_instance_id": goal.get("goal_instance_id"), "authority": entry}
+ service.store.save_checkpoint(proposal_id, step="boundary_authority_prepared", receipt=prepared)
+ entry = prepared.get("authority")
+ if (prepared.get("goal_id") != goal_id or prepared.get("goal_instance_id") != goal.get("goal_instance_id")
+ or not isinstance(entry, dict) or entry.get("write_scope") != review["writeScope"]
+ or entry.get("decision_id") != proposal_id or entry.get("source") != "goal_creation_review"
+ or entry.get("status") != "active" or entry.get("decision") != "approve"):
+ raise ActionConflictError("The original reviewed write approval changed; retain its recorded operation")
+
+ def observe() -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ current = load_goal_from_registry(service.registry_path, goal_id)
+ if (current is None or current.get("creation_operation_id") != proposal_id
+ or current.get("goal_instance_id") != prepared["goal_instance_id"]):
+ raise ActionConflictError("The original Goal lifetime changed before approval readback")
+ coordination = current.get("coordination") or {}
+ entries = coordination.get("checkpointed_boundary_authority") or []
+ if not isinstance(entries, list):
+ raise ActionConflictError("The original boundary authority is unreadable")
+ return coordination, [row for row in entries if isinstance(row, dict) and row.get("decision_id") == proposal_id]
+
+ coordination, matches = observe()
+ if not matches:
+ if steps.get("boundary_authority_write_started") is not None or steps.get("boundary_authority_recorded") is not None:
+ raise ActionConflictError("The original approval publication is unconfirmed or revoked; read back that operation before proceeding")
+ service.store.save_checkpoint(proposal_id, step="boundary_authority_write_started",
+ receipt={"goal_id": goal_id, "decision_id": proposal_id})
+ configure_goal(registry_path=service.registry_path, goal_id=goal_id,
+ write_scope=review["writeScope"], boundary_authority_scopes=entry["write_scope"],
+ boundary_authority_source=entry["source"], boundary_authority_decision_id=entry["decision_id"],
+ boundary_authority_recorded_at=entry["recorded_at"], execute=True)
+ coordination, matches = observe()
+ if (matches != [entry] or any(scope not in (coordination.get("write_scope") or []) for scope in review["writeScope"])):
+ raise ActionConflictError("The original write approval or declared scope changed; do not refresh it from a creation replay")
+ service.store.save_checkpoint(proposal_id, step="boundary_authority_recorded", receipt={
+ "outcome": "boundary_authority_recorded", **prepared,
+ })
+
+
+def retain_original_task_request(service: Any, proposal_id: str, session: dict[str, Any]) -> dict[str, Any] | None:
+ """Persist the same reviewed request before queueing, without executing it."""
+ from ..capabilities.native_chat.steward_managed_mode import StewardManagedMode
+ from ..control_plane.effect_runtime import effect_runtime_result
+ from ..control_plane.goals.acceptance import inspect_goal_acceptance
+ proposal = service.store.load(proposal_id)
+ if proposal["normalized_parameters"].get("start_execution") is not True:
+ return None
+ controller = service.runtime_controller
+ basis = inspect_goal_acceptance(registry_path=service.registry_path,
+ runtime_root=str(controller.coordination_runtime_root), goal_id=session["goal_id"],
+ agent_id=session["managed_agent_id"])
+ selection = effect_runtime_result("goal.task.creation_selection", {"basis": basis})
+ request = effect_runtime_result("goal.creation.execution_request.prepare", {
+ "proposal": proposal, "session": session,
+ "goal": StewardManagedMode(controller, None)._goal(session["goal_id"]),
+ "current_original_task": selection,
+ })
+ prior = ((proposal.get("checkpoint") or {}).get("steps") or {}).get("original_task_requested")
+ receipt = {"outcome": "original_task_requested", **request, "source": {
+ "request_digest": proposal["request_digest"],
+ "expected_state_fingerprint": proposal["expected_state_fingerprint"],
+ "upstream_thread_id": session["upstream_thread_id"],
+ }}
+ if prior is not None and prior != receipt:
+ raise ActionConflictError("The retained original Task execution request changed")
+ if prior is None:
+ service.store.save_checkpoint(proposal_id, step="original_task_requested", receipt=receipt)
+ return request
diff --git a/loopx/chat/journal.py b/loopx/chat/journal.py
new file mode 100644
index 0000000000..5bc29b27fb
--- /dev/null
+++ b/loopx/chat/journal.py
@@ -0,0 +1,22 @@
+"""Decode Chat journal rows for both complete and scoped history reads."""
+
+import json
+from typing import Any
+
+
+def decode_chat_journal(lines: list[bytes], *, strict: bool) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for line in lines:
+ if not line.strip():
+ continue
+ try:
+ item = json.loads(line)
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ if strict:
+ raise ValueError("invalid Chat journal record") from exc
+ continue
+ if isinstance(item, dict):
+ rows.append(item)
+ elif strict:
+ raise ValueError("invalid Chat journal record")
+ return rows
diff --git a/loopx/chat/result_files_api.py b/loopx/chat/result_files_api.py
index 8a59a6f2e7..b06060a1b8 100644
--- a/loopx/chat/result_files_api.py
+++ b/loopx/chat/result_files_api.py
@@ -1,14 +1,90 @@
-"""Download an immutable returned file through its existing original Chat row."""
+"""Read media from its original Chat message."""
-from urllib.parse import quote
+import re
+from base64 import b64decode
+from hashlib import sha256
+from urllib.parse import quote, unquote
from ..capabilities.manager_context.roundtrip import read_chat_return_file
+from ..chat_attachments import CHAT_IMAGE_MAX_BYTES, CHAT_IMAGE_TYPES
+from ..control_plane.content_digest import BARE_SHA256_PATTERN
from ..control_plane.effect_runtime import effect_runtime_request_scope
+def is_bound_steward_history(session):
+ context = session.get("steward_context") if session else None
+ return isinstance(context, dict) and context.get("kind") == "bound_steward"
+
+
+def _inline_image(attachment):
+ if not isinstance(attachment, dict):
+ return None
+ mime, data, size = (attachment.get(k) for k in ("mime_type", "data_url", "size"))
+ if (not isinstance(mime, str) or mime not in CHAT_IMAGE_TYPES or not isinstance(data, str)
+ or type(size) is not int or not 0 < size <= CHAT_IMAGE_MAX_BYTES
+ or not data.startswith(f"data:{mime};base64,")
+ or len(data.partition(",")[2]) != ((size + 2) // 3) * 4):
+ return None
+ return mime, data, size
+
+
+def link_chat_history_images(session_id, messages):
+ """Project history images as scoped URLs without changing the stored rows."""
+ result = []
+ for message in messages:
+ attachments = message.get("attachments")
+ if not isinstance(attachments, list):
+ result.append(message)
+ continue
+ projected = []
+ for index, attachment in enumerate(attachments):
+ image = _inline_image(attachment)
+ if image is None:
+ projected.append(attachment)
+ continue
+ _, data, _ = image
+ # The URL changes if the image bytes change, so the existing visible
+ # page digest and history resume proof still bind the original image.
+ identity = sha256(data.encode()).hexdigest()
+ route = (f"/api/chat/sessions/{quote(session_id, safe='')}/messages/"
+ f"{quote(message['message_id'], safe='')}/images/{index}/{identity}")
+ projected.append({**attachment, "data_url": route})
+ result.append({**message, "attachments": projected})
+ return result
+
+
+def read_chat_history_image(store, session_id, message_id, index, identity):
+ session = store.load_session(session_id)
+ if not is_bound_steward_history(session):
+ raise KeyError("session unavailable")
+ attachments = store.read_history_message(session_id, message_id).get("attachments")
+ if not isinstance(attachments, list) or not 0 <= index < len(attachments):
+ raise KeyError("image unavailable")
+ image = _inline_image(attachments[index])
+ if image is None:
+ raise KeyError("image unavailable")
+ mime, data, size = image
+ if sha256(data.encode()).hexdigest() != identity:
+ raise KeyError("image version unavailable")
+ body = b64decode(data.partition(",")[2], validate=True)
+ if len(body) != size:
+ raise KeyError("image unavailable")
+ return mime, body
+
+
class ChatResultFilesRequestMixin:
+ def _link_history_images(self, session_id, session, selection, rows):
+ if (self.headers.get("X-LoopX-History-Images") == "linked"
+ and selection["message_limit"] is not None and selection["turn_id"] is None
+ and is_bound_steward_history(session)):
+ return link_chat_history_images(session_id, rows)
+ return rows
+
def _dispatch_result_file_read(self, path: str) -> bool:
parts = path.strip("/").split("/")
+ if (len(parts) == 9 and parts[:3] == ["api", "chat", "sessions"]
+ and parts[4] == "messages" and parts[6] == "images"):
+ return self._serve_chat_history_image(parts)
if (len(parts) != 8 or parts[:3] != ["api", "chat", "sessions"]
or parts[4] != "messages" or parts[6] != "files"):
return False
@@ -33,3 +109,29 @@ def _dispatch_result_file_read(self, path: str) -> bool:
self.end_headers()
self.wfile.write(body)
return True
+
+ def _serve_chat_history_image(self, parts) -> bool:
+ if not self._require_loopback_origin():
+ return True
+ if self.headers.get("Sec-Fetch-Site") == "cross-site":
+ self._send_error("Conversation images are only available to the original App.", status=403)
+ return True
+ try:
+ if not re.fullmatch(r"[0-9]{1,3}", parts[7]) or not BARE_SHA256_PATTERN.fullmatch(parts[8]):
+ raise KeyError("image unavailable")
+ mime, body = read_chat_history_image(
+ self.server.chat_store, unquote(parts[3]), unquote(parts[5]), int(parts[7]), parts[8])
+ except (KeyError, ValueError):
+ self._send_error("Image was not found in this conversation.", status=404)
+ except (OSError, RuntimeError):
+ self._send_error("Conversation image is temporarily unavailable.", status=503)
+ else:
+ self.send_response(200)
+ self.send_header("Content-Type", mime)
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Cache-Control", "no-store")
+ self.send_header("Cross-Origin-Resource-Policy", "same-origin")
+ self.send_header("X-Content-Type-Options", "nosniff")
+ self.end_headers()
+ self.wfile.write(body)
+ return True
diff --git a/loopx/chat/session_open.py b/loopx/chat/session_open.py
index e140d3fb4d..167eff8947 100644
--- a/loopx/chat/session_open.py
+++ b/loopx/chat/session_open.py
@@ -20,15 +20,140 @@
from __future__ import annotations
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any, Mapping
from ..chat_manager import open_manager_session
+if TYPE_CHECKING:
+ from ..chat_action_store import ChatActionStore
+ from ..chat_runtime import ChatRuntimeController
+ from ..chat_store import ChatSessionStore
+
# The executor a Goal-scoped session runs on when the caller makes no explicit
# pick. The steward channel does not use this: it resolves its own default.
DEFAULT_GOAL_AGENT_ID = "codex"
+def require_regular_session_paths(chat_store: ChatSessionStore, session_id: str) -> None:
+ """A redirected or incomplete reservation cannot identify an original."""
+ directory, metadata = chat_store._session_dir(session_id), chat_store._session_path(session_id)
+ if (directory.is_symlink() or metadata.is_symlink()
+ or directory.exists() and not directory.is_dir()
+ or metadata.exists() and not metadata.is_file()):
+ raise ValueError("The original Session reservation is unavailable; restore its regular metadata")
+
+
+def read_goal_creation_session(
+ action_store: ChatActionStore,
+ chat_store: ChatSessionStore | None,
+ *,
+ proposal_id: str,
+ session_id: str,
+ goal_id: str,
+ agent_id: str,
+ workspace: Path,
+ goal_instance_id: str | None,
+ expected_managed_agent: str | None = None,
+) -> dict[str, Any]:
+ """Read the original metadata against the creation's fresh checkpoint."""
+ from ..control_plane.collaboration import conversation_scope
+
+ if chat_store is not None:
+ require_regular_session_paths(chat_store, session_id)
+ session = chat_store.load_session(session_id) if chat_store is not None else None
+ scope = conversation_scope(session) if session is not None else {}
+ if (session is None or session.get("session_id") != session_id or session.get("goal_id") != goal_id
+ or session.get("agent_id") != agent_id
+ or scope.get("goal_ids") != [goal_id] or scope.get("kind") != "owner_goal"):
+ raise ValueError("The original first Session is unavailable; restore it before retrying")
+ if expected_managed_agent is not None and session.get("managed_agent_id") != expected_managed_agent:
+ raise ValueError("The original registered Agent Session identity changed")
+ recorded_proposal = action_store.load(proposal_id)
+ if recorded_proposal is None:
+ raise ValueError("The original creation checkpoint is unavailable")
+ recorded = ((recorded_proposal.get("checkpoint") or {}).get("steps") or {}).get("first_session_opened") or {}
+ for field in ("channel_id", "managed_agent_id", "goal_instance_id"):
+ if field in recorded and recorded[field] != session.get(field):
+ raise ValueError("The original first Session route changed; restore its recorded identity")
+ if session.get("managed_agent_id") is not None and (
+ session["managed_agent_id"] != agent_id
+ or session.get("goal_instance_id") != goal_instance_id
+ or session.get("managed_workspace_path") != str(workspace)
+ ):
+ raise ValueError("The original registered Agent Session identity changed")
+ return session
+
+
+def recover_goal_creation_session(
+ chat_store: ChatSessionStore,
+ *,
+ client_turn_id: str,
+ goal_id: str,
+ agent_id: str,
+) -> dict[str, Any] | None:
+ """Recover a unique published original, preferring its original client Turn."""
+ from ..control_plane.collaboration import conversation_scope
+
+ candidates = []
+ for directory in chat_store.sessions_root.iterdir():
+ if not directory.is_dir() and not directory.is_symlink():
+ continue
+ require_regular_session_paths(chat_store, directory.name)
+ if not chat_store._session_path(directory.name).is_file():
+ raise ValueError("The original Session reservation is unconfirmed; restore its metadata")
+ row = chat_store.load_session(directory.name)
+ if row is None or row.get("session_id") != directory.name:
+ raise ValueError("Original Session discovery is unreadable; restore it before retrying")
+ if (row.get("goal_id") == goal_id and row.get("agent_id") == agent_id
+ and conversation_scope(row).get("kind") == "owner_goal"):
+ candidates.append(row)
+ matches = [row for row in candidates if chat_store.turn_for_client(row["session_id"], client_turn_id) is not None]
+ if len(matches) > 1 or not matches and len(candidates) > 1:
+ raise ValueError("The original first Session is ambiguous; restore its recorded operation")
+ if matches:
+ return matches[0]
+ if candidates:
+ raise ValueError("The original first Session opening is unconfirmed; restore its exact checkpoint")
+ return None
+
+
+def read_exact_original_session(
+ controller: ChatRuntimeController,
+ *,
+ session_id: str,
+ selected_scope: Mapping[str, object],
+ agent_id: str,
+ work_dir: Path,
+ requested_model: str | None = None,
+ requested_effort: str | None = None,
+) -> dict[str, Any] | None:
+ """Read one exact opening under the caller's existing Session opening lock."""
+ from ..capabilities.native_chat.steward_managed_mode import require_managed_agent_session
+ from ..chat_store import CHAT_SESSION_MODE_MANAGED, RESUMABLE_SESSION_STATES
+ from ..control_plane.collaboration import conversation_scope
+
+ require_regular_session_paths(controller.store, session_id)
+ original = controller.store.load_session(session_id)
+ if original is not None:
+ if (original.get("session_id") != session_id
+ or original.get("goal_id") != selected_scope.get("goal_id") or original.get("agent_id") != agent_id
+ or original.get("executor_endpoint_id") != agent_id
+ or original.get("channel_id") != selected_scope.get("channel_id")
+ or original.get("managed_agent_id") != selected_scope.get("managed_agent_id")
+ or original.get("goal_instance_id") != selected_scope.get("goal_instance_id")
+ or original.get("session_mode") != CHAT_SESSION_MODE_MANAGED
+ or conversation_scope(original)["kind"] != "owner_goal"
+ or original.get("status") not in RESUMABLE_SESSION_STATES
+ or requested_model and original.get("agent_model_id") != requested_model
+ or requested_effort and original.get("agent_reasoning_effort") != requested_effort):
+ raise ValueError("the original Goal Session opening identity changed")
+ require_managed_agent_session(controller, original, work_dir)
+ return original
+ if controller.store._session_dir(session_id).exists():
+ raise ValueError("the original Goal Session is unreadable; restore it before retrying")
+ return None
+
+
def open_chat_session(
*,
controller: Any,
@@ -49,6 +174,22 @@ def open_chat_session(
raise ValueError("a registered managed Agent requires its local Goal conversation")
if context_kind == "manager":
+ # The App's persisted source choice owns the default entry on the
+ # server too. API callers must not fork a local manager when the
+ # selected private conversation is unavailable.
+ bindings = controller.project_contexts.conversation_bindings
+ if bindings is not None:
+ session = bindings.app_steward_session()
+ if session is not None:
+ if mode != "resume_latest":
+ raise ValueError("Continue the selected original steward conversation; start a new conversation from its original source.")
+ if any(requested and requested != session.get(field) for requested, field in (
+ (requested_endpoint, "executor_endpoint_id"),
+ (agent_model_id, "agent_model_id"),
+ (agent_reasoning_effort, "agent_reasoning_effort"),
+ )):
+ raise ValueError("Change the selected steward's model in Settings before continuing its original conversation.")
+ return session, True
return open_manager_session(
controller=controller,
goal_id=goal_id,
@@ -81,3 +222,19 @@ def open_chat_session(
agent_model_id=agent_model_id or None,
**({"agent_reasoning_effort": agent_reasoning_effort} if agent_reasoning_effort is not None else {}),
)
+
+
+def goal_creation_display_message(store: ChatSessionStore, *, session_id: str, client_turn_id: str, objective: str) -> str:
+ """Show confirmed intent on creation; preserve the original display on retry.
+
+ The execution request remains unchanged. An old recorded message is never
+ rewritten using the Goal's later objective or a new presentation default.
+ """
+ turn = store.turn_for_client(session_id, client_turn_id)
+ if turn is None:
+ return objective
+ messages = [row for row in store.messages(session_id, strict=True)
+ if row.get("turn_id") == turn["turn_id"] and row.get("role") == "user"]
+ if len(messages) != 1 or not isinstance(messages[0].get("text"), str):
+ raise ValueError("The original first Turn display is unavailable; restore its recorded message")
+ return messages[0]["text"]
diff --git a/loopx/chat/status_api.py b/loopx/chat/status_api.py
index 86e03e339b..c43b0e48d0 100644
--- a/loopx/chat/status_api.py
+++ b/loopx/chat/status_api.py
@@ -75,7 +75,7 @@ def _goal_task_map(server: Any, goal_id: str) -> dict[str, Any] | None:
goal_id=goal_id,
runtime_root_arg=str(runtime_root) if runtime_root else None,
)
- except (OSError, ValueError):
+ except (OSError, ValueError, LocalCoordinationAuthorityUnavailable):
# An unreadable Todo source leaves the rest of the review usable.
return None
todos = [row for row in listed.get("todos") or [] if isinstance(row, dict)]
diff --git a/loopx/chat/todo_actions.py b/loopx/chat/todo_actions.py
index 3d805121d3..4bdc1150f2 100644
--- a/loopx/chat/todo_actions.py
+++ b/loopx/chat/todo_actions.py
@@ -2,14 +2,26 @@
from __future__ import annotations
+from collections.abc import Iterator
+from contextlib import ExitStack, contextmanager
+from pathlib import Path
from typing import Any
+from ..chat_store import ChatSessionStore, TERMINAL_TURN_STATES
+from ..file_lock import exclusive_cross_runtime_file_lock
+from ..history import load_registry
+from ..registry import find_registry_goal
+from ..control_plane.goals.activation import goal_is_stopped
+from ..control_plane.coordination.shadow_management import shadow_maintenance_lock_target
+from ..control_plane.runtime.runtime_projection_route import resolve_goal_source_runtime_route
from ..control_plane.todos.mutation_api import complete_goal_todo, update_goal_todo
+from ..control_plane.todos.completion_validation import COMPLETION_VALIDATION_IN_PROGRESS
from ..control_plane.coordination.local_authority import (
LocalCoordinationAuthorityUnavailable, read_canonical_todos_if_promoted,
)
from ..paths import effective_runtime_root
from ..control_plane.todos.provider_projection import projection_delivery_requires_ack
+from ..control_plane.work_items.task_lease import lease_is_active
def _decision_readback(result: dict[str, Any]) -> dict[str, Any]:
@@ -24,6 +36,158 @@ def _decision_readback(result: dict[str, Any]) -> dict[str, Any]:
class ChatTodoActionMixin:
"""Keep Todo preview/apply parity separate from general orchestration."""
+ @contextmanager
+ def _confirmed_task_commit(
+ self, *, goal_id: str, todo_id: str, endpoint: str, project: Path,
+ claim: dict[str, Any],
+ ) -> Iterator[None]:
+ """Fence acceptance with the same registry and canonical writers as Stop and Todo edits."""
+ invoked = self.registry_path.resolve()
+ route = resolve_goal_source_runtime_route(registry_path=invoked, goal_id=goal_id)
+ source = Path(route["source_registry"])
+ # Claim used this runtime. Recheck it after taking the same maintenance
+ # guard as canonical writers, in the order used by Goal deletion.
+ runtime = effective_runtime_root(invoked, None).resolve()
+ targets: tuple[Path, ...] = (shadow_maintenance_lock_target(runtime, goal_id), source)
+ if source != invoked:
+ targets += (invoked,)
+ with ExitStack() as locks:
+ for target in targets:
+ locks.enter_context(exclusive_cross_runtime_file_lock(target, operation="confirm_task_admission"))
+ if (route != resolve_goal_source_runtime_route(registry_path=invoked, goal_id=goal_id)
+ or runtime != effective_runtime_root(invoked, None).resolve()):
+ raise ValueError("The reviewed Task's Goal source changed")
+ goal = find_registry_goal(load_registry(source), goal_id)
+ if goal is None or goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
+ raise ValueError("The Task's Goal is no longer active")
+ if Path(str(goal.get("repo") or ".")).expanduser().resolve() != project:
+ raise ValueError("The reviewed Task's project root changed")
+ owner = claim["claimed_by"]
+ if self._resolve_goal_agent(goal_id, endpoint, goal=goal) != owner:
+ raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent")
+ authority = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=goal_id, include_leases=True)
+ todo = next((row for row in authority["todos"] if row["todo_id"] == todo_id), None)
+ if (todo is None or todo.get("role") != "agent" or todo.get("status") != "open"
+ or todo.get("claimed_by") != owner or authority["handoff_mode"] != claim["handoff_mode"]):
+ raise ValueError("The reviewed Task assignment changed before launch")
+ if authority["handoff_mode"] == "hard_lease":
+ lease = next((row for row in authority["leases"] if row["todo_id"] == todo_id), None)
+ original = claim.get("lease")
+ if (not lease or not isinstance(original, dict) or not lease_is_active(lease)
+ or any(lease.get(key) != original.get(key) for key in ("owner", "idempotency_key", "lease_epoch"))):
+ raise ValueError("The reviewed Task execution lease changed before launch")
+ yield
+
+ @staticmethod
+ def _read_task_start(
+ chat: ChatSessionStore, *, goal_id: str, agent_id: str, channel_id: str,
+ client_turn_id: str, checkpoint: dict[str, Any] | None,
+ ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
+ from ..chat_actions import _opaque
+
+ if checkpoint is not None:
+ sid = _opaque(checkpoint.get("session_id"), field="session_id")
+ session = chat.load_session(sid)
+ if (session is None or session.get("goal_id") != goal_id
+ or session.get("agent_id") != agent_id or session.get("channel_id") != channel_id):
+ raise ValueError("The original Task Session is unavailable")
+ return session, chat.turn_for_client(sid, client_turn_id)
+
+ # A process may have persisted the Session before the proposal's
+ # checkpoint. Include closed Sessions so retry cannot replace one.
+ sessions = chat.session_candidates(goal_id=goal_id, agent_id=agent_id, channel_id=channel_id)
+ matches = [
+ (session, turn) for session in sessions
+ if (turn := chat.turn_for_client(session["session_id"], client_turn_id)) is not None
+ ]
+ if len(matches) == 1:
+ return matches[0]
+ if len(sessions) > 1:
+ raise ValueError("The original Task Session is ambiguous")
+ return (sessions[0] if sessions else None), None
+
+ def _start_confirmed_task(
+ self, proposal_id: str, parameters: dict[str, Any], todo_id: str, steps: dict[str, Any],
+ ) -> dict[str, Any]:
+ from ..chat_actions import _opaque
+
+ controller = self.runtime_controller
+ chat = getattr(controller, "store", None) or self.chat_store
+ if chat is None:
+ raise ValueError("Chat Runtime Controller is unavailable")
+ goal_id = str(parameters["goal_id"])
+ owner = str(parameters["agent_id"])
+ endpoint = str(parameters.get("endpoint_id") or owner)
+ message = str(parameters["text"])
+ channel_id = f"task.{todo_id}"
+ client_turn_id = f"task-start-{proposal_id}"
+ opened = steps.get("task_session_opened")
+ execution = steps.get("execution_started")
+ session, turn = self._read_task_start(
+ chat, goal_id=goal_id, agent_id=endpoint, channel_id=channel_id,
+ client_turn_id=client_turn_id, checkpoint=execution if execution is not None else opened,
+ )
+ if execution is not None and (turn is None or turn["turn_id"] != execution.get("turn_id")):
+ raise ValueError("The original Task Turn is unavailable")
+ if turn is not None and turn.get("message") != message:
+ raise ValueError("The original Task Turn request changed")
+
+ # An already dispatched or terminal Turn is readback. Only work that
+ # still needs dispatch passes through the current Goal and claim gates.
+ created = False
+ if turn is None or (
+ turn.get("status") not in TERMINAL_TURN_STATES
+ and not (turn.get("started_at") or turn.get("upstream_turn_id"))
+ ):
+ if controller is None:
+ raise ValueError("Chat Runtime Controller is unavailable")
+ if session is not None and session.get("status") == "closed":
+ raise ValueError("The original Task Session is closed")
+ goal = self._goal(goal_id)
+ if goal.get("status", "active") not in {"active", "ready"} or goal_is_stopped(goal):
+ raise ValueError("The Task's Goal is no longer active")
+ project = Path(str(goal.get("repo") or ".")).expanduser().resolve()
+ if not project.is_dir():
+ raise ValueError("the Goal project root is unavailable")
+ self._agent_eligibility(endpoint, project=project)
+ if parameters.get("endpoint_id") and self._resolve_goal_agent(goal_id, endpoint) != owner:
+ raise ValueError("The reviewed Agent endpoint now belongs to another Goal Agent")
+ claim_args = {
+ "registry_path": self.registry_path, "goal_id": goal_id, "todo_id": todo_id,
+ "claimed_by": owner, "agent_id": owner, "claim_only": True, "manage_execution": True,
+ }
+ claim = update_goal_todo(**claim_args, claim_operation_id=f"chat-task-start:{proposal_id}", dry_run=False)
+ if claim["handoff_mode"] == "soft_claim" and claim["status"] in {"recovered", "replayed"}:
+ # A past soft claim still needs a read-only current-owner check.
+ if update_goal_todo(**claim_args, dry_run=True)["changed"]:
+ raise ValueError("The reviewed Task assignment changed before launch")
+ if not isinstance(steps.get("todo_assigned"), dict):
+ self.store.save_checkpoint(
+ proposal_id, step="todo_assigned", receipt={"todo_id": todo_id, "agent_id": owner},
+ )
+ if session is None:
+ session, _ = controller.open_session(
+ goal_id=goal_id, agent_id=endpoint, work_dir=project, objective=message,
+ mode="resume_latest", channel_id=channel_id, agent_goal_id=goal_id,
+ )
+ sid = _opaque(session.get("session_id"), field="session_id")
+ if opened is None and execution is None:
+ self.store.save_checkpoint(proposal_id, step="task_session_opened", receipt={"session_id": sid})
+ turn, created = controller.submit_turn(
+ session_id=sid, client_turn_id=client_turn_id, message=message, work_dir=project, objective=message,
+ _goal_commit=lambda: self._confirmed_task_commit(
+ goal_id=goal_id, todo_id=todo_id, endpoint=endpoint, project=project, claim=claim,
+ ),
+ )
+
+ identity = {
+ "session_id": _opaque(turn.get("session_id"), field="session_id"),
+ "turn_id": _opaque(turn.get("turn_id"), field="turn_id"),
+ }
+ if execution is None:
+ self.store.save_checkpoint(proposal_id, step="execution_started", receipt=identity)
+ return {**identity, "status": str(turn.get("status") or "accepted"), "created": created}
+
def _run_todo_update(
self, parameters: dict[str, Any], *, dry_run: bool,
basis: dict[str, Any] | None = None, operation_id: str | None = None,
@@ -171,6 +335,7 @@ def _apply_reviewed_todo_edit(
Both paths drain the current projection, never an old receipt's state.
"""
from ..chat_actions import _digest, _opaque
+ from ..chat_action_store import ActionConflictError
operation_id = f"chat-update:{proposal_id}"
basis = proposal["canonical_update_basis"]
@@ -181,6 +346,9 @@ def _apply_reviewed_todo_edit(
try:
result = run(parameters, dry_run=False, basis=basis, operation_id=operation_id)
except LocalCoordinationAuthorityUnavailable as error:
+ if error.code == COMPLETION_VALIDATION_IN_PROGRESS:
+ # The original caller still owns its result and proposal.
+ raise ActionConflictError(str(error)) from error
if (terminal and error.code == "authority_source_changed"
and error.payload.get("completion_validation_executed") is True):
self.store.mark_failed(
diff --git a/loopx/chat_action_normalization.py b/loopx/chat_action_normalization.py
index bb67f17b15..ebdfc9f9a8 100644
--- a/loopx/chat_action_normalization.py
+++ b/loopx/chat_action_normalization.py
@@ -546,6 +546,7 @@ def _normalize(
"stop_condition",
"initial_todos",
"native_token_budget",
+ "start_execution",
},
)
goal_id = _opaque(values.get("goal_id"), field="goal_id")
@@ -569,11 +570,13 @@ def _normalize(
"objective",
"completion_criteria",
"execution_boundary",
- "permission",
"stop_condition",
):
if values.get(field):
result[field] = _text(values[field], field=field, limit=1000)
+ if "permission" in values or "start_execution" in values:
+ from .control_plane.effect_runtime import effect_runtime_result
+ result.update(effect_runtime_result("goal.creation.execution.normalize", values))
for field in ("agent_id", "workspace_ref"):
if values.get(field):
result[field] = _opaque(values[field], field=field)
diff --git a/loopx/chat_actions.py b/loopx/chat_actions.py
index 0e2b1ba01d..f743e72841 100644
--- a/loopx/chat_actions.py
+++ b/loopx/chat_actions.py
@@ -20,7 +20,7 @@
)
from .chat_goal_lifecycle_actions import ChatGoalLifecycleActionMixin
from .chat.monitor_actions import ChatMonitorActionMixin
-from .chat_store import ChatSessionStore
+from .chat_store import ChatSessionStore, TERMINAL_TURN_STATES
from .chat.todo_actions import ChatTodoActionMixin
from .control_plane.goals.acceptance_actions import GoalAcceptanceActionMixin
from .control_plane.goals.goal_objective_actions import GoalObjectiveActionMixin
@@ -41,6 +41,7 @@
from .quota import build_quota_should_run
from .registry import registry_goals
from .control_plane.todos.mutation_api import add_goal_todo, update_goal_todo
+from .file_lock import try_exclusive_file_lock
CHAT_ACTION_RESPONSE_SCHEMA_VERSION = "loopx_chat_action_response_v1"
@@ -241,6 +242,8 @@ def __init__(
self.registry_path = Path(registry_path).expanduser().resolve()
self.chat_store = chat_store
self.runtime_controller = runtime_controller
+ if runtime_controller is not None:
+ runtime_controller.original_task_action_store = store
# The runtime root the serving Chat selected (its --runtime-root). A
# creation on a registry that does not exist yet has no recorded root
# to follow, so the first Goal must persist where the service already
@@ -420,11 +423,14 @@ def _agent_family(value: str) -> str:
return family
return token
- def _resolve_goal_agent(self, goal_id: str, endpoint_id: str) -> str:
+ def _resolve_goal_agent(
+ self, goal_id: str, endpoint_id: str, *, goal: dict[str, object] | None = None,
+ ) -> str:
"""Resolve a runtime Endpoint to the Goal's durable peer identity."""
self._agent_eligibility(endpoint_id)
- goal = self._goal(goal_id)
+ if goal is None:
+ goal = self._goal(goal_id)
registered = registered_agent_ids_for_goal(goal)
if endpoint_id in registered:
return endpoint_id
@@ -664,7 +670,8 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
),
None,
)
- progress = effect_runtime_result("presentation.action_review_plan.compile", {"proposal": proposal}).get("creationProgress") or {}
+ creation_plan = effect_runtime_result("presentation.action_review_plan.compile", {"proposal": proposal})
+ progress = creation_plan.get("creationProgress") or {}
if (proposal.get("checkpoint") or {}).get("steps") and not progress:
raise ValueError("Goal creation checkpoints do not match the original request; inspect the recorded operation")
project, source_goal = self._project_for_goal_create(proposal, progress=progress)
@@ -783,6 +790,9 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
},
)
todo_ids: list[str] = list(progress.get("todoIds") or [])
+ if creation_plan.get("creationExecution"):
+ from .chat.goal_creation_execution import retain_creation_write_approval
+ retain_creation_write_approval(self, proposal_id, creation_plan["creationExecution"])
# Canonical File/SQLite own replay after a committed write loses its
# response. Historical target-only creation retains its old adapter.
pending_todos = (parameters.get("initial_todos") or []) if "todoIds" not in progress else []
@@ -799,6 +809,8 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
agent_id=agent_id or None,
dry_run=False,
operation_id=f"goal-create:{proposal_id}:todo:{index}" if authority is not None else None,
+ **({"required_write_scopes": creation_plan["creationExecution"]["writeScope"]}
+ if creation_plan.get("creationExecution", {}).get("writeScope") else {}),
)
if todo.get("todo_id"):
todo_ids.append(str(todo["todo_id"]))
@@ -838,63 +850,119 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
raise ValueError(
"Goal projection did not retain the selected Agent binding"
)
+ from functools import partial
+ from .chat.session_open import read_goal_creation_session, recover_goal_creation_session, require_regular_session_paths, goal_creation_display_message
+
+ read_original_session = partial(read_goal_creation_session,
+ self.store, self.chat_store or getattr(self.runtime_controller, "store", None),
+ proposal_id=proposal_id, goal_id=goal_id, agent_id=agent_id,
+ workspace=project, goal_instance_id=projected.get("goal_instance_id"))
+
turn_result: dict[str, Any] | None = None
session_id = ""
+ first_turn_message = (f"/goal start --tokens {parameters['native_token_budget']} {objective}"
+ if parameters.get("native_token_budget") else (
+ f"开始推进 Goal {goal_id}。先核对目标边界和现有 Todo,"
+ f"首个 Todo:{';'.join(str(item) for item in (parameters.get('initial_todos') or [])[:3]) or '按目标边界建立首个可验证进展'}。"
+ "然后直接推进并报告可验证结果;遇到权限边界时停止并提出明确 Gate。"
+ ))
+ opening_session_id = _digest({"goal_create": proposal_id, "goal_id": goal_id})[:32]
+ expected_managed_agent = (creation_plan.get("creationSession") or {}).get("managedAgentId")
+ turn_store = self.chat_store or getattr(self.runtime_controller, "store", None)
+ if not progress.get("firstTurn") and not progress.get("sessionId") and turn_store is not None:
+ require_regular_session_paths(turn_store, opening_session_id)
+ original = turn_store.load_session(opening_session_id)
+ if original is not None:
+ read_original_session(session_id=opening_session_id, expected_managed_agent=expected_managed_agent)
+ elif turn_store._session_dir(opening_session_id).exists():
+ raise ValueError("The original first Session is unreadable; restore it before retrying")
+ elif existing_goal is not None:
+ # Historical opening responses carried no operation-bound id.
+ # Recover only an unambiguous original; never choose latest.
+ original = recover_goal_creation_session(turn_store,
+ client_turn_id=f"goal-start-{proposal_id}", goal_id=goal_id, agent_id=agent_id)
+ if original is not None:
+ read_original_session(session_id=original["session_id"])
+ progress = {**progress, "sessionId": original["session_id"]}
if progress.get("firstTurn"):
session_id = progress["firstTurn"]["sessionId"]
turn_id = progress["firstTurn"]["turnId"]
turn_store = self.chat_store or getattr(self.runtime_controller, "store", None)
- session = turn_store.load_session(session_id) if turn_store is not None else None
- turn = turn_store.load_turn(session_id, turn_id) if session is not None else None
- if session is None or session.get("goal_id") != goal_id or session.get("agent_id") != agent_id or turn is None:
+ session = read_original_session(session_id=session_id)
+ turn = turn_store.load_turn(session_id, turn_id) if turn_store is not None else None
+ if turn is None:
raise ValueError("The recorded first Turn is unavailable; restore its original Session instead of starting another")
+ if (turn.get("message") != first_turn_message
+ or turn.get("client_turn_id") != f"goal-start-{proposal_id}"):
+ raise ValueError("The original first Turn request changed; retain its recorded operation")
require_first_turn_readback(turn)
turn_result = {"turn_id": turn_id, "status": str(turn["status"]), "created": False}
+ elif progress.get("sessionId"):
+ turn_store = self.chat_store or getattr(self.runtime_controller, "store", None)
+ if turn_store is None:
+ raise ValueError("The original first Session is unavailable; restore it before retrying")
+ original_session = read_original_session(session_id=progress["sessionId"])
+ session, turn = self._read_task_start(
+ turn_store, goal_id=goal_id, agent_id=agent_id, channel_id=original_session["channel_id"],
+ client_turn_id=f"goal-start-{proposal_id}", checkpoint={"session_id": progress["sessionId"]},
+ )
+ if turn is not None:
+ if turn.get("message") != first_turn_message:
+ raise ValueError("The original first Turn request changed; retain its recorded operation")
+ require_first_turn_readback(turn)
+ if turn.get("status") in TERMINAL_TURN_STATES or turn.get("started_at") or turn.get("upstream_turn_id"):
+ session_id = session["session_id"]
+ turn_result = {"turn_id": turn["turn_id"], "status": str(turn["status"]), "created": False}
+ self.store.save_checkpoint(proposal_id, step="first_turn_started", receipt={
+ "outcome": "first_turn_started", "session_id": session_id, "turn_id": turn["turn_id"],
+ })
first_turn_gate: dict[str, Any] | None = None
- try:
- from .status import collect_status
+ if agent_id and self.runtime_controller is not None and turn_result is None:
+ try:
+ from .status import collect_status
- status_payload = collect_status(
- registry_path=self.registry_path,
- runtime_root_override=str(runtime_root) if runtime_root else None,
- limit=5,
- goal_id=goal_id,
- available_capabilities=(
- self.runtime_controller.capabilities()
- if self.runtime_controller is not None
- else None
- ),
- )
- guard = build_quota_should_run(
- status_payload,
- goal_id=goal_id,
- agent_id=agent_id or None,
- available_capabilities=(
- self.runtime_controller.capabilities()
- if self.runtime_controller is not None
- else None
- ),
- )
- except Exception:
- guard = {"should_run": True, "state": "status_unavailable"}
- if guard.get("should_run") is not True and turn_result is None:
- first_turn_gate = {
- "kind": "goal_quota_gate",
- "summary": str(
- guard.get("reason")
- or "The new Goal is not eligible for its first Agent Turn."
- )[:600],
- "next_action": str(
- guard.get("recommended_action")
- or "Resolve the projected Goal Gate and retry the first Turn."
- )[:600],
- "quota_state": str(guard.get("state") or "waiting"),
- }
+ status_payload = collect_status(
+ registry_path=self.registry_path,
+ runtime_root_override=str(runtime_root) if runtime_root else None,
+ limit=5,
+ goal_id=goal_id,
+ available_capabilities=(
+ self.runtime_controller.capabilities()
+ if self.runtime_controller is not None
+ else None
+ ),
+ )
+ guard = build_quota_should_run(
+ status_payload,
+ goal_id=goal_id,
+ agent_id=agent_id or None,
+ available_capabilities=(
+ self.runtime_controller.capabilities()
+ if self.runtime_controller is not None
+ else None
+ ),
+ )
+ except Exception as exc:
+ raise ValueError(
+ "The first Turn's Goal admission could not be verified. "
+ "Retain this creation and retry when its admission source is available."
+ ) from exc
+ if guard.get("should_run") is not True:
+ first_turn_gate = {
+ "kind": "goal_quota_gate",
+ "summary": str(
+ guard.get("reason")
+ or "The new Goal is not eligible for its first Agent Turn."
+ )[:600],
+ "next_action": str(
+ guard.get("recommended_action")
+ or "Resolve the projected Goal Gate and retry the first Turn."
+ )[:600],
+ "quota_state": str(guard.get("state") or "waiting"),
+ }
if agent_id and self.runtime_controller is not None and first_turn_gate is None and turn_result is None:
if progress.get("sessionId"):
- session = self.runtime_controller.store.load_session(progress["sessionId"])
- if session is None or session.get("goal_id") != goal_id or session.get("agent_id") != agent_id:
- raise ValueError("The original first Session is unavailable; restore it before retrying")
+ session = read_original_session(session_id=progress["sessionId"])
else:
session, _resumed = self.runtime_controller.open_session(
goal_id=goal_id,
@@ -906,24 +974,34 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
agent_id=agent_id,
work_dir=project,
objective=objective,
- mode="resume_latest",
+ mode="new",
+ session_id=opening_session_id,
channel_id=f"goal.{goal_id}",
agent_goal_id=goal_id,
+ **({"managed_agent_id": creation_plan["creationSession"]["managedAgentId"]}
+ if creation_plan.get("creationSession") else {}),
)
session_id = _opaque(session.get("session_id"), field="session_id")
+ if not progress.get("sessionId") and session_id != opening_session_id:
+ raise ValueError("The original first Session opening returned another operation")
+ session = read_original_session(session_id=session_id,
+ expected_managed_agent=expected_managed_agent if not progress.get("sessionId") else None)
self.store.save_checkpoint(proposal_id, step="first_session_opened",
- receipt={"outcome": "first_session_opened", "session_id": session_id})
+ receipt={"outcome": "first_session_opened", "session_id": session_id,
+ "channel_id": session["channel_id"],
+ **({"managed_agent_id": session["managed_agent_id"],
+ "goal_instance_id": session.get("goal_instance_id")}
+ if session.get("managed_agent_id") is not None else {}),
+ **({"upstream_thread_id": session.get("upstream_thread_id")}
+ if creation_plan.get("creationExecution") else {})})
first_turn, created = self.runtime_controller.submit_turn(
session_id=session_id,
client_turn_id=f"goal-start-{proposal_id}",
- message=(f"/goal start --tokens {parameters['native_token_budget']} {objective}"
- if parameters.get("native_token_budget") else (
- f"开始推进 Goal {goal_id}。先核对目标边界和现有 Todo,"
- f"首个 Todo:{';'.join(str(item) for item in (parameters.get('initial_todos') or [])[:3]) or '按目标边界建立首个可验证进展'}。"
- "然后直接推进并报告可验证结果;遇到权限边界时停止并提出明确 Gate。"
- )),
+ message=first_turn_message,
work_dir=project,
objective=objective,
+ **({"display_message": goal_creation_display_message(turn_store, session_id=session_id,
+ client_turn_id=f"goal-start-{proposal_id}", objective=objective)} if expected_managed_agent else {}),
)
require_first_turn_readback(first_turn)
turn_result = {
@@ -946,6 +1024,18 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
step="first_turn_gated",
receipt={"outcome": "first_turn_gated", "gate": first_turn_gate},
)
+ if creation_plan.get("creationExecution"):
+ # An applied receipt is immutable. Keep this confirmed start
+ # retryable until its original Session/request is retained;
+ # quota denial cannot silently discard the requested work.
+ raise ValueError("The original Goal and Task are retained, but their first Turn admission is held. "
+ + first_turn_gate["summary"] + " Retry this same creation when its allowance is ready.")
+ if session_id:
+ session = read_original_session(session_id=session_id)
+ original_task_request = None
+ if session_id and parameters.get("start_execution") is True:
+ from .chat.goal_creation_execution import retain_original_task_request
+ original_task_request = retain_original_task_request(self, proposal_id, session)
child_gate: dict[str, Any] | None = first_turn_gate
if heartbeat.get("enabled") is True:
heartbeat_parameters = {
@@ -989,18 +1079,24 @@ def require_first_turn_readback(turn: dict[str, Any]) -> None:
**({"agent_id": agent_id} if agent_id else {}),
**({"todo_ids": todo_ids} if todo_ids else {}),
**({"session_id": session_id} if session_id else {}),
+ **({"managed_agent_id": session["managed_agent_id"], "channel_id": session["channel_id"],
+ "goal_instance_id": session.get("goal_instance_id")}
+ if session_id and session.get("managed_agent_id") is not None else {}),
**({"turn_id": turn_result["turn_id"]} if turn_result else {}),
},
**({"child_gate": child_gate} if child_gate else {}),
"step_receipts": (
(self.store.load(proposal_id) or {}).get("checkpoint") or {}
).get("steps", {}),
+ **({"original_task_request": original_task_request} if original_task_request is not None else {}),
}
stored = self.store.apply(
proposal_id,
current_state_fingerprint=str(proposal["expected_state_fingerprint"]),
receipt=receipt,
)
+ if original_task_request is not None:
+ self.runtime_controller.resume_session_queue(session_id=session_id, work_dir=project, objective=objective)
return {"proposal": stored, "turn": turn_result, "gate": child_gate}
def _apply_agent_bind(
@@ -1517,6 +1613,18 @@ def regenerate(self, proposal_id: str) -> dict[str, Any]:
def apply(self, proposal_id: str, *, steward_context: dict[str, Any] | None = None,
steward_confirmed_at: str | None = None) -> dict[str, Any]:
+ result = self._apply_owner_action(proposal_id, steward_context=steward_context,
+ steward_confirmed_at=steward_confirmed_at)
+ # A committed action changes current facts. Existing queue readers may
+ # reobserve their retained requests; this content-free hint performs no
+ # transport, Task admission, permission change or new submission.
+ wakeup = getattr(self.runtime_controller, "turn_release_wakeup", None)
+ if (result.get("proposal") or {}).get("status") == "applied" and wakeup is not None:
+ wakeup.notify()
+ return result
+
+ def _apply_owner_action(self, proposal_id: str, *, steward_context: dict[str, object] | None = None,
+ steward_confirmed_at: str | None = None) -> dict[str, object]:
proposal = self.store.load(proposal_id)
if proposal is None:
raise KeyError("typed Chat action proposal was not found")
@@ -1542,7 +1650,22 @@ def apply(self, proposal_id: str, *, steward_context: dict[str, Any] | None = No
"next_action": "Confirm the exact request through its authenticated operation card.",
},
)
+ parameters = proposal.get("normalized_parameters")
+ if (proposal.get("action_kind") in {"todo.create", "goal.create"} and isinstance(parameters, dict)
+ and parameters.get("start_execution") is True):
+ key = _opaque(proposal_id, field="proposal_id")
+ with try_exclusive_file_lock(
+ self.store.root / "task-starts" / f"{key}.json", operation="confirm_task_start",
+ ) as held:
+ if held is None:
+ raise ActionConflictError("The original Task confirmation is in progress. Retry it when it finishes.")
+ return self._apply_confirmed_action(proposal_id)
+ return self._apply_confirmed_action(proposal_id)
+
+ def _apply_confirmed_action(self, proposal_id: str) -> dict[str, object]:
proposal = self.store.start_apply(proposal_id)
+ if proposal["status"] == "applied":
+ return {"proposal": proposal, "turn": self._turn_from_receipt(proposal.get("receipt"))}
action_kind = str(proposal.get("action_kind") or "")
parameters = proposal.get("normalized_parameters")
if not isinstance(parameters, dict):
@@ -1632,7 +1755,8 @@ def apply(self, proposal_id: str, *, steward_context: dict[str, Any] | None = No
},
)
agent_id = parameters.get("agent_id")
- if agent_id and not isinstance(steps.get("todo_assigned"), dict):
+ start_execution = parameters.get("start_execution") is True
+ if agent_id and not start_execution and not isinstance(steps.get("todo_assigned"), dict):
update_goal_todo(
registry_path=self.registry_path,
goal_id=str(parameters["goal_id"]),
@@ -1659,60 +1783,12 @@ def apply(self, proposal_id: str, *, steward_context: dict[str, Any] | None = No
"canonical_receipt": canonical_receipt,
}
turn_result = None
- if parameters.get("start_execution"):
- if self.runtime_controller is None:
- raise ValueError("Chat Runtime Controller is unavailable")
- execution_agent_id = str(
- parameters.get("endpoint_id") or parameters["agent_id"]
- )
- execution_step = steps.get("execution_started")
- if isinstance(execution_step, dict) and execution_step.get(
- "session_id"
- ):
- session_id = _opaque(
- execution_step.get("session_id"), field="session_id"
- )
- turn_id = _opaque(execution_step.get("turn_id"), field="turn_id")
- created = False
- else:
- goal = self._goal(str(parameters["goal_id"]))
- project = Path(str(goal.get("repo") or ".")).expanduser().resolve()
- if not project.is_dir():
- raise ValueError("the Goal project root is unavailable")
- self._agent_eligibility(execution_agent_id, project=project)
- session, _resumed = self.runtime_controller.open_session(
- goal_id=str(parameters["goal_id"]),
- agent_id=execution_agent_id,
- work_dir=project,
- objective=str(parameters["text"]),
- mode="resume_latest",
- channel_id=f"task.{todo_id}",
- agent_goal_id=str(parameters["goal_id"]),
- )
- session_id = _opaque(session.get("session_id"), field="session_id")
- turn, created = self.runtime_controller.submit_turn(
- session_id=session_id,
- client_turn_id=f"task-start-{proposal_id}",
- message=str(parameters["text"]),
- work_dir=project,
- objective=str(parameters["text"]),
- )
- turn_id = _opaque(turn.get("turn_id"), field="turn_id")
- self.store.save_checkpoint(
- proposal_id,
- step="execution_started",
- receipt={"session_id": session_id, "turn_id": turn_id},
- )
+ if start_execution:
+ turn_result = self._start_confirmed_task(proposal_id, parameters, todo_id, steps)
receipt["resource_ids"].update(
- {"session_id": session_id, "turn_id": turn_id}
+ {"session_id": turn_result["session_id"], "turn_id": turn_result["turn_id"]}
)
receipt["outcome"] = "task_execution_started"
- turn_result = {
- "session_id": session_id,
- "turn_id": turn_id,
- "status": "queued",
- "created": created,
- }
stored = self.store.apply(
proposal_id,
current_state_fingerprint=current_fingerprint,
@@ -1778,8 +1854,7 @@ def apply(self, proposal_id: str, *, steward_context: dict[str, Any] | None = No
}
raise ValueError(f"unsupported action_kind: {action_kind}")
- @staticmethod
- def _turn_from_receipt(receipt: Any) -> dict[str, Any] | None:
+ def _turn_from_receipt(self, receipt: Any) -> dict[str, Any] | None:
if not isinstance(receipt, dict) or not isinstance(
receipt.get("resource_ids"), dict
):
@@ -1787,12 +1862,17 @@ def _turn_from_receipt(receipt: Any) -> dict[str, Any] | None:
resource_ids = receipt["resource_ids"]
if not resource_ids.get("turn_id"):
return None
+ session_id = resource_ids.get("session_id")
+ turn_id = str(resource_ids["turn_id"])
+ status = "accepted"
+ if receipt.get("outcome") == "task_execution_started" and session_id:
+ chat = getattr(self.runtime_controller, "store", None) or self.chat_store
+ turn = chat.load_turn(str(session_id), turn_id) if chat is not None else None
+ if turn and turn.get("session_id") == session_id and turn.get("turn_id") == turn_id:
+ status = str(turn.get("status") or status)
return {
- "session_id": str(resource_ids["session_id"])
- if resource_ids.get("session_id")
- else None,
- "turn_id": str(resource_ids["turn_id"]),
- "status": "accepted",
- "created": receipt.get("outcome")
- in {"turn_created", "task_execution_started"},
+ "session_id": str(session_id) if session_id else None,
+ "turn_id": turn_id,
+ "status": status,
+ "created": receipt.get("outcome") == "turn_created",
}
diff --git a/loopx/chat_agent.py b/loopx/chat_agent.py
index 951c6832b8..033b57975a 100644
--- a/loopx/chat_agent.py
+++ b/loopx/chat_agent.py
@@ -720,6 +720,8 @@ class CodexChatAgentSession:
_launch_guard: Callable[[], AbstractContextManager[None]] | None = field(
default=None, repr=False
)
+ _native_task_policy_used: bool = field(default=False, repr=False)
+ _managed_goal_read_default: bool = field(default=False, repr=False)
@classmethod
def start(
@@ -1734,28 +1736,15 @@ def send(
on_native_item: Callable[[dict[str, Any]], None] | None = None,
turn_start_guard: Callable[[], AbstractContextManager[None]] | None = None,
check_running: Callable[[], None] | None = None,
+ _native_task: bool = False,
+ sandbox_policy: dict[str, object] | None = None,
) -> dict[str, Any]:
- text = str(user_message or "")
- if not text.strip():
- raise ValueError("user message is required")
- if self.read_only_review and not self.metadata_review and not self.answer_review:
- text = (
- "Review the existing results of the interrupted original request below. "
- "Its earlier execution may have already changed files or external systems. "
- "Use the original native history and current local artifacts to verify what actually happened. "
- "This Turn is read-only: do not re-execute the business request, write, send, delegate or start background work. "
- "Return a clear answer to the original user, distinguishing verified results from remaining gaps. "
- "If verification is incomplete, report the concrete limitation; do not claim completion. "
- "Original request: " + text
- )
- if project_collaboration:
- if (self.execution_mode or self.read_only_review or output_schema is not None
- or not self.project_context or self.project_context.get("audience") != "bound_owner"):
- raise ValueError("original project collaboration requires its existing bound project session")
- from .control_plane.effect_runtime import effect_runtime_result
- output_schema = effect_runtime_result("collaboration.project.response_schema", {})
- if output_schema is not None and not self.execution_mode and not project_collaboration:
- raise ValueError("structured Turn output requires an execution session")
+ if not _native_task and (self._native_task_policy_used or self._managed_goal_read_default) and sandbox_policy is None:
+ sandbox_policy = {"type": "readOnly", "networkAccess": False}
+ from .capabilities.native_chat.codex_adapter import prepare_native_turn_text
+ text, output_schema = prepare_native_turn_text(self, user_message, output_schema=output_schema,
+ project_collaboration=project_collaboration, native_task=_native_task,
+ sandbox_policy=sandbox_policy, turn_start_guard=turn_start_guard)
with self._request_id_lock:
request_id = self.next_request_id
self.next_request_id += 1
@@ -1763,7 +1752,7 @@ def send(
text = _turn_prompt(
text,
context_summary=self.context_summary,
- execution_mode=self.execution_mode,
+ execution_mode=self.execution_mode or _native_task,
runtime_profile=self.runtime_profile,
project_work=self.project_context is not None and self.sandbox == "workspace-write",
public_source_read_context=self._public_source_read_context,
@@ -1777,6 +1766,10 @@ def send(
started_at = time.monotonic()
start_timeout = min(self.idle_timeout_sec, self.hard_timeout_sec
if self.hard_timeout_sec is not None else self.idle_timeout_sec)
+ if _native_task:
+ # Publication may be uncertain. Every subsequent ordinary send
+ # must narrow the sticky native policy, even after an exception.
+ self._native_task_policy_used = True
turn_result = self._request(
"turn/start",
{
@@ -1788,9 +1781,13 @@ def send(
# Chat renders native summaries, but a resumed thread may have
# disabled them. Request the public summary on each Chat Turn;
# execution hosts retain their own verbosity configuration.
- **({"summary": "concise"} if not self.execution_mode else {}),
+ **({"summary": "concise"} if not (self.execution_mode or _native_task) else {}),
"approvalPolicy": "never",
**({"permissions": self.permissions_profile} if self.permissions_profile else {}),
+ **({"sandboxPolicy": sandbox_policy} if sandbox_policy is not None else {}),
+ **({"runtimeWorkspaceRoots": [str(self.work_dir.resolve())]}
+ if _native_task and sandbox_policy is not None
+ and sandbox_policy.get("type") == "workspaceWrite" else {}),
**(
{"outputSchema": output_schema} if output_schema is not None else {}
),
diff --git a/loopx/chat_ingress.py b/loopx/chat_ingress.py
index 7052737e04..0d180d9703 100644
--- a/loopx/chat_ingress.py
+++ b/loopx/chat_ingress.py
@@ -247,6 +247,11 @@ def read(path):
and str(payload.get("turn_id") or "") != active_turn_id
):
rows.append(payload)
+ # The ordinary read has no selectable Turn when storage has no queued
+ # candidates. Explicit capacity and strict reads still use the owner.
+ if not rows and not strict and not include_reserved and capacity_at is None:
+ return []
+
from .control_plane.chat_turn_acceptance import queued_chat_turn_ids
selected = set(queued_chat_turn_ids(rows, active_turn_id, include_reserved=include_reserved, capacity_at=capacity_at))
return sorted(
@@ -335,15 +340,28 @@ def mutate_queued_input(self, session_id: str, turn_id: str, request: dict[str,
def steering_receipt(self, session_id: str, ingress_id: str):
"""A corrupt receipt cannot be treated as absence and resent."""
- from .chat_store import CHAT_INGRESS_SCHEMA_VERSION
+ return self._strict_ingress_receipt(session_id, ingress_id)
+
+ def _strict_ingress_receipt(self, session_id: str, ingress_id: str) -> dict[str, Any] | None:
+ """Absent is ``None``; any other unreadable receipt fails closed."""
+ from .chat_store import CHAT_INGRESS_SCHEMA_VERSION, _opaque_id
+ # The receipt is stored under the normalized id, so a replay that repeats
+ # the original (padded) text must be matched against that same id.
+ ingress_id = _opaque_id(ingress_id, field="client_ingress_id")
path = self._ingress_path(session_id, ingress_id)
try:
value = json.loads(path.read_text(encoding="utf-8"))
- except FileNotFoundError:
+ except FileNotFoundError as exc:
+ if os.path.lexists(path):
+ # A link whose target is gone is an existing entry, not absence:
+ # replacing it would resend a message that may have been delivered.
+ raise OSError("Ingress receipt is unreadable") from exc
return None
+ except (OSError, ValueError) as exc:
+ raise OSError("Ingress receipt is unreadable") from exc
if (not isinstance(value, dict) or value.get("schema_version") != CHAT_INGRESS_SCHEMA_VERSION
or value.get("session_id") != session_id or value.get("client_ingress_id") != ingress_id):
- raise OSError("Steering receipt is unreadable")
+ raise OSError("Ingress receipt is unreadable")
return value
def steering_delivery_lock(self, session_id: str, ingress_id: str):
@@ -588,7 +606,7 @@ def create_ingress_receipt(
) -> tuple[dict[str, Any], bool]:
"""Reserve one idempotent external ingress before provider delivery."""
- from .chat_store import _opaque_id, _read_json, _atomic_write_json, utc_now, CHAT_INGRESS_SCHEMA_VERSION
+ from .chat_store import _opaque_id, _atomic_write_json, utc_now, CHAT_INGRESS_SCHEMA_VERSION
if self.load_session(session_id) is None:
raise KeyError("chat session was not found")
@@ -598,8 +616,10 @@ def create_ingress_receipt(
agent_id="loopx-chat",
operation="create_chat_ingress_receipt",
):
- existing = _read_json(path)
- if existing.get("schema_version") == CHAT_INGRESS_SCHEMA_VERSION:
+ # A damaged receipt may record a delivered send. It is not absence:
+ # recreating it would resend the message and erase that evidence.
+ existing = self._strict_ingress_receipt(session_id, client_ingress_id)
+ if existing is not None:
request = {"mode": _opaque_id(mode, field="mode"), "message": str(message)}
if expected_turn_id is not None or "expected_turn_id" in existing:
request["expected_turn_id"] = expected_turn_id
diff --git a/loopx/chat_loopx_mode.py b/loopx/chat_loopx_mode.py
index 646e2dfe68..07a853d34f 100644
--- a/loopx/chat_loopx_mode.py
+++ b/loopx/chat_loopx_mode.py
@@ -49,7 +49,7 @@
"The host supplies the Goal and preparing Agent. It saves only a reviewable goal.acceptance.check proposal; it does not configure acceptance or run commands. "
"The local owner can use that plan beside the delivery in the workspace. "
"Action=outcomes reads persistent supporting outcomes and the provider revision. "
- "Action=refine_outcome takes operation_id, expected_provider_revision and document with outcome_id; add only changed requirements [{id,description}], todo_ids or review. Creation also needs the original objective. source_summary is required for creation/new requirements; omit it for existing-outcome reviews/work links and put milestone evidence in review.evidence_refs to retain declaration origins. "
+ "Action=refine_outcome takes operation_id, expected_provider_revision and document with outcome_id; add only changed requirements [{id,description}], todo_ids or review. Creation also needs the original objective. storage_format=records explicitly retains the existing declaration in paged record storage when cumulative capacity is reached; keep the same outcome and all origins. review_patch reviews up to 32 named requirements without refreshing the others. source_summary is required for creation/new requirements; omit it for existing-outcome reviews/work links and put milestone evidence in review.evidence_refs to retain declaration origins. "
"Action=prepare_goal_objective takes operation_id and document {objective,reason}; it prepares an owner-reviewed shared objective revision without changing root commitments. Action=adopt_goal_objective takes operation_id, expected_provider_revision and document {revision,digest,work_digest,review_summary} after reconciling your work; action=outcomes returns its basis. "
"Optional review addresses every retained requirement with {id,conclusion: met|unmet|uncertain,evidence_refs: strings,note}. "
"The host fixes the owner and retains the first source Turn for an unchanged operation in this conversation. After response loss, retry the same operation, revision and document. "
@@ -69,7 +69,7 @@
"expected_provider_revision": {"type": "string"},
"document": {
"type": "object",
- "description": "For refine_outcome: outcome_id, plus changed requirements [{id,description}], todo_ids (existing work) or review; original objective required on creation. source_summary is required only for creation/new requirements; omit for review/work maintenance, with new evidence in review.evidence_refs. No actor/source routing. For prepare_check, prefer {outcome_id, criteria: [{id: existing requirement ID, validation_argv: string array, optional validation_timeout_seconds}]}; the owner resolves retained descriptions and linked work. Legacy standalone check document: objective (string), non_goals (strings), scope ({kind: selected_work, todo_ids: existing advancement Todo ids} or {kind: all_advancement}), criteria (id, description, validation_argv string array, optional validation_timeout_seconds), bindings (todo_id, criterion_ids). Checks use the registered Goal workspace or its pinned oracle snapshot only after local-owner apply. Use known requirements and approved scope; do not invent an oracle or authorization.",
+ "description": "For refine_outcome: outcome_id, plus changed requirements [{id,description}], todo_ids (existing work) or review; original objective required on creation. source_summary is required only for creation/new requirements; omit for review/work maintenance, with new evidence in review.evidence_refs. For a full retained declaration, set storage_format to records in the refinement; use review_patch for changed requirement reviews. Preserve original operation identity on ambiguous writes; changed intent after a confirmed rejection needs a new operation id. No actor/source routing. For prepare_check, prefer {outcome_id, criteria: [{id: existing requirement ID, validation_argv: string array, optional validation_timeout_seconds}]}; the owner resolves retained descriptions and linked work. Legacy standalone check document: objective (string), non_goals (strings), scope ({kind: selected_work, todo_ids: existing advancement Todo ids} or {kind: all_advancement}), criteria (id, description, validation_argv string array, optional validation_timeout_seconds), bindings (todo_id, criterion_ids). Checks use the registered Goal workspace or its pinned oracle snapshot only after local-owner apply. Use known requirements and approved scope; do not invent an oracle or authorization.",
},
"limit": {"type": "integer", "minimum": 1, "maximum": 50},
"cursor": {"type": "string"},
@@ -936,7 +936,7 @@ def dispatch(name, arguments):
if set(arguments) != {"action", "operation_id", "expected_provider_revision", "document"}:
raise ValueError("refine_outcome needs its stable operation, inspected revision and document")
document = arguments["document"]
- if not isinstance(document, dict) or "outcome_id" not in document or set(document) - {"outcome_id", "objective", "requirements", "todo_ids", "source_summary", "review"}:
+ if not isinstance(document, dict) or "outcome_id" not in document or set(document) - {"outcome_id", "objective", "requirements", "todo_ids", "source_summary", "review", "review_patch", "storage_format"}:
raise ValueError("refine_outcome document cannot replace host identity or source")
if not isinstance(operation_id, str) or not operation_id.strip():
raise ValueError("refine_outcome requires a stable operation id")
@@ -951,7 +951,7 @@ def dispatch(name, arguments):
"document": document,
},
)
- refinement = {key: document[key] for key in ("outcome_id", "objective", "requirements", "todo_ids") if key in document}
+ refinement = {key: document[key] for key in ("outcome_id", "objective", "requirements", "todo_ids", "review_patch", "storage_format") if key in document}
if "review" in document:
refinement["review"] = document["review"]
refinement["owner_agent_id"] = settings["agent_id"]
diff --git a/loopx/chat_manager_context.py b/loopx/chat_manager_context.py
index 0b8773c5b2..a062086810 100644
--- a/loopx/chat_manager_context.py
+++ b/loopx/chat_manager_context.py
@@ -488,7 +488,11 @@ def manager_authorization_scope_is_current(
or not isinstance(expected_scope_id, str)
):
return False
- current = scope_resolver(session)
+ try:
+ current = scope_resolver(session)
+ except (OSError, ValueError, KeyError, TypeError):
+ # Losing the source or its audience proof holds the existing scope.
+ return False
return (
isinstance(current, list)
and manager_authorization_scope_id_for_registry(
diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py
index c018072005..beb4d4a687 100644
--- a/loopx/chat_runtime.py
+++ b/loopx/chat_runtime.py
@@ -24,6 +24,7 @@
steward_machine_defaults,
)
from .chat.coordination import PROJECT_COORDINATION_GUIDANCE, PROJECT_CONTEXT_VERSION, apply_context_handoff
+from .chat.session_open import read_exact_original_session
from .capabilities.native_chat import codex_context, project_context as project_context_policy
from .capabilities.native_chat.codex_adapter import (
CodexAppServerAdapter, NativeHistoryRestoration, NativeWorkingContinuation, start_attachment_turn,
@@ -59,6 +60,7 @@
from .file_lock import (
LOCK_HOLDER_DEAD, LOCK_HOLDER_LIVE, LOCK_HOLDER_RELEASED,
_lock_id, lock_holder_host_label, lock_holder_liveness, process_is_alive, try_exclusive_file_lock,
+ exclusive_cross_runtime_file_lock,
)
from .kiro_cli_goal_mode import (
KIRO_CLI_BIN,
@@ -299,6 +301,7 @@ def __init__(
self.session_queue_workers: set[str] = set()
self.session_queue_threads: dict[str, threading.Thread] = {}
self.session_queue_wakeups: set[str] = set()
+ self.original_task_action_store = None
self.closed = threading.Event()
from .chat_loopx_mode import ChatLoopXMode
self.loopx_mode = ChatLoopXMode(self)
@@ -372,6 +375,8 @@ def _start_adapter(
manager_runtime: Mapping[str, Any] | None = None,
project_coordination: bool = False,
loopx_tools: bool = False,
+ check_preparation: bool = False,
+ managed_read_default: bool = False,
executor_model: Mapping[str, str | None] | None = None,
project_context: dict[str, str] | None = None,
agent_config: dict[str, str] | None = None,
@@ -410,11 +415,9 @@ def _start_adapter(
manager_runtime=manager_runtime, executor_model=executor_model,
agent_config=agent_config, execution_mode=execution_mode,
)
- native_context = {
- "objective": self._session_objective(goal_id=goal_id, objective=objective,
- project_coordination=project_coordination and not execution_mode),
- "runtime_profile": str(manager_profile["runtime_profile"]) if manager_profile else "restricted",
- }
+ from .capabilities.native_chat.codex_adapter import native_runtime_context, start_runtime_adapter
+ native_context = native_runtime_context(self, goal_id=goal_id, objective=objective,
+ manager_profile=manager_profile, project_coordination=project_coordination, execution_mode=execution_mode)
if agent_id == "antigravity":
from .capabilities.native_chat.antigravity_adapter import AntigravityAdapter
if execution_mode or project_context is not None or read_only_review:
@@ -431,11 +434,12 @@ def _start_adapter(
hard_timeout_sec=self.hard_timeout_sec,
)
if agent_id == "codex":
- from .capabilities.native_chat.codex_adapter import start_runtime_adapter
return start_runtime_adapter(self, work_dir=work_dir, goal_id=goal_id, native_context=native_context,
manager_profile=manager_profile, model_config=model_config, history=history,
resume_thread_id=resume_thread_id, execution_mode=execution_mode, project_context=project_context,
project_coordination=project_coordination, loopx_tools=loopx_tools,
+ check_preparation=check_preparation,
+ managed_read_default=managed_read_default,
codex_home_override=codex_home_override, read_only_review=read_only_review,
metadata_review_context=metadata_review_context, answer_review_context=answer_review_context,
history_check=history_check, working_continuation=working_continuation)
@@ -521,6 +525,7 @@ def open_session(
agent_goal_id: str | None = None,
goal_instance_id: str | None = None,
managed_agent_id: str | None = None,
+ session_id: str | None = None,
manager_executor_allocation: Mapping[str, Any] | None = None,
project_ref: str | None = None,
conversation_binding_id: str | None = None,
@@ -541,6 +546,8 @@ def open_session(
error_code="unsupported_configuration", gate=None)
if mode not in {"resume_latest", "new"}:
raise ValueError("mode must be resume_latest or new")
+ if session_id is not None and mode != "new":
+ raise ValueError("an exact Session opening requires mode=new")
selected_channel = channel_id or f"goal.{goal_id}"
project_context = None
steward_context = None
@@ -593,9 +600,24 @@ def open_session(
goal_id = MANAGER_AGENT_GOAL_ID
route_goal_id = "*" if is_manager_channel(selected_channel) else goal_id
route_key = (route_goal_id, agent_id, selected_channel)
+ if session_id is not None:
+ if not isinstance(session_id, str) or session_id != session_id.strip() or session_id in {".", ".."}:
+ raise ValueError("session_id must retain its exact non-empty opaque identity")
+ session_id = _opaque_id(session_id, field="session_id")
+ if (project_context is not None or steward_context is not None or is_manager_channel(selected_channel)
+ or goal_id is None or agent_goal_id is not None and agent_goal_id != goal_id
+ or conversation_scope(selected_scope)["kind"] != "owner_goal"):
+ raise ValueError("an exact Session opening requires its original local Goal route")
with self.lock:
route_lock = self.session_open_locks.setdefault(route_key, threading.Lock())
- with route_lock:
+ with route_lock, (exclusive_cross_runtime_file_lock(
+ self.store.root / "session-open-locks" / session_id, operation="open_original_goal_session")
+ if session_id is not None else nullcontext()):
+ if session_id is not None:
+ original = read_exact_original_session(self, session_id=session_id, selected_scope=selected_scope,
+ agent_id=agent_id, work_dir=work_dir, requested_model=agent_model_id, requested_effort=agent_reasoning_effort)
+ if original is not None:
+ return original, True
latest = None
if not is_manager_channel(selected_channel) and project_context is None:
exact_attached, strict_profile = select_current_attached_session(
@@ -618,7 +640,7 @@ def open_session(
error_code="source_session_managed_chat_unsupported",
gate=None,
)
- if mode == "resume_latest":
+ if mode == "resume_latest" and session_id is None:
latest = self.store.latest_session(
goal_id=None if is_manager_channel(selected_channel) else goal_id,
agent_id=agent_id,
@@ -674,6 +696,8 @@ def open_session(
objective=objective,
execution_mode=selected_channel.startswith("task."),
project_coordination=conversation_scope(selected_scope)["kind"] == "owner_goal",
+ check_preparation=managed_agent_id is not None,
+ managed_read_default=managed_agent_id is not None,
manager_runtime=manager_runtime,
project_context=project_context,
executor_model=alloc.manager_executor_model(manager_executor_allocation),
@@ -686,6 +710,7 @@ def open_session(
require_managed_agent_session(self, selected_scope, work_dir)
observed_settings = self._observed_model_settings(adapter, agent_reasoning_effort, agent_model_id)
persisted = self.store.create_session(
+ **({"session_id": session_id} if session_id is not None else {}),
goal_id=goal_id,
goal_instance_id=goal_instance_id,
**({"managed_agent_id": managed_agent_id, "managed_workspace_path": str(work_dir.resolve())} if managed_agent_id is not None else {}),
@@ -1020,6 +1045,7 @@ def check_route_configuration():
execution_mode=str(session.get("channel_id") or "").startswith("task."),
project_coordination=conversation_scope(session)["kind"] == "owner_goal",
loopx_tools=session.get("loopx_tools") is True,
+ managed_read_default=session.get("managed_agent_id") is not None,
executor_model=(alloc.manager_executor_model(model_allocation)
if model_allocation is not None else alloc.restored_executor_model(session)),
manager_runtime=manager_runtime,
@@ -1169,6 +1195,7 @@ def submit_turn(
loopx_execution: bool = False,
loopx_request: dict[str, object] | None = None,
_goal_commit: ManagedSessionGoalCommit | None = None,
+ display_message: str | None = None,
) -> tuple[dict[str, Any], bool]:
commit = _goal_commit or nullcontext
session = self.store.load_session(session_id)
@@ -1189,16 +1216,9 @@ def submit_turn(
if parse_native_goal_command(message) is not None:
validate_goal_chat(session, attachments)
if session.get("session_mode") == CHAT_SESSION_MODE_ATTACHED:
- if attachments:
- raise ValueError("attached host session queue does not yet accept attachments")
return enqueue_attached_agent_turn(
- store=self.store,
- registry_path=self.registry_path,
- session_id=session_id,
- client_turn_id=client_turn_id,
- message=message,
- origin="web",
- )
+ store=self.store, registry_path=self.registry_path, session_id=session_id,
+ client_turn_id=client_turn_id, message=message, origin="web", attachments=attachments)
with self._session_adapter_lock(session_id):
session = self.store.load_session(session_id)
if session is None or session.get("status") == "closed":
@@ -1236,7 +1256,7 @@ def submit_turn(
"wake": "成员结果已验收,继续推进 LoopX 模式。",
}.get(str((loopx_request or {}).get("operation")), "恢复 LoopX 模式。")
if loopx_execution
- else None
+ else display_message
),
loopx_execution=loopx_execution,
loopx_request=loopx_request,
@@ -1534,6 +1554,7 @@ def resume_session_queue(
return
if session_id in self.session_queue_workers:
self.session_queue_wakeups.add(session_id)
+ self.turn_release_wakeup.notify()
return
worker = threading.Thread(
target=self._drain_session_queue,
@@ -1548,123 +1569,13 @@ def resume_session_queue(
self.session_queue_threads[session_id] = worker
worker.start()
- def _drain_session_queue(
- self,
- *,
- session_id: str,
- work_dir: Path,
- objective: str,
- ) -> None:
- try:
- while not self.closed.is_set():
- session = self.store.load_session(session_id)
- if (
- self.closed.is_set()
- or session is None
- or session.get("status") == "closed"
- or session.get("session_mode") == CHAT_SESSION_MODE_ATTACHED
- ):
- return
- turn = None
- active_turn_id = str(session.get("active_turn_id") or "")
- if active_turn_id:
- try:
- self.recover_exited_turn(session_id, active_turn_id)
- except OSError:
- # Storage can still be unavailable. Retry only the
- # non-executing lifecycle repair, never the old input.
- self.closed.wait(0.25)
- continue
- active = self.store.load_turn(session_id, active_turn_id)
- if (active and active.get("status") == "queued" and "_acceptance" not in active
- and active.get("started_at") is None and active.get("upstream_turn_id") is None
- and active.get("delta_count") == 0):
- # A crash can leave the queue claim before native
- # dispatch. Keep that exact claim and pass through the
- # normal preparation and execution fences below.
- turn = active
- else:
- with self.lock:
- attached = self.adapters.get(session_id)
- if attached is None or not attached.healthcheck():
- try:
- self._ensure_adapter(
- session,
- work_dir=work_dir,
- objective=objective,
- )
- except Exception as exc:
- self._fail_queue_preparation(session_id, active_turn_id, exc)
- else:
- continue
- active = self.store.load_turn(session_id, active_turn_id)
- if active and active.get("status") not in TERMINAL_TURN_STATES:
- self.closed.wait(0.05)
- continue
- self.store.release_active_turn(session_id, active_turn_id)
- refreshed = self.store.load_session(session_id)
- if refreshed is None:
- return
- with self.lock:
- self.session_queue_wakeups.discard(session_id)
- if turn is None:
- turn = self.store.claim_next_queued_turn(session_id)
- if turn is None:
- with self.lock:
- if session_id in self.session_queue_wakeups:
- continue
- worker = self.session_queue_threads.get(session_id)
- if worker is threading.current_thread():
- self.session_queue_workers.discard(session_id)
- self.session_queue_threads.pop(session_id, None)
- return
- turn_id = str(turn["turn_id"])
- try:
- if turn.get("origin") == "peer" or "collaboration_request" in turn:
- from .capabilities.native_chat.conversation_bindings import OriginalConversationRequests
- OriginalConversationRequests(self).validate_turn(session_id, turn)
- # An empty queue needs no provider preparation. Claim real
- # work first, keeping the existing enqueue/retirement fence
- # above and the Turn's execution/stop checks below.
- current = self.store.load_session(session_id)
- if current is None or current.get("active_turn_id") != turn_id:
- return
- adapter = self._ensure_adapter(
- current,
- work_dir=work_dir,
- objective=objective,
- )
- if (self.store.load_session(session_id) or {}).get("active_turn_id") != turn_id:
- return
- except Exception as exc:
- # The claimed request still owns a terminal outcome when
- # workspace preparation or adapter restoration fails.
- self._fail_queue_preparation(session_id, turn_id, exc)
- continue
- done_event = threading.Event()
- with self.lock:
- self.turn_done_events[(session_id, turn_id)] = done_event
- try:
- self._run_turn(
- session_id=session_id,
- turn_id=turn_id,
- message=str(turn.get("message") or ""),
- attachments=turn.get("attachments") or [],
- adapter=adapter,
- done_event=done_event,
- )
- except OSError:
- # _run_turn has released its execution fence/done event.
- # A failed error checkpoint must not kill this queue worker;
- # the next iteration reconciles the original durable state.
- self.closed.wait(0.25)
- finally:
- with self.lock:
- worker = self.session_queue_threads.get(session_id)
- if worker is threading.current_thread():
- self.session_queue_workers.discard(session_id)
- self.session_queue_threads.pop(session_id, None)
- self.session_queue_wakeups.discard(session_id)
+ def resume_creation_requests(self) -> None:
+ from .capabilities.native_chat.creation_queue import resume_creation_requests
+ resume_creation_requests(self)
+
+ def _drain_session_queue(self, *, session_id: str, work_dir: Path, objective: str) -> None:
+ from .capabilities.native_chat.session_queue import drain_session_queue
+ drain_session_queue(self, session_id=session_id, work_dir=work_dir, objective=objective)
def _fail_queue_preparation(
self, session_id: str, turn_id: str, error: Exception,
@@ -2484,6 +2395,7 @@ def resume_session(self, *, session_id: str, work_dir: Path, objective: str) ->
def close(self) -> None:
self.closed.set()
+ self.turn_release_wakeup.notify()
with self.lock:
adapters = list(self.adapters.values())
event_buffers = list(self.turn_event_buffers.values())
diff --git a/loopx/chat_server.py b/loopx/chat_server.py
index 711818a2a4..39087d8b67 100644
--- a/loopx/chat_server.py
+++ b/loopx/chat_server.py
@@ -67,6 +67,7 @@
from .capabilities.manager_context.roundtrip import (
ReturnService,
parse_chat_history_selection,
+ prepare_chat_history_session,
read_chat_history_selection,
)
from .control_plane.goals.active_state_metadata import active_state_section_text
@@ -925,25 +926,27 @@ def _session_turn(self, session_id: str) -> None:
}
)
+ def _project_queue_reply_history(self, store: object, session: dict[str, object], rows: list[dict[str, object]]) -> list[dict[str, object]]:
+ return project_private_reply_history(store, session, rows)
+
@effect_runtime_request_scope()
def _session_snapshot(self, session_id: str) -> None:
try:
selection = parse_chat_history_selection(parse_qs(urlparse(self.path).query, keep_blank_values=True))
- # A historical Turn read must not recover an unrelated execution.
- if selection["turn_id"] is None:
- self.server.runtime_controller.recover_exited_turn(session_id)
store = self.server.chat_store
- session = store.load_session(session_id) or {}
+ session = prepare_chat_history_session(store, session_id, selection,
+ recover_turn=self.server.runtime_controller.recover_exited_turn)
media = self.server.private_media_history
contexts = getattr(self.server.runtime_controller, "project_contexts", None)
bindings = getattr(contexts, "conversation_bindings", None)
- markers = [] if selection["turn_id"] is not None else media.read(store, bindings, session)
+ scoped = selection["turn_id"] is not None or selection["report_message_id"] is not None
+ markers = [] if scoped else media.read(store, bindings, session)
payload = read_chat_history_selection(
self.server.runtime_controller.coordination_runtime_root, store, session_id,
registry=self.server.registry_path, selection=selection,
project_history_messages=(lambda messages: media.insert(messages, markers)) if markers else None,
- project_provider=lambda rows: project_private_reply_history(
- store, session, rows))
+ project_provider=lambda rows: self._link_history_images(
+ session_id, session, selection, project_private_reply_history(store, session, rows)))
if markers and "session" in payload:
payload["session"] = media.summary(payload["session"], markers)
self._send_json(payload)
@@ -954,31 +957,6 @@ def _session_snapshot(self, session_id: str) -> None:
except OSError:
self._send_error("Chat history is temporarily unavailable", status=503)
- def _managed_native_turn(self, session_id: str, *, execute: bool = False) -> None:
- from .capabilities.native_chat.steward_managed_mode import ManagedSessionTurn
- service = ManagedSessionTurn(self.server.runtime_controller)
- try:
- if execute:
- body = self._read_json()
- if set(body) - {"agent_id", "operation_id", "todo_id"}:
- raise ValueError("unsupported managed Turn arguments")
- turn, created = service.submit(session_id, **body)
- return self._send_json({"ok": True, "session_id": session_id, "turn": turn, "created": created}, status=202)
- query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
- sources = query.get("calendar_task_sources", ["false"])
- if sources not in (["true"], ["false"]):
- raise ValueError("calendar_task_sources must be one true or false value")
- include_sources = sources == ["true"]
- if include_sources and (set(query) - {"calendar_task_sources", "agent_id", "operation_id"}
- or any(len(values) != 1 for values in query.values())):
- raise ValueError("select one original managed Session and Agent for Task sources")
- self._send_json(service.inspect(session_id, agent_id=query.get("agent_id", [None])[0],
- operation_id=query.get("operation_id", [None])[0], include_calendar_task_sources=include_sources))
- except KeyError:
- self._send_error("chat session was not found", status=404)
- except (TypeError, ValueError, RuntimeError) as exc:
- self._send_error(str(exc), status=409, error_code="managed_turn_unavailable")
-
def _list_sessions(self) -> None:
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
if "managed_agent_id" in query:
@@ -2033,6 +2011,9 @@ def _wake_goal_context(session: dict[str, object]) -> dict[str, object]:
server.delegation_wake_service = DelegationWakeService(
server.runtime_controller, goal_context=_wake_goal_context
).start()
+ # Resume only retained, explicitly confirmed creation requests through the
+ # existing Session queue. Its owner rechecks source, native work and gates.
+ server.runtime_controller.resume_creation_requests()
url = f"http://{host}:{port}{DEFAULT_CHAT_PATH}"
print(f"Serving LoopX Chat at {url}", flush=True)
print(f"Agent boundary: local adapters, project grant {project_workspace_grant}, approval policy never", flush=True)
diff --git a/loopx/chat_store.py b/loopx/chat_store.py
index 5d719fb771..8a56a117ca 100644
--- a/loopx/chat_store.py
+++ b/loopx/chat_store.py
@@ -2,10 +2,10 @@
from __future__ import annotations
-from bisect import bisect_right
-from contextlib import suppress
+from collections import OrderedDict
+from contextlib import contextmanager, suppress
from copy import deepcopy
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timezone
import hashlib
import json
import os
@@ -25,7 +25,8 @@
MODEL_SELECTION_UNSET as _MODEL_SELECTION_UNSET, normalize_agent_model_id as normalize_agent_model_id,
normalize_session_model_settings, session_model_settings_supported, normalize_session_model_changes,
)
-from .chat.event_cache import ChatEventCache
+from .chat.event_cache import ChatEventCache, ChatEventStreamMixin
+from .chat.journal import decode_chat_journal
from .chat_ingress import (
ChatIngressStore,
SESSION_QUEUE_MAX_PENDING as SESSION_QUEUE_MAX_PENDING,
@@ -36,7 +37,7 @@
AcceptedManagedTurn,
plan_managed_turn_acceptance,
)
-from .file_lock import exclusive_file_lock, write_json_atomic
+from .file_lock import exclusive_file_lock, try_exclusive_file_lock, write_json_atomic
CHAT_STORE_SCHEMA_VERSION = "loopx_chat_store_v1"
@@ -55,6 +56,11 @@
_OPAQUE_ID = re.compile(r"^[A-Za-z0-9._-]{1,160}$")
_SESSION_RELEASE_UNSET = object()
+# Keep both active conversation journals warm within the original total budget.
+_PAGED_HISTORY_MAX_SESSIONS = 2
+_PAGED_HISTORY_MAX_BYTES = 64 * 1024 * 1024
+_PAGED_HISTORY_MAX_ROWS = 8192
+
def utc_now() -> str:
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
@@ -100,25 +106,7 @@ def _read_jsonl(
if raise_on_error:
raise
return []
- return _decode_jsonl(lines, strict=strict)
-
-
-def _decode_jsonl(lines: list[bytes], *, strict: bool) -> list[dict[str, Any]]:
- rows: list[dict[str, Any]] = []
- for line in lines:
- if not line.strip():
- continue
- try:
- item = json.loads(line)
- except (UnicodeDecodeError, json.JSONDecodeError) as exc:
- if strict:
- raise ValueError("invalid Chat journal record") from exc
- continue
- if isinstance(item, dict):
- rows.append(item)
- elif strict:
- raise ValueError("invalid Chat journal record")
- return rows
+ return decode_chat_journal(lines, strict=strict)
def _session_channel(payload: dict[str, Any]) -> str:
@@ -209,7 +197,7 @@ def _replace_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
os.replace(temporary, path)
-class ChatSessionStore(ChatIngressStore):
+class ChatSessionStore(ChatEventStreamMixin, ChatIngressStore):
"""Filesystem store kept outside project and public LoopX run history."""
def __init__(self, runtime_root: Path, *, startup_maintenance: bool = True) -> None:
@@ -221,7 +209,8 @@ def __init__(self, runtime_root: Path, *, startup_maintenance: bool = True) -> N
self._event_cache = ChatEventCache(self._event_lock)
self._event_pending: dict[tuple[str, str], list[tuple[dict[str, Any], str]]] = {}
self._event_flush_locks: WeakValueDictionary[tuple[str, str], threading.Lock] = WeakValueDictionary()
- self._paged_history: tuple[str, bytes, list[dict[str, Any]]] | None = None
+ self._paged_history_lock = threading.Lock()
+ self._paged_history: OrderedDict[str, tuple[bytes, int, list[dict[str, Any]]]] = OrderedDict()
self.sessions_root.mkdir(parents=True, exist_ok=True, mode=0o700)
os.chmod(self.root, 0o700)
os.chmod(self.sessions_root, 0o700)
@@ -245,9 +234,21 @@ def _session_lock(self, session_id: str) -> threading.Lock:
with self._session_lock_guard:
return self._session_locks.setdefault(token, threading.Lock())
+ @contextmanager
+ def _locked_session_path(self, session_id: str, operation: str) -> Iterator[Path]:
+ path = self._session_path(session_id)
+ with self._session_lock(session_id), exclusive_file_lock(path, agent_id="loopx-chat", operation=operation):
+ yield path
+
def _turn_path(self, session_id: str, turn_id: str) -> Path:
return self._session_dir(session_id) / "turns" / f"{_opaque_id(turn_id, field='turn_id')}.json"
+ @contextmanager
+ def _locked_turn_path(self, session_id: str, turn_id: str, operation: str) -> Iterator[Path]:
+ path = self._turn_path(session_id, turn_id)
+ with exclusive_file_lock(path, agent_id="loopx-chat", operation=operation):
+ yield path
+
def turn_execution_lock_path(self, session_id: str, turn_id: str) -> Path:
return self._turn_path(session_id, turn_id).with_suffix(".execution")
@@ -404,6 +405,28 @@ def load_session(self, session_id: str) -> dict[str, Any] | None:
payload = _read_json(self._session_path(session_id))
return payload if payload.get("schema_version") == CHAT_SESSION_SCHEMA_VERSION else None
+ @contextmanager
+ def read_session_fenced(self, session_id: str) -> Iterator[dict[str, Any] | None]:
+ """Keep Session state stable through a caller's local decision.
+
+ Reuse the writer fences without waiting for ongoing work or changing
+ its holder record. Callers must keep provider IO outside this scope.
+ """
+ path = self._session_path(session_id)
+ if not path.exists():
+ yield None
+ return
+ lock = self._session_lock(session_id)
+ if not lock.acquire(blocking=False):
+ raise ValueError("chat session is changing; retry")
+ try:
+ with try_exclusive_file_lock(path, preserve_holder=True) as held:
+ if held is None:
+ raise ValueError("chat session is changing; retry")
+ yield self.load_session(session_id)
+ finally:
+ lock.release()
+
def reserve_loopx_outcome_request(
self, session_id: str, *, turn_id: str, operation_id: str,
request: dict[str, Any],
@@ -448,178 +471,137 @@ def update_session(self, session_id: str, *, expected_statuses: set[str] | None
quota_recovery: bool = False,
answer_review_admission: bool = False,
**changes: Any) -> dict[str, Any]:
- path = self._session_path(session_id)
- with self._session_lock(session_id):
- with exclusive_file_lock(
- path,
- agent_id="loopx-chat",
- operation="update_chat_session",
+ with self._locked_session_path(session_id, "update_chat_session") as path:
+ payload = self.load_session(session_id)
+ if payload is None:
+ raise KeyError("chat session was not found")
+ if expected_statuses is not None and payload.get("status") not in expected_statuses:
+ raise KeyError("chat session is no longer open")
+ if expected_upstream_thread_id is not None and payload.get("upstream_thread_id") != expected_upstream_thread_id:
+ raise ValueError("native executor binding changed")
+ if payload.get("managed_agent_id") is not None and "goal_id" in changes and changes["goal_id"] != payload["goal_id"]:
+ raise ValueError("a registered Agent Session cannot change its original Goal")
+ allowed = {
+ "status", "active_turn_id", "last_activity_at", "last_error_code",
+ "upstream_thread_id", "upstream_mode", "codex_home",
+ "manager_context_version", "upstream_context_history", "coordination_context_version",
+ "external_conversation_binding_id", "loopx_mode", "loopx_tools", "loopx_executor",
+ "loopx_deliveries", "native_goal", "manager_authorization_scope_id",
+ "manager_runtime_profile", "manager_runtime_configuration_revision", "manager_runtime_status",
+ "manager_runtime_sandbox", "manager_runtime_standing_grant", "manager_runtime_tool_classes",
+ "manager_executor_allocation", "agent_model_id", "agent_reasoning_effort", "agent_service_tier",
+ "requested_agent_model_id", "requested_agent_reasoning_effort", "goal_id",
+ "agent_id", "executor_endpoint_id", "adapter_kind", "manager_quota_block",
+ "answer_review", "parked_native_working", "native_working_checkpoint",
+ }
+ unknown = set(changes) - allowed
+ if unknown:
+ raise ValueError(f"unsupported chat session fields: {sorted(unknown)}")
+ if "answer_review" in changes and (type(changes["answer_review"]) is not bool
+ or changes["answer_review"] and payload.get("steward_context") is None):
+ raise ValueError("answer review requires a bound steward and a boolean adapter marker")
+ if {"native_working_checkpoint", "parked_native_working"} & changes.keys():
+ from .capabilities.native_chat.codex_adapter import validate_native_working_update
+ active_id = payload.get("active_turn_id") if changes.get("parked_native_working") is not None else None
+ validate_native_working_update(payload, changes, expected_thread=expected_upstream_thread_id,
+ active=self.load_turn(session_id, active_id) if active_id else None)
+ if "manager_quota_block" in changes and "agent_id" not in changes:
+ raise ValueError("quota observation belongs to an executor transition")
+ if any(key in changes for key in ("agent_id", "executor_endpoint_id", "adapter_kind")):
+ allocation = normalize_manager_executor_allocation(changes.get("manager_executor_allocation", {}))
+ active = self.load_turn(session_id, payload["active_turn_id"]) if payload.get("active_turn_id") else None
+ endpoint = changes.get("agent_id")
+ history = changes.get("upstream_context_history") or []
+ if (expected_upstream_thread_id is None or not _session_channel(payload).startswith("manager")
+ or payload.get("session_mode") != CHAT_SESSION_MODE_MANAGED or payload.get("managed_agent_id")
+ or payload.get("upstream_mode") not in {"default", "chat"}
+ or not active or active.get("status") != "queued" or active.get("upstream_turn_id")
+ or active.get("origin") == "native_loopx"
+ or answer_review_admission and changes.get("answer_review") is not True
+ or ("-recovery-" in str(active.get("client_turn_id")) and not ((metadata_review or quota_recovery or answer_review_admission)
+ and payload.get("steward_context") is not None and endpoint == "codex"
+ and str(active.get("client_turn_id")).endswith(
+ "-metadata-1" if metadata_review else "-review-1" if answer_review_admission else "-quota-1")))
+ or allocation["selection_policy"] != "flexible"
+ or allocation["configured_endpoint"] != "antigravity"
+ or set(allocation["eligible_endpoints"]) != {"antigravity", "codex"}
+ or endpoint not in {"antigravity", "codex"} or endpoint == payload.get("agent_id")
+ or changes.get("executor_endpoint_id") != endpoint or allocation["executor_endpoint"] != endpoint
+ or changes.get("adapter_kind") != ("codex_app_server" if endpoint == "codex" else "antigravity_ls")
+ or changes.get("upstream_mode") != ("chat" if endpoint == "codex" else "default")
+ or not history or history[-1] != {"thread_id": payload["upstream_thread_id"],
+ "manager_context_version": payload.get("manager_context_version"),
+ "agent_id": payload["agent_id"], "agent_model_id": payload.get("agent_model_id")}
+ or changes.get("upstream_thread_id") in {None, payload["upstream_thread_id"]}):
+ raise ValueError("executor transition requires one unstarted steward Turn and preserved native provenance")
+ if "upstream_context_history" in changes:
+ history = changes["upstream_context_history"]
+ previous = payload.get("upstream_context_history") or []
+ if not isinstance(history, list) or history[:len(previous)] != previous:
+ raise ValueError("native context provenance must preserve its prior prefix")
+ for item in history:
+ if (not isinstance(item, dict) or set(item) not in (
+ {"thread_id", "manager_context_version"},
+ {"thread_id", "manager_context_version", "agent_id", "agent_model_id"})
+ or item["manager_context_version"] is not None and (
+ type(item["manager_context_version"]) is not int or item["manager_context_version"] < 0)):
+ raise ValueError("invalid native context provenance")
+ _opaque_id(item["thread_id"], field="upstream_thread_id")
+ if "agent_id" in item and (item["agent_id"] not in {"codex", "antigravity"}
+ or not isinstance(item["agent_model_id"], str)):
+ raise ValueError("invalid historical executor provenance")
+ if "external_conversation_binding_id" in changes:
+ identity = _opaque_id(changes["external_conversation_binding_id"], field="external_conversation_binding_id")
+ if payload.get("session_mode") != CHAT_SESSION_MODE_ATTACHED or payload.get("external_conversation_binding_id") not in {None, identity}:
+ raise ValueError("an attached Session cannot change its external audience")
+ changes["external_conversation_binding_id"] = identity
+ if "coordination_context_version" in changes:
+ version = changes["coordination_context_version"]
+ if type(version) is not int or version < 1:
+ raise ValueError("coordination context version must be a positive integer")
+ if "goal_id" in changes:
+ from .chat_manager import MANAGER_AGENT_GOAL_ID
+ if _session_channel(payload) != "manager" or changes["goal_id"] != MANAGER_AGENT_GOAL_ID:
+ raise ValueError("only the owner manager may migrate to global identity")
+ if "upstream_thread_id" in changes:
+ changes["upstream_thread_id"] = _upstream_id(changes["upstream_thread_id"])
+ normalize_session_model_changes(changes)
+ for field in (
+ "upstream_mode", "manager_authorization_scope_id",
+ "manager_runtime_profile", "manager_runtime_status",
+ "manager_runtime_sandbox", "manager_runtime_standing_grant",
):
- payload = self.load_session(session_id)
- if payload is None:
- raise KeyError("chat session was not found")
- if expected_statuses is not None and payload.get("status") not in expected_statuses:
- raise KeyError("chat session is no longer open")
- if expected_upstream_thread_id is not None and payload.get("upstream_thread_id") != expected_upstream_thread_id:
- raise ValueError("native executor binding changed")
- if payload.get("managed_agent_id") is not None and "goal_id" in changes and changes["goal_id"] != payload["goal_id"]:
- raise ValueError("a registered Agent Session cannot change its original Goal")
- allowed = {
- "status",
- "active_turn_id",
- "last_activity_at",
- "last_error_code",
- "upstream_thread_id",
- "upstream_mode",
- "codex_home",
- "manager_context_version",
- "upstream_context_history",
- "coordination_context_version",
- "external_conversation_binding_id",
- "loopx_mode",
- "loopx_tools", "loopx_executor",
- "loopx_deliveries",
- "native_goal",
- "manager_authorization_scope_id",
- "manager_runtime_profile",
- "manager_runtime_configuration_revision",
- "manager_runtime_status",
- "manager_runtime_sandbox",
- "manager_runtime_standing_grant",
- "manager_runtime_tool_classes",
- "manager_executor_allocation",
- "agent_model_id",
- "agent_reasoning_effort", "agent_service_tier",
- "requested_agent_model_id", "requested_agent_reasoning_effort",
- "goal_id",
- "agent_id", "executor_endpoint_id", "adapter_kind", "manager_quota_block",
- "answer_review", "parked_native_working", "native_working_checkpoint",
- }
- unknown = set(changes) - allowed
- if unknown:
- raise ValueError(f"unsupported chat session fields: {sorted(unknown)}")
- if "answer_review" in changes and (type(changes["answer_review"]) is not bool
- or changes["answer_review"] and payload.get("steward_context") is None):
- raise ValueError("answer review requires a bound steward and a boolean adapter marker")
- if {"native_working_checkpoint", "parked_native_working"} & changes.keys():
- from .capabilities.native_chat.codex_adapter import validate_native_working_update
- active_id = payload.get("active_turn_id") if changes.get("parked_native_working") is not None else None
- validate_native_working_update(payload, changes, expected_thread=expected_upstream_thread_id,
- active=self.load_turn(session_id, active_id) if active_id else None)
- if "manager_quota_block" in changes and "agent_id" not in changes:
- raise ValueError("quota observation belongs to an executor transition")
- if any(key in changes for key in ("agent_id", "executor_endpoint_id", "adapter_kind")):
- allocation = normalize_manager_executor_allocation(changes.get("manager_executor_allocation", {}))
- active = self.load_turn(session_id, payload["active_turn_id"]) if payload.get("active_turn_id") else None
- endpoint = changes.get("agent_id")
- history = changes.get("upstream_context_history") or []
- if (expected_upstream_thread_id is None or not _session_channel(payload).startswith("manager")
- or payload.get("session_mode") != CHAT_SESSION_MODE_MANAGED or payload.get("managed_agent_id")
- or payload.get("upstream_mode") not in {"default", "chat"}
- or not active or active.get("status") != "queued" or active.get("upstream_turn_id")
- or active.get("origin") == "native_loopx"
- or answer_review_admission and changes.get("answer_review") is not True
- or ("-recovery-" in str(active.get("client_turn_id")) and not ((metadata_review or quota_recovery or answer_review_admission)
- and payload.get("steward_context") is not None and endpoint == "codex"
- and str(active.get("client_turn_id")).endswith(
- "-metadata-1" if metadata_review else "-review-1" if answer_review_admission else "-quota-1")))
- or allocation["selection_policy"] != "flexible"
- or allocation["configured_endpoint"] != "antigravity"
- or set(allocation["eligible_endpoints"]) != {"antigravity", "codex"}
- or endpoint not in {"antigravity", "codex"} or endpoint == payload.get("agent_id")
- or changes.get("executor_endpoint_id") != endpoint or allocation["executor_endpoint"] != endpoint
- or changes.get("adapter_kind") != ("codex_app_server" if endpoint == "codex" else "antigravity_ls")
- or changes.get("upstream_mode") != ("chat" if endpoint == "codex" else "default")
- or not history or history[-1] != {"thread_id": payload["upstream_thread_id"],
- "manager_context_version": payload.get("manager_context_version"),
- "agent_id": payload["agent_id"], "agent_model_id": payload.get("agent_model_id")}
- or changes.get("upstream_thread_id") in {None, payload["upstream_thread_id"]}):
- raise ValueError("executor transition requires one unstarted steward Turn and preserved native provenance")
- if "upstream_context_history" in changes:
- history = changes["upstream_context_history"]
- previous = payload.get("upstream_context_history") or []
- if not isinstance(history, list) or history[:len(previous)] != previous:
- raise ValueError("native context provenance must preserve its prior prefix")
- for item in history:
- if (not isinstance(item, dict) or set(item) not in (
- {"thread_id", "manager_context_version"},
- {"thread_id", "manager_context_version", "agent_id", "agent_model_id"})
- or item["manager_context_version"] is not None and (
- type(item["manager_context_version"]) is not int or item["manager_context_version"] < 0)):
- raise ValueError("invalid native context provenance")
- _opaque_id(item["thread_id"], field="upstream_thread_id")
- if "agent_id" in item and (item["agent_id"] not in {"codex", "antigravity"}
- or not isinstance(item["agent_model_id"], str)):
- raise ValueError("invalid historical executor provenance")
- if "external_conversation_binding_id" in changes:
- identity = _opaque_id(changes["external_conversation_binding_id"], field="external_conversation_binding_id")
- if payload.get("session_mode") != CHAT_SESSION_MODE_ATTACHED or payload.get("external_conversation_binding_id") not in {None, identity}:
- raise ValueError("an attached Session cannot change its external audience")
- changes["external_conversation_binding_id"] = identity
- if "coordination_context_version" in changes:
- version = changes["coordination_context_version"]
- if type(version) is not int or version < 1:
- raise ValueError("coordination context version must be a positive integer")
- if "goal_id" in changes:
- from .chat_manager import MANAGER_AGENT_GOAL_ID
- if _session_channel(payload) != "manager" or changes["goal_id"] != MANAGER_AGENT_GOAL_ID:
- raise ValueError("only the owner manager may migrate to global identity")
- if "upstream_thread_id" in changes:
- changes["upstream_thread_id"] = _upstream_id(changes["upstream_thread_id"])
- normalize_session_model_changes(changes)
- if "upstream_mode" in changes:
- changes["upstream_mode"] = _opaque_id(changes["upstream_mode"], field="upstream_mode")
- if "manager_authorization_scope_id" in changes:
- changes["manager_authorization_scope_id"] = _opaque_id(
- changes["manager_authorization_scope_id"],
- field="manager_authorization_scope_id",
- )
- for field in (
- "manager_runtime_profile",
- "manager_runtime_status",
- "manager_runtime_sandbox",
- "manager_runtime_standing_grant",
- ):
- if field in changes:
- changes[field] = _opaque_id(changes[field], field=field)
- if "manager_runtime_configuration_revision" in changes:
- revision = str(
- changes["manager_runtime_configuration_revision"] or ""
- ).strip()
- if not revision or len(revision) > 160 or any(
- ord(character) < 32 for character in revision
- ):
- raise ValueError(
- "manager_runtime_configuration_revision is invalid"
- )
- changes["manager_runtime_configuration_revision"] = revision
- if "manager_runtime_tool_classes" in changes:
- tool_classes = changes["manager_runtime_tool_classes"]
- if not isinstance(tool_classes, list):
- raise TypeError("manager_runtime_tool_classes must be a list")
- changes["manager_runtime_tool_classes"] = [
- _opaque_id(item, field="manager_runtime_tool_class")
- for item in tool_classes
- ]
- if "manager_executor_allocation" in changes:
- allocation = changes["manager_executor_allocation"]
- if not isinstance(allocation, dict):
- raise TypeError("manager_executor_allocation must be an object")
- changes["manager_executor_allocation"] = (
- normalize_manager_executor_allocation(allocation)
- )
- if "codex_home" in changes:
- home = changes["codex_home"]
- if (not isinstance(home, str) or not Path(home).is_absolute()
- or changes.get("agent_id", payload.get("agent_id")) != "codex"
- or payload.get("session_mode") != CHAT_SESSION_MODE_MANAGED):
- raise ValueError("codex_home must be an absolute managed Codex home")
- if payload.get("codex_home") not in (None, home):
- raise ValueError("cannot rebind a managed Codex home")
- payload.update(changes)
- payload["updated_at"] = utc_now()
- _atomic_write_json(path, payload, preserve_mode=True)
- return payload
+ if field in changes:
+ changes[field] = _opaque_id(changes[field], field=field)
+ if "manager_runtime_configuration_revision" in changes:
+ revision = str(changes["manager_runtime_configuration_revision"] or "").strip()
+ if not revision or len(revision) > 160 or any(ord(character) < 32 for character in revision):
+ raise ValueError("manager_runtime_configuration_revision is invalid")
+ changes["manager_runtime_configuration_revision"] = revision
+ if "manager_runtime_tool_classes" in changes:
+ tool_classes = changes["manager_runtime_tool_classes"]
+ if not isinstance(tool_classes, list):
+ raise TypeError("manager_runtime_tool_classes must be a list")
+ changes["manager_runtime_tool_classes"] = [
+ _opaque_id(item, field="manager_runtime_tool_class") for item in tool_classes
+ ]
+ if "manager_executor_allocation" in changes:
+ allocation = changes["manager_executor_allocation"]
+ if not isinstance(allocation, dict):
+ raise TypeError("manager_executor_allocation must be an object")
+ changes["manager_executor_allocation"] = normalize_manager_executor_allocation(allocation)
+ if "codex_home" in changes:
+ home = changes["codex_home"]
+ if (not isinstance(home, str) or not Path(home).is_absolute()
+ or changes.get("agent_id", payload.get("agent_id")) != "codex"
+ or payload.get("session_mode") != CHAT_SESSION_MODE_MANAGED):
+ raise ValueError("codex_home must be an absolute managed Codex home")
+ if payload.get("codex_home") not in (None, home):
+ raise ValueError("cannot rebind a managed Codex home")
+ payload.update(changes)
+ payload["updated_at"] = utc_now()
+ _atomic_write_json(path, payload, preserve_mode=True)
+ return payload
def prepare_managed_session_resume(
self,
@@ -628,41 +610,22 @@ def prepare_managed_session_resume(
preserve_active_turn: bool,
) -> tuple[dict[str, Any], bool]:
"""Begin managed resume without taking ownership from an active Turn."""
-
- path = self._session_path(session_id)
- with self._session_lock(session_id):
- with exclusive_file_lock(
- path,
- agent_id="loopx-chat",
- operation="prepare_managed_chat_resume",
+ with self._locked_session_path(session_id, "prepare_managed_chat_resume") as path:
+ payload = self.load_session(session_id)
+ if payload is None or payload.get("status") == "closed":
+ raise KeyError("chat session was not found")
+ active_turn_id = str(payload.get("active_turn_id") or "")
+ active_turn = self.load_turn(session_id, active_turn_id) if active_turn_id else None
+ if (
+ preserve_active_turn
+ and active_turn is not None
+ and active_turn.get("status") in {"queued", "starting", "running", "completing", "interrupting"}
):
- payload = self.load_session(session_id)
- if payload is None or payload.get("status") == "closed":
- raise KeyError("chat session was not found")
- active_turn_id = str(payload.get("active_turn_id") or "")
- active_turn = (
- self.load_turn(session_id, active_turn_id)
- if active_turn_id
- else None
- )
- if (
- preserve_active_turn
- and active_turn is not None
- and active_turn.get("status")
- in {"queued", "starting", "running", "completing", "interrupting"}
- ):
- return payload, True
- resume_snapshot = dict(payload)
- payload.update(
- {
- "status": "stale",
- "active_turn_id": None,
- "last_error_code": None,
- "updated_at": utc_now(),
- }
- )
- _atomic_write_json(path, payload, preserve_mode=True)
- return resume_snapshot, False
+ return payload, True
+ resume_snapshot = dict(payload)
+ payload.update({"status": "stale", "active_turn_id": None, "last_error_code": None, "updated_at": utc_now()})
+ _atomic_write_json(path, payload, preserve_mode=True)
+ return resume_snapshot, False
def restore_managed_session_if_idle(
self,
@@ -672,47 +635,31 @@ def restore_managed_session_if_idle(
upstream_mode: str | None = None,
) -> dict[str, Any]:
"""Restore a managed Session only while it has no active Turn."""
-
- path = self._session_path(session_id)
- with self._session_lock(session_id):
- with exclusive_file_lock(
- path,
- agent_id="loopx-chat",
- operation="restore_managed_chat_session",
- ):
- payload = self.load_session(session_id)
- if payload is None:
- raise KeyError("chat session was not found")
- if payload.get("session_mode") == CHAT_SESSION_MODE_ATTACHED:
- raise ValueError("the selected Session is an attached host session")
- if payload.get("status") == "closed":
- raise KeyError("chat session was not found")
- identity_changes: dict[str, Any] = {}
- if upstream_thread_id is not None:
- identity_changes["upstream_thread_id"] = _upstream_id(
- upstream_thread_id
- )
- if upstream_mode is not None:
- identity_changes["upstream_mode"] = _opaque_id(
- upstream_mode,
- field="upstream_mode",
- )
- if payload.get("active_turn_id"):
- if identity_changes:
- payload.update(identity_changes)
- payload["updated_at"] = utc_now()
- _atomic_write_json(path, payload, preserve_mode=True)
- return payload
- changes = {
- "status": "ready",
- "last_error_code": None,
- "last_activity_at": utc_now(),
- **identity_changes,
- }
- payload.update(changes)
- payload["updated_at"] = utc_now()
- _atomic_write_json(path, payload, preserve_mode=True)
+ with self._locked_session_path(session_id, "restore_managed_chat_session") as path:
+ payload = self.load_session(session_id)
+ if payload is None:
+ raise KeyError("chat session was not found")
+ if payload.get("session_mode") == CHAT_SESSION_MODE_ATTACHED:
+ raise ValueError("the selected Session is an attached host session")
+ if payload.get("status") == "closed":
+ raise KeyError("chat session was not found")
+ identity_changes: dict[str, Any] = {}
+ if upstream_thread_id is not None:
+ identity_changes["upstream_thread_id"] = _upstream_id(upstream_thread_id)
+ if upstream_mode is not None:
+ identity_changes["upstream_mode"] = _opaque_id(upstream_mode, field="upstream_mode")
+ if payload.get("active_turn_id"):
+ if identity_changes:
+ payload.update(identity_changes)
+ payload["updated_at"] = utc_now()
+ _atomic_write_json(path, payload, preserve_mode=True)
return payload
+ payload.update(
+ {"status": "ready", "last_error_code": None, "last_activity_at": utc_now(), **identity_changes}
+ )
+ payload["updated_at"] = utc_now()
+ _atomic_write_json(path, payload, preserve_mode=True)
+ return payload
def release_active_turn(
self,
@@ -723,32 +670,19 @@ def release_active_turn(
last_error_code: str | None | object = _SESSION_RELEASE_UNSET,
) -> bool:
"""Release this Turn's claim, preserving metadata omitted by the caller."""
-
- path = self._session_path(session_id)
- with self._session_lock(session_id):
- with exclusive_file_lock(
- path,
- agent_id="loopx-chat",
- operation="release_active_chat_turn",
- ):
- payload = self.load_session(session_id)
- if payload is None:
- raise KeyError("chat session was not found")
- if payload.get("active_turn_id") != turn_id:
- return False
- payload.update(
- {
- "status": "ready",
- "active_turn_id": None,
- "updated_at": utc_now(),
- }
- )
- if last_activity_at is not _SESSION_RELEASE_UNSET:
- payload["last_activity_at"] = last_activity_at
- if last_error_code is not _SESSION_RELEASE_UNSET:
- payload["last_error_code"] = last_error_code
- _atomic_write_json(path, payload, preserve_mode=True)
- return True
+ with self._locked_session_path(session_id, "release_active_chat_turn") as path:
+ payload = self.load_session(session_id)
+ if payload is None:
+ raise KeyError("chat session was not found")
+ if payload.get("active_turn_id") != turn_id:
+ return False
+ payload.update({"status": "ready", "active_turn_id": None, "updated_at": utc_now()})
+ if last_activity_at is not _SESSION_RELEASE_UNSET:
+ payload["last_activity_at"] = last_activity_at
+ if last_error_code is not _SESSION_RELEASE_UNSET:
+ payload["last_error_code"] = last_error_code
+ _atomic_write_json(path, payload, preserve_mode=True)
+ return True
def latest_session(
self,
@@ -757,12 +691,7 @@ def latest_session(
agent_id: str,
channel_id: str | None = None,
) -> dict[str, Any] | None:
- """Return the newest resumable session row on one explicit channel.
-
- Omitting ``channel_id`` pins the exact ``goal.`` channel:
- a single namespace key, not a search over that goal's recorded
- conversations. Use ``list_sessions`` for intentional discovery.
- """
+ """Return the newest resumable session row; see ``session_candidates`` for channel scoping."""
candidates = self.resumable_session_candidates(
goal_id=goal_id,
agent_id=agent_id,
@@ -777,12 +706,7 @@ def resumable_session_candidates(
agent_id: str,
channel_id: str | None = None,
) -> list[dict[str, Any]]:
- """Return matching storage facts without deciding Goal identity.
-
- Omitting ``channel_id`` pins the exact ``goal.