diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index 44a663e03e..f2d992fb88 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -814,23 +814,35 @@ loopx --format json quota should-run \ --available-capability benchmark_runner ``` -A live `quota should-run` or executing `turn run-once` automatically remembers, -through the admitted turn-start capability hook, these five runtime observations -for the registered Agent on this host: +A live `quota should-run`, executing `turn run-once`, committed `refresh-state` / +`quota spend-slot` / `quota monitor-poll` settlement, or verified live external +capability execution (such as Goal-bound `pr-review` or `issue-fix pr-lifecycle --fetch-metadata`) +automatically remembers these five runtime observations for the registered Agent +on this host: `network`, `benchmark_runner`, `external_evidence_poll`, `worker_bridge`, and -`cli_bridge`. Later decisions, including `quota spend-slot` and `monitor-poll` -rechecks, read that Agent's observations without repeating flags. Goal/project -`available_capabilities` declarations are inherited dynamically; Agent observations -never write back into Goal configuration or propagate to peer Agents. +`cli_bridge`. In addition, when the host is not in a network-disabled sandbox +(`CODEX_SANDBOX_NETWORK_DISABLED=1` / `LOOPX_OFFLINE=1`) and local GitHub CLI +polling readiness (`gh` + configured auth/token) is detected, LoopX probes +`external_evidence_poll` automatically by default (`probed`) so fresh Goals and +Agents observe upstream PR/evidence dependencies out of the box without manual +`agent-capabilities --execute` or `--available-capability` ceremony. Later +decisions, including `heartbeat-prompt` pre-quota projection, `quota spend-slot`, +and `monitor-poll` rechecks, read that Agent's effective availability without +repeating flags. Goal/project `available_capabilities` declarations are +inherited dynamically; Agent observations never write back into Goal configuration +or propagate to peer Agents. The hook declares only its Agent-private write scope, returns no private payload, and fails in isolation; quota selection itself performs no provider or memory write. -The scope is the resolved runtime root, registry path, Goal id and registered -Agent id. Separate hosts/runtimes or registries do not inherit these observations. -A reused Agent id in the same scope refers to the same runtime declaration; -use distinct Agent identities for environments with different tools. Observations -are caller declarations, not independently verified probe receipts. They persist -until corrected or forgotten; omission of a flag does not revoke them. +The scope is the resolved runtime root, canonical project `source_registry` path +(unifying synced `registry.global.json` mirrors with the project's `.loopx/registry.json`), +Goal id and registered Agent id. Separate hosts/runtimes or unrelated registries do +not inherit these observations. A reused Agent id in the same scope refers to the +same runtime declaration; use distinct Agent identities for environments with +different tools. Explicit negative observations (`--unavailable-capability`) +override both Goal inheritance and automatic host probes (`probed`), and are +preserved across passive task-facing executions until explicitly cleared or replaced. +Explicit and verified observations persist until corrected or forgotten. A forget masks the old mirror value on subsequent reads. Local readiness probes apply to the current invocation. A network-disabled host suppresses PR polling even with an earlier positive observation. ```bash # Read current Agent observations and inherited/effective declarations. diff --git a/docs/reference/todo-continuation-readback.md b/docs/reference/todo-continuation-readback.md index d96cd7eebf..5ea548675c 100644 --- a/docs/reference/todo-continuation-readback.md +++ b/docs/reference/todo-continuation-readback.md @@ -34,13 +34,14 @@ requirements, claims, leases or Goal acceptance. Deferred ready work still needs its normal lifecycle transition. The existing typed capability owner resolves `external_evidence_poll` from the -current Goal declaration, remembered host observations and invocation facts; -remembered revocation defeats inherited permission. No per-command flag is -required when the owner already supplies permission. Shell/filesystem access, -Todo requirements and explicit prequota invocation do not grant network access. +current Goal declaration, automatic local host readiness probes (`probed`: `gh` +CLI + configured auth outside network-disabled sandboxes), remembered host +observations and invocation facts; remembered revocation (`--unavailable-capability`) +defeats both inherited permission and automatic host probes. No per-command flag is +required on equipped hosts. Shell/filesystem access alone and Todo requirements +do not grant network access on offline/unconfigured sandboxes. Unavailable permission sources return a failure without contacting GitHub. -Remove all inherited grants or record the capability as unavailable to stop -future automatic reads; previously verified merge facts remain usable. +Set `LOOPX_AUTO_CAPABILITY_PROBE=0` to disable local discovery. A network-disabled host suppresses PR observation even with a remembered or explicit declaration. Previously verified merge facts remain usable. Fresh executing `quota should-run` and `turn run-once --execute` compose the same registered hook before collecting the governing decision. Compatibility @@ -100,11 +101,11 @@ single-flight,并发调用只读回观察进行中,不重复请求。仓库 仍保留原展示边界,重启不需要重复远端读取或改写合并时间。离开 open 列表、关闭未合并或 provider 失败不能解除等待。观察不修改 Todo 状态、要求、认领、lease 或 Goal 验收; 已满足条件的 deferred Todo 仍走正常生命周期转换。 -既有 typed capability owner 从当前 Goal 声明、已记住的宿主观察和本次参数解析 -`external_evidence_poll`;宿主记录的撤销优先于继承授权。owner 已提供权限时,不必给 -每条命令手工补 flag。filesystem/shell、Todo 要求与显式调用 prequota 都不授予网络 -权限。权限来源不可用时只返回失败,不联系 GitHub。移除所有继承授权或记录能力不可用, -即可停止后续自动读取;已验证合并事实保留。 +既有 typed capability owner 从当前 Goal 声明、默认本机能力自动探测(`probed`:非离线沙箱下检测到 +`gh` CLI 与认证凭据时自动开启)、已记住的宿主观察和本次参数解析 +`external_evidence_poll`;宿主记录的撤销(`--unavailable-capability`)同时优先于继承授权和自动探测。 +本机工具就绪时无需手工传参或预先写入记忆。离线沙箱中仅凭 filesystem/shell 或 Todo 要求不会授予网络 +权限。权限来源不可用时只返回失败,不联系 GitHub。设置 `LOOPX_AUTO_CAPABILITY_PROBE=0` 可关闭本地探测。宿主禁网时,即使存在历史或显式能力声明也会停止 PR 观察;已验证的合并事实仍然可用。 执行性的 `quota should-run` 与新的 `turn run-once --execute` 在 governing decision 前组合相同注册 hook;兼容 `heartbeat-prequota` 也调用它。full/thin heartbeat 在宿主 diff --git a/loopx/capabilities/external_research/README.md b/loopx/capabilities/external_research/README.md index 68efe5fb21..3f61f189bc 100644 --- a/loopx/capabilities/external_research/README.md +++ b/loopx/capabilities/external_research/README.md @@ -69,10 +69,20 @@ JSON 与默认 Markdown 输出分别报告文件读取、JSON 解析和根对象 便于调用者修正输入。 ```bash -loopx external-evidence discover \ - --connector-registry \ +# Default zero-flag auto-detection: probes local methods (public-github, +# public-source-reader, gh-cli, ego-browser) + default connector inventory. +loopx external-evidence discover --format json + +# Default zero-flag planning with pinned GitHub source refs (auto-probes public-github): +loopx external-evidence plan \ + --objective "Compare current behavior" \ + --user-activity "Choose an implementation" \ + --decision "Whether to adopt it" \ + --evidence-kind current_behavior \ + --source https://github.com/OWNER/REPO/blob/FULL_COMMIT_SHA/README.md \ --format json +# Explicit custom provider inventory override remains supported: loopx external-evidence plan \ --objective "Compare current behavior" \ --user-activity "Choose an implementation" \ @@ -294,15 +304,17 @@ ledger. It requires the active research question to match the plan objective. Retries for the same admission are idempotent. Wrong questions, unrelated existing sources and exhausted source budgets remain blockers; partial projection stays retained until every admitted source is actually read back with matching lineage. -Omit `--execute` for read-only projection; omit `--public-github` to avoid the -provider readiness probe. There is no persistent provider enablement to uninstall. +Omit `--execute` for read-only projection; pass `--no-auto-detect` (or an +explicit `--provider-inventory-json` without `--public-github`) to disable automatic +provider readiness probing. There is no persistent provider enablement to uninstall. Original sources remain available on partial, empty and failed results. `execute --execute` 只授权读取来源;`readback --execute` 只把已明确采纳的紧凑证据 写入现有研究账本,且要求研究问题与 plan objective 相同。同一 admission 可幂等重试; 问题不匹配、已有不相关来源或预算耗尽仍为 blocker。部分下游投影保持 retained, -直至全部已采纳来源以匹配 lineage 实际回读。省略 `--execute` 可只读回读;省略 -`--public-github` 不探测该 provider。没有持久开关需要卸载。部分、空或失败证据 +直至全部已采纳来源以匹配 lineage 实际回读。省略 `--execute` 可只读回读;传入 +`--no-auto-detect`(或不带 `--public-github` 的显式 `--provider-inventory-json`) +可关闭默认 provider 就绪探测。没有持久开关需要卸载。部分、空或失败证据 保留原始来源退路;字面匹配不证明语义结论或证据完整性。 Real qualification (anonymous network reads, disposable synthetic ledger): diff --git a/loopx/capabilities/external_research/cli.py b/loopx/capabilities/external_research/cli.py index ae402cea77..9116610ecb 100644 --- a/loopx/capabilities/external_research/cli.py +++ b/loopx/capabilities/external_research/cli.py @@ -10,6 +10,7 @@ from ..connector_registry.core import load_connector_registry from ...extensions.public_github_research import execute_public_github, inspect_provider from .projection import readback, render_readback, validate_receipt +from .provider_probe import probe_local_evidence_providers PrintPayload = Callable[ @@ -39,7 +40,7 @@ def _load_object(path_text: str, *, label: str) -> dict[str, Any]: return value -def _load_receipt(path_text: str) -> dict: +def _load_receipt(path_text: str) -> dict[str, Any]: value = _load_object(path_text, label="external evidence receipt") receipt = value.get("receipt", value) if not isinstance(receipt, dict): @@ -148,6 +149,13 @@ def register_external_evidence_commands( help="Path to a JSON object with a providers array; not inline JSON.", ) discover.add_argument("--connector-registry", nargs="?", const="") + discover.add_argument( + "--no-auto-detect", + dest="auto_detect", + action="store_false", + default=True, + help="Disable default host evidence method and connector auto-detection.", + ) add_subcommand_format(discover) plan = actions.add_parser( @@ -167,6 +175,13 @@ def register_external_evidence_commands( plan.add_argument("--search-term", action="append", default=[]) plan.add_argument("--connector-registry", nargs="?", const="") plan.add_argument("--preferred-provider-id") + plan.add_argument( + "--no-auto-detect", + dest="auto_detect", + action="store_false", + default=True, + help="Disable default host evidence provider auto-detection when --provider-inventory-json is omitted.", + ) add_subcommand_format(plan) execute = actions.add_parser("execute", help="Execute the exact public GitHub plan without admitting evidence.") @@ -218,34 +233,75 @@ def handle_external_evidence_command( return None try: if args.external_evidence_action == "discover": - providers = _merge_providers( - _connector_inventory(args.connector_registry), - [] - if args.provider_inventory_json is None - else _provider_inventory( - _load_object( - args.provider_inventory_json, - label="external evidence provider inventory", + auto_detect = ( + getattr(args, "auto_detect", True) + and args.provider_inventory_json is None + and args.connector_registry is None + ) + connector_arg = "" if auto_detect else args.connector_registry + observed_providers = ( + probe_local_evidence_providers(for_plan=False) + if auto_detect + else ( + [] + if args.provider_inventory_json is None + else _provider_inventory( + _load_object( + args.provider_inventory_json, + label="external evidence provider inventory", + ) ) - ), + ) + ) + providers = _merge_providers( + _connector_inventory(connector_arg), + observed_providers, ) payload = effect_runtime_result( "external_evidence.discover", {"providers": providers}, ) elif args.external_evidence_action == "plan": - if not args.provider_inventory_json and not getattr(args, "public_github", False): + sources = list(getattr(args, "source", []) or []) + explicit_public_github = bool(getattr(args, "public_github", False)) + auto_detect = ( + getattr(args, "auto_detect", True) + and not args.provider_inventory_json + and not explicit_public_github + ) + if not args.provider_inventory_json and not explicit_public_github and not auto_detect: raise ValueError("plan requires provider inventory or explicit --public-github") - inventory = _load_object(args.provider_inventory_json, - label="external evidence provider inventory") if args.provider_inventory_json else {"providers": []} - if getattr(args, "public_github", False): - if len(getattr(args, "source", [])) > 8: + if explicit_public_github and len(sources) > 8: + raise ValueError("public GitHub plan allows at most eight sources") + if auto_detect: + if len(sources) > 8: raise ValueError("public GitHub plan allows at most eight sources") - inventory["providers"] = _merge_providers(_provider_inventory(inventory), [inspect_provider(getattr(args, "source", []))]) - providers = _merge_providers( - _connector_inventory(args.connector_registry), - _provider_inventory(inventory), - ) + connector_arg = "" if args.connector_registry is None else args.connector_registry + providers = _merge_providers( + _connector_inventory(connector_arg), + probe_local_evidence_providers( + source_refs=sources, + for_plan=True, + ), + ) + else: + inventory = ( + _load_object( + args.provider_inventory_json, + label="external evidence provider inventory", + ) + if args.provider_inventory_json + else {"providers": []} + ) + if explicit_public_github: + inventory["providers"] = _merge_providers( + _provider_inventory(inventory), + [inspect_provider(sources)], + ) + providers = _merge_providers( + _connector_inventory(args.connector_registry), + _provider_inventory(inventory), + ) payload = effect_runtime_result( "external_evidence.plan", { @@ -255,7 +311,7 @@ def handle_external_evidence_command( "decision": args.decision, "evidence_kinds": args.evidence_kind, "constraints": args.constraint, - **({"source_refs": getattr(args, "source", [])} if getattr(args, "source", []) else {}), + **({"source_refs": sources} if sources else {}), **({"search_terms": getattr(args, "search_term", [])} if getattr(args, "search_term", []) else {}), }, "providers": providers, diff --git a/loopx/capabilities/external_research/provider_probe.py b/loopx/capabilities/external_research/provider_probe.py new file mode 100644 index 0000000000..45c2351789 --- /dev/null +++ b/loopx/capabilities/external_research/provider_probe.py @@ -0,0 +1,169 @@ +"""Automatic local external-evidence method discovery and readiness probes. + +Deterministic local checks only: probes never grant owner-held permissions or +fabricated execution receipts, and honor network-disabled sandbox environments. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import os +from pathlib import Path +import shutil +import ssl +from typing import Any + +from ...control_plane.agents.capability_probe import ( + host_network_sandbox_disabled, + probe_github_cli_evidence_ready, +) +from ...extensions import public_github_research + + +def probe_ego_browser_ready( + *, + env: Mapping[str, str] | None = None, +) -> tuple[bool, bool, str | None]: + """Return `(installed, ready, unavailable_reason)` for local Ego browser evidence.""" + environment = os.environ if env is None else env + path_env = environment.get("PATH") + home_raw = str(environment.get("HOME") or "").strip() + home = Path(home_raw).expanduser() if home_raw else Path.home() + ego_cli = shutil.which("ego-browser", path=path_env) + if not ego_cli: + candidate = home / ".local" / "bin" / "ego-browser" + if candidate.is_file() and os.access(candidate, os.X_OK): + ego_cli = str(candidate) + app_installed = ( + Path("/Applications/Ego Lite.app").exists() + or (home / "Applications" / "Ego Lite.app").exists() + ) + installed = bool(ego_cli or app_installed) + if not installed: + return False, False, "ego_browser_not_installed" + if host_network_sandbox_disabled(environment): + return True, False, "sandbox_network_disabled" + if not ego_cli: + return True, False, "ego_browser_cli_not_on_path" + return True, True, None + + +def _all_pinned_public_github_sources(source_refs: Sequence[str]) -> bool: + if not source_refs or len(source_refs) > 8: + return False + try: + for ref in source_refs: + public_github_research._source(str(ref)) + except ValueError: + return False + return True + + +def probe_local_evidence_providers( + *, + source_refs: Sequence[str] = (), + for_plan: bool = False, + env: Mapping[str, str] | None = None, +) -> list[dict[str, Any]]: + """Auto-detect bundled and host-local external-evidence methods.""" + environment = os.environ if env is None else env + sandbox_disabled = host_network_sandbox_disabled(environment) + tls_available = ssl.OPENSSL_VERSION is not None + + providers: list[dict[str, Any]] = [] + + if for_plan and _all_pinned_public_github_sources(source_refs): + if sandbox_disabled: + providers.append( + { + "provider_id": public_github_research.PROVIDER_ID, + "provider_kind": "method", + "protocol": "external_evidence_research_v0", + "declared": True, + "installed": True, + "enabled": True, + "ready": False, + "unavailable_reason": "sandbox_network_disabled", + } + ) + else: + providers.append(public_github_research.inspect_provider(list(source_refs))) + else: + if sandbox_disabled: + gh_method_ready = False + gh_method_reason: str | None = "sandbox_network_disabled" + elif not tls_available: + gh_method_ready = False + gh_method_reason = "tls_runtime_unavailable" + elif for_plan: + gh_method_ready = False + gh_method_reason = "pinned_github_source_refs_required" + else: + gh_method_ready = True + gh_method_reason = None + providers.append( + { + "provider_id": public_github_research.PROVIDER_ID, + "provider_kind": "method", + "protocol": "external_evidence_research_v0", + "declared": True, + "installed": True, + "enabled": True, + "ready": gh_method_ready, + "unavailable_reason": gh_method_reason, + } + ) + + static_ready = bool(tls_available and not sandbox_disabled) + static_reason = ( + "sandbox_network_disabled" + if sandbox_disabled + else (None if tls_available else "tls_runtime_unavailable") + ) + providers.append( + { + "provider_id": "method:public-source-reader", + "provider_kind": "method", + "protocol": "external_evidence_research_v0", + "declared": True, + "installed": True, + "enabled": True, + "ready": static_ready, + "unavailable_reason": static_reason, + } + ) + + gh_installed = bool(shutil.which("gh", path=environment.get("PATH"))) + gh_ready, gh_reason = probe_github_cli_evidence_ready(env=environment) + providers.append( + { + "provider_id": "method:gh-cli", + "provider_kind": "method", + "protocol": "external_evidence_research_v0", + "declared": True, + "installed": gh_installed, + "enabled": gh_installed, + "ready": gh_ready, + "unavailable_reason": None + if gh_ready + else (gh_reason or "gh_cli_unavailable"), + } + ) + + ego_installed, ego_ready, ego_reason = probe_ego_browser_ready(env=environment) + providers.append( + { + "provider_id": "method:ego-browser", + "provider_kind": "method", + "protocol": "external_evidence_research_v0", + "declared": True, + "installed": ego_installed, + "enabled": ego_installed, + "ready": ego_ready, + "unavailable_reason": None + if ego_ready + else (ego_reason or "ego_browser_unavailable"), + } + ) + + return providers diff --git a/loopx/capabilities/issue_fix/cli.py b/loopx/capabilities/issue_fix/cli.py index 4ee2c8e7a6..27eca84ecc 100644 --- a/loopx/capabilities/issue_fix/cli.py +++ b/loopx/capabilities/issue_fix/cli.py @@ -1178,6 +1178,33 @@ def _handle_pr_lifecycle( generated_at=generated_at, ) pending_source_events = payload.pop("_maintainer_correction_source_events", None) + if ( + fetch_metadata + and payload.get("external_reads_performed") is True + and args.goal_id + and registry_path is not None + ): + from ...control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + from ...history import load_registry + from ...paths import resolve_runtime_root + + try: + resolved_runtime = resolve_runtime_root( + load_registry(registry_path), + runtime_root_arg, + registry_path=registry_path, + ) + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=resolved_runtime, + goal_id=args.goal_id, + agent_id=args.claimed_by, + available=("network", "external_evidence_poll"), + ) + except Exception: # noqa: BLE001 - optional host observation stays fail-open + pass if origin is not None: payload["origin_request"] = origin if should_write and ledger_path is not None: diff --git a/loopx/capabilities/issue_fix/pr_gate_reconcile.py b/loopx/capabilities/issue_fix/pr_gate_reconcile.py index fd37b4ee93..6d4e585c4d 100644 --- a/loopx/capabilities/issue_fix/pr_gate_reconcile.py +++ b/loopx/capabilities/issue_fix/pr_gate_reconcile.py @@ -433,6 +433,21 @@ def reconcile_acknowledged_issue_fix_pr_reviews( results.append(result) failure_count = sum(result.get("ok") is False for result in results) + external_read_count = sum( + result.get("external_read_performed") is True for result in results + ) + if any(row.get("ok") is True and row.get("external_read_performed") is True for row in results): + from ...control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + available=("network", "external_evidence_poll"), + ) return { "ok": True, "schema_version": PR_REVIEW_ACKED_RECONCILIATION_SCHEMA_VERSION, @@ -449,9 +464,7 @@ def reconcile_acknowledged_issue_fix_pr_reviews( "already_reconciled_count": sum( result.get("already_reconciled") is True for result in results ), - "external_read_count": sum( - result.get("external_read_performed") is True for result in results - ), + "external_read_count": external_read_count, "failure_count": failure_count, "private_material_read": False, "external_write_performed": False, diff --git a/loopx/cli_commands/_host_thread.py b/loopx/cli_commands/_host_thread.py index 35111cb7e9..c873c8f6a1 100644 --- a/loopx/cli_commands/_host_thread.py +++ b/loopx/cli_commands/_host_thread.py @@ -1,37 +1,10 @@ from __future__ import annotations import argparse -import os -from ..agy_goal_mode import ANTIGRAVITY_CONVERSATION_ID_ENV -from ..kiro_cli_goal_mode import KIRO_CLI_AGENT_TYPE, KIRO_CLI_SESSION_ID_ENV +from ..thread_agent_binding import HOST_THREAD_ID_ENV, ambient_host_thread_id -# Host surface -> the environment variable that host exports for its own -# session/thread id. A binding is only durable if the host guarantees the id, so -# a surface stays out of this table unless its runtime actually exports one; it -# then resolves to no thread id instead of guessing from prose or reusing -# another host's variable. -HOST_THREAD_ID_ENV: dict[str, str] = { - "codex-app": "CODEX_THREAD_ID", - "codex-app-ssh": "CODEX_THREAD_ID", - "codex-ide-plugin": "CODEX_THREAD_ID", - "codex-cli-tui": "CODEX_THREAD_ID", - "trae_app": "TRAECLI_THREAD_ID", - "traex-cli": "TRAECLI_THREAD_ID", - "antigravity-app": ANTIGRAVITY_CONVERSATION_ID_ENV, - "agy": ANTIGRAVITY_CONVERSATION_ID_ENV, - KIRO_CLI_AGENT_TYPE: KIRO_CLI_SESSION_ID_ENV, -} - - -def ambient_host_thread_id(host_surface: str) -> str | None: - """Read the host-provided local context, never a caller's route override. - - This is a trusted-local-runtime fence, not authentication against another - process that can change this OS user's environment or canonical files. - """ - variable = HOST_THREAD_ID_ENV.get(host_surface) - return (os.environ.get(variable) or None) if variable else None +__all__ = ["HOST_THREAD_ID_ENV", "ambient_host_thread_id", "current_host_thread_id"] def current_host_thread_id(args: argparse.Namespace) -> str | None: diff --git a/loopx/cli_commands/agent_capabilities.py b/loopx/cli_commands/agent_capabilities.py index fcdf571010..3137028274 100644 --- a/loopx/cli_commands/agent_capabilities.py +++ b/loopx/cli_commands/agent_capabilities.py @@ -42,8 +42,9 @@ def render_agent_capabilities(payload): return payload["error"] state = payload["agent_capabilities"] lines = [f"Runtime observations: {state['goal_id']} / {state['agent_id']} (this host)"] - for key in ("goal", "agent", "unavailable", "effective"): - lines.append(f"{key}: {', '.join(payload['availability'][key]) or '(none)'}") + for key in ("goal", "probed", "agent", "unavailable", "effective"): + if key in payload["availability"]: + lines.append(f"{key}: {', '.join(payload['availability'][key]) or '(none)'}") if "proposed" in state: lines.append(f"Preview: {state['proposed']}; use --execute to apply.") if state["invocation_only"]: diff --git a/loopx/cli_commands/pr_review.py b/loopx/cli_commands/pr_review.py index 93a65d74ba..6720cf3d26 100644 --- a/loopx/cli_commands/pr_review.py +++ b/loopx/cli_commands/pr_review.py @@ -295,6 +295,19 @@ def handle_pr_review_command( if not repository: raise ValueError("approval closeout requires a GitHub repository") payload = read_github_approval_closeout(repository=repository, exact_head=args.check_approval_closeout) + if goal_id and runtime_root is not None: + from ..control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + goal=goal, + agent_id=review_agent_id, + available=("network", "external_evidence_poll"), + ) print_payload(payload, output_format(args), lambda value: json.dumps(value, indent=2)) return 1 if payload["status"] == "hold" else 0 if goal_id: @@ -440,6 +453,19 @@ def handle_pr_review_command( ) } payload["local_goal_observation_write_performed"] = True + if source == "github_cli": + from ..control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + goal=goal, + agent_id=review_agent_id, + available=("network", "external_evidence_poll"), + ) print_payload( payload, output_format(args), @@ -662,6 +688,19 @@ def handle_pr_review_command( autonomous_review=autonomous_review, ) payload["request"]["local_checkpoint_write_performed"] = True + if goal_id and runtime_root is not None and not args.fixture: + from ..control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + goal=goal, + agent_id=review_agent_id, + available=("network", "external_evidence_poll"), + ) except Exception as exc: from ..usage_ping import capture_failure capture_failure(exc) diff --git a/loopx/cli_commands/project_lifecycle_refresh_state.py b/loopx/cli_commands/project_lifecycle_refresh_state.py index ee77f10d2d..f0702ab572 100644 --- a/loopx/cli_commands/project_lifecycle_refresh_state.py +++ b/loopx/cli_commands/project_lifecycle_refresh_state.py @@ -651,6 +651,23 @@ def handle_refresh_state_command( ) and not payload.get("dry_run") ) + if material_refresh_ready and args.available_capabilities and args.agent_id: + from ..control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=resolve_runtime_root( + load_registry(registry_path), + args.runtime_root, + registry_path=registry_path, + ), + goal_id=args.goal_id, + agent_id=str(args.agent_id), + available=args.available_capabilities, + preserve_unavailable=False, + ) if material_refresh_ready and reward_memory_reflection_json: validation_workspace_text = str( getattr(args, "delivery_workspace_path", None) diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index 5ee2319909..f33e280e51 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -517,6 +517,19 @@ def _execute_quota_command( include_presentation_projections=False, ), ) + if bool(args.execute) and payload.get("ok") and args.available_capabilities: + from ..control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=args.goal_id, + agent_id=args.agent_id, + available=args.available_capabilities, + preserve_unavailable=False, + ) elif args.quota_command in { "scheduler-ack", "scheduler-ack-current", @@ -554,6 +567,19 @@ def _execute_quota_command( registry_path=registry_path, goal_ref=goal_ref, ) + if bool(args.execute) and payload.get("ok") and args.available_capabilities: + from ..control_plane.agents.capability_memory import ( + record_verified_agent_capability_observation, + ) + + record_verified_agent_capability_observation( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=args.goal_id, + agent_id=args.agent_id, + available=args.available_capabilities, + preserve_unavailable=False, + ) elif args.quota_command == "void-slot": payload = _export("void_quota_slot")( status_payload, diff --git a/loopx/cli_commands/support_control_heartbeat.py b/loopx/cli_commands/support_control_heartbeat.py index c2b76090f0..7997f75158 100644 --- a/loopx/cli_commands/support_control_heartbeat.py +++ b/loopx/cli_commands/support_control_heartbeat.py @@ -132,15 +132,44 @@ def handle_heartbeat_prompt_command( agent_registry_path, args.goal_id, effective_agent_id ) reward_memory_enabled = False + effective_available_capabilities: list[str] | None = None if effective_agent_id is not None: from ..capabilities.reward_memory.configuration import ( reward_memory_automatic_ingest_for_agent, ) + from ..control_plane.agents.capability_memory import ( + resolve_agent_capabilities, + ) + from ..history import load_registry + from ..paths import resolve_runtime_root reward_memory_enabled = reward_memory_automatic_ingest_for_agent( registry_goal if isinstance(registry_goal, dict) else {}, effective_agent_id, ) + if isinstance(registry_goal, dict): + try: + resolved_runtime = resolve_runtime_root( + load_registry(agent_registry_path), + args.runtime_root, + registry_path=agent_registry_path, + ) + effective_available_capabilities = list( + resolve_agent_capabilities( + { + "registry": str(agent_registry_path.resolve()), + "runtime_root": str(resolved_runtime.resolve()), + }, + goal_id=args.goal_id, + agent_identity={"agent_id": effective_agent_id}, + item=registry_goal, + project_asset={}, + available=args.available_capabilities, + ).get("effective") + or [] + ) + except Exception: # noqa: BLE001 - prompt rendering stays fail-open + effective_available_capabilities = None explicit_scheduler_fields = ( args.host_surface, args.scheduler_owner, @@ -196,6 +225,7 @@ def handle_heartbeat_prompt_command( agent_profile=agent_profile, registered_agents=registered_agents, available_capabilities=args.available_capabilities, + effective_available_capabilities=effective_available_capabilities, runtime_profile=runtime_profile, scheduler_execution_context=( { diff --git a/loopx/control_plane/agents/capability_gate.ts b/loopx/control_plane/agents/capability_gate.ts index b4e933af48..fb70916987 100644 --- a/loopx/control_plane/agents/capability_gate.ts +++ b/loopx/control_plane/agents/capability_gate.ts @@ -180,19 +180,23 @@ export function projectRuntimeCapabilityReentry(request: JsonObject): JsonObject }; } -/** Agent negatives override inherited declarations; a fresh explicit observation wins. */ +/** Agent negatives override inherited and auto-probed declarations; a fresh explicit observation wins. */ export function projectCapabilityAvailability(request: JsonObject): JsonObject { const goal = unique(requireStringArray(request.goal, "goal")); const runtime = unique(requireStringArray(request.runtime, "runtime")); + const probed = unique(requireStringArray(request.probed ?? [], "probed")) + .filter(c => OBSERVABLE_RUNTIME_CAPABILITIES.has(c)); const state = requireJsonObject(request.agent ?? {}, "agent"); const remembered = requireStringArray(state.available ?? [], "agent.available") .filter(c => OBSERVABLE_RUNTIME_CAPABILITIES.has(c)); const unavailable = requireStringArray(state.unavailable ?? [], "agent.unavailable") .filter(c => OBSERVABLE_RUNTIME_CAPABILITIES.has(c) && !runtime.includes(c)); - const runtimeAvailable = unique([...remembered, ...runtime]).filter(c => !unavailable.includes(c)); - return {goal, agent: remembered, unavailable, invocation: runtime, + const hostUnavailable = requireStringArray(request.host_unavailable ?? [], "host_unavailable"); + const usable = (c: string) => !unavailable.includes(c) && !hostUnavailable.includes(c); + const runtimeAvailable = unique([...probed, ...remembered, ...runtime]).filter(usable); + return {goal, probed, agent: remembered, unavailable, invocation: runtime, runtime_available: runtimeAvailable, - effective: unique([...goal, ...runtimeAvailable]).filter(c => !unavailable.includes(c))}; + effective: unique([...goal, ...runtimeAvailable]).filter(usable)}; } export function evaluateCapabilityGate(value: unknown): JsonObject { diff --git a/loopx/control_plane/agents/capability_memory.py b/loopx/control_plane/agents/capability_memory.py index dac6bd25e3..f5a77a0250 100644 --- a/loopx/control_plane/agents/capability_memory.py +++ b/loopx/control_plane/agents/capability_memory.py @@ -1,5 +1,6 @@ """Adapt registered host-local Agent observations to the typed state owner.""" +from collections.abc import Mapping from typing import Any, TYPE_CHECKING, cast from pathlib import Path @@ -9,32 +10,149 @@ from ..todos.contract import normalize_required_capabilities, normalize_todo_claimed_by +def canonical_capability_registry_scope( + registry_path: Path, goal: Mapping[str, Any] | None +) -> tuple[str, list[str]]: + """Unify synced global-registry mirrors with their canonical project source_registry.""" + resolved = str(registry_path.expanduser().resolve()) + if isinstance(goal, Mapping): + raw_source = str(goal.get("source_registry") or "").strip() + if raw_source: + canonical = str(Path(raw_source).expanduser().resolve()) + if canonical != resolved: + return canonical, [resolved] + return resolved, [] + + def agent_capability_memory( *, registry_path: Path, runtime_root: Path, goal_id: str, agent_id: str, available: Any = None, unavailable: Any = None, forget: Any = None, - execute: bool = False, + execute: bool = False, preserve_unavailable: bool = False, ) -> dict[str, Any]: goal_id = str(goal_id).strip() normalized_agent = normalize_todo_claimed_by(agent_id) if not normalized_agent: raise ValueError("agent_id must be a public-safe registered agent id") goal = load_goal_from_registry(registry_path, goal_id) - result = effect_runtime_result("agent.capability_memory", { + canonical_registry, legacy_registries = canonical_capability_registry_scope( + registry_path, goal + ) + request: dict[str, Any] = { "schema_version": "agent_runtime_capability_request_v0", "runtime_root": str(runtime_root.expanduser().resolve()), - "registry": str(registry_path.expanduser().resolve()), + "registry": canonical_registry, "goal_id": goal_id, "agent_id": normalized_agent, "registered_agents": registered_agent_ids_for_goal(goal), "available": normalize_required_capabilities(available), "unavailable": normalize_required_capabilities(unavailable), "forget": normalize_required_capabilities(forget), "execute": execute, - }) + } + if legacy_registries: + request["legacy_registries"] = legacy_registries + if preserve_unavailable: + request["preserve_unavailable"] = True + result = effect_runtime_result("agent.capability_memory", request) if not isinstance(result, dict) or result.get("schema_version") != "agent_runtime_capabilities_v0": raise TypeError("invalid agent runtime capability memory result") return result +def resolve_executing_registered_agent( + *, + goal: Mapping[str, Any] | None, + explicit_agent_id: str | None = None, +) -> str | None: + """Resolve the executing registered Agent without guessing across unbound peers.""" + if not isinstance(goal, Mapping): + return None + registered = registered_agent_ids_for_goal(dict(goal)) + if not registered: + return None + normalized_explicit = normalize_todo_claimed_by(explicit_agent_id) if explicit_agent_id else None + if normalized_explicit: + return normalized_explicit if normalized_explicit in registered else None + + from ...thread_agent_binding import ( + HOST_THREAD_ID_ENV, + ambient_host_thread_id, + resolve_thread_agent_binding, + ) + + bound_agents: set[str] = set() + saw_conflict = False + for surface in sorted(HOST_THREAD_ID_ENV): + thread_id = ambient_host_thread_id(surface) + if not thread_id: + continue + try: + binding = resolve_thread_agent_binding( + dict(goal), host_surface=surface, thread_id=thread_id + ) + except Exception: # noqa: BLE001 - ambient host lookup must never fail task commands + continue + status = binding.get("status") + if status == "conflict": + saw_conflict = True + break + if status == "bound": + candidate = normalize_todo_claimed_by(binding.get("agent_id")) + if candidate and candidate in registered: + bound_agents.add(candidate) + if not saw_conflict and len(bound_agents) == 1: + return next(iter(bound_agents)) + if saw_conflict or len(bound_agents) > 1: + return None + if len(registered) == 1: + return registered[0] + return None + + +def record_verified_agent_capability_observation( + *, + registry_path: Path | None, + runtime_root: Path | None, + goal_id: str | None, + available: Any, + agent_id: str | None = None, + goal: Mapping[str, Any] | None = None, + preserve_unavailable: bool = True, +) -> dict[str, Any] | None: + """Persist a verified host runtime observation for the executing registered Agent.""" + normalized_goal_id = str(goal_id or "").strip() + normalized_available = normalize_required_capabilities(available) + if ( + registry_path is None + or runtime_root is None + or not normalized_goal_id + or not normalized_available + ): + return None + try: + resolved_goal = ( + dict(goal) + if isinstance(goal, Mapping) + else load_goal_from_registry(registry_path, normalized_goal_id) + ) + target_agent = resolve_executing_registered_agent( + goal=resolved_goal, + explicit_agent_id=agent_id, + ) + if not target_agent: + return None + return agent_capability_memory( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=normalized_goal_id, + agent_id=target_agent, + available=normalized_available, + execute=True, + preserve_unavailable=preserve_unavailable, + ) + except Exception: # noqa: BLE001 - optional host capability memory must fail open + return None + + if TYPE_CHECKING: from ..capability_hooks import TurnStartHookRegistration @@ -130,8 +248,9 @@ def resolve_agent_capabilities( item: dict[str, Any], project_asset: dict[str, Any], available: Any, state: dict[str, Any] | None = None, ) -> dict[str, Any]: - """Read current scoped observations even when the caller's status is cached.""" + """Read current scoped observations and auto-probed host readiness.""" from .capability_gate import _evaluate + from .capability_probe import host_network_sandbox_disabled, probe_host_runtime_capabilities from ..quota.goal_boundary import declared_available_capabilities root, registry = status_payload.get("runtime_root"), status_payload.get("registry") @@ -150,7 +269,10 @@ def resolve_agent_capabilities( availability = _evaluate( "availability", goal=[*declared_available_capabilities(item), *declared_available_capabilities(project_asset)], - runtime=normalize_required_capabilities(available), agent=state or {}, + runtime=normalize_required_capabilities(available), + probed=probe_host_runtime_capabilities(), + host_unavailable=["external_evidence_poll"] if host_network_sandbox_disabled() else [], + agent=state or {}, ) if agent_identity: # Default status/quota surfaces need only the compact runtime input used diff --git a/loopx/control_plane/agents/capability_memory.ts b/loopx/control_plane/agents/capability_memory.ts index e50d1c73bb..b6826a68f6 100644 --- a/loopx/control_plane/agents/capability_memory.ts +++ b/loopx/control_plane/agents/capability_memory.ts @@ -24,6 +24,10 @@ export async function agentCapabilityMemory(request: JsonObject): Promise registry.length > 0 && registry !== scope.registry); + const preserveUnavailable = request.preserve_unavailable === undefined + ? false : requireBoolean(request.preserve_unavailable, "preserve_unavailable"); const registered = requireStringArray(request.registered_agents, "registered_agents"); if (!registered.includes(scope.agent_id)) throw new TypeError("agent must be registered for this Goal"); const supplied = unique(requireStringArray(request.available ?? [], "available")); @@ -37,17 +41,20 @@ export async function agentCapabilityMemory(request: JsonObject): Promise => { + const scopePath = (targetScope: typeof scope) => { + const key = createHash("sha256").update(JSON.stringify(targetScope)).digest("hex"); + return join(root, "agent-runtime-capabilities", `${key}.json`); + }; + const path = scopePath(scope); + const readScope = async (targetScope: typeof scope): Promise<{observations: JsonObject; forgotten: string[]}> => { let bytes: string; - try { bytes = await readFile(path, "utf8"); } + try { bytes = await readFile(scopePath(targetScope), "utf8"); } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") return {}; + if ((error as NodeJS.ErrnoException).code === "ENOENT") return {observations: {}, forgotten: []}; throw error; } const state = requireJsonObject(JSON.parse(bytes), "agent runtime capability state"); - if (state.schema_version !== SCHEMA || Object.entries(scope).some(([k, v]) => state[k] !== v)) { + if (state.schema_version !== SCHEMA || Object.entries(targetScope).some(([k, v]) => state[k] !== v)) { throw new TypeError("agent runtime capability state scope/schema mismatch"); } const observations = requireJsonObject(state.observations, "observations"); @@ -56,16 +63,38 @@ export async function agentCapabilityMemory(request: JsonObject): Promise !observable(c) || Object.hasOwn(observations, c))) { + throw new TypeError("invalid forgotten runtime capability"); + } + return {observations, forgotten}; }; const update = async (): Promise => { - const previous = await read(); + const canonical = await readScope(scope); + const previous: JsonObject = {}; + for (const registry of legacyRegistries) { + Object.assign(previous, (await readScope({...scope, registry})).observations); + } + for (const c of canonical.forgotten) delete previous[c]; + Object.assign(previous, canonical.observations); const next = {...previous}; - for (const c of available) next[c] = "available"; + const forgotten = new Set(canonical.forgotten); + for (const c of available) { + if (!preserveUnavailable || previous[c] !== "unavailable") next[c] = "available"; + } for (const c of unavailable) next[c] = "unavailable"; - for (const c of forget) delete next[c]; + for (const c of [...available, ...unavailable]) forgotten.delete(c); + for (const c of forget) { + delete next[c]; + forgotten.add(c); + } + const markers = unique([...forgotten]); const changed = JSON.stringify(sortedEntries(previous)) !== JSON.stringify(sortedEntries(next)); - if (execute && changed) await durableWriteJson(path, {schema_version: SCHEMA, ...scope, observations: next}); + const updated = JSON.stringify(sortedEntries(canonical.observations)) !== JSON.stringify(sortedEntries(next)) + || JSON.stringify(markers) !== JSON.stringify(canonical.forgotten); + const shouldWrite = execute && (available.length + unavailable.length + forget.length > 0) && updated; + if (shouldWrite) await durableWriteJson(path, {schema_version: SCHEMA, ...scope, observations: next, + ...(markers.length ? {forgotten: markers} : {})}); const project = (observations: JsonObject) => ({ available: Object.keys(observations).filter(c => observations[c] === "available").sort(lexical), unavailable: Object.keys(observations).filter(c => observations[c] === "unavailable").sort(lexical), @@ -76,7 +105,7 @@ export async function agentCapabilityMemory(request: JsonObject): Promise !observable(c)), - written: execute && changed, durable_grant_written: false, + written: shouldWrite, durable_grant_written: false, }; }; return execute && (available.length || unavailable.length || forget.length) diff --git a/loopx/control_plane/agents/capability_probe.py b/loopx/control_plane/agents/capability_probe.py new file mode 100644 index 0000000000..cc64e2241f --- /dev/null +++ b/loopx/control_plane/agents/capability_probe.py @@ -0,0 +1,97 @@ +"""Automatic host runtime capability readiness probes. + +Deterministic local readiness checks only: probes never grant owner-held +permissions (`credentials`, `production_access`), never mutate Goal policy, and +never override explicit `unavailable` revocations recorded in capability memory. +""" + +from __future__ import annotations + +from collections.abc import Mapping +import os +from pathlib import Path +import shutil + +_TRUTHY = frozenset({"1", "true", "yes", "on"}) +_FALSY = frozenset({"0", "false", "no", "off"}) + + +def host_network_sandbox_disabled(env: Mapping[str, str] | None = None) -> bool: + """Return True when the host environment explicitly disables network access.""" + environment = os.environ if env is None else env + for key in ("CODEX_SANDBOX_NETWORK_DISABLED", "LOOPX_OFFLINE"): + if str(environment.get(key) or "").strip().lower() in _TRUTHY: + return True + return False + + +def auto_capability_probe_enabled(env: Mapping[str, str] | None = None) -> bool: + """Allow explicit opt-out via LOOPX_AUTO_CAPABILITY_PROBE=0 while on by default.""" + environment = os.environ if env is None else env + raw = str(environment.get("LOOPX_AUTO_CAPABILITY_PROBE") or "").strip().lower() + if raw in _FALSY: + return False + return True + + +def _gh_hosts_config_paths(env: Mapping[str, str]) -> tuple[Path, ...]: + configured = str(env.get("GH_CONFIG_DIR") or "").strip() + if configured: + return (Path(configured).expanduser() / "hosts.yml",) + candidates: list[Path] = [] + home_raw = str(env.get("HOME") or "").strip() + home = Path(home_raw).expanduser() if home_raw else Path.home() + xdg = str(env.get("XDG_CONFIG_HOME") or "").strip() + if xdg: + candidates.append(Path(xdg).expanduser() / "gh" / "hosts.yml") + candidates.append(home / ".config" / "gh" / "hosts.yml") + appdata = str(env.get("APPDATA") or "").strip() + if appdata: + candidates.append(Path(appdata).expanduser() / "GitHub CLI" / "hosts.yml") + return tuple(candidates) + + +def probe_github_cli_evidence_ready( + *, + env: Mapping[str, str] | None = None, +) -> tuple[bool, str | None]: + """Check whether `gh` CLI can poll external GitHub PR/evidence metadata.""" + environment = os.environ if env is None else env + if host_network_sandbox_disabled(environment): + return False, "sandbox_network_disabled" + path_env = environment.get("PATH") + gh_executable = shutil.which("gh", path=path_env) + if not gh_executable: + return False, "gh_cli_not_installed" + for token_key in ( + "GH_TOKEN", + "GITHUB_TOKEN", + "GITHUB_ENTERPRISE_TOKEN", + "GH_ENTERPRISE_TOKEN", + ): + if str(environment.get(token_key) or "").strip(): + return True, None + for hosts_file in _gh_hosts_config_paths(environment): + try: + if hosts_file.is_file() and hosts_file.stat().st_size > 0: + return True, None + except OSError: + continue + return False, "gh_auth_not_configured" + + +def probe_host_runtime_capabilities( + *, + env: Mapping[str, str] | None = None, +) -> list[str]: + """Auto-detect default host runtime capabilities without mutating durable state.""" + environment = os.environ if env is None else env + if not auto_capability_probe_enabled(environment): + return [] + probed: list[str] = [] + gh_ready, _ = probe_github_cli_evidence_ready( + env=environment, + ) + if gh_ready: + probed.append("external_evidence_poll") + return probed diff --git a/loopx/control_plane/collaboration/__init__.py b/loopx/control_plane/collaboration/__init__.py index f1f8d3a9f0..5b3986d39c 100644 --- a/loopx/control_plane/collaboration/__init__.py +++ b/loopx/control_plane/collaboration/__init__.py @@ -18,24 +18,27 @@ def conversation_trigger(mode: str | None = None, **evidence: bool) -> dict[str, def conversation_scope(session: dict[str, Any], *, origin: str | None = None) -> dict[str, Any]: # Core distinguishes an absent legacy Goal field from an explicit project null. - return effect_runtime_result("collaboration.conversation.scope", { + return cast(dict[str, Any], effect_runtime_result("collaboration.conversation.scope", { **{key: session[key] for key in ( "channel_id", "goal_id", "project_context", "steward_context", "managed_agent_id", "session_mode", ) if key in session}, **({"origin": origin} if origin is not None else {}), - }) + })) def conversation_reply_context(route: dict[str, Any]) -> dict[str, Any]: - return effect_runtime_result( - "collaboration.conversation.reply_context", - { - "message_id": route.get("message_id"), - "parent_id": route.get("parent_id"), - "conversation_id": route.get("source_conversation_id"), - "reply_context": route.get("reply_context"), - "root_id": route.get("root_id"), - "thread_id": route.get("thread_id"), - "thread_context": route.get("thread_context"), - }, + return cast( + dict[str, Any], + effect_runtime_result( + "collaboration.conversation.reply_context", + { + "message_id": route.get("message_id"), + "parent_id": route.get("parent_id"), + "conversation_id": route.get("source_conversation_id"), + "reply_context": route.get("reply_context"), + "root_id": route.get("root_id"), + "thread_id": route.get("thread_id"), + "thread_context": route.get("thread_context"), + }, + ), ) diff --git a/loopx/control_plane/heartbeat/builder.py b/loopx/control_plane/heartbeat/builder.py index c50af3e961..658efa793e 100644 --- a/loopx/control_plane/heartbeat/builder.py +++ b/loopx/control_plane/heartbeat/builder.py @@ -171,6 +171,7 @@ def _heartbeat_prompt_commands( registry_path: str | Path | None, normalized_agent_id: str | None, normalized_available_capabilities: tuple[str, ...], + effective_available_capabilities: tuple[str, ...], task_body_available_capabilities: tuple[str, ...], runtime_profile: str | None, scheduler_execution_context: Any, @@ -257,7 +258,7 @@ def _heartbeat_prompt_commands( f"heartbeat-prequota -g {shlex.quote(goal_id)} " f"-a {shlex.quote(normalized_agent_id)}" if normalized_agent_id - and "external_evidence_poll" in normalized_available_capabilities + and "external_evidence_poll" in effective_available_capabilities else None ) commands = { @@ -374,6 +375,7 @@ def build_heartbeat_prompt( agent_profile: dict[str, Any] | None = None, registered_agents: list[str] | tuple[str, ...] | None = None, available_capabilities: list[str] | tuple[str, ...] | None = None, + effective_available_capabilities: list[str] | tuple[str, ...] | None = None, runtime_profile: str | None = None, scheduler_execution_context: dict[str, Any] | None = None, visible_goal_host: str | None = None, @@ -506,6 +508,11 @@ def build_heartbeat_prompt( normalized_available_capabilities = normalize_required_capabilities( available_capabilities ) + resolved_effective_capabilities = ( + normalize_required_capabilities(effective_available_capabilities) + if effective_available_capabilities is not None + else normalized_available_capabilities + ) initial_runtime_capability_projection = ( build_visible_goal_initial_runtime_capability_projection( normalized_available_capabilities @@ -538,8 +545,9 @@ def build_heartbeat_prompt( runtime_root=runtime_root, registry_path=registry_path, normalized_agent_id=normalized_agent_id, - normalized_available_capabilities=normalized_available_capabilities, - task_body_available_capabilities=task_body_available_capabilities, + normalized_available_capabilities=tuple(normalized_available_capabilities), + effective_available_capabilities=tuple(resolved_effective_capabilities), + task_body_available_capabilities=tuple(task_body_available_capabilities), runtime_profile=runtime_profile, scheduler_execution_context=scheduler_execution_context, native_goal_host=native_goal_host, diff --git a/loopx/thread_agent_binding.py b/loopx/thread_agent_binding.py index a9490403b4..c07a96ce19 100644 --- a/loopx/thread_agent_binding.py +++ b/loopx/thread_agent_binding.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os import re from dataclasses import dataclass from pathlib import Path @@ -13,6 +14,24 @@ from .history import load_registry from .registry import find_registry_goal, registry_goals +HOST_THREAD_ID_ENV: dict[str, str] = { + "codex-app": "CODEX_THREAD_ID", + "codex-app-ssh": "CODEX_THREAD_ID", + "codex-ide-plugin": "CODEX_THREAD_ID", + "codex-cli-tui": "CODEX_THREAD_ID", + "trae_app": "TRAECLI_THREAD_ID", + "traex-cli": "TRAECLI_THREAD_ID", + "antigravity-app": "ANTIGRAVITY_CONVERSATION_ID", + "agy": "ANTIGRAVITY_CONVERSATION_ID", + "kiro-cli": "KIRO_SESSION_ID", +} + + +def ambient_host_thread_id(host_surface: str) -> str | None: + """Read the host-provided local context, never a caller's route override.""" + variable = HOST_THREAD_ID_ENV.get(host_surface) + return (os.environ.get(variable) or None) if variable else None + THREAD_ID_MAX_LENGTH = 128 THREAD_BINDING_SCHEMA_VERSION = "loopx_thread_agent_binding_v0" THREAD_BINDING_RESOLUTION_SCHEMA_VERSION = "loopx_thread_agent_binding_resolution_v0" @@ -304,6 +323,7 @@ def _registry_thread_binding_request( else None ) session_locator = None + normalized_thread_id: str | None if thread_link: if ( normalized_surface is not None diff --git a/tests/capabilities/test_external_evidence_cli.py b/tests/capabilities/test_external_evidence_cli.py index c7fa096e05..f4b3082fc0 100644 --- a/tests/capabilities/test_external_evidence_cli.py +++ b/tests/capabilities/test_external_evidence_cli.py @@ -638,3 +638,103 @@ def save(name: str, payload: dict) -> str: assert "recorded_at" not in direct_row and "publication_date" not in direct_row finally: restart_effect_runtime() + + +def test_zero_flag_discover_and_plan_auto_detect_local_evidence_capabilities( + tmp_path: Path, monkeypatch +) -> None: + from loopx.extensions import public_github_research as gh_provider + + monkeypatch.setenv("LOOPX_USAGE_PING", "0") + monkeypatch.setenv("HOME", str(tmp_path / "home")) + (tmp_path / "home").mkdir() + monkeypatch.delenv("CODEX_SANDBOX_NETWORK_DISABLED", raising=False) + monkeypatch.delenv("LOOPX_OFFLINE", raising=False) + + payloads: list[dict] = [] + + def emit(payload, *_): + payloads.append(payload) + + try: + # 1. Zero-flag discover automatically projects local methods + default connector registry. + discover_args = argparse.Namespace( + command="external-evidence", + external_evidence_action="discover", + provider_inventory_json=None, + connector_registry=None, + auto_detect=True, + ) + assert ( + cli.handle_external_evidence_command( + discover_args, + output_format=lambda _: "json", + print_payload=emit, + ) + == 0 + ) + discovered = payloads[-1] + assert discovered["schema_version"] == "loopx_external_evidence_discovery_v0" + assert discovered["status"] == "ready" + assert discovered["summary"]["method_count"] == 4 + assert discovered["summary"]["connector_count"] >= 1 + assert "method:public-github" in discovered["ready_provider_ids"] + assert "method:public-source-reader" in discovered["ready_provider_ids"] + assert discovered["truth_contract"]["execution_observed"] is False + + # 2. Under network-disabled sandbox, zero-flag discover reports inventory_only with zero ready methods. + monkeypatch.setenv("CODEX_SANDBOX_NETWORK_DISABLED", "1") + assert ( + cli.handle_external_evidence_command( + discover_args, + output_format=lambda _: "json", + print_payload=emit, + ) + == 0 + ) + sandboxed = payloads[-1] + assert sandboxed["status"] == "inventory_only" + assert sandboxed["summary"]["ready_count"] == 0 + monkeypatch.delenv("CODEX_SANDBOX_NETWORK_DISABLED", raising=False) + + # 3. Zero-flag plan with pinned GitHub source refs auto-probes public-github without --public-github. + monkeypatch.setattr( + gh_provider, + "_read", + lambda url: b'{"private": false}' + if url.startswith("https://api.github.com/") + else b"Pinned content\n", + ) + pinned_source = ( + "https://github.com/example/public/blob/" + "c" * 40 + "/README.md" + ) + plan_args = argparse.Namespace( + command="external-evidence", + external_evidence_action="plan", + objective="Inspect pinned public behavior", + user_activity="Auto-detect ready evidence method", + decision="Whether to adopt", + evidence_kind=["current_behavior"], + constraint=[], + provider_inventory_json=None, + public_github=False, + source=[pinned_source], + search_term=["Pinned"], + connector_registry=None, + preferred_provider_id=None, + auto_detect=True, + ) + assert ( + cli.handle_external_evidence_command( + plan_args, + output_format=lambda _: "json", + print_payload=emit, + ) + == 0 + ) + planned = payloads[-1] + assert planned["schema_version"] == "loopx_external_evidence_plan_v0" + assert planned["status"] == "ready" + assert planned["selected_provider"]["provider_id"] == "method:public-github" + finally: + restart_effect_runtime() diff --git a/tests/control_plane/test_agent_capability_memory.py b/tests/control_plane/test_agent_capability_memory.py index 39e9f9849b..f6457a725b 100644 --- a/tests/control_plane/test_agent_capability_memory.py +++ b/tests/control_plane/test_agent_capability_memory.py @@ -1,6 +1,8 @@ """Separate CLI processes must share only the registered agent's local observations.""" import json +import pytest + from loopx.cli import main from tests.control_plane.test_quota_settlement_cli import ( @@ -181,3 +183,451 @@ def test_agent_alias_uses_existing_identity_normalization(tmp_path): "--agent-id", AGENT_ID) assert rc == 0, state assert state["agent_capabilities"]["available"] == ["network"] + + +def test_global_registry_sync_shares_canonical_source_registry_capability_memory(tmp_path): + _, runtime, registry = _write_fixture( + tmp_path, required_capability="external_evidence_poll", provider="sqlite" + ) + global_registry = runtime / "registry.global.json" + source_payload = json.loads(registry.read_text()) + synced_goal = dict(source_payload["goals"][0]) + synced_goal["source_registry"] = str(registry.resolve()) + global_registry.parent.mkdir(parents=True, exist_ok=True) + global_registry.write_text( + json.dumps({**source_payload, "goals": [synced_goal]}) + ) + + rc, recorded = _run_cli( + registry, + runtime, + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--available-capability", + "external_evidence_poll", + "--execute", + ) + assert rc == 0 and recorded["agent_capabilities"]["written"] is True, recorded + + rc, via_global = _run_cli( + global_registry, + runtime, + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + ) + assert rc == 0, via_global + assert via_global["capability_gate"]["action"] == "run" + + rc, prompt = _run_cli( + global_registry, + runtime, + "heartbeat-prompt", + "--thin", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + ) + assert rc == 0, prompt + assert "heartbeat-prequota" in prompt["task_body"] + assert "--available-capability external_evidence_poll" not in prompt["task_body"] + + rc, revoked = _run_cli( + global_registry, + runtime, + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--unavailable-capability", + "external_evidence_poll", + "--execute", + ) + assert rc == 0, revoked + rc, revoked_prompt = _run_cli( + registry, + runtime, + "heartbeat-prompt", + "--thin", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + ) + assert rc == 0, revoked_prompt + assert "heartbeat-prequota" not in revoked_prompt["task_body"] + + +@pytest.mark.parametrize("original", ["available", "unavailable"]) +@pytest.mark.parametrize("via_mirror", [True, False]) +def test_forget_legacy_observation_survives_fresh_registry_reads(tmp_path, original, via_mirror): + _, runtime, project = _write_fixture(tmp_path, provider="sqlite") + mirror = runtime / "registry.global.json" + mirror.parent.mkdir(parents=True, exist_ok=True) + mirror.write_bytes(project.read_bytes()) + args = ("agent-capabilities", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID) + capability = "external_evidence_poll" + + def observe(registry, *flags): + rc, result = _run_cli(registry, runtime, *args, *flags) + assert rc == 0, result + return result["agent_capabilities"] + + observe(mirror, f"--{original}-capability", capability, "--available-capability", "cli_bridge", "--execute") + synced = json.loads(mirror.read_text()) + synced["goals"][0]["source_registry"] = str(project.resolve()) + mirror.write_text(json.dumps(synced)) + clear = ("--forget-capability", capability, "--execute") + assert observe(mirror if via_mirror else project, *clear)["written"] + assert not observe(mirror if via_mirror else project, *clear)["written"] + for registry in (project, mirror): + current = observe(registry) + assert capability not in current["available"] + current["unavailable"] + assert "cli_bridge" in observe(mirror)["available"] + observe(mirror, "--available-capability", capability, "--execute") + assert set(observe(project)["available"]) == {"cli_bridge", capability} + + +def test_live_task_facing_capability_commands_auto_record_observations( + tmp_path, monkeypatch, capsys +): + from loopx.capabilities.issue_fix import pr_lifecycle + from loopx.cli_commands import pr_review as pr_review_cmd + + def _run_inproc(*cli_args: str) -> tuple[int, dict]: + rc = main( + [ + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + *cli_args, + ] + ) + return rc, json.loads(capsys.readouterr().out) + + project, runtime, registry = _write_fixture( + tmp_path, required_capability="external_evidence_poll", provider="sqlite" + ) + data = json.loads(registry.read_text()) + data["goals"][0]["coordination"]["registered_agents"].append("peer-b") + data["goals"][0]["coordination"]["thread_agent_bindings"] = [ + { + "schema_version": "loopx_thread_agent_binding_v0", + "host_surface": "codex-app", + "thread_id": "thread-agent-primary", + "agent_id": AGENT_ID, + "bound_at": "2026-11-23T00:00:00Z", + } + ] + registry.write_text(json.dumps(data)) + + fixture_path = tmp_path / "pr-fixture.json" + fixture_path.write_text( + json.dumps( + { + "repository": "owner/repo", + "reviewer_login": "reviewer", + "pull_requests": [], + } + ) + ) + monkeypatch.setenv("CODEX_THREAD_ID", "thread-agent-primary") + rc, fixture_review = _run_inproc( + "pr-review", + "--goal-id", + GOAL_ID, + "--fixture", + str(fixture_path), + ) + assert rc == 0, fixture_review + assert not (runtime / "agent-runtime-capabilities").exists() + + monkeypatch.setattr( + pr_review_cmd, "resolve_current_github_repository", lambda: "owner/repo" + ) + monkeypatch.setattr( + pr_review_cmd, "resolve_current_github_login", lambda: "reviewer" + ) + monkeypatch.setattr( + pr_review_cmd, + "scan_github_pull_requests", + lambda **kwargs: {"pull_requests": [], "truncated": False}, + ) + rc, live_review = _run_inproc( + "pr-review", + "--goal-id", + GOAL_ID, + ) + assert rc == 0, live_review + + rc, state = _run_cli( + registry, + runtime, + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + ) + assert rc == 0, state + assert state["agent_capabilities"]["available"] == [ + "external_evidence_poll", + "network", + ] + rc, peer_state = _run_cli( + registry, + runtime, + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + "peer-b", + ) + assert rc == 0 and peer_state["agent_capabilities"]["available"] == [] + + # Explicit negative observations are preserved across passive task-facing polls. + rc, _ = _run_cli( + registry, + runtime, + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + "peer-b", + "--unavailable-capability", + "external_evidence_poll", + "--execute", + ) + assert rc == 0 + monkeypatch.delenv("CODEX_THREAD_ID", raising=False) + monkeypatch.setattr( + pr_lifecycle, + "fetch_github_pr_lifecycle_payload", + lambda reference, **kwargs: { + "url": f"https://github.com/{reference['repo']}/pull/{reference['number']}", + "number": reference["number"], + "state": "OPEN", + }, + ) + rc, lifecycle = _run_inproc( + "issue-fix", + "pr-lifecycle", + "--project", + str(project), + "--goal-id", + GOAL_ID, + "--claimed-by", + "peer-b", + "--repo", + "owner/repo", + "--pr-ref", + "#42", + "--fetch-metadata", + ) + assert rc == 0, lifecycle + rc, peer_after = _run_cli( + registry, + runtime, + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + "peer-b", + ) + assert rc == 0, peer_after + assert peer_after["agent_capabilities"]["available"] == ["network"] + assert peer_after["agent_capabilities"]["unavailable"] == [ + "external_evidence_poll" + ] + + +def test_failed_read_and_unrelated_local_success_do_not_record_availability(tmp_path, monkeypatch): + from loopx.capabilities.issue_fix import pr_gate_reconcile as reconcile + + _, runtime, registry = _write_fixture(tmp_path, required_capability="external_evidence_poll", provider="sqlite") + receipts = [{"binding": {"todo_id": key, "permalink": "https://github.com/owner/repo/pull/1"}} + for key in ("failed", "already-closed")] + monkeypatch.setattr(reconcile, "load_issue_fix_pr_review_ack_receipts", lambda **kwargs: receipts) + + def reconcile_one(*, todo_id, **kwargs): + if todo_id == "failed": + raise ValueError("provider unavailable") + return {"ok": True, "external_read_performed": False, "skip_reason": "todo_not_open"} + + monkeypatch.setattr(reconcile, "reconcile_issue_fix_pr_review", reconcile_one) + result = reconcile.reconcile_acknowledged_issue_fix_pr_reviews( + registry_path=registry, runtime_root_arg=str(runtime), goal_id=GOAL_ID, + agent_id=AGENT_ID, project=None, fetch_metadata=True, + ) + assert (result["external_read_count"], result["failure_count"]) == (1, 1) + assert not (runtime / "agent-runtime-capabilities").exists() + + +def test_fresh_agent_auto_probes_external_evidence_poll_by_default_and_honors_sandbox_or_revocation( + tmp_path, monkeypatch +): + import contextlib + import io + + from loopx.capabilities.issue_fix import pr_lifecycle + from loopx.todos import add_goal_todo, list_goal_todos + + _, runtime, registry = _write_fixture( + tmp_path, required_capability="external_evidence_poll", provider="sqlite" + ) + + fake_bin = tmp_path / "bin" + fake_bin.mkdir() + fake_gh = fake_bin / "gh" + fake_gh.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + fake_gh.chmod(0o755) + gh_cfg = tmp_path / "gh-config" + gh_cfg.mkdir() + (gh_cfg / "hosts.yml").write_text( + "github.com:\n user: fixture\n git_protocol: https\n", + encoding="utf-8", + ) + monkeypatch.setenv("GH_CONFIG_DIR", str(gh_cfg)) + monkeypatch.setenv("PATH", f"{fake_bin}:{tmp_path}") + monkeypatch.delenv("CODEX_SANDBOX_NETWORK_DISABLED", raising=False) + monkeypatch.delenv("LOOPX_OFFLINE", raising=False) + + def _run_inproc(*argv: str): + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main( + [ + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + *argv, + ] + ) + return code, json.loads(buf.getvalue()) + + # 1. Read-only inspection on a brand-new Agent immediately sees probed availability without writing memory. + rc, inspected = _run_inproc( + "agent-capabilities", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID + ) + assert rc == 0, inspected + assert inspected["availability"]["probed"] == ["external_evidence_poll"] + assert inspected["availability"]["effective"] == ["external_evidence_poll"] + assert not (runtime / "agent-runtime-capabilities").exists() + + # 2. Zero-flag heartbeat-prompt automatically projects heartbeat-prequota for the fresh Agent. + rc, prompt = _run_inproc( + "heartbeat-prompt", + "--thin", + "--codex-app", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + ) + assert rc == 0, prompt + assert "heartbeat-prequota" in prompt["task_body"] + + # 3. Turn 1 executing quota should-run auto-probes & polls upstream PR wait out of the box. + wait_todo = add_goal_todo( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + role="agent", + claimed_by=AGENT_ID, + text="Resume automatically when upstream PR merges", + resume_when="pr_merged:owner/repo#77", + )["todo_id"] + calls = [] + + def fake_fetch(reference, **kwargs): + calls.append(reference) + return { + "url": f"https://github.com/{reference['repo']}/pull/{reference['number']}", + "state": "MERGED", + "mergedAt": "2026-11-23T08:00:00Z", + } + + monkeypatch.setattr(pr_lifecycle, "fetch_github_pr_lifecycle_payload", fake_fetch) + rc, guard = _run_inproc( + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--context-delivery", + "off", + ) + assert rc == 0, guard + assert guard["capability_gate"]["action"] == "run" + assert len(calls) == 1 + assert ( + list_goal_todos( + registry_path=registry, + runtime_root_arg=str(runtime), + goal_id=GOAL_ID, + todo_id=wait_todo, + )["todo"]["resume_ready"] + is True + ) + + # A successful first-turn probe alone must not become a durable declaration. + assert not (runtime / "agent-runtime-capabilities").exists() + scope = ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID) + monkeypatch.setenv("LOOPX_AUTO_CAPABILITY_PROBE", "0") + assert _run_inproc("agent-capabilities", *scope)[1]["availability"]["effective"] == [] + monkeypatch.delenv("LOOPX_AUTO_CAPABILITY_PROBE") + _run_inproc("agent-capabilities", *scope, "--available-capability", "external_evidence_poll", "--execute") + pending = add_goal_todo( + registry_path=registry, runtime_root_arg=str(runtime), goal_id=GOAL_ID, role="agent", + claimed_by=AGENT_ID, text="Wait for a second review", resume_when="pr_merged:owner/repo#78", + )["todo_id"] + for flag in ("LOOPX_OFFLINE", "CODEX_SANDBOX_NETWORK_DISABLED"): + monkeypatch.setenv(flag, "1") + rc, status = _run_inproc("agent-capabilities", *scope) + assert rc == 0 and status["availability"]["effective"] == [], status + assert "external_evidence_poll" in status["agent_capabilities"]["available"] + assert "heartbeat-prequota" not in _run_inproc("heartbeat-prompt", "--thin", "--codex-app", *scope)[1]["task_body"] + rc, poll = _run_inproc("heartbeat-prequota", *scope) + assert rc == 0 and poll["checks"]["pr_dependencies"]["external_read_count"] == 0, poll + assert len(calls) == 1 + assert not list_goal_todos(registry_path=registry, runtime_root_arg=str(runtime), + goal_id=GOAL_ID, todo_id=pending)["todo"]["resume_ready"] + monkeypatch.delenv(flag) + + rc, recovered = _run_inproc("heartbeat-prequota", *scope) + assert rc == 0 and recovered["checks"]["pr_dependencies"]["external_read_count"] == 1, recovered + assert len(calls) == 2 + assert list_goal_todos( + registry_path=registry, runtime_root_arg=str(runtime), goal_id=GOAL_ID, todo_id=pending, + )["todo"]["resume_ready"] + + rc, revoked = _run_inproc( + "agent-capabilities", + "--goal-id", + GOAL_ID, + "--agent-id", + AGENT_ID, + "--unavailable-capability", + "external_evidence_poll", + "--execute", + ) + assert rc == 0, revoked + assert revoked["availability"]["probed"] == ["external_evidence_poll"] + assert revoked["availability"]["effective"] == [] diff --git a/tests/control_plane_ts/agent_capability_memory.test.ts b/tests/control_plane_ts/agent_capability_memory.test.ts index c8dd92f3ea..a2b37a0c5a 100644 --- a/tests/control_plane_ts/agent_capability_memory.test.ts +++ b/tests/control_plane_ts/agent_capability_memory.test.ts @@ -4,7 +4,7 @@ import {mkdtemp, readdir, readFile, rm, writeFile} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join} from "node:path"; import {agentCapabilityMemory} from "../../loopx/control_plane/agents/capability_memory.ts"; -import {projectCapabilityAvailability} from "../../loopx/control_plane/agents/capability_gate.ts"; +import {evaluateCapabilityGate, projectCapabilityAvailability} from "../../loopx/control_plane/agents/capability_gate.ts"; import type {JsonObject} from "../../loopx/control_plane/effect_program.ts"; async function fixture(t: {after(fn: () => Promise): void}) { @@ -81,3 +81,70 @@ test("corruption, foreign scopes and invalid updates fail without overwriting ev assert.equal(await readFile(path, "utf8"), corrupt); } }); + +test("legacy global-registry alias merges into canonical source_registry and preserve_unavailable honors revocations", async t => { + const {call} = await fixture(t); + await call({registry: "global-registry", available: ["network"], unavailable: ["external_evidence_poll"], execute: true}); + const inherited = await call({registry: "source-registry", legacy_registries: ["global-registry"]}); + assert.deepEqual(inherited.available, ["network"]); + assert.deepEqual(inherited.unavailable, ["external_evidence_poll"]); + + const passive = await call({ + registry: "source-registry", + legacy_registries: ["global-registry"], + available: ["external_evidence_poll", "cli_bridge"], + preserve_unavailable: true, + execute: true, + }); + assert.equal(passive.written, true); + assert.deepEqual(passive.available, ["cli_bridge", "network"]); + assert.deepEqual(passive.unavailable, ["external_evidence_poll"]); + + const canonicalRead = await call({registry: "source-registry"}); + assert.deepEqual(canonicalRead.available, ["cli_bridge", "network"]); + assert.deepEqual(canonicalRead.unavailable, ["external_evidence_poll"]); + + const explicit = await call({ + registry: "source-registry", + available: ["external_evidence_poll"], + execute: true, + }); + assert.deepEqual(explicit.available, ["cli_bridge", "external_evidence_poll", "network"]); + assert.deepEqual(explicit.unavailable, []); +}); + +test("auto-probed host capabilities are effective by default and yield to explicit unavailable revocations", () => { + const fresh = evaluateCapabilityGate({ + schema_version: "capability_gate_request_v0", + operation: "availability", + goal: [], + runtime: [], + probed: ["external_evidence_poll", "credentials"], + agent: {}, + }).result as Record; + assert.deepEqual(fresh.probed, ["external_evidence_poll"]); + assert.deepEqual(fresh.runtime_available, ["external_evidence_poll"]); + assert.deepEqual(fresh.effective, ["external_evidence_poll"]); + + const revoked = evaluateCapabilityGate({ + schema_version: "capability_gate_request_v0", + operation: "availability", + goal: ["external_evidence_poll"], + runtime: [], + probed: ["external_evidence_poll"], + agent: {available: [], unavailable: ["external_evidence_poll"]}, + }).result as Record; + assert.deepEqual(revoked.probed, ["external_evidence_poll"]); + assert.deepEqual(revoked.runtime_available, []); + assert.deepEqual(revoked.effective, []); + + const recovered = evaluateCapabilityGate({ + schema_version: "capability_gate_request_v0", + operation: "availability", + goal: [], + runtime: ["external_evidence_poll"], + probed: ["external_evidence_poll"], + agent: {available: [], unavailable: ["external_evidence_poll"]}, + }).result as Record; + assert.deepEqual(recovered.effective, ["external_evidence_poll"]); +});