diff --git a/docs/reference/protocols/decision-context-architecture-v0.md b/docs/reference/protocols/decision-context-architecture-v0.md index 17b1943404..86169a0789 100644 --- a/docs/reference/protocols/decision-context-architecture-v0.md +++ b/docs/reference/protocols/decision-context-architecture-v0.md @@ -5,8 +5,11 @@ Status: experimental contract ## Position Decision Context is a built-in, default-off, goal-scoped LoopX capability. It -runs above LoopX Core, consumes Core truth, and does not enter -`loopx/control_plane/` or alter todo, gate, quota, or authority semantics. +runs above LoopX Core, consumes Core truth, and does not alter Core todo, gate, +quota eligibility, or authority semantics; its optional host-local turn-start +hook binding uses the TypeScript capability-hook owner seam under +`loopx/control_plane/capabilities/decision_context_hook.ts` without moving +domain scoring, source adapters, or decision recommendations into Core. ```mermaid flowchart TD @@ -267,6 +270,14 @@ registering a private adapter in the public package. Activation projects only private. Missing or mismatched runtime providers fail open without advancing a cursor. +Host-local turn-start integration (`decision_context.turn_context`) follows the +same default-off and read-only boundary: an explicit CAS-managed binding under +`/decision-context/agent-bindings/` opts one registered +`(goal_id, agent_id)` into a public-safe `decision_context_hook_view_v1` +observation on `quota should-run` and `turn run-once`, omitting private +locators, cursors, and source bodies while leaving review settlement and cursor +commits untouched. + ### P1: first dogfood Use one private, redacted decision-assistant scenario. Let a domain adapter map diff --git a/docs/reference/protocols/decision-context-architecture-v0.zh-CN.md b/docs/reference/protocols/decision-context-architecture-v0.zh-CN.md index 2d34333ccf..f817c8b923 100644 --- a/docs/reference/protocols/decision-context-architecture-v0.zh-CN.md +++ b/docs/reference/protocols/decision-context-architecture-v0.zh-CN.md @@ -5,8 +5,9 @@ ## 定位 Decision Context 是 LoopX 内置、默认关闭、goal-scoped 的高层决策 capability。 -它运行在 LoopX Core 之上,消费 Core truth,但不进入 -`loopx/control_plane/`,也不改变 todo、gate、quota、authority 的语义。 +它运行在 LoopX Core 之上,消费 Core truth,不改变 Core 的 todo、gate、quota 准入或 +authority 语义;其可选本机回合起始钩子绑定遵循 TypeScript 控制面迁移契约,落在 +`loopx/control_plane/capabilities/decision_context_hook.ts` 能力钩子边界内,不把领域打分、信源适配器或决策建议下沉进 Core。 ```mermaid flowchart TD @@ -277,6 +278,11 @@ checkpoint 路径,而不必把私有 adapter 注册进公开包。activation `runtime-bound`;adapter 名称、配置、locator、payload 和 cursor 均留在私有边界。 provider 缺失或身份不匹配时 fail open,且不会推进 cursor。 +本机轮次启动钩子(`decision_context.turn_context`)同样遵守默认关闭与只读边界:只有通过 +`/decision-context/agent-bindings/` 下的事务型 CAS 绑定显式接入单个已注册 +`(goal_id, agent_id)` 后,`quota should-run` 与 `turn run-once` 才会交付公开安全的 +`decision_context_hook_view_v1` 新鲜度/变更摘要,不暴露私有路径、游标与正文,也不触发审阅结算或游标提交。 + ### P1:首个 dogfood - 在一个私有、脱敏的决策助手场景,由领域 adapter 把新事实映射到稳定私有论点; diff --git a/loopx/capabilities/decision_context/README.md b/loopx/capabilities/decision_context/README.md index bafe99c45a..be981a2bbf 100644 --- a/loopx/capabilities/decision_context/README.md +++ b/loopx/capabilities/decision_context/README.md @@ -113,6 +113,7 @@ change touches. | `capture.py` | Opt-in source-reference capture and `capture-status` | | `capture_recovery.py` | Reference-preserving capture diagnosis and recovery | | `extension_provider.py` | Advisory context provider delivered by an extension (`decision_context_advisory_provider_v0`) | +| `turn_start_hook.py` | Opt-in host-local Agent turn-start hook binding and public-safe freshness/change view | | `architecture.py` | `architecture` readback of the capability contract | | `catalog_entry.py` | Capability catalog record | | `cli.py` | Every `loopx decision-context` subcommand and its rendering | @@ -547,6 +548,41 @@ pointing at a deleted checkout), when the last tick failed, when the spool is gone, or when a recorded source is stale or failing. Remove the record of a deliberately retired host. +### Opt-in Host-Local Turn-Start Hook Binding + +Decision Context remains **default off** on `quota should-run` and `turn run-once`. +Untouched runtimes and unbound Agents make zero provider or RPC calls. An operator +can explicitly bind a registered `(goal_id, agent_id)` lane to an existing private +profile through the transactional host-local binding store under +`/decision-context/agent-bindings/`: + +```bash +loopx decision-context hook read \ + --goal-id --agent-id --format json + +loopx decision-context hook bind \ + --goal-id --agent-id \ + --profile \ + [--cursor-state ] \ + [--spool ] \ + [--mode prepare_evidence|source_manifest|capture_status] \ + --expected-revision none --operation-id bind-ops-v1 \ + --execute --format json +``` + +Once bound, `quota should-run` and `turn run-once` invoke the read-only +`decision_context.turn_context` hook (`capability_id=decision-context`) and deliver +a public-safe `decision_context_hook_view_v1` summary (`changed_source_ids`, +`alerted_source_ids`, `uncovered_p0_source_ids`, `freshness_counts`, advisory +recall health, and bounded follow-up commands) into `work_context.sources`. +Private file paths, cursors, and source bodies never enter the hook receipt or +turn packet, and turn-start observations never commit cursors. While bound, +read-only CLI commands (`inspect-profile`, `source-manifest`, `prepare-evidence`, +`recall-context`, `capture-status`) can omit `--profile` (and `--cursor-state` / +`--spool`) to resolve the bound private locators in-process. Use `hook unbind` +with the current `--expected-revision` to retire the binding and invalidate +cached turn assumptions. + ## Relationship To Other Capabilities | Capability | Primary question | Relationship | diff --git a/loopx/capabilities/decision_context/README.zh-CN.md b/loopx/capabilities/decision_context/README.zh-CN.md index 6663beae7a..772aa5bc5a 100644 --- a/loopx/capabilities/decision_context/README.zh-CN.md +++ b/loopx/capabilities/decision_context/README.zh-CN.md @@ -100,6 +100,7 @@ exact-read 完整度和未覆盖的 P0 source 投影为公开安全的回执。` | `capture.py` | opt-in 的 source-reference capture 与 `capture-status` | | `capture_recovery.py` | 保留引用的 capture 诊断与恢复 | | `extension_provider.py` | 由扩展交付的 advisory context provider(`decision_context_advisory_provider_v0`) | +| `turn_start_hook.py` | 显式启用的本机 Agent turn-start 钩子绑定与公开安全的新鲜度/变更视图 | | `architecture.py` | 能力合同的 `architecture` 读回 | | `catalog_entry.py` | 能力 catalog 记录 | | `cli.py` | 所有 `loopx decision-context` 子命令及其渲染 | @@ -455,6 +456,36 @@ provider 读取失败会更新 `last_checked_at` 并累加 `failure_streak`, 已删除的 checkout)、最后一次 tick 失败、spool 丢失,或记录中的来源陈旧/持续失败时告警。 主动退役的 host 需删除其记录。 +### 显式绑定本机 Turn-Start Hook + +`quota should-run` 与 `turn run-once` 上的 Decision Context 钩子**默认关闭**:未绑定时不做任何 +provider 或 RPC 调用。操作者可通过 `/decision-context/agent-bindings/` +下的事务型本机绑定存储,为已注册的 `(goal_id, agent_id)` 显式绑定既有私有 profile: + +```bash +loopx decision-context hook read \ + --goal-id --agent-id --format json + +loopx decision-context hook bind \ + --goal-id --agent-id \ + --profile \ + [--cursor-state ] \ + [--spool ] \ + [--mode prepare_evidence|source_manifest|capture_status] \ + --expected-revision none --operation-id bind-ops-v1 \ + --execute --format json +``` + +绑定生效后,`quota should-run` 与 `turn run-once` 会执行只读的 +`decision_context.turn_context` 钩子(`capability_id=decision-context`),向 +`work_context.sources` 注入公开安全的 `decision_context_hook_view_v1` 视图(包含 +`changed_source_ids`、`alerted_source_ids`、`uncovered_p0_source_ids`、 +`freshness_counts`、advisory recall 状态及有界后续命令)。私有路径、游标与信源正文 +绝不进入钩子回执或轮次数据包,且轮次启动观察绝不推进审阅游标。绑定处于激活态时,只读 CLI +(`inspect-profile`、`source-manifest`、`prepare-evidence`、`recall-context`、 +`capture-status`)可省略 `--profile`(及 `--cursor-state` / `--spool`)并在进程内解析已绑定私有路径。 +停用时用当前 `--expected-revision` 执行 `hook unbind` 退役绑定并使旧缓存失效。 + ## 与其他能力的关系 | 能力 | 核心问题 | 与 Decision Context 的关系 | diff --git a/loopx/capabilities/decision_context/__init__.py b/loopx/capabilities/decision_context/__init__.py index 3a2e274fd1..5f45af8a75 100644 --- a/loopx/capabilities/decision_context/__init__.py +++ b/loopx/capabilities/decision_context/__init__.py @@ -1,133 +1,169 @@ """Goal-scoped Decision Context capability contracts.""" -from .assembler import ( - DECISION_CONTEXT_ASSEMBLY_SCHEMA_VERSION, - DECISION_CONTEXT_EPHEMERAL_RECALL_SCHEMA_VERSION, - DECISION_CURSOR_CHECKPOINT_SCHEMA_VERSION, - DecisionAuthorityEvidence, - DecisionContextAssembly, - DecisionEvidenceCollection, - DecisionEvidenceRecords, - DecisionRecallEvidence, - assemble_decision_evidence, -) -from .architecture import ( - DECISION_CONTEXT_ARCHITECTURE_SCHEMA_VERSION, - build_decision_context_architecture_packet, -) -from .profile import ( - DECISION_CONTEXT_ACTIVATION_STATUS_SCHEMA_VERSION, - DECISION_CONTEXT_PROFILE_SCHEMA_VERSION, - DecisionContextProfile, - DecisionSourceProviderBinding, - load_decision_context_profile, - normalize_decision_context_profile, - resolve_decision_context_activation, -) -from .packets import ( - DECISION_EVIDENCE_PACKET_SCHEMA_VERSION, - DECISION_OUTCOME_RECEIPT_SCHEMA_VERSION, - DECISION_PROPOSAL_SCHEMA_VERSION, - DECISION_REVIEW_RECEIPT_SCHEMA_VERSION, - build_decision_evidence_packet, - build_decision_outcome_receipt, - build_decision_proposal, - build_decision_review_receipt, -) -from .sources import ( - DECISION_SOURCE_MANIFEST_SCHEMA_VERSION, - DECISION_SOURCE_SCAN_RECEIPT_SCHEMA_VERSION, - DecisionSourceExactRead, - DecisionSourceItem, - DecisionSourceProvider, - DecisionSourceScan, - DecisionSourceSpec, - build_decision_source_item_refs, - build_decision_source_manifest, -) -from .providers import ( - LOCAL_FILE_SOURCE_ADAPTER, - LocalFileDecisionSourceProvider, - build_decision_source_provider, - decision_source_provider_registered, - register_decision_source_provider, -) -from .cursor_commit import ( - DECISION_CURSOR_COMMIT_RECEIPT_SCHEMA_VERSION, - commit_profile_decision_cursors, -) -from .private_state import ( - DECISION_PENDING_SETTLEMENT_SCHEMA_VERSION, - load_private_decision_cursors, - load_private_pending_decision_settlement, - write_private_pending_decision_settlement, -) -from .runtime import ( - assemble_profile_decision_evidence, - decision_evidence_records_from_mapping, - recall_profile_decision_context, -) -from .review_settlement import ( - DECISION_REVIEW_SETTLEMENT_SCHEMA_VERSION, - settle_profile_decision_review, -) -from .outcome_feedback import ( - DECISION_OUTCOME_FEEDBACK_SCHEMA_VERSION, - build_decision_outcome_feedback, -) +from __future__ import annotations -__all__ = [ - "DECISION_CONTEXT_ASSEMBLY_SCHEMA_VERSION", - "DECISION_CONTEXT_EPHEMERAL_RECALL_SCHEMA_VERSION", - "DECISION_CONTEXT_ARCHITECTURE_SCHEMA_VERSION", - "DECISION_CONTEXT_ACTIVATION_STATUS_SCHEMA_VERSION", - "DECISION_CURSOR_CHECKPOINT_SCHEMA_VERSION", - "DECISION_CURSOR_COMMIT_RECEIPT_SCHEMA_VERSION", - "DECISION_EVIDENCE_PACKET_SCHEMA_VERSION", - "DECISION_OUTCOME_RECEIPT_SCHEMA_VERSION", - "DECISION_OUTCOME_FEEDBACK_SCHEMA_VERSION", - "DECISION_PROPOSAL_SCHEMA_VERSION", - "DECISION_REVIEW_RECEIPT_SCHEMA_VERSION", - "DECISION_PENDING_SETTLEMENT_SCHEMA_VERSION", - "DECISION_REVIEW_SETTLEMENT_SCHEMA_VERSION", - "DECISION_CONTEXT_PROFILE_SCHEMA_VERSION", - "DECISION_SOURCE_MANIFEST_SCHEMA_VERSION", - "DECISION_SOURCE_SCAN_RECEIPT_SCHEMA_VERSION", - "DecisionAuthorityEvidence", - "DecisionContextAssembly", - "DecisionContextProfile", - "DecisionEvidenceCollection", - "DecisionEvidenceRecords", - "DecisionRecallEvidence", - "DecisionSourceExactRead", - "DecisionSourceProviderBinding", - "DecisionSourceItem", - "DecisionSourceProvider", - "DecisionSourceScan", - "DecisionSourceSpec", - "LOCAL_FILE_SOURCE_ADAPTER", - "LocalFileDecisionSourceProvider", - "assemble_decision_evidence", - "assemble_profile_decision_evidence", - "commit_profile_decision_cursors", - "build_decision_context_architecture_packet", - "build_decision_evidence_packet", - "build_decision_outcome_receipt", - "build_decision_outcome_feedback", - "build_decision_proposal", - "build_decision_review_receipt", - "build_decision_source_item_refs", - "build_decision_source_manifest", - "build_decision_source_provider", - "decision_source_provider_registered", - "load_decision_context_profile", - "load_private_decision_cursors", - "load_private_pending_decision_settlement", - "normalize_decision_context_profile", - "register_decision_source_provider", - "recall_profile_decision_context", - "resolve_decision_context_activation", - "decision_evidence_records_from_mapping", - "settle_profile_decision_review", - "write_private_pending_decision_settlement", -] +from importlib import import_module +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from .architecture import ( + DECISION_CONTEXT_ARCHITECTURE_SCHEMA_VERSION as DECISION_CONTEXT_ARCHITECTURE_SCHEMA_VERSION, + build_decision_context_architecture_packet as build_decision_context_architecture_packet, + ) + from .assembler import ( + DECISION_CONTEXT_ASSEMBLY_SCHEMA_VERSION as DECISION_CONTEXT_ASSEMBLY_SCHEMA_VERSION, + DECISION_CONTEXT_EPHEMERAL_RECALL_SCHEMA_VERSION as DECISION_CONTEXT_EPHEMERAL_RECALL_SCHEMA_VERSION, + DECISION_CURSOR_CHECKPOINT_SCHEMA_VERSION as DECISION_CURSOR_CHECKPOINT_SCHEMA_VERSION, + DecisionAuthorityEvidence as DecisionAuthorityEvidence, + DecisionContextAssembly as DecisionContextAssembly, + DecisionEvidenceCollection as DecisionEvidenceCollection, + DecisionEvidenceRecords as DecisionEvidenceRecords, + DecisionRecallEvidence as DecisionRecallEvidence, + assemble_decision_evidence as assemble_decision_evidence, + ) + from .cursor_commit import ( + DECISION_CURSOR_COMMIT_RECEIPT_SCHEMA_VERSION as DECISION_CURSOR_COMMIT_RECEIPT_SCHEMA_VERSION, + commit_profile_decision_cursors as commit_profile_decision_cursors, + ) + from .outcome_feedback import ( + DECISION_OUTCOME_FEEDBACK_SCHEMA_VERSION as DECISION_OUTCOME_FEEDBACK_SCHEMA_VERSION, + build_decision_outcome_feedback as build_decision_outcome_feedback, + ) + from .packets import ( + DECISION_EVIDENCE_PACKET_SCHEMA_VERSION as DECISION_EVIDENCE_PACKET_SCHEMA_VERSION, + DECISION_OUTCOME_RECEIPT_SCHEMA_VERSION as DECISION_OUTCOME_RECEIPT_SCHEMA_VERSION, + DECISION_PROPOSAL_SCHEMA_VERSION as DECISION_PROPOSAL_SCHEMA_VERSION, + DECISION_REVIEW_RECEIPT_SCHEMA_VERSION as DECISION_REVIEW_RECEIPT_SCHEMA_VERSION, + build_decision_evidence_packet as build_decision_evidence_packet, + build_decision_outcome_receipt as build_decision_outcome_receipt, + build_decision_proposal as build_decision_proposal, + build_decision_review_receipt as build_decision_review_receipt, + ) + from .private_state import ( + DECISION_PENDING_SETTLEMENT_SCHEMA_VERSION as DECISION_PENDING_SETTLEMENT_SCHEMA_VERSION, + load_private_decision_cursors as load_private_decision_cursors, + load_private_pending_decision_settlement as load_private_pending_decision_settlement, + write_private_pending_decision_settlement as write_private_pending_decision_settlement, + ) + from .profile import ( + DECISION_CONTEXT_ACTIVATION_STATUS_SCHEMA_VERSION as DECISION_CONTEXT_ACTIVATION_STATUS_SCHEMA_VERSION, + DECISION_CONTEXT_PROFILE_SCHEMA_VERSION as DECISION_CONTEXT_PROFILE_SCHEMA_VERSION, + DecisionContextProfile as DecisionContextProfile, + DecisionSourceProviderBinding as DecisionSourceProviderBinding, + load_decision_context_profile as load_decision_context_profile, + normalize_decision_context_profile as normalize_decision_context_profile, + resolve_decision_context_activation as resolve_decision_context_activation, + ) + from .providers import ( + LOCAL_FILE_SOURCE_ADAPTER as LOCAL_FILE_SOURCE_ADAPTER, + LocalFileDecisionSourceProvider as LocalFileDecisionSourceProvider, + build_decision_source_provider as build_decision_source_provider, + decision_source_provider_registered as decision_source_provider_registered, + register_decision_source_provider as register_decision_source_provider, + ) + from .review_settlement import ( + DECISION_REVIEW_SETTLEMENT_SCHEMA_VERSION as DECISION_REVIEW_SETTLEMENT_SCHEMA_VERSION, + settle_profile_decision_review as settle_profile_decision_review, + ) + from .runtime import ( + assemble_profile_decision_evidence as assemble_profile_decision_evidence, + decision_evidence_records_from_mapping as decision_evidence_records_from_mapping, + recall_profile_decision_context as recall_profile_decision_context, + ) + from .sources import ( + DECISION_SOURCE_MANIFEST_SCHEMA_VERSION as DECISION_SOURCE_MANIFEST_SCHEMA_VERSION, + DECISION_SOURCE_SCAN_RECEIPT_SCHEMA_VERSION as DECISION_SOURCE_SCAN_RECEIPT_SCHEMA_VERSION, + DecisionSourceExactRead as DecisionSourceExactRead, + DecisionSourceItem as DecisionSourceItem, + DecisionSourceProvider as DecisionSourceProvider, + DecisionSourceScan as DecisionSourceScan, + DecisionSourceSpec as DecisionSourceSpec, + build_decision_source_item_refs as build_decision_source_item_refs, + build_decision_source_manifest as build_decision_source_manifest, + ) + from .turn_start_hook import ( + DECISION_CONTEXT_HOOK_CAPABILITY_ID as DECISION_CONTEXT_HOOK_CAPABILITY_ID, + DECISION_CONTEXT_TURN_HOOK_ID as DECISION_CONTEXT_TURN_HOOK_ID, + decision_context_hook_binding as decision_context_hook_binding, + extend_turn_start_dispatch as extend_turn_start_dispatch, + read_decision_context_turn_context as read_decision_context_turn_context, + resolve_bound_decision_context_locators as resolve_bound_decision_context_locators, + ) + +# The Turn start hook checks local bindings without eagerly importing providers, +# profile loaders, capture spools, or evidence assembly on unbound turns. +_EXPORTS = { + "DECISION_CONTEXT_ASSEMBLY_SCHEMA_VERSION": "assembler", + "DECISION_CONTEXT_EPHEMERAL_RECALL_SCHEMA_VERSION": "assembler", + "DECISION_CONTEXT_ARCHITECTURE_SCHEMA_VERSION": "architecture", + "DECISION_CONTEXT_ACTIVATION_STATUS_SCHEMA_VERSION": "profile", + "DECISION_CONTEXT_HOOK_CAPABILITY_ID": "turn_start_hook", + "DECISION_CONTEXT_TURN_HOOK_ID": "turn_start_hook", + "DECISION_CURSOR_CHECKPOINT_SCHEMA_VERSION": "assembler", + "DECISION_CURSOR_COMMIT_RECEIPT_SCHEMA_VERSION": "cursor_commit", + "DECISION_EVIDENCE_PACKET_SCHEMA_VERSION": "packets", + "DECISION_OUTCOME_RECEIPT_SCHEMA_VERSION": "packets", + "DECISION_OUTCOME_FEEDBACK_SCHEMA_VERSION": "outcome_feedback", + "DECISION_PROPOSAL_SCHEMA_VERSION": "packets", + "DECISION_REVIEW_RECEIPT_SCHEMA_VERSION": "packets", + "DECISION_PENDING_SETTLEMENT_SCHEMA_VERSION": "private_state", + "DECISION_REVIEW_SETTLEMENT_SCHEMA_VERSION": "review_settlement", + "DECISION_CONTEXT_PROFILE_SCHEMA_VERSION": "profile", + "DECISION_SOURCE_MANIFEST_SCHEMA_VERSION": "sources", + "DECISION_SOURCE_SCAN_RECEIPT_SCHEMA_VERSION": "sources", + "DecisionAuthorityEvidence": "assembler", + "DecisionContextAssembly": "assembler", + "DecisionContextProfile": "profile", + "DecisionEvidenceCollection": "assembler", + "DecisionEvidenceRecords": "assembler", + "DecisionRecallEvidence": "assembler", + "DecisionSourceExactRead": "sources", + "DecisionSourceProviderBinding": "profile", + "DecisionSourceItem": "sources", + "DecisionSourceProvider": "sources", + "DecisionSourceScan": "sources", + "DecisionSourceSpec": "sources", + "LOCAL_FILE_SOURCE_ADAPTER": "providers", + "LocalFileDecisionSourceProvider": "providers", + "assemble_decision_evidence": "assembler", + "assemble_profile_decision_evidence": "runtime", + "commit_profile_decision_cursors": "cursor_commit", + "build_decision_context_architecture_packet": "architecture", + "build_decision_evidence_packet": "packets", + "build_decision_outcome_receipt": "packets", + "build_decision_outcome_feedback": "outcome_feedback", + "build_decision_proposal": "packets", + "build_decision_review_receipt": "packets", + "build_decision_source_item_refs": "sources", + "build_decision_source_manifest": "sources", + "build_decision_source_provider": "providers", + "decision_source_provider_registered": "providers", + "load_decision_context_profile": "profile", + "load_private_decision_cursors": "private_state", + "load_private_pending_decision_settlement": "private_state", + "normalize_decision_context_profile": "profile", + "register_decision_source_provider": "providers", + "recall_profile_decision_context": "runtime", + "resolve_decision_context_activation": "profile", + "decision_context_hook_binding": "turn_start_hook", + "decision_evidence_records_from_mapping": "runtime", + "extend_turn_start_dispatch": "turn_start_hook", + "read_decision_context_turn_context": "turn_start_hook", + "resolve_bound_decision_context_locators": "turn_start_hook", + "settle_profile_decision_review": "review_settlement", + "write_private_pending_decision_settlement": "private_state", +} +__all__ = list(_EXPORTS) + + +def __getattr__(name: str) -> Any: + module = _EXPORTS.get(name) + if module is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + value = getattr(import_module(f".{module}", __name__), name) + globals()[name] = value + return value + + +def __dir__() -> list[str]: + return sorted(set(globals()) | set(__all__)) diff --git a/loopx/capabilities/decision_context/catalog_entry.py b/loopx/capabilities/decision_context/catalog_entry.py index c3bbadac14..d1dae97a4e 100644 --- a/loopx/capabilities/decision_context/catalog_entry.py +++ b/loopx/capabilities/decision_context/catalog_entry.py @@ -151,6 +151,21 @@ def decision_context_configuration_descriptor() -> dict[str, Any]: "updates private cursors; no external action or authority change" ), }, + { + "command": ( + "loopx decision-context hook read|bind|unbind|history|turn-context " + "--goal-id --agent-id [--format json]" + ), + "purpose": ( + "Manage or inspect an opt-in host-local turn-start hook binding " + "and its public-safe source freshness/change projection." + ), + "write_boundary": ( + "bind/unbind --execute writes only the scoped private hook " + "binding store; turn-context and turn-start observations are " + "read-only and never advance cursors or emit private locators" + ), + }, ], "implemented_protocols": [ { @@ -215,6 +230,10 @@ def decision_context_configuration_descriptor() -> dict[str, Any]: "decision_review_settlement_v0", "loopx.capabilities.decision_context.review_settlement", ), + ( + "decision_context_hook_view_v1", + "loopx.capabilities.decision_context.turn_start_hook", + ), ) ], "smokes": ["python3 examples/decision-context-contract-smoke.py"], @@ -229,6 +248,7 @@ def decision_context_configuration_descriptor() -> dict[str, Any]: "DecisionSourceProvider rebases current authority; ContextProvider supplies advisory recall only.", "Prepare-evidence is read-only; prepare-review writes only private unapplied state when explicitly executed.", "Cursor commit requires a canonical review receipt, exact gate or semantic no-change proof, lifecycle-event readback, private-state CAS, and atomic verified write; future outcome observation is separate.", + "Turn-start hook bindings are opt-in per registered Goal/Agent, project only public-safe freshness and changed-source ids, and never commit cursors.", ], "next_real_step": ( "Exercise one private source profile through approve, reject, defer, and " diff --git a/loopx/capabilities/decision_context/cli.py b/loopx/capabilities/decision_context/cli.py index ece48d0629..da20d1bf76 100644 --- a/loopx/capabilities/decision_context/cli.py +++ b/loopx/capabilities/decision_context/cli.py @@ -121,8 +121,16 @@ def register_decision_context_commands( add_subcommand_format(capture) capture.add_argument("--goal-id", required=True) capture.add_argument("--agent-id", required=True) - capture.add_argument("--profile", required=True) - capture.add_argument("--spool", required=True) + capture.add_argument( + "--profile", + required=name != "capture-status", + help="Private local profile (optional for capture-status when a hook binding is active).", + ) + capture.add_argument( + "--spool", + required=name != "capture-status", + help="Private SQLite spool (optional for capture-status when a hook binding is active).", + ) capture.add_argument("--cursor-state") if name == "capture": capture.add_argument("--execute", action="store_true") @@ -132,6 +140,9 @@ def register_decision_context_commands( capture.add_argument("--rebase-json", required=True) capture.add_argument("--pending-settlement", required=True) capture.add_argument("--execute", action="store_true") + from .turn_start_hook import register_decision_context_hook_commands + + register_decision_context_hook_commands(commands, add_subcommand_format) architecture = commands.add_parser( "architecture", help="Render the default-off Stage-0 Decision Context contract.", @@ -146,7 +157,7 @@ def register_decision_context_commands( status.add_argument("--agent-id", required=True) status.add_argument( "--profile", - help="Private local profile. Omit it to prove the default-off route.", + help="Private local profile. Omit it to prove the default-off route or inspect a bound hook profile.", ) manifest = commands.add_parser( @@ -156,7 +167,10 @@ def register_decision_context_commands( add_subcommand_format(manifest) manifest.add_argument("--goal-id", required=True) manifest.add_argument("--agent-id", required=True) - manifest.add_argument("--profile", required=True) + manifest.add_argument( + "--profile", + help="Private local profile (optional when an active hook binding exists).", + ) manifest.add_argument( "--observed-at", help="Optional timezone-aware ISO-8601 time for a reproducible manifest.", @@ -171,7 +185,10 @@ def register_decision_context_commands( add_subcommand_format(prepare) prepare.add_argument("--goal-id", required=True) prepare.add_argument("--agent-id", required=True) - prepare.add_argument("--profile", required=True) + prepare.add_argument( + "--profile", + help="Private local profile (optional when an active hook binding exists).", + ) prepare.add_argument("--decision-id", required=True) prepare.add_argument( "--cursor-state", @@ -208,7 +225,10 @@ def register_decision_context_commands( add_subcommand_format(recall) recall.add_argument("--goal-id", required=True) recall.add_argument("--agent-id", required=True) - recall.add_argument("--profile", required=True) + recall.add_argument( + "--profile", + help="Private local profile (optional when an active hook binding exists).", + ) recall.add_argument("--context-scope-ref", required=True) recall.add_argument("--query", required=True) recall.add_argument("--query-summary", required=True) @@ -275,15 +295,95 @@ def register_decision_context_commands( ) +def _bound_locators_for_args( + args: argparse.Namespace, + *, + registry_path: Path | None, + runtime_root: Path | None, +) -> dict[str, object] | None: + goal_id = str(getattr(args, "goal_id", None) or "").strip() + agent_id = str(getattr(args, "agent_id", None) or "").strip() + if not goal_id or not agent_id: + return None + from .turn_start_hook import resolve_bound_decision_context_locators + + return resolve_bound_decision_context_locators( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + ) + + +def _resolved_profile_path( + args: argparse.Namespace, + *, + bound: dict[str, object] | None, + required: bool, +) -> Path | None: + explicit = str(getattr(args, "profile", None) or "").strip() + if explicit: + return Path(explicit) + if bound and str(bound.get("profile_path") or "").strip(): + return Path(str(bound["profile_path"])) + if required: + raise ValueError( + "--profile is required when no active Decision Context hook binding exists" + ) + return None + + def handle_decision_context_command( args: argparse.Namespace, *, runtime_root: Path | None, + registry_path: Path | None = None, output_format: FormatSelector, print_payload: PrintPayload, ) -> int | None: if args.command != "decision-context": return None + if args.decision_context_command == "hook": + if registry_path is None or runtime_root is None: + raise ValueError("decision-context hook requires registry and runtime_root") + from ...control_plane.effect_runtime import ( + EffectRuntimeRemoteError, + EffectRuntimeStartupError, + ) + from .turn_start_hook import ( + handle_decision_context_hook, + render_decision_context_hook, + ) + + try: + payload = handle_decision_context_hook( + args, + registry_path=registry_path, + runtime_root=runtime_root, + ) + except ( + ValueError, + TypeError, + OSError, + EffectRuntimeRemoteError, + EffectRuntimeStartupError, + ) as exc: + payload = { + "ok": False, + "schema_version": "decision_context_hook_error_v0", + "status": "invalid_request", + "error": str(exc), + } + print_payload(payload, output_format(args), render_decision_context_hook) + return 2 + print_payload(payload, output_format(args), render_decision_context_hook) + return 0 if payload.get("ok") else 2 + + bound = _bound_locators_for_args( + args, + registry_path=registry_path, + runtime_root=runtime_root, + ) if args.decision_context_command in {"capture-diagnose", "capture-recovery"}: from .capture_recovery import diagnose_capture_source, recover_capture_source @@ -315,12 +415,28 @@ def handle_decision_context_command( assemble_captured_decision_evidence, ) + profile_path = _resolved_profile_path(args, bound=bound, required=True) + assert profile_path is not None + explicit_spool = str(getattr(args, "spool", None) or "").strip() + spool_value = explicit_spool or ( + str(bound.get("spool_path") or "").strip() if bound else "" + ) + if not spool_value: + raise ValueError( + "--spool is required when no active hook spool binding exists" + ) + explicit_cursor = str(getattr(args, "cursor_state", None) or "").strip() + cursor_value = explicit_cursor or ( + str(bound.get("cursor_state_path") or "").strip() + if bound and not explicit_spool and not getattr(args, "profile", None) + else "" + ) capture_args = dict( goal_id=args.goal_id, agent_id=args.agent_id, - profile_path=Path(args.profile), - spool_path=Path(args.spool), - cursor_path=Path(args.cursor_state) if args.cursor_state else None, + profile_path=profile_path, + spool_path=Path(spool_value), + cursor_path=Path(cursor_value) if cursor_value else None, ) if args.decision_context_command == "prepare-captured": records = decision_evidence_records_from_mapping( @@ -350,6 +466,7 @@ def handle_decision_context_command( elif args.decision_context_command == "architecture": payload = build_decision_context_architecture_packet() elif args.decision_context_command == "recall-context": + profile_path = _resolved_profile_path(args, bound=bound, required=True) observed_at = ( str(getattr(args, "observed_at", None) or "").strip() or datetime.now(timezone.utc).isoformat() @@ -357,7 +474,7 @@ def handle_decision_context_command( payload = recall_profile_decision_context( goal_id=args.goal_id, agent_id=args.agent_id, - profile_path=Path(args.profile), + profile_path=profile_path, context_scope_ref=args.context_scope_ref, query=args.query, query_summary=args.query_summary, @@ -371,6 +488,17 @@ def handle_decision_context_command( observed_at = str(getattr(args, "observed_at", None) or "").strip() or now before = str(getattr(args, "before", None) or "").strip() or observed_at prepare_review = args.decision_context_command == "prepare-review" + profile_path = _resolved_profile_path( + args, + bound=None if prepare_review else bound, + required=True, + ) + explicit_cursor = str(getattr(args, "cursor_state", None) or "").strip() + cursor_value = explicit_cursor or ( + str(bound.get("cursor_state_path") or "").strip() + if (not prepare_review and bound and not getattr(args, "profile", None)) + else "" + ) records = ( decision_evidence_records_from_mapping( _load_json_mapping(args.rebase_json, label="rebase JSON") @@ -381,15 +509,11 @@ def handle_decision_context_command( activation, assembly = assemble_profile_decision_evidence( goal_id=args.goal_id, agent_id=args.agent_id, - profile_path=Path(args.profile), + profile_path=profile_path, decision_id=args.decision_id, observed_at=observed_at, before=before, - cursor_path=( - Path(args.cursor_state) - if str(getattr(args, "cursor_state", None) or "").strip() - else None - ), + cursor_path=Path(cursor_value) if cursor_value else None, source_ids=( tuple(args.source_id) if getattr(args, "source_id", None) is not None @@ -446,11 +570,15 @@ def handle_decision_context_command( execute=bool(args.execute), ) elif args.decision_context_command in {"inspect-profile", "source-manifest"}: - profile_value = str(getattr(args, "profile", None) or "").strip() + profile_path = _resolved_profile_path( + args, + bound=bound, + required=args.decision_context_command == "source-manifest", + ) status, profile = resolve_decision_context_activation( goal_id=args.goal_id, agent_id=args.agent_id, - profile_path=Path(profile_value) if profile_value else None, + profile_path=profile_path, ) if args.decision_context_command == "inspect-profile": payload = status diff --git a/loopx/capabilities/decision_context/turn_start_hook.py b/loopx/capabilities/decision_context/turn_start_hook.py new file mode 100644 index 0000000000..abc44d7030 --- /dev/null +++ b/loopx/capabilities/decision_context/turn_start_hook.py @@ -0,0 +1,810 @@ +"""Host-local turn-start hook adapter for the TS-owned Decision Context binding.""" + +from __future__ import annotations + +from collections.abc import Mapping +from datetime import datetime, timezone +import json +from pathlib import Path +import shlex +from typing import Any, overload + +DECISION_CONTEXT_TURN_HOOK_ID = "decision_context.turn_context" +DECISION_CONTEXT_HOOK_CAPABILITY_ID = "decision-context" +DECISION_CONTEXT_HOOK_BINDINGS_DIRNAME = Path("decision-context") / "agent-bindings" + + +def _goal_scope_fields( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + agent_id: str, +) -> dict[str, Any]: + from ...agent_registry import load_goal_from_registry, registered_agent_ids_for_goal + from ...paths import registry_project_root + + goal = load_goal_from_registry(registry_path, goal_id) + if not goal or not goal.get("repo") or not goal.get("state_file"): + raise ValueError( + "Decision Context hook requires a registered Goal with a project and state file" + ) + project = Path(str(goal["repo"])).expanduser() + if not project.is_absolute(): + project = registry_project_root(registry_path) / project + owner = (project / str(goal["state_file"])).resolve() + return { + "schema_version": "decision_context_hook_request_v1", + "goal_state_ref": str(owner), + "goal_instance_id": goal.get("goal_instance_id"), + "runtime_root": str(runtime_root.expanduser().resolve()), + "goal_id": goal_id, + "agent_id": agent_id, + "registered_agents": registered_agent_ids_for_goal(goal), + } + + +def decision_context_hook_binding( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + agent_id: str, + action: str = "read", + **fields: Any, +) -> dict[str, Any]: + from ...control_plane.effect_runtime import effect_runtime_result + + request = { + **_goal_scope_fields( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + ), + "action": action, + **fields, + } + result = effect_runtime_result("decision_context.hook", request) + if not isinstance(result, dict): + raise TypeError("invalid decision-context hook response") + return result + + +def resolve_bound_decision_context_locators( + *, + registry_path: Path | None, + runtime_root: Path | None, + goal_id: str, + agent_id: str, +) -> dict[str, Any] | None: + """Resolve an active local hook binding without exposing private paths publicly.""" + if registry_path is None or runtime_root is None: + return None + try: + (runtime_root / DECISION_CONTEXT_HOOK_BINDINGS_DIRNAME).stat() + except FileNotFoundError: + return None + except OSError: + pass + try: + resolved = decision_context_hook_binding( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + action="resolve_local", + ) + except Exception: # noqa: BLE001 - callers surface explicit missing/invalid profiles + return None + local_binding = resolved.get("local_binding") + return dict(local_binding) if isinstance(local_binding, Mapping) else None + + +def _freshness_counts_and_alerts( + freshness: Mapping[str, Any] | None, +) -> tuple[dict[str, int], list[str]]: + counts = {"fresh": 0, "stale": 0, "never_read": 0, "not_scanned": 0} + alerted: list[str] = [] + if not isinstance(freshness, Mapping): + return counts, alerted + sources = freshness.get("sources") + if not isinstance(sources, list): + return counts, alerted + for row in sources: + if not isinstance(row, Mapping): + continue + status = str(row.get("status") or "") + if status in counts: + counts[status] += 1 + reasons = row.get("alert_reasons") + source_id = str(row.get("source_id") or "").strip() + if source_id and ( + status in {"stale", "never_read"} + or (isinstance(reasons, list) and len(reasons) > 0) + ): + alerted.append(source_id) + return counts, sorted(set(alerted)) + + +def _bound_cli_commands( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + agent_id: str, + spool_configured: bool, +) -> dict[str, str]: + from ...command_invocation import loopx_cli_argv + + prefix = [ + *loopx_cli_argv(), + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + ] + scope_flags = ["--goal-id", goal_id, "--agent-id", agent_id, "--format", "json"] + commands = { + "turn_context": shlex.join([*prefix, "hook", "turn-context", *scope_flags]), + "inspect_profile": shlex.join([*prefix, "inspect-profile", *scope_flags]), + "source_manifest": shlex.join([*prefix, "source-manifest", *scope_flags]), + "prepare_evidence": shlex.join( + [*prefix, "prepare-evidence", "--decision-id", "turn-rebase", *scope_flags] + ), + "recall_context": shlex.join( + [ + *prefix, + "recall-context", + "--context-scope-ref", + "goal", + "--query", + "current decision context", + "--query-summary", + "Current turn decision context", + *scope_flags, + ] + ), + } + if spool_configured: + commands["capture_status"] = shlex.join([*prefix, "capture-status", *scope_flags]) + return commands + + +def _collect_public_safe_observation( + *, + goal_id: str, + agent_id: str, + runtime_root: Path, + local_binding: Mapping[str, Any], + observed_at: str, +) -> dict[str, Any]: + from .assembler import DecisionEvidenceRecords + from .profile import resolve_decision_context_activation + from .runtime import assemble_profile_decision_evidence + from .sources import build_decision_source_manifest + + mode = str(local_binding.get("mode") or "prepare_evidence") + profile_path = Path(str(local_binding["profile_path"])).expanduser() + cursor_raw = local_binding.get("cursor_state_path") + cursor_path = Path(str(cursor_raw)).expanduser() if cursor_raw else None + spool_raw = local_binding.get("spool_path") + spool_path = Path(str(spool_raw)).expanduser() if spool_raw else None + + activation, profile = resolve_decision_context_activation( + goal_id=goal_id, + agent_id=agent_id, + profile_path=profile_path, + ) + if activation.get("available") is not True or profile is None: + reason = str( + activation.get("reason_code") + or activation.get("status") + or "profile_unavailable" + ) + return { + "status": "unavailable", + "error_code": f"decision_context_{reason}", + } + + enabled_count = sum(1 for source in profile.sources if source.enabled) + advisory_default = ( + "not_invoked" if profile.context_provider is not None else "not_configured" + ) + + if mode == "source_manifest": + manifest = build_decision_source_manifest( + goal_id=goal_id, + observed_at=observed_at, + sources=profile.sources, + ) + p0_enabled = sorted( + source.source_id + for source in profile.sources + if source.enabled and source.priority == "p0" + ) + source_count_val = manifest.get("source_count") + return { + "status": "available", + "observed_at": str(manifest["observed_at"]), + "source_count": ( + source_count_val + if isinstance(source_count_val, int) + else len(profile.sources) + ), + "enabled_source_count": enabled_count, + "changed_source_ids": [], + "failed_source_ids": [], + "alerted_source_ids": [], + "uncovered_p0_source_ids": p0_enabled, + "p0_complete": len(p0_enabled) == 0, + "freshness_counts": { + "fresh": 0, + "stale": 0, + "never_read": 0, + "not_scanned": enabled_count, + }, + "advisory_recall_status": advisory_default, + "capture_pending_batch_count": None, + "raw_content_captured": False, + "private_locator_captured": False, + } + + if mode == "capture_status": + if spool_path is None: + return { + "status": "unavailable", + "error_code": "decision_context_spool_not_configured", + } + from .capture import capture_profile_sources + + status_packet = capture_profile_sources( + goal_id=goal_id, + agent_id=agent_id, + profile_path=profile_path, + spool_path=spool_path, + cursor_path=cursor_path, + execute=False, + health_runtime_root=runtime_root, + ) + if status_packet.get("ok") is not True: + reason = str( + status_packet.get("reason_code") + or status_packet.get("status") + or "capture_unavailable" + ) + return { + "status": "unavailable", + "error_code": f"decision_context_{reason}", + } + counts, alerted = _freshness_counts_and_alerts( + status_packet.get("source_freshness") + if isinstance(status_packet.get("source_freshness"), Mapping) + else None + ) + changed: list[str] = [] + failed: list[str] = [] + raw_sources = status_packet.get("sources") + source_rows = raw_sources if isinstance(raw_sources, list) else [] + for row in source_rows: + if not isinstance(row, Mapping): + continue + sid = str(row.get("source_id") or "").strip() + if not sid: + continue + pending_count = row.get("pending_batch_count") + if isinstance(pending_count, int) and pending_count > 0: + changed.append(sid) + streak = row.get("failure_streak") + if (isinstance(streak, int) and streak > 0) or row.get("acquisition_held"): + failed.append(sid) + p0_uncovered = sorted( + source.source_id + for source in profile.sources + if source.enabled + and source.priority == "p0" + and source.source_id in (set(alerted) | set(failed)) + ) + raw_pending_total = status_packet.get("pending_batch_count") + pending_total = raw_pending_total if isinstance(raw_pending_total, int) else 0 + return { + "status": "available", + "observed_at": observed_at, + "source_count": len(profile.sources), + "enabled_source_count": enabled_count, + "changed_source_ids": sorted(set(changed)), + "failed_source_ids": sorted(set(failed)), + "alerted_source_ids": alerted, + "uncovered_p0_source_ids": p0_uncovered, + "p0_complete": len(p0_uncovered) == 0, + "freshness_counts": counts, + "advisory_recall_status": advisory_default, + "capture_pending_batch_count": pending_total, + "raw_content_captured": False, + "private_locator_captured": False, + } + + # Default mode == "prepare_evidence": bounded read-only authority scan + + # optional configured advisory recall receipt; cursors are never mutated. + if profile.context_provider is not None and not profile.context_provider.get( + "scope_ref" + ): + return { + "status": "unavailable", + "error_code": "decision_context_scope_ref_missing", + } + _act, assembly = assemble_profile_decision_evidence( + goal_id=goal_id, + agent_id=agent_id, + profile_path=profile_path, + decision_id="turn-start-observation", + observed_at=observed_at, + before=observed_at, + cursor_path=cursor_path, + rebase=lambda _collection: DecisionEvidenceRecords(), + runtime_root=runtime_root, + ) + if assembly is None: + return { + "status": "unavailable", + "error_code": "decision_context_assembly_unavailable", + } + packet = assembly.public_packet() + raw_scans = packet.get("source_scan_receipts") + scans: list[Any] = raw_scans if isinstance(raw_scans, list) else [] + changed_ids = sorted( + { + str(scan["source_id"]) + for scan in scans + if isinstance(scan, Mapping) + and scan.get("status") == "completed" + and isinstance(scan.get("changed_count"), int) + and int(scan["changed_count"]) > 0 + } + ) + failed_ids = sorted( + { + str(scan["source_id"]) + for scan in scans + if isinstance(scan, Mapping) + and scan.get("status") in {"failed", "unavailable"} + } + ) + raw_freshness = packet.get("source_freshness") + counts, alerted = _freshness_counts_and_alerts( + raw_freshness if isinstance(raw_freshness, Mapping) else None + ) + raw_coverage = packet.get("source_coverage") + coverage: Mapping[str, Any] = ( + raw_coverage if isinstance(raw_coverage, Mapping) else {} + ) + raw_uncovered = coverage.get("incomplete_required_source_ids") + uncovered_list = raw_uncovered if isinstance(raw_uncovered, list) else [] + uncovered_p0 = [str(item) for item in uncovered_list if str(item).strip()] + raw_retrieval = packet.get("context_retrieval_receipt") + retrieval: Mapping[str, Any] | None = ( + raw_retrieval if isinstance(raw_retrieval, Mapping) else None + ) + recall_status = ( + str(retrieval.get("status") or "unavailable") + if retrieval is not None + else advisory_default + ) + return { + "status": "available", + "observed_at": observed_at, + "source_count": len(profile.sources), + "enabled_source_count": enabled_count, + "changed_source_ids": changed_ids, + "failed_source_ids": failed_ids, + "alerted_source_ids": alerted, + "uncovered_p0_source_ids": sorted(set(uncovered_p0)), + "p0_complete": bool(coverage.get("complete", len(uncovered_p0) == 0)), + "freshness_counts": counts, + "advisory_recall_status": recall_status, + "capture_pending_batch_count": None, + "raw_content_captured": False, + "private_locator_captured": False, + } + + +def read_decision_context_turn_context( + *, + registry_path: Path, + runtime_root: Path, + goal_id: str, + agent_id: str, + observed_at: str | None = None, +) -> dict[str, Any]: + """Build the validated public-safe turn context view for one Goal/Agent.""" + explicit_now = ( + str(observed_at).strip() + if observed_at and str(observed_at).strip() + else None + ) + projected: dict[str, Any] | None = None + for _attempt in range(3): + now = explicit_now or datetime.now(timezone.utc).isoformat() + resolved = decision_context_hook_binding( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + action="resolve_local", + ) + if not resolved.get("ok"): + return resolved + if resolved.get("status") == "absent": + return { + "ok": True, + "status": "absent", + "goal_id": goal_id, + "agent_id": agent_id, + "observation_count": 0, + "current": resolved["current"], + } + + current_view = resolved.get("current") + expected_revision = ( + current_view.get("revision") + if isinstance(current_view, Mapping) + else None + ) + local_binding = resolved.get("local_binding") + spool_configured = bool( + isinstance(local_binding, Mapping) and local_binding.get("spool_path") + ) + commands = _bound_cli_commands( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + spool_configured=spool_configured, + ) + if not isinstance(local_binding, Mapping): + # Retired binding: project retirement notice through the TS owner, + # guarded by expected_revision so a concurrent re-bind cannot be masked. + projected = decision_context_hook_binding( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + action="project_turn_view", + expected_revision=expected_revision, + observation={"status": "retired"}, + commands=commands, + ) + else: + try: + observation = _collect_public_safe_observation( + goal_id=goal_id, + agent_id=agent_id, + runtime_root=runtime_root, + local_binding=local_binding, + observed_at=now, + ) + except Exception: # noqa: BLE001 - isolate provider/file errors to an unavailable receipt + observation = { + "status": "unavailable", + "error_code": "decision_context_observation_failed", + } + projected = decision_context_hook_binding( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + action="project_turn_view", + expected_revision=expected_revision, + observation=observation, + commands=commands, + ) + if projected.get("status") != "revision_conflict": + return projected + assert projected is not None + return projected + + +@overload +def extend_turn_start_dispatch( + dispatch: dict[str, Any], + *, + runtime_root: Path, + registry_path: Path, + goal_id: str, + agent_id: str | None, +) -> dict[str, Any]: ... + + +@overload +def extend_turn_start_dispatch( + dispatch: None, + *, + runtime_root: Path, + registry_path: Path, + goal_id: str, + agent_id: str | None, +) -> dict[str, Any] | None: ... + + +def extend_turn_start_dispatch( + dispatch: dict[str, Any] | None, + *, + runtime_root: Path, + registry_path: Path, + goal_id: str, + agent_id: str | None, +) -> dict[str, Any] | None: + """Attach Decision Context turn-start observation with strict default-off parity.""" + if not agent_id: + return dispatch + try: + (runtime_root / DECISION_CONTEXT_HOOK_BINDINGS_DIRNAME).stat() + except FileNotFoundError: + return dispatch + except OSError: + # Let the typed provider disclose permission denial rather than + # treating an inaccessible existing namespace as disabled. + pass + + from ...command_invocation import loopx_cli_argv + from ...control_plane.capability_hooks import ( + TURN_START_HOOK_RESULT_SCHEMA_VERSION, + TurnStartHookRegistration, + dispatch_turn_start_hooks, + ) + + snapshot: dict[str, Any] | None = None + + def produce() -> dict[str, Any]: + nonlocal snapshot + state = read_decision_context_turn_context( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=agent_id, + ) + snapshot = state + if not state.get("ok"): + error_code = ( + "decision_context_hook_permission_denied" + if state.get("status") == "permission_denied" + else str(state.get("error") or "decision_context_hook_unavailable") + ) + return { + "schema_version": TURN_START_HOOK_RESULT_SCHEMA_VERSION, + "hook_id": DECISION_CONTEXT_TURN_HOOK_ID, + "capability_id": DECISION_CONTEXT_HOOK_CAPABILITY_ID, + "phase": "turn_start", + "status": "unavailable", + "observation_count": 0, + "agent_read_required": False, + "external_reads_performed": False, + "external_writes_performed": False, + "local_private_state_mutated": False, + "private_content_returned": False, + "provider_payload_returned": False, + "error_code": error_code, + } + count = int(state.get("observation_count") or 0) + return { + "schema_version": TURN_START_HOOK_RESULT_SCHEMA_VERSION, + "hook_id": DECISION_CONTEXT_TURN_HOOK_ID, + "capability_id": DECISION_CONTEXT_HOOK_CAPABILITY_ID, + "phase": "turn_start", + "status": "observed" if count > 0 else "empty", + "observation_count": count, + "agent_read_required": count > 0, + "external_reads_performed": False, + "external_writes_performed": False, + "local_private_state_mutated": False, + "private_content_returned": False, + "provider_payload_returned": False, + "error_code": None, + } + + command = shlex.join( + [ + *loopx_cli_argv(), + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "turn-context", + "--goal-id", + goal_id, + "--agent-id", + agent_id, + "--format", + "json", + ] + ) + hook = TurnStartHookRegistration( + hook_id=DECISION_CONTEXT_TURN_HOOK_ID, + capability_id=DECISION_CONTEXT_HOOK_CAPABILITY_ID, + requested_read_scope=("owner_private_decision_context",), + requested_write_scope=(), + producer=produce, + context_reader=lambda: { + "ok": True, + "status": "read", + "goal_id": goal_id, + "agent_id": agent_id, + "current": snapshot["current"], + } + if snapshot is not None + else { + "ok": False, + "error": "decision_context_snapshot_missing", + }, + required_read={ + "kind": "decision_context", + "command": command, + "reason": ( + "Read current Decision Context source freshness, changed-source refs " + "and uncovered P0 alerts before acting. Context grants no authority." + ), + "ordering": "before_work", + }, + ) + + extra = dispatch_turn_start_hooks((hook,)) + # Another Goal/Agent's binding directory does not opt this scope into + # Decision Context. Retired bindings remain present to invalidate cache. + if ( + snapshot is not None + and snapshot.get("ok") is True + and snapshot.get("status") == "absent" + ): + return dispatch + + result: dict[str, Any] = dict(dispatch or {}) + for key in ("results", "required_reads", "failures", "contexts"): + extra_items = extra.get(key) + if key == "contexts" and not (isinstance(extra_items, list) and extra_items): + continue + existing_items = result.get(key) + result[key] = ( + (list(existing_items) if isinstance(existing_items, list) else []) + + (list(extra_items) if isinstance(extra_items, list) else []) + ) + for key in ("registered_count", "invoked_count"): + existing_count = result.get(key) + extra_count = extra.get(key) + result[key] = ( + (existing_count if isinstance(existing_count, int) else 0) + + (extra_count if isinstance(extra_count, int) else 0) + ) + return result + + +def register_decision_context_hook_commands( + commands: Any, + add_format: Any, +) -> None: + parser = commands.add_parser( + "hook", + help="Read, bind, unbind or inspect host-local Decision Context turn-start hooks.", + ) + parser.add_argument( + "decision_context_hook_action", + choices=["read", "bind", "unbind", "history", "turn-context"], + ) + add_format(parser) + parser.add_argument("--goal-id", required=True) + parser.add_argument("--agent-id", required=True) + parser.add_argument( + "--profile", + help="Private local profile path to bind (required for bind).", + ) + parser.add_argument( + "--cursor-state", + help="Optional private reviewed-cursor JSON path to bind.", + ) + parser.add_argument( + "--spool", + help="Optional private SQLite capture spool path to bind.", + ) + parser.add_argument( + "--mode", + choices=["prepare_evidence", "source_manifest", "capture_status"], + default="prepare_evidence", + help="Read-only turn-start observation mode for an active binding.", + ) + parser.add_argument( + "--expected-revision", + help="Current read revision; use 'none' only for an empty store.", + ) + parser.add_argument( + "--operation-id", + help="Stable operation id for idempotent bind/unbind commits.", + ) + parser.add_argument("--after-cursor", help="History page continuation.") + parser.add_argument("--observed-at", help="Optional UTC ISO-8601 observation time.") + parser.add_argument( + "--execute", + action="store_true", + help="Commit a bind/unbind change; otherwise preview only.", + ) + + +def handle_decision_context_hook( + args: Any, + *, + registry_path: Path, + runtime_root: Path, +) -> dict[str, Any]: + action = str(args.decision_context_hook_action) + if action == "turn-context": + return read_decision_context_turn_context( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=args.goal_id, + agent_id=args.agent_id, + observed_at=getattr(args, "observed_at", None), + ) + fields: dict[str, Any] = {"execute": bool(args.execute)} + if action in {"bind", "unbind"}: + if args.expected_revision is None: + raise ValueError( + "read hook binding first, then pass --expected-revision " + "(or 'none' for an empty store)" + ) + if not str(args.operation_id or "").strip(): + raise ValueError("--operation-id is required for bind and unbind") + fields["expected_revision"] = ( + None if args.expected_revision == "none" else args.expected_revision + ) + fields["operation_id"] = str(args.operation_id).strip() + fields["source_kind"] = "operator_configuration" + if action == "bind": + from .profile import resolve_decision_context_activation + + if not str(args.profile or "").strip(): + raise ValueError("--profile is required for bind") + profile_path = Path(str(args.profile)).expanduser().resolve() + activation, _ = resolve_decision_context_activation( + goal_id=args.goal_id, + agent_id=args.agent_id, + profile_path=profile_path, + ) + if activation.get("available") is not True: + reason = str( + activation.get("reason_code") + or activation.get("status") + or "profile_unavailable" + ) + raise ValueError( + f"profile must be available for {args.goal_id}/{args.agent_id} " + f"before binding ({reason})" + ) + fields.update( + profile_path=str(profile_path), + cursor_state_path=( + str(Path(str(args.cursor_state)).expanduser().resolve()) + if str(args.cursor_state or "").strip() + else None + ), + spool_path=( + str(Path(str(args.spool)).expanduser().resolve()) + if str(args.spool or "").strip() + else None + ), + mode=str(args.mode or "prepare_evidence"), + ) + if action == "history": + fields["after_cursor"] = args.after_cursor + return decision_context_hook_binding( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id=args.goal_id, + agent_id=args.agent_id, + action=action, + **fields, + ) + + +def render_decision_context_hook(payload: Mapping[str, object]) -> str: + return json.dumps(payload, ensure_ascii=False, indent=2) + "\n" diff --git a/loopx/cli.py b/loopx/cli.py index 9f039398bb..32a2a3608c 100644 --- a/loopx/cli.py +++ b/loopx/cli.py @@ -13,6 +13,7 @@ register_automation_cadence_command, handle_automation_cadence_command, ) +from pathlib import Path import sys from .cli_commands.agent_capabilities import register_agent_capabilities @@ -559,15 +560,32 @@ def _main(argv: list[str] | None = None) -> int: if agent_turn_recall_result is not None: return agent_turn_recall_result + def _decision_context_runtime_root() -> Path | None: + if args.command != "decision-context": + return None + if args.decision_context_command in { + "hook", + "recall-context", + "prepare-evidence", + "prepare-review", + "capture", + }: + return effective_runtime_root(registry_path, args.runtime_root) + if args.decision_context_command in { + "inspect-profile", + "source-manifest", + "capture-status", + } and not str(getattr(args, "profile", None) or "").strip(): + try: + return effective_runtime_root(registry_path, args.runtime_root) + except (OSError, ValueError): + return None + return None + decision_context_result = handle_decision_context_command( args, - runtime_root=( - effective_runtime_root(registry_path, args.runtime_root) - if args.command == "decision-context" - and args.decision_context_command - in {"recall-context", "prepare-evidence", "prepare-review", "capture"} - else None - ), + runtime_root=_decision_context_runtime_root(), + registry_path=registry_path, output_format=output_format, print_payload=print_payload, ) diff --git a/loopx/cli_commands/quota_should_run.py b/loopx/cli_commands/quota_should_run.py index 22aa489382..582d8cc188 100644 --- a/loopx/cli_commands/quota_should_run.py +++ b/loopx/cli_commands/quota_should_run.py @@ -87,6 +87,9 @@ def dispatch_quota_turn_start_hooks( agent_id=args.agent_id, ) if args.agent_id: + from ..capabilities.decision_context.turn_start_hook import ( + extend_turn_start_dispatch as extend_decision_context, + ) from ..capabilities.manager_context import turn_start_hook from ..capabilities.semantic_preference.agent_preferences import ( extend_turn_start_dispatch as extend_preferences, @@ -133,6 +136,13 @@ def dispatch_quota_turn_start_hooks( goal_id=args.goal_id, agent_id=args.agent_id, ) + context_dispatch = extend_decision_context( + context_dispatch, + runtime_root=root, + registry_path=registry_path, + goal_id=args.goal_id, + agent_id=args.agent_id, + ) dispatch = dict(dispatch) for key in ("results", "required_reads", "failures", "contexts"): if key == "contexts" and not context_dispatch.get(key): diff --git a/loopx/cli_commands/turn.py b/loopx/cli_commands/turn.py index e4a58ec422..a5b072c3ad 100644 --- a/loopx/cli_commands/turn.py +++ b/loopx/cli_commands/turn.py @@ -310,9 +310,19 @@ def execution_preparer(decision: Mapping[str, Any]) -> str | None: available=args.available_capabilities, ) + from ..capabilities.decision_context.turn_start_hook import ( + extend_turn_start_dispatch as extend_decision_context, + ) from ..capabilities.semantic_preference.agent_preferences import extend_turn_start_dispatch as extend_preferences turn_start_hook_dispatch = extend_preferences(turn_start_hook_dispatch, runtime_root=runtime_root, registry_path=registry_path, goal_id=args.goal_id, agent_id=args.agent_id) + turn_start_hook_dispatch = extend_decision_context( + turn_start_hook_dispatch, + runtime_root=runtime_root, + registry_path=registry_path, + goal_id=args.goal_id, + agent_id=args.agent_id, + ) if delegated_context is not None: # Invocation material shares normal capture/delivery. It is not a # capability observation, another decision or a new read command. diff --git a/loopx/control_plane/capabilities/decision_context_hook.ts b/loopx/control_plane/capabilities/decision_context_hook.ts new file mode 100644 index 0000000000..4c2cbef6c9 --- /dev/null +++ b/loopx/control_plane/capabilities/decision_context_hook.ts @@ -0,0 +1,775 @@ +/** Scoped host-local Decision Context turn-start binding and view projection. + * Advisory context only; AuthorityStore owns durability, Core owns permissions. + */ +import {createHash} from "node:crypto"; +import {access, constants} from "node:fs/promises"; +import {join} from "node:path"; +import type {AuthorityStore} from "../coordination/authority_store.ts"; +import {canonicalAuthorityBytes} from "../coordination/authority_store_codec.ts"; +import {FileAuthorityStore} from "../coordination/file_authority_store.ts"; +import type {JsonObject} from "../effect_program.ts"; +import { + jsonObject, + requireBoolean, + requireInteger, + requireJsonObject, + requireNonEmptyString, + requireStringArray, +} from "../runtime_decode.ts"; + +export const DECISION_CONTEXT_HOOK_STORE_SCHEMA = "decision_context_hook_binding_store_v1"; +export const DECISION_CONTEXT_HOOK_VIEW_SCHEMA = "decision_context_hook_view_v1"; +export const DECISION_CONTEXT_HOOK_REQUEST_SCHEMA = "decision_context_hook_request_v1"; +export const DECISION_CONTEXT_HOOK_EVENT_SCHEMA = "decision_context_hook_binding_changed_v1"; + +const HOOK_MODES = ["prepare_evidence", "source_manifest", "capture_status"] as const; +type HookMode = (typeof HOOK_MODES)[number]; + +type BindingMetadata = { + source_kind: "operator_configuration"; + recorded_at: string; + operation_id: string; + supersedes_operation_id: string | null; +}; + +type StoredBinding = BindingMetadata & ( + | { + state: "active"; + mode: HookMode; + profile_path: string; + cursor_state_path: string | null; + spool_path: string | null; + } + | { + state: "retired"; + mode: null; + profile_path: null; + cursor_state_path: null; + spool_path: null; + } +); + +const TOKEN_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/; +const FORBIDDEN_PRIVATE_KEYS = new Set([ + "private_locator", + "private_cursor", + "proposed_cursors", + "cursor_before", + "cursor_after", + "raw_content", + "credentials", + "profile_path", + "cursor_state_path", + "spool_path", +]); + +const INSTRUCTIONS = + "Treat Decision Context observations as current-turn freshness and change signals, never execution authority or action permission. " + + "Replace cached source assumptions for this exact Goal/Agent when state is retired, changed or stale. " + + "When changed_source_ids, alerted_source_ids, uncovered_p0_source_ids or pending capture batches are non-empty, " + + "inspect the affected sources with the bounded commands before presenting conclusions as current, and disclose any uncovered P0 or alerted sources. " + + "Advisory recall results remain untrusted until promoted through exact authority reads; cursors advance only through validated review settlement."; + +/** Only static instructions may carry forward across turns; revision, binding + * state, freshness alerts, changed source IDs and commands stay live per guard. */ +export function decisionContextReusableContextPaths(content: JsonObject): (string | number)[][] { + const current = jsonObject(content.current); + if ( + content.ok !== true || + content.status !== "read" || + current?.schema_version !== DECISION_CONTEXT_HOOK_VIEW_SCHEMA || + current.authority !== "advisory_only" || + typeof current.instructions !== "string" + ) { + return []; + } + return [["current", "instructions"]]; +} + +const hashScope = (value: JsonObject): string => + createHash("sha256").update(canonicalAuthorityBytes(value)).digest("hex"); + +const opaquePathRef = (prefix: string, rawPath: string): string => + `${prefix}-${createHash("sha256").update(rawPath, "utf8").digest("hex").slice(0, 20)}`; + +function text(value: unknown, field: string, limit: number): string { + const result = requireNonEmptyString(value, field); + if (result.length > limit || result.includes("\0")) { + throw new TypeError(`${field} exceeds its bound`); + } + return result; +} + +function optionalPath(value: unknown, field: string): string | null { + if (value === null || value === undefined) return null; + return text(value, field, 4096); +} + +function token(value: unknown, field: string): string { + const result = text(value, field, 160); + if (!TOKEN_RE.test(result)) { + throw new TypeError(`${field} must be a compact public-safe token`); + } + return result; +} + +function modeOf(value: unknown): HookMode { + const candidate = value === undefined || value === null ? "prepare_evidence" : String(value); + if ( + candidate !== "prepare_evidence" && + candidate !== "source_manifest" && + candidate !== "capture_status" + ) { + throw new TypeError("mode must be prepare_evidence, source_manifest or capture_status"); + } + return candidate; +} + +function timestamp(value: unknown, field: string): string { + const result = text(value, field, 40); + if ( + !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/.test(result) || + !Number.isFinite(Date.parse(result)) + ) { + throw new TypeError(`${field} must be a UTC ISO timestamp`); + } + const normalized = new Date(result).toISOString(); + if (normalized.slice(0, 19) !== result.slice(0, 19)) { + throw new TypeError(`${field} is not a calendar timestamp`); + } + return normalized; +} + +function revision(value: unknown): string | null { + if (value === null) return null; + return text(value, "expected_revision (use null for an empty store)", 256); +} + +function scopeOf(request: JsonObject): JsonObject { + const scope = { + goal_state_ref: text(request.goal_state_ref, "goal_state_ref", 4096), + goal_instance_id: + request.goal_instance_id == null + ? null + : text(request.goal_instance_id, "goal_instance_id", 256), + goal_id: token(request.goal_id, "goal_id"), + agent_id: token(request.agent_id, "agent_id"), + }; + if (!requireStringArray(request.registered_agents, "registered_agents").includes(scope.agent_id)) { + throw new TypeError("agent must be registered in this Goal"); + } + return scope; +} + +function storedBindingOf(head: JsonObject, scope: JsonObject): StoredBinding { + if ( + head.schema_version !== DECISION_CONTEXT_HOOK_STORE_SCHEMA || + canonicalAuthorityBytes(requireJsonObject(head.scope, "scope")).compare( + canonicalAuthorityBytes(scope), + ) !== 0 + ) { + throw new TypeError("decision-context hook store scope/schema mismatch"); + } + const raw = requireJsonObject(head.record, "decision-context hook record"); + if (raw.source_kind !== "operator_configuration") { + throw new TypeError("invalid decision-context hook source_kind"); + } + const base: BindingMetadata = { + source_kind: "operator_configuration", + operation_id: text(raw.operation_id, "operation_id", 128), + recorded_at: timestamp(raw.recorded_at, "recorded_at"), + supersedes_operation_id: + raw.supersedes_operation_id === null + ? null + : text(raw.supersedes_operation_id, "supersedes_operation_id", 128), + }; + if (raw.state === "active") { + const mode = modeOf(raw.mode); + const profilePath = text(raw.profile_path, "profile_path", 4096); + const cursorStatePath = optionalPath(raw.cursor_state_path, "cursor_state_path"); + const spoolPath = optionalPath(raw.spool_path, "spool_path"); + if (mode === "capture_status" && spoolPath === null) { + throw new TypeError("capture_status mode requires spool_path"); + } + return { + ...base, + state: "active", + mode, + profile_path: profilePath, + cursor_state_path: cursorStatePath, + spool_path: spoolPath, + }; + } + if (raw.state !== "retired") { + throw new TypeError("invalid decision-context hook binding state"); + } + if ( + raw.mode !== null || + raw.profile_path !== null || + raw.cursor_state_path !== null || + raw.spool_path !== null + ) { + throw new TypeError("retired decision-context hook binding must clear locators"); + } + return { + ...base, + state: "retired", + mode: null, + profile_path: null, + cursor_state_path: null, + spool_path: null, + }; +} + +function publicBinding(record: StoredBinding | null): JsonObject { + if (record === null) { + return { + state: "unconfigured", + mode: null, + profile_ref: null, + cursor_state_configured: false, + spool_configured: false, + operation_id: null, + recorded_at: null, + supersedes_operation_id: null, + private_locator_captured: false, + }; + } + if (record.state === "retired") { + return { + state: "retired", + mode: null, + profile_ref: null, + cursor_state_configured: false, + spool_configured: false, + operation_id: record.operation_id, + recorded_at: record.recorded_at, + supersedes_operation_id: record.supersedes_operation_id, + private_locator_captured: false, + }; + } + return { + state: "active", + mode: record.mode, + profile_ref: opaquePathRef("profile-path", record.profile_path), + cursor_state_configured: record.cursor_state_path !== null, + spool_configured: record.spool_path !== null, + operation_id: record.operation_id, + recorded_at: record.recorded_at, + supersedes_operation_id: record.supersedes_operation_id, + private_locator_captured: false, + }; +} + +function currentView( + scope: JsonObject, + record: StoredBinding | null, + providerRevision: string | null, +): JsonObject { + return { + schema_version: DECISION_CONTEXT_HOOK_VIEW_SCHEMA, + goal_id: scope.goal_id, + agent_id: scope.agent_id, + revision: providerRevision, + authority: "advisory_only", + binding: publicBinding(record), + instructions: INSTRUCTIONS, + }; +} + +function assertNoPrivateKeys(value: unknown, depth = 0): void { + if (depth > 16) throw new TypeError("decision-context observation nesting exceeds bound"); + if (Array.isArray(value)) { + for (const item of value) assertNoPrivateKeys(item, depth + 1); + return; + } + const obj = jsonObject(value); + if (!obj) return; + for (const [key, child] of Object.entries(obj)) { + if (FORBIDDEN_PRIVATE_KEYS.has(key)) { + throw new TypeError(`decision-context hook observation cannot include ${key}`); + } + if ( + (key === "raw_content_captured" || + key === "raw_provider_payload_captured" || + key === "private_locator_captured" || + key === "private_locators_captured" || + key === "private_cursor_captured" || + key === "private_cursors_captured" || + key === "credentials_captured") && + child !== false + ) { + throw new TypeError(`decision-context hook observation violated safety flag ${key}`); + } + assertNoPrivateKeys(child, depth + 1); + } +} + +function sortedUniqueTokens(values: unknown, field: string, maxItems = 64): string[] { + if (!Array.isArray(values)) throw new TypeError(`${field} must be an array`); + if (values.length > maxItems) throw new TypeError(`${field} exceeds bound`); + const unique = new Set(); + for (const raw of values) { + unique.add(token(raw, field)); + } + return [...unique].sort(); +} + +function validatedCommands(raw: unknown): JsonObject { + const candidate = requireJsonObject(raw, "commands"); + const allowed = new Set([ + "turn_context", + "inspect_profile", + "source_manifest", + "prepare_evidence", + "recall_context", + "capture_status", + ]); + const output: JsonObject = {}; + for (const [key, value] of Object.entries(candidate)) { + if (!allowed.has(key)) { + throw new TypeError(`unsupported decision-context hook command slot: ${key}`); + } + if (value === null || value === undefined) continue; + const command = text(value, `commands.${key}`, 1024).trim(); + if (/[\u0000-\u001f\u007f]/.test(command) || Buffer.byteLength(command, "utf8") > 1024) { + throw new TypeError(`commands.${key} is outside the admitted command envelope`); + } + output[key] = command; + } + return output; +} + +function projectActiveObservation(rawObservation: unknown, mode: HookMode): { + summary: JsonObject; + observationCount: number; +} { + const obs = requireJsonObject(rawObservation, "observation"); + assertNoPrivateKeys(obs); + const observedAt = text(obs.observed_at, "observation.observed_at", 64); + if (!Number.isFinite(Date.parse(observedAt))) { + throw new TypeError("observation.observed_at must be an ISO-8601 timestamp"); + } + const sourceCount = requireInteger(obs.source_count, "observation.source_count"); + const enabledSourceCount = requireInteger( + obs.enabled_source_count, + "observation.enabled_source_count", + ); + if (sourceCount < 0 || sourceCount > 64 || enabledSourceCount < 0 || enabledSourceCount > 64) { + throw new TypeError("observation source counts are outside bounds"); + } + const changedSourceIds = sortedUniqueTokens( + obs.changed_source_ids ?? [], + "observation.changed_source_ids", + ); + const failedSourceIds = sortedUniqueTokens( + obs.failed_source_ids ?? [], + "observation.failed_source_ids", + ); + const alertedSourceIds = sortedUniqueTokens( + obs.alerted_source_ids ?? [], + "observation.alerted_source_ids", + ); + const uncoveredP0SourceIds = sortedUniqueTokens( + obs.uncovered_p0_source_ids ?? [], + "observation.uncovered_p0_source_ids", + ); + const p0Complete = requireBoolean(obs.p0_complete, "observation.p0_complete"); + const freshnessRaw = requireJsonObject( + obs.freshness_counts ?? {fresh: 0, stale: 0, never_read: 0, not_scanned: 0}, + "observation.freshness_counts", + ); + const freshnessCounts: JsonObject = { + fresh: requireInteger(freshnessRaw.fresh ?? 0, "freshness_counts.fresh"), + stale: requireInteger(freshnessRaw.stale ?? 0, "freshness_counts.stale"), + never_read: requireInteger(freshnessRaw.never_read ?? 0, "freshness_counts.never_read"), + not_scanned: requireInteger(freshnessRaw.not_scanned ?? 0, "freshness_counts.not_scanned"), + }; + const advisoryRecallStatus = token( + obs.advisory_recall_status ?? "not_configured", + "observation.advisory_recall_status", + ); + const pendingBatchCount = + obs.capture_pending_batch_count === null || obs.capture_pending_batch_count === undefined + ? null + : requireInteger(obs.capture_pending_batch_count, "observation.capture_pending_batch_count"); + if (pendingBatchCount !== null && (pendingBatchCount < 0 || pendingBatchCount > 100_000)) { + throw new TypeError("capture_pending_batch_count is outside bounds"); + } + const signalCount = + 1 + + changedSourceIds.length + + failedSourceIds.length + + alertedSourceIds.length + + uncoveredP0SourceIds.length + + (pendingBatchCount !== null && pendingBatchCount > 0 ? 1 : 0); + return { + observationCount: Math.min(10_000, signalCount), + summary: { + status: "observed", + mode, + observed_at: observedAt, + source_count: sourceCount, + enabled_source_count: enabledSourceCount, + changed_source_ids: changedSourceIds, + failed_source_ids: failedSourceIds, + alerted_source_ids: alertedSourceIds, + uncovered_p0_source_ids: uncoveredP0SourceIds, + p0_complete: p0Complete, + freshness_counts: freshnessCounts, + advisory_recall_status: advisoryRecallStatus, + capture_pending_batch_count: pendingBatchCount, + raw_content_captured: false, + private_locator_captured: false, + }, + }; +} + +/** Injectable persistence seam exercised against both File and SQLite stores. */ +export async function executeDecisionContextHook( + request: JsonObject, + store: AuthorityStore, + now = new Date().toISOString(), +): Promise { + if (request.schema_version !== DECISION_CONTEXT_HOOK_REQUEST_SCHEMA) { + throw new TypeError("decision-context hook request schema mismatch"); + } + const scope = scopeOf(request); + const action = String(request.action ?? ""); + if ( + ![ + "read", + "observe", + "resolve_local", + "project_turn_view", + "bind", + "unbind", + "history", + ].includes(action) + ) { + throw new TypeError("invalid decision-context hook action"); + } + const loaded = await store.loadAuthority(); + if (loaded.status !== "loaded" && loaded.status !== "missing") { + return { + ok: false, + status: "unavailable", + error: "decision_context_hook_store_unreadable", + }; + } + const record = loaded.status === "loaded" ? storedBindingOf(loaded.head, scope) : null; + const actualRevision = loaded.status === "loaded" ? loaded.provider_revision : null; + + if (action === "observe") { + return { + ok: true, + status: record === null ? "absent" : "observed", + binding_state: record === null ? "unconfigured" : record.state, + observation_count: record === null ? 0 : 1, + }; + } + + const view = currentView(scope, record, actualRevision); + + if (action === "resolve_local") { + return { + ok: true, + status: record === null ? "absent" : "observed", + current: view, + local_binding: + record !== null && record.state === "active" + ? { + mode: record.mode, + profile_path: record.profile_path, + cursor_state_path: record.cursor_state_path, + spool_path: record.spool_path, + } + : null, + }; + } + + if (action === "read") { + return {ok: true, status: "read", current: view}; + } + + if (action === "project_turn_view") { + if (!("expected_revision" in request)) { + throw new TypeError("project_turn_view requires expected_revision"); + } + const expectedRevision = + request.expected_revision === null + ? null + : text(request.expected_revision, "expected_revision", 256); + if (expectedRevision !== actualRevision) { + return { + ok: false, + status: "revision_conflict", + error: "observed_binding_revision_mismatch", + goal_id: scope.goal_id, + agent_id: scope.agent_id, + expected_revision: expectedRevision, + actual_revision: actualRevision, + current: view, + }; + } + if (record === null) { + return { + ok: true, + status: "absent", + goal_id: scope.goal_id, + agent_id: scope.agent_id, + observation_count: 0, + current: view, + }; + } + const commands = validatedCommands(request.commands ?? {}); + if (record.state === "retired") { + return { + ok: true, + status: "read", + goal_id: scope.goal_id, + agent_id: scope.agent_id, + observation_count: 1, + current: { + ...view, + observation: { + status: "retired", + summary: + "Decision Context hook binding is retired for this Goal/Agent; discard cached source assumptions.", + raw_content_captured: false, + private_locator_captured: false, + }, + commands, + }, + }; + } + const rawObs = requireJsonObject(request.observation, "observation"); + if (rawObs.status !== "available") { + const errorCode = token( + rawObs.error_code ?? "decision_context_observation_unavailable", + "observation.error_code", + ); + return { + ok: false, + status: "unavailable", + error: errorCode, + goal_id: scope.goal_id, + agent_id: scope.agent_id, + }; + } + const {summary, observationCount} = projectActiveObservation(rawObs, record.mode); + return { + ok: true, + status: "read", + goal_id: scope.goal_id, + agent_id: scope.agent_id, + observation_count: observationCount, + current: { + ...view, + observation: summary, + commands, + }, + }; + } + + if (action === "history") { + const cursor = + request.after_cursor === null || request.after_cursor === undefined + ? null + : text(request.after_cursor, "after_cursor", 256); + const page = await store.scanCommitted(cursor, 20); + if (page.status !== "page") { + return { + ok: false, + status: "unavailable", + error: "decision_context_hook_history_unreadable", + }; + } + return { + ok: true, + status: "history", + events: page.transactions.flatMap(tx => tx.events), + next_cursor: page.next_cursor, + has_more: page.has_more, + current: view, + }; + } + + const expected = revision(request.expected_revision); + const operation = text(request.operation_id, "operation_id", 128); + if (request.source_kind !== "operator_configuration") { + throw new TypeError("only explicit operator configuration may update hook bindings"); + } + let proposed: StoredBinding; + if (action === "bind") { + const mode = modeOf(request.mode); + const profilePath = text(request.profile_path, "profile_path", 4096); + const cursorStatePath = optionalPath(request.cursor_state_path, "cursor_state_path"); + const spoolPath = optionalPath(request.spool_path, "spool_path"); + if (mode === "capture_status" && spoolPath === null) { + throw new TypeError("capture_status mode requires spool_path"); + } + proposed = { + source_kind: "operator_configuration", + recorded_at: now, + operation_id: operation, + supersedes_operation_id: record?.operation_id ?? null, + state: "active", + mode, + profile_path: profilePath, + cursor_state_path: cursorStatePath, + spool_path: spoolPath, + }; + } else { + if (record === null) { + throw new TypeError("unbind requires an existing decision-context hook binding"); + } + proposed = { + source_kind: "operator_configuration", + recorded_at: now, + operation_id: operation, + supersedes_operation_id: record.operation_id, + state: "retired", + mode: null, + profile_path: null, + cursor_state_path: null, + spool_path: null, + }; + } + + const intent: JsonObject = { + scope, + action, + operation_id: operation, + expected_revision: expected, + mode: proposed.mode, + profile_ref: + proposed.state === "active" + ? opaquePathRef("profile-path", proposed.profile_path) + : null, + cursor_state_ref: + proposed.state === "active" && proposed.cursor_state_path !== null + ? opaquePathRef("cursor-path", proposed.cursor_state_path) + : null, + spool_ref: + proposed.state === "active" && proposed.spool_path !== null + ? opaquePathRef("spool-path", proposed.spool_path) + : null, + }; + const intentHash = hashScope(intent); + + const prior = await store.readReceipt(operation); + if (prior.status === "found") { + if (prior.receipts.length !== 1 || prior.receipts[0]?.intent_hash !== intentHash) { + return {ok: false, status: "operation_conflict", current: view}; + } + const fresh = await store.loadAuthority(); + if (fresh.status !== "loaded") { + return { + ok: false, + status: "unavailable", + error: "decision_context_hook_readback_unavailable", + }; + } + return { + ok: true, + status: "replayed", + receipt: prior.receipts[0]!, + current: currentView( + scope, + storedBindingOf(fresh.head, scope), + fresh.provider_revision, + ), + }; + } + if (prior.status !== "missing") { + return { + ok: false, + status: "unavailable", + error: "decision_context_hook_receipt_unreadable", + }; + } + if (actualRevision !== expected) { + return {ok: false, status: "revision_conflict", current: view}; + } + + const publicProposed = publicBinding(proposed); + const receipt: JsonObject = { + operation_id: operation, + intent_hash: intentHash, + state: proposed.state, + mode: proposed.mode, + profile_ref: publicProposed.profile_ref, + supersedes_operation_id: proposed.supersedes_operation_id, + }; + if (request.execute !== true) { + return {ok: true, status: "preview", proposed: publicProposed, current: view}; + } + + const event: JsonObject = { + schema_version: DECISION_CONTEXT_HOOK_EVENT_SCHEMA, + ...publicProposed, + }; + const committed = await store.commitAuthority({ + expected_provider_revision: expected, + operation_id: operation, + events: [event], + next_projection: { + schema_version: DECISION_CONTEXT_HOOK_STORE_SCHEMA, + scope, + record: proposed, + }, + receipts: [receipt], + }); + if (committed.status !== "applied") { + return { + ok: false, + status: committed.status, + error: "decision_context_hook_commit_not_confirmed", + }; + } + const readback = await store.loadAuthority(); + if (readback.status !== "loaded") { + return { + ok: false, + status: "ambiguous", + error: "decision_context_hook_readback_unavailable", + operation_id: operation, + }; + } + return { + ok: true, + status: "applied", + receipt, + current: currentView( + scope, + storedBindingOf(readback.head, scope), + readback.provider_revision, + ), + }; +} + +export async function decisionContextHook(request: JsonObject): Promise { + const scope = scopeOf(request); + const directory = join( + text(request.runtime_root, "runtime_root", 4096), + "decision-context", + "agent-bindings", + hashScope(scope), + ); + const mutating = + (request.action === "bind" || request.action === "unbind") && request.execute === true; + const store = new FileAuthorityStore(directory, "binding", {existingOnly: !mutating}); + try { + await access(store.path, constants.R_OK); + } catch (error) { + if (["EACCES", "EPERM"].includes(String((error as NodeJS.ErrnoException).code))) { + return { + ok: false, + status: "permission_denied", + error: "decision_context_hook_permission_denied", + }; + } + } + return executeDecisionContextHook(request, store); +} diff --git a/loopx/control_plane/capability_hooks.ts b/loopx/control_plane/capability_hooks.ts index 9f3676b130..2d531e18ab 100644 --- a/loopx/control_plane/capability_hooks.ts +++ b/loopx/control_plane/capability_hooks.ts @@ -23,6 +23,7 @@ import { projectPendingCapabilityIntent } from "./work_items/pending_capability_ import {exploreResultWritebackAffordance, exploreReusableContextPaths} from "./capabilities/explore_context_delivery.ts"; import {agentPreferenceReusableContextPaths} from "./capabilities/agent_preferences.ts"; +import {decisionContextReusableContextPaths} from "./capabilities/decision_context_hook.ts"; /** The registered owner selects reusable read-model subtrees. Unknown hooks * remain complete; payloads cannot nominate their own execution fields. */ @@ -46,6 +47,11 @@ export function reusableTurnContext(source: JsonObject, binding: JsonObject): { if ((content.goal_id !== undefined && content.goal_id !== goal) || (content.agent_id !== undefined && content.agent_id !== agent)) return null; paths = agentPreferenceReusableContextPaths(content); + } else if (source.hook_id === "decision_context.turn_context" && source.capability_id === "decision-context" + && source.kind === "decision_context") { + goal = binding.goal_id; agent = binding.agent_id; + if (content.goal_id !== goal || content.agent_id !== agent) return null; + paths = decisionContextReusableContextPaths(content); } else return null; return paths.length && typeof goal === "string" && typeof agent === "string" ? {identity: [source.source, source.hook_id, source.capability_id, goal, agent, content.todo_id ?? null], paths} : null; diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 46ce8842d5..b0e94dd470 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -300,6 +300,7 @@ export function createEffectRuntimeHandlers( ["benchmark.terminal-followthrough.prepare", lazyHandler(() => import("./capabilities/benchmark_terminal_followthrough.ts"), ({prepareBenchmarkTerminalFollowthrough}) => prepareBenchmarkTerminalFollowthrough)], ["benchmark.cli_source_activation", lazyHandler(() => import("./capabilities/benchmark_cli_source_activation.ts"), ({qualifyCliSourceActivation}) => qualifyCliSourceActivation)], ["agent.preferences", lazyHandler(() => import("./capabilities/agent_preferences.ts"), ({agentPreferences}) => agentPreferences)], + ["decision_context.hook", lazyHandler(() => import("./capabilities/decision_context_hook.ts"), ({decisionContextHook}) => decisionContextHook)], ["todo.archive.capture_dependencies", lazyHandler(() => Promise.all([import("./todos/archive_capture.ts"), import("./coordination/source_transfer.ts")]), ([{captureArchivedTodoDependencies}, {withCoordinationSourceTransfer}]) => withCoordinationSourceTransfer("todo.archive.capture_dependencies", captureArchivedTodoDependencies))], ["agent.supervisor.plan_append", lazyHandler(() => import("./agents/supervisor_event_append.ts"), ({planSupervisorEventAppend}) => planSupervisorEventAppend)], ["coordination.source.project", lazyHandler(() => Promise.all([import("./coordination/source_projection.ts"), import("./coordination/source_transfer.ts")]), ([{projectCoordinationSource}, {withCoordinationSourceTransfer}]) => withCoordinationSourceTransfer("coordination.source.project", projectCoordinationSource))], diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index 27286b396d..fdfbf4db51 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -197,6 +197,9 @@ function reusableFirstReadFields(context: JsonObject, exactBody?: ReusableExactB } if (source?.kind === "agent_preferences") return [{path, freshKeys: ["ok", "revision", "instruction"], minimumBytes: MIN_REUSABLE_BODY_BYTES}]; + if (source?.kind === "decision_context" && content.ok === true && content.status === "read" + && typeof jsonObject(content.current)?.instructions === "string") + return [{path: [...path, "current", "instructions"], freshKeys: [], minimumBytes: MIN_REUSABLE_BODY_BYTES}]; if (source?.source !== "goal_acceptance") return []; const outcomesPath = [...path, "goal_acceptance_contract", "outcome_requirements", "outcomes"]; const outcomes = at(context, outcomesPath); diff --git a/tests/capabilities/test_decision_context_turn_hook.py b/tests/capabilities/test_decision_context_turn_hook.py new file mode 100644 index 0000000000..0c19966bba --- /dev/null +++ b/tests/capabilities/test_decision_context_turn_hook.py @@ -0,0 +1,551 @@ +"""Tests for opt-in Decision Context turn-start hook binding and isolation.""" + +from __future__ import annotations + +import json +from pathlib import Path +import subprocess +import sys + +import pytest + +from loopx.capabilities.decision_context.turn_start_hook import ( + DECISION_CONTEXT_TURN_HOOK_ID, + extend_turn_start_dispatch, + read_decision_context_turn_context, +) + + +def _run_cli(*args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, "-m", "loopx.cli", *args], + capture_output=True, + text=True, + check=False, + ) + + +def _setup_goal_fixture( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch | None = None, + provider: str = "file", +) -> tuple[Path, Path, Path, Path]: + from tests.control_plane.canonical_authority_fixture import ( + initialize_canonical_authority, + isolate_sqlite_runtime, + ) + from loopx.control_plane.coordination.runtime_shadow import ( + build_todo_runtime_shadow_projection, + ) + from loopx.control_plane.todos.active_state_todo_parser import ( + parse_active_state_todos, + ) + + if provider == "sqlite" and monkeypatch is not None: + isolate_sqlite_runtime(tmp_path, monkeypatch) + + repo = tmp_path / "repo" + state_dir = repo / ".loopx" / "goals" / "ops-goal" + state_dir.mkdir(parents=True) + state_file = state_dir / "ACTIVE_GOAL_STATE.md" + state_file.write_text( + "# Goal State\n\n" + "## Objective\n\nVerify Decision Context turn-start hook delivery.\n\n" + "## Next Action\n\n- Verify bounded source freshness.\n\n" + "## Agent Todo\n\n" + "- [ ] [P1] Verify bounded source freshness.\n" + " \n\n" + "## User Todo\n", + encoding="utf-8", + ) + runtime_root = tmp_path / "runtime" + runtime_root.mkdir() + registry_path = repo / ".loopx" / "registry.json" + goal = { + "id": "ops-goal", + "display_name": "Ops Goal", + "domain": "project-goal-control-plane", + "status": "active-read-only", + "repo": str(repo), + "state_file": ".loopx/goals/ops-goal/ACTIVE_GOAL_STATE.md", + "adapter": { + "kind": "read_only_project_map_v0", + "status": "connected-read-only", + }, + "coordination": { + "registered_agents": ["operations", "reviewer"], + "agent_model": "peer_v1", + }, + "authority_sources": [], + "quota": { + "compute": 1.0, + "window_hours": 24, + "allowed_slots": 2, + }, + } + registry = { + "schema_version": "0.1", + "common_runtime_root": str(runtime_root), + "goals": [goal], + } + registry_path.write_text(json.dumps(registry, indent=2), encoding="utf-8") + fields = parse_active_state_todos( + state_file.read_text(encoding="utf-8"), goal=goal, item_limit=None + ) + projection = build_todo_runtime_shadow_projection( + goal_id="ops-goal", + todos=fields["agent_todos"]["items"] + + fields.get("user_todos", {}).get("items", []), + handoff_mode="soft_claim", + ) + initialize_canonical_authority( + runtime_root, + "ops-goal", + projection, + state_path=state_file, + provider=provider, + ) + + private_dir = tmp_path / "private-secrets" + private_dir.mkdir(mode=0o700) + authority_doc = private_dir / "SECRET_CONTEXT.md" + authority_doc.write_text( + "TOP_SECRET_BODY_DO_NOT_LEAK_12345\nUpdated priority fact.\n", + encoding="utf-8", + ) + profile_path = private_dir / "ops-profile.json" + profile_payload = { + "schema_version": "decision_context_profile_v0", + "goal_id": "ops-goal", + "enabled": True, + "enabled_agents": ["operations"], + "source_provider_bindings": [ + { + "provider_id": "local-authorities", + "adapter": "local-file", + "config": {"max_bytes": 65536}, + } + ], + "sources": [ + { + "source_id": "ops:primary-context", + "provider_id": "local-authorities", + "source_kind": "document", + "priority": "p0", + "evidence_level": "s1", + "objectives": ["editorial_alignment"], + "scan_mode": "incremental", + "exact_read_policy": "always", + "freshness_seconds": 86400, + "private_locator": str(authority_doc), + "max_changes": 1, + "enabled": True, + } + ], + "context_provider": None, + "automation": {"automatic_capture": False, "fail_open": True}, + } + profile_path.write_text(json.dumps(profile_payload, indent=2), encoding="utf-8") + return registry_path, runtime_root, profile_path, authority_doc + + +def test_default_off_parity_when_unbound(tmp_path: Path) -> None: + registry_path, runtime_root, _profile_path, _doc = _setup_goal_fixture(tmp_path) + + initial_dispatch: dict[str, object] = {"registered_count": 0, "invoked_count": 0} + unchanged = extend_turn_start_dispatch( + initial_dispatch, + runtime_root=runtime_root, + registry_path=registry_path, + goal_id="ops-goal", + agent_id="operations", + ) + assert unchanged == initial_dispatch + assert not (runtime_root / "decision-context").exists() + + inspect = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "inspect-profile", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--format", + "json", + ) + assert inspect.returncode == 0, inspect.stderr + payload = json.loads(inspect.stdout) + assert payload["status"] == "disabled" + assert payload["profile_configured"] is False + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_bind_turn_hook_delivers_redacted_view_and_isolates_other_agents( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + registry_path, runtime_root, profile_path, authority_doc = _setup_goal_fixture( + tmp_path, + monkeypatch=monkeypatch, + provider=provider, + ) + + bind = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "bind", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--profile", + str(profile_path), + "--mode", + "prepare_evidence", + "--expected-revision", + "none", + "--operation-id", + "bind-ops-1", + "--execute", + "--format", + "json", + ) + assert bind.returncode == 0, bind.stderr + bind_payload = json.loads(bind.stdout) + assert bind_payload["ok"] is True + assert bind_payload["status"] == "applied" + assert str(profile_path) not in bind.stdout + assert "private-secrets" not in bind.stdout + + # Bound CLI subcommands resolve the private profile without --profile on argv. + manifest = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "source-manifest", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--format", + "json", + ) + assert manifest.returncode == 0, manifest.stderr + manifest_payload = json.loads(manifest.stdout) + assert manifest_payload["available"] is True + assert manifest_payload["source_manifest"]["source_count"] == 1 + assert "private-secrets" not in manifest.stdout + + prepare = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "prepare-evidence", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--decision-id", + "check-bound-prepare", + "--format", + "json", + ) + assert prepare.returncode == 0, prepare.stderr + prepare_payload = json.loads(prepare.stdout) + assert prepare_payload["available"] is True + assert prepare_payload["cursor_state_mutated"] is False + assert "TOP_SECRET_BODY_DO_NOT_LEAK_12345" not in prepare.stdout + assert str(authority_doc) not in prepare.stdout + + # Turn-start dispatch observes changed source for operations, without leaking paths or bodies. + dispatched = extend_turn_start_dispatch( + {}, + runtime_root=runtime_root, + registry_path=registry_path, + goal_id="ops-goal", + agent_id="operations", + ) + assert dispatched is not None + assert dispatched["invoked_count"] == 1 + hook_result = dispatched["results"][0] + assert hook_result["hook_id"] == DECISION_CONTEXT_TURN_HOOK_ID + assert hook_result["status"] == "observed" + assert hook_result["local_private_state_mutated"] is False + assert hook_result["private_content_returned"] is False + assert len(dispatched["contexts"]) == 1 + context_view = dispatched["contexts"][0]["content"] + assert context_view["ok"] is True + obs = context_view["current"]["observation"] + assert obs["changed_source_ids"] == ["ops:primary-context"] + assert obs["p0_complete"] is True + serialized = json.dumps(dispatched) + assert "TOP_SECRET_BODY_DO_NOT_LEAK_12345" not in serialized + assert "private-secrets" not in serialized + + # Other registered agents on the same Goal remain completely untouched. + other_agent_dispatch = extend_turn_start_dispatch( + {"registered_count": 0, "invoked_count": 0}, + runtime_root=runtime_root, + registry_path=registry_path, + goal_id="ops-goal", + agent_id="reviewer", + ) + assert other_agent_dispatch == {"registered_count": 0, "invoked_count": 0} + + # Real quota should-run --dry-run delivers decision_context inline in work_context.sources. + should_run = _run_cli( + "--format", + "json", + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "quota", + "should-run", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--dry-run", + "--context-delivery", + "off", + ) + assert should_run.returncode == 0, should_run.stderr + sr_payload = json.loads(should_run.stdout) + sources = ( + sr_payload["interaction_contract"]["agent_channel"]["work_context"].get( + "sources" + ) + or [] + ) + dc_sources = [s for s in sources if s.get("kind") == "decision_context"] + assert len(dc_sources) == 1 + assert ( + dc_sources[0]["content"]["current"]["observation"]["changed_source_ids"] + == ["ops:primary-context"] + ) + assert "TOP_SECRET_BODY_DO_NOT_LEAK_12345" not in should_run.stdout + assert "private-secrets" not in should_run.stdout + + +def test_missing_bound_profile_surfaces_unavailable_without_crashing_turn( + tmp_path: Path, +) -> None: + registry_path, runtime_root, profile_path, _doc = _setup_goal_fixture(tmp_path) + + bind = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "bind", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--profile", + str(profile_path), + "--expected-revision", + "none", + "--operation-id", + "bind-ops-missing-test", + "--execute", + "--format", + "json", + ) + assert bind.returncode == 0, bind.stderr + revision = json.loads(bind.stdout)["current"]["revision"] + + # Remove the profile file after binding to simulate unavailable private storage. + profile_path.unlink() + + turn_view = read_decision_context_turn_context( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id="ops-goal", + agent_id="operations", + ) + assert turn_view["ok"] is False + assert turn_view["status"] == "unavailable" + + dispatched = extend_turn_start_dispatch( + {}, + runtime_root=runtime_root, + registry_path=registry_path, + goal_id="ops-goal", + agent_id="operations", + ) + assert dispatched is not None + assert dispatched["results"][0]["status"] == "unavailable" + assert dispatched["results"][0]["agent_read_required"] is False + assert dispatched["required_reads"] == [] + + # Unbind recovers cleanly even while the old profile path is gone. + unbind = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "unbind", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--expected-revision", + revision, + "--operation-id", + "unbind-ops-missing-test", + "--execute", + "--format", + "json", + ) + assert unbind.returncode == 0, unbind.stderr + assert json.loads(unbind.stdout)["current"]["binding"]["state"] == "retired" + + +def test_bind_rejects_disabled_or_mismatched_agent_profile(tmp_path: Path) -> None: + registry_path, runtime_root, profile_path, _doc = _setup_goal_fixture(tmp_path) + + rejected = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "bind", + "--goal-id", + "ops-goal", + "--agent-id", + "reviewer", + "--profile", + str(profile_path), + "--expected-revision", + "none", + "--operation-id", + "bind-wrong-agent", + "--execute", + "--format", + "json", + ) + assert rejected.returncode == 2 + payload = json.loads(rejected.stdout) + assert payload["ok"] is False + assert "agent_not_enabled" in payload["error"] + + +def test_turn_context_re_reads_when_binding_revision_changes_mid_observation( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + import loopx.capabilities.decision_context.turn_start_hook as hook_mod + + registry_path, runtime_root, profile_a, _doc_a = _setup_goal_fixture(tmp_path) + doc_b = profile_a.parent / "owner-b.md" + doc_b.write_text("# Profile B Fresh Fact\n", encoding="utf-8") + profile_b = profile_a.parent / "profile-b.json" + profile_b_data = json.loads(profile_a.read_text(encoding="utf-8")) + source_b = dict(profile_b_data["sources"][0]) + source_b["source_id"] = "ops:doc-b-only" + source_b["private_locator"] = str(doc_b) + profile_b_data["sources"] = [source_b] + profile_b.write_text(json.dumps(profile_b_data, indent=2), encoding="utf-8") + + bind_a = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "bind", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--profile", + str(profile_a), + "--expected-revision", + "none", + "--operation-id", + "bind-profile-a", + "--execute", + "--format", + "json", + ) + assert bind_a.returncode == 0, bind_a.stderr + rev_a = json.loads(bind_a.stdout)["current"]["revision"] + ref_a = json.loads(bind_a.stdout)["current"]["binding"]["profile_ref"] + + real_collect = hook_mod._collect_public_safe_observation + swapped = False + rev_b_holder: dict[str, str] = {} + + def collect_with_concurrent_rebind(**kwargs: object) -> dict[str, object]: + nonlocal swapped + obs = real_collect(**kwargs) # type: ignore[arg-type] + if not swapped: + swapped = True + rebind = _run_cli( + "--registry", + str(registry_path), + "--runtime-root", + str(runtime_root), + "decision-context", + "hook", + "bind", + "--goal-id", + "ops-goal", + "--agent-id", + "operations", + "--profile", + str(profile_b), + "--expected-revision", + rev_a, + "--operation-id", + "rebind-profile-b-mid-flight", + "--execute", + "--format", + "json", + ) + assert rebind.returncode == 0, rebind.stderr + rebind_payload = json.loads(rebind.stdout) + rev_b_holder["revision"] = rebind_payload["current"]["revision"] + rev_b_holder["profile_ref"] = rebind_payload["current"]["binding"]["profile_ref"] + return obs + + monkeypatch.setattr(hook_mod, "_collect_public_safe_observation", collect_with_concurrent_rebind) + + turn_view = read_decision_context_turn_context( + registry_path=registry_path, + runtime_root=runtime_root, + goal_id="ops-goal", + agent_id="operations", + ) + assert swapped is True + assert turn_view["ok"] is True + assert turn_view["current"]["revision"] == rev_b_holder["revision"] + assert turn_view["current"]["binding"]["profile_ref"] == rev_b_holder["profile_ref"] + assert turn_view["current"]["binding"]["profile_ref"] != ref_a + # Must reflect profile B's source ("ops:doc-b-only"), NOT profile A's sources! + assert turn_view["current"]["observation"]["changed_source_ids"] == ["ops:doc-b-only"] + assert turn_view["current"]["observation"]["uncovered_p0_source_ids"] == [] + assert turn_view["current"]["observation"]["p0_complete"] is True diff --git a/tests/control_plane_ts/decision_context_hook.test.ts b/tests/control_plane_ts/decision_context_hook.test.ts new file mode 100644 index 0000000000..284cbf6a6d --- /dev/null +++ b/tests/control_plane_ts/decision_context_hook.test.ts @@ -0,0 +1,316 @@ +import assert from "node:assert/strict"; +import {mkdtempSync, rmSync} from "node:fs"; +import {tmpdir} from "node:os"; +import {join} from "node:path"; +import test from "node:test"; +import { + DECISION_CONTEXT_HOOK_REQUEST_SCHEMA, + DECISION_CONTEXT_HOOK_VIEW_SCHEMA, + decisionContextReusableContextPaths, + executeDecisionContextHook, +} from "../../loopx/control_plane/capabilities/decision_context_hook.ts"; +import {reusableTurnContext} from "../../loopx/control_plane/capability_hooks.ts"; +import {FileAuthorityStore} from "../../loopx/control_plane/coordination/file_authority_store.ts"; +import {SqliteAuthorityStore} from "../../loopx/control_plane/coordination/sqlite_authority_store.ts"; +import type {AuthorityStore} from "../../loopx/control_plane/coordination/authority_store.ts"; +import type {JsonObject} from "../../loopx/control_plane/effect_program.ts"; + +function baseRequest(overrides: JsonObject = {}): JsonObject { + return { + schema_version: DECISION_CONTEXT_HOOK_REQUEST_SCHEMA, + goal_state_ref: "/workspace/goal/ACTIVE_GOAL_STATE.md", + goal_instance_id: "goal-inst-1", + goal_id: "personal-ops", + agent_id: "operations", + registered_agents: ["operations", "reviewer"], + runtime_root: "/workspace/runtime", + action: "read", + ...overrides, + }; +} + +for (const [label, createStore] of [ + [ + "FileAuthorityStore", + (dir: string): AuthorityStore => new FileAuthorityStore(join(dir, "file"), "binding"), + ], + [ + "SqliteAuthorityStore", + (dir: string): AuthorityStore => new SqliteAuthorityStore(join(dir, "sqlite"), "binding"), + ], +] as const) { + test(`decision-context hook lifecycle, CAS, replay and redaction (${label})`, async () => { + const dir = mkdtempSync(join(tmpdir(), "dc-hook-ts-")); + try { + const store = createStore(dir); + const now = "2026-11-26T15:00:00Z"; + + const initialObserve = await executeDecisionContextHook( + baseRequest({action: "observe"}), + store, + now, + ); + assert.deepEqual(initialObserve, { + ok: true, + status: "absent", + binding_state: "unconfigured", + observation_count: 0, + }); + + const preview = await executeDecisionContextHook( + baseRequest({ + action: "bind", + expected_revision: null, + operation_id: "op-bind-1", + source_kind: "operator_configuration", + profile_path: "/private/secret/ops-profile.json", + cursor_state_path: "/private/secret/cursors.json", + mode: "prepare_evidence", + execute: false, + }), + store, + now, + ); + assert.equal(preview.ok, true); + assert.equal(preview.status, "preview"); + assert.equal(JSON.stringify(preview).includes("/private/secret"), false); + + const applied = await executeDecisionContextHook( + baseRequest({ + action: "bind", + expected_revision: null, + operation_id: "op-bind-1", + source_kind: "operator_configuration", + profile_path: "/private/secret/ops-profile.json", + cursor_state_path: "/private/secret/cursors.json", + mode: "prepare_evidence", + execute: true, + }), + store, + now, + ); + assert.equal(applied.ok, true); + assert.equal(applied.status, "applied"); + assert.equal(JSON.stringify(applied).includes("/private/secret"), false); + const current1 = applied.current as JsonObject; + const rev1 = String(current1.revision); + assert.ok(rev1.length > 0); + + // Idempotent replay with same operation_id returns replayed + fresh state. + const replayed = await executeDecisionContextHook( + baseRequest({ + action: "bind", + expected_revision: null, + operation_id: "op-bind-1", + source_kind: "operator_configuration", + profile_path: "/private/secret/ops-profile.json", + cursor_state_path: "/private/secret/cursors.json", + mode: "prepare_evidence", + execute: true, + }), + store, + now, + ); + assert.equal(replayed.ok, true); + assert.equal(replayed.status, "replayed"); + + // Conflicting intent under same operation_id fails closed. + const conflict = await executeDecisionContextHook( + baseRequest({ + action: "bind", + expected_revision: null, + operation_id: "op-bind-1", + source_kind: "operator_configuration", + profile_path: "/private/secret/other-profile.json", + mode: "prepare_evidence", + execute: true, + }), + store, + now, + ); + assert.equal(conflict.ok, false); + assert.equal(conflict.status, "operation_conflict"); + + // Trusted resolve_local returns locators; public read & history never do. + const localResolved = await executeDecisionContextHook( + baseRequest({action: "resolve_local"}), + store, + now, + ); + assert.equal( + (localResolved.local_binding as JsonObject).profile_path, + "/private/secret/ops-profile.json", + ); + + const projected = await executeDecisionContextHook( + baseRequest({ + action: "project_turn_view", + expected_revision: rev1, + observation: { + status: "available", + observed_at: "2026-11-26T15:05:00Z", + source_count: 4, + enabled_source_count: 4, + changed_source_ids: ["ops:board", "ops:lark-small"], + failed_source_ids: [], + alerted_source_ids: ["ops:lark-small"], + uncovered_p0_source_ids: [], + p0_complete: true, + freshness_counts: {fresh: 3, stale: 1, never_read: 0, not_scanned: 0}, + advisory_recall_status: "completed", + capture_pending_batch_count: null, + raw_content_captured: false, + private_locator_captured: false, + }, + commands: { + turn_context: + "loopx decision-context hook turn-context --goal-id personal-ops --agent-id operations --format json", + prepare_evidence: + "loopx decision-context prepare-evidence --decision-id turn-rebase --goal-id personal-ops --agent-id operations --format json", + }, + }), + store, + now, + ); + assert.equal(projected.ok, true); + assert.equal(projected.status, "read"); + assert.equal(projected.observation_count, 4); + assert.equal(JSON.stringify(projected).includes("/private/secret"), false); + + // Reusable turn context exposes only static instructions, keeping live observation fresh. + assert.deepEqual(decisionContextReusableContextPaths(projected), [ + ["current", "instructions"], + ]); + const reusable = reusableTurnContext( + { + source: "turn_start_capability_hook", + hook_id: "decision_context.turn_context", + capability_id: "decision-context", + kind: "decision_context", + content: projected, + }, + {goal_id: "personal-ops", agent_id: "operations"}, + ); + assert.deepEqual(reusable, { + identity: [ + "turn_start_capability_hook", + "decision_context.turn_context", + "decision-context", + "personal-ops", + "operations", + null, + ], + paths: [["current", "instructions"]], + }); + assert.equal( + reusableTurnContext( + { + source: "turn_start_capability_hook", + hook_id: "decision_context.turn_context", + capability_id: "decision-context", + kind: "decision_context", + content: projected, + }, + {goal_id: "personal-ops", agent_id: "reviewer"}, + ), + null, + ); + + // Private-key smuggling inside observation fails closed. + await assert.rejects(() => + executeDecisionContextHook( + baseRequest({ + action: "project_turn_view", + expected_revision: rev1, + observation: { + status: "available", + observed_at: "2026-11-26T15:05:00Z", + source_count: 1, + enabled_source_count: 1, + p0_complete: true, + private_locator: "/private/secret/leak.md", + }, + commands: {}, + }), + store, + now, + ), + ); + + // Unbind retires binding, clears private locators, and keeps observation_count=1 to invalidate cache. + const unbound = await executeDecisionContextHook( + baseRequest({ + action: "unbind", + expected_revision: rev1, + operation_id: "op-unbind-1", + source_kind: "operator_configuration", + execute: true, + }), + store, + "2026-11-26T15:10:00Z", + ); + assert.equal(unbound.ok, true); + assert.equal(unbound.status, "applied"); + const rev2 = String((unbound.current as JsonObject).revision); + + // Stale observation collected under rev1 is rejected rather than projected onto rev2. + const staleProjection = await executeDecisionContextHook( + baseRequest({ + action: "project_turn_view", + expected_revision: rev1, + observation: { + status: "available", + observed_at: "2026-11-26T15:09:59Z", + source_count: 1, + enabled_source_count: 1, + p0_complete: false, + uncovered_p0_source_ids: ["ops:stale-a"], + }, + commands: {}, + }), + store, + "2026-11-26T15:10:00Z", + ); + assert.equal(staleProjection.ok, false); + assert.equal(staleProjection.status, "revision_conflict"); + assert.equal(staleProjection.error, "observed_binding_revision_mismatch"); + + const retiredLocal = await executeDecisionContextHook( + baseRequest({action: "resolve_local"}), + store, + "2026-11-26T15:10:00Z", + ); + assert.equal(retiredLocal.local_binding, null); + const retiredTurn = await executeDecisionContextHook( + baseRequest({ + action: "project_turn_view", + expected_revision: rev2, + commands: {}, + }), + store, + "2026-11-26T15:10:00Z", + ); + assert.equal(retiredTurn.ok, true); + assert.equal(retiredTurn.observation_count, 1); + assert.equal( + ((retiredTurn.current as JsonObject).observation as JsonObject).status, + "retired", + ); + + const history = await executeDecisionContextHook( + baseRequest({action: "history"}), + store, + "2026-11-26T15:10:00Z", + ); + assert.equal(history.ok, true); + assert.equal((history.events as unknown[]).length, 2); + assert.equal(JSON.stringify(history).includes("/private/secret"), false); + assert.equal( + ((history.current as JsonObject).schema_version), + DECISION_CONTEXT_HOOK_VIEW_SCHEMA, + ); + } finally { + rmSync(dir, {recursive: true, force: true}); + } + }); +}