From ae819b5321c380f688589b7118928c4dbdf91e38 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:07:57 +0800 Subject: [PATCH 1/2] feat(control-plane,rfc): add L0 session & quota fabric contract for single-workbench convergence Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/architecture/rfcs/README.md | 11 + docs/architecture/rfcs/STATUS.md | 3 +- docs/architecture/rfcs/STATUS.zh-CN.md | 3 +- .../rfcs/session-and-quota-fabric-v0.md | 217 ++++++++++++ .../rfcs/session-and-quota-fabric-v0.zh-CN.md | 135 +++++++ .../collaboration/session_quota_fabric.ts | 335 ++++++++++++++++++ .../session_quota_fabric.test.ts | 208 +++++++++++ 7 files changed, 910 insertions(+), 2 deletions(-) create mode 100644 docs/architecture/rfcs/session-and-quota-fabric-v0.md create mode 100644 docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md create mode 100644 loopx/control_plane/collaboration/session_quota_fabric.ts create mode 100644 tests/control_plane_ts/session_quota_fabric.test.ts diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md index 34dc50e1dd..c13bfa3ea2 100644 --- a/docs/architecture/rfcs/README.md +++ b/docs/architecture/rfcs/README.md @@ -496,6 +496,17 @@ Paired diffs do not certify translation accuracy. the Desktop frontends RFC, local service lifecycle with the daemon RFC, and continuation with the manager RFC. Optional preview hosts, session rotation, and host promotion remain unapproved. +- [Session and Quota Fabric for Single-Workbench Convergence v0](session-and-quota-fabric-v0.md) + ([中文版](session-and-quota-fabric-v0.zh-CN.md)) + - **Delivery on `main`:** Partial; typed L0 codecs, additive + `ssh_host_catalog_v0` readiness projection, and Turn/lease-fenced handover + guards (`loopx/control_plane/collaboration/session_quota_fabric.ts`) ship on + this baseline while downstream UI/daemon convergence milestones remain + staged. + - **Current boundary:** Extracts SSH host observation and quota-aware handover + from Calli/LooChat proposals into an optional L0 contract converging into + the single Goal Workbench (`apps/presentation/dashboard`) instead of a second + frontend shell or parallel Task authority. - [Goal Channel Collaboration v0](goal-channel-collaboration-v0.md) ([中文版](goal-channel-collaboration-v0.zh-CN.md)) - **Delivery on `main`:** Lark vertical implemented. diff --git a/docs/architecture/rfcs/STATUS.md b/docs/architecture/rfcs/STATUS.md index f3409dcff3..f5ac8630de 100644 --- a/docs/architecture/rfcs/STATUS.md +++ b/docs/architecture/rfcs/STATUS.md @@ -18,7 +18,7 @@ appendix may keep dated history, but no dated log heading may precede it. [中文版](STATUS.zh-CN.md) is the semantic mirror of this file. -## Accepted (52) +## Accepted (53) | RFC | Header status | Supersedes / closes | Ledger | | --- | --- | --- | --- | @@ -69,6 +69,7 @@ appendix may keep dated history, but no dated log heading may precede it. | [RFC: Research Exploration Control Plane v0](research-exploration-control-plane-v0.md) | Accepted | none | — | | [Preserve the selected runtime during rollback](self-update-explicit-runtime-route-v0.md) | Accepted | none | — | | [RFC: Semantic Vocabulary Convergence and Commit-Time Drift Checks (v0)](semantic-vocabulary-convergence-v0.md) | Accepted | none | [7 entries](ledger/semantic-vocabulary-convergence-v0/) | +| [RFC: Session and Quota Fabric for Single-Workbench Convergence (v0)](session-and-quota-fabric-v0.md) | Accepted | none | — | | [RFC: Shared Goal Alignment and Governed Amendment Protocol (v0)](shared-goal-alignment-and-governed-amendment-v0.md) | Accepted | none | [2 entries](ledger/shared-goal-alignment-and-governed-amendment-v0/) | | [RFC: LoopX Shared Control-Plane Authority and Pluggable State Providers (v0)](shared-goal-authority-state-provider-v0.md) | Accepted | none | [24 entries](ledger/shared-goal-authority-state-provider-v0/) | | [RFC: Single-Owner Local Daemon (v0)](single-owner-local-daemon-v0.md) | Accepted | none | — | diff --git a/docs/architecture/rfcs/STATUS.zh-CN.md b/docs/architecture/rfcs/STATUS.zh-CN.md index cd61d9c972..14742147ce 100644 --- a/docs/architecture/rfcs/STATUS.zh-CN.md +++ b/docs/architecture/rfcs/STATUS.zh-CN.md @@ -15,7 +15,7 @@ [English](STATUS.md) 与本文互为语义镜像。 -## 已接受 (52) +## 已接受 (53) | RFC | 头部状态 | 替代 / 关闭 | Ledger | | --- | --- | --- | --- | @@ -66,6 +66,7 @@ | [RFC:研究型探索控制面 v0](research-exploration-control-plane-v0.zh-CN.md) | 已接受 | 无 | — | | [回滚全程保留所选运行目录](self-update-explicit-runtime-route-v0.zh-CN.md) | 已接受 | 无 | — | | [RFC:语义词表收敛与提交期漂移检查(v0)](semantic-vocabulary-convergence-v0.zh-CN.md) | 已接受 | 无 | [7 条](ledger/semantic-vocabulary-convergence-v0/) | +| [RFC:面向单一工作台收敛的 L0 会话与额度底座(v0)](session-and-quota-fabric-v0.zh-CN.md) | 已接受 | 无 | — | | [RFC:共享 Goal 对齐与受治理 Amendment 协议(v0)](shared-goal-alignment-and-governed-amendment-v0.zh-CN.md) | 已接受 | 无 | [2 条](ledger/shared-goal-alignment-and-governed-amendment-v0/) | | [RFC:LoopX 共享控制面权威与可插拔状态 Provider(v0)](shared-goal-authority-state-provider-v0.zh-CN.md) | 已接受 | 无 | [24 条](ledger/shared-goal-authority-state-provider-v0/) | | [RFC: Single-Owner Local Daemon (v0)](single-owner-local-daemon-v0.md) | 已接受 | none | — | diff --git a/docs/architecture/rfcs/session-and-quota-fabric-v0.md b/docs/architecture/rfcs/session-and-quota-fabric-v0.md new file mode 100644 index 0000000000..781e0076a8 --- /dev/null +++ b/docs/architecture/rfcs/session-and-quota-fabric-v0.md @@ -0,0 +1,217 @@ +# RFC: Session and Quota Fabric for Single-Workbench Convergence (v0) + +- **RFC status:** Accepted +- **Supersedes / closes:** none +- **Delivery maturity:** Partial. The additive L0 codecs and handover guard (`session_quota_fabric.ts`) ship on this baseline; host runtime adapters and dashboard UI composition remain staged follow-on slices. +- **Authors / owners:** Architecture convergence workgroup; control-plane ownership, package boundaries, and merge authorization belong to LoopX maintainers +- **Created:** 2026-11-17 +- **Last normative revision:** 2026-11-17 +- **Implementation baseline:** `31944d8354` +- **Related contracts:** + [Agent session execution modes](agent-session-execution-modes-v0.md), + [Desktop execution frontends](desktop-execution-frontends-v0.md), + [Single-owner local daemon](single-owner-local-daemon-v0.md), + [Monorepo distribution split](monorepo-distribution-split-v0.md), + [Overall roadmap](loopx-overall-roadmap-v0.md), + [Status data contract](../../status-data-contract.md), + [Compute quota](../../quota-allocation.md), + [Design system](../../development/design.md) +- **Language mirror:** [中文版](session-and-quota-fabric-v0.zh-CN.md) + +## Document map and maintenance contract + +Sections 1–10 define the durable design and acceptance contract. Section 11 +defines the normative delivery plan. Section 12 records open decisions where +recommendations are non-binding until accepted by maintainers. No dated log +headings appear above appendices; historical checkpoints belong in +[`ledger/`](ledger/README.md). This English specification and its +[Chinese mirror](./session-and-quota-fabric-v0.zh-CN.md) are semantic mirrors and stay synchronized for +all normative rules. + +--- + +## 1. Decision summary + +1. **What becomes authoritative or changes.** LoopX extracts multi-host SSH + readiness (`session_fabric_ssh_observation_v0`), opaque-profile quota-window + observations (`session_quota_window_observation_v0`), and fence-bound handover + evaluation (`governed_session_handover_proposal_v0`) into a standalone L0 + control-plane contract implemented in + [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts), + independently deliverable without waiting for a new frontend shell. +2. **What stays unchanged.** `loopx-core` remains the sole writer of Goal, Todo, + claim, lease, quota, Turn, and Gate state; `ssh_host_catalog_v0` remains the + authoritative SSH alias catalog; the single Goal Workbench in + `apps/presentation/dashboard` remains the official presentation entry point. +3. **Default and opt-in boundary.** Feature-off behavior is byte-for-byte + identical to baseline: when L0 observations are absent, + `ssh_host_catalog_v0` emits `{ alias }` entries only, and governed handover + never executes without explicit Turn/lease fencing or (when enabled) shared + Gate confirmation. +4. **Principal safety and UI convergence constraint.** No 40k–192k LOC second + frontend application (`apps/presentation/calli-workbench/`, `apps/workbench/`) + or duplicated task/daemon authority is introduced. Session, host, quota, and + triage surfaces embed directly into the existing Goal Workbench views. +5. **What this RFC does not approve.** Automatic credential migration, silent + `attached_host` <-> `managed_runtime` mode switching, parallel Node Todo + daemons, or automatic quota spend on failed/unknown windows remain rejected. + +## 2. Problem and motivation + +Multi-host, multi-CLI workbench proposals (#8778, #8782–#8784, #8843) demonstrated +strong demand for unifying local and SSH-remote agent sessions alongside quota-aware +profile switching. However, shipping that capability via a standalone 40k–192k LOC +frontend and parallel Node daemon (`apps/presentation/calli-workbench/` in +#8783/#8784; `apps/workbench/` across 881 files in #8843) fragments the product: + +- Users are forced between the official Goal Workbench (`apps/presentation/dashboard`) + and a second unrelated shell with separate proxy paths, CSS tokens, and routes. +- Existing baseline seams — `configured_ssh_host_aliases` (`ssh_host_catalog_v0`), + `/api/chat/codex-attached`, and `GoalAgentWorkPage` — are duplicated instead + of extended. +- Daemon-local state stores (`todos`, schedules, revert handlers) race with Core's + single-owner lease and Turn fencing guarantees. + +Decomposing L0 host/session/quota primitives away from frontend chrome lets LoopX +land the real substrate gaps first and embed the UI cleanly inside the existing +single Goal Workbench. + +### Invariants + +- **I1 Single host and work authority.** Goal/Todo/lease/Gate state stays owned + by `loopx-core`; SSH host identity stays owned by `ssh_host_catalog_v0`. L0 + observations targeting aliases absent from `ssh_host_catalog_v0` fail closed. +- **I2 Opaque quota privacy boundary.** Quota observations carry opaque + `profile_id` tokens, never emails, secrets, bearer tokens, or home paths. +- **I3 Shared Gate confirmation.** When `ask_before_switch=true`, handover resolves + to `user_gate_required` on the existing Inbox/Gate projection rather than a + custom modal authority. +- **I4 Turn and lease fencing across handover.** Handover cannot implicitly flip + `attached_host` <-> `managed_runtime` modes and remains `await_turn_fence` + until both `current_turn_fenced=true` and `previous_lease_released=true`. +- **I5 Feature-off parity.** Absent L0 observations yield byte-identical + `ssh_host_catalog_v0` output; `"unknown"` quota availability never triggers + handover (`no_handover_needed`). + +## 3. Scope and non-goals + +### In scope + +- Typed TypeScript L0 codecs and evaluators for additive SSH readiness + observations (`session_fabric_ssh_observation_v0`), opaque quota windows + (`session_quota_window_observation_v0`), and fenced handover proposals + (`governed_session_handover_proposal_v0`) in `loopx/control_plane/collaboration/session_quota_fabric.ts`. +- Architectural convergence rules embedding multi-host, session, and triage + surfaces into `apps/presentation/dashboard` instead of adding a second app. + +### Non-goals + +- Importing a standalone `apps/workbench/` or `apps/presentation/calli-workbench/` + package, Node SQLite daemon, or browser build toolchain. +- Bypassing `loopx/presentation/codex_attached_api.py` ownership boundaries or + shipping concrete OpenSSH child-process supervisors inside this RFC slice. + +## 4. Current-system contract (baseline `31944d8354`) + +- **SSH catalog:** [`ssh_host_catalog.py`](../../../loopx/control_plane/status/ssh_host_catalog.py) + serves `/ssh-hosts` with `{ ok: true, schema_version: "ssh_host_catalog_v0", hosts: [{ alias }] }`. +- **Dashboard SSH client:** [`ssh-host-catalog.ts`](../../../apps/presentation/dashboard/src/data/ssh-host-catalog.ts) + already parses `ssh_host_catalog_v0` and invokes `/api/ssh-source/ensure` and + `/api/ssh-source/goal-lifecycle`. +- **Attached sessions & Goal UI:** + [`codex_attached_api.py`](../../../loopx/presentation/codex_attached_api.py) + currently filters `row["host_surface"] == "codex-app"` in `bound_conversations()`, + while [`attached-agent-conversations.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx) + and [`goal-agent-work-page.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx) + render bound attached and managed conversations inside one Goal view. +- **L0 contract module (delivered in this baseline):** + [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts) + provides zero-I/O validated projections and handover state transitions. + +## 5. Proposed architecture + +### Ownership and authority + +| Layer | Owner | Contract / Surface | +| --- | --- | --- | +| L0 SSH & quota observation | Optional host provider implementing `session_quota_fabric.ts` | Emits `session_fabric_ssh_observation_v0` & `session_quota_window_observation_v0` | +| L1 Work, quota & handover fence | `loopx-core` (`control_plane/collaboration/`, `quota/`) | Validates handover via `evaluateGovernedSessionHandover`, enforces lease/Turn fence | +| L1/L2 Attached API generalization | [`codex_attached_api.py`](../../../loopx/presentation/codex_attached_api.py) follow-on | Broadens `host_surface` filter by registered capability rather than hardcoding `"codex-app"` | +| L3 Single Goal Workbench | `apps/presentation/dashboard` | Embeds host selector, session timeline, quota indicator, and Gate triage drawer | + +### State model and schema + +1. `session_fabric_ssh_observation_v0`: validates `alias`, + `connection_state` (`connected | degraded | disconnected | unknown`), + `failure_code` (strictly the seven codes `no_ssh | host_key | auth | unreachable | ssh_failed | daemon_missing | forward_denied`, + required when `degraded | disconnected` and forbidden otherwise), + `checked_at`, and `tunnel_latency_ms`. `projectSshHostCatalogPayload` attaches + observations strictly to known `ssh_host_catalog_v0` aliases and leaves + un-observed hosts as bare `{ alias }`. +2. `session_quota_window_observation_v0`: validates opaque `profile_id` + (forbidding `@`, `/`, `.ssh/`, `sk-`, `ghp_`, `bearer`), `availability` + (`available | near_limit | exhausted | unknown`), `used_ratio` (`[0, 1]` or + strictly `null` when `unknown`), `resets_at`, and `eligible_models`. +3. `governed_session_handover_proposal_v0`: rejects cross-mode switches + (`from_session_mode !== to_session_mode`), rejects `from_profile_id === to_profile_id`, + returns `no_handover_needed` when `unknown` or below `threshold_ratio`, + `user_gate_required` when `ask_before_switch=true`, `await_turn_fence` when + fencing/release is incomplete, and `ready_for_lease_reacquisition` only when + all preconditions hold. + +## 6. Alternatives and design choices + +Directly answers open convergence review question D1/D2 across #8778, #8782–#8784, and #8843: + +| Option | Verdict | Architectural trade-off | +| --- | --- | --- | +| A. Ad-hoc per-CLI patches inside existing views | Rejected | Repeats SSH error handling and quota logic across dashboard hooks with no shared contract | +| B. **Independent L0 Session & Quota Fabric + single Goal Workbench embedding** | **Chosen** | Delivers validated SSH/quota/handover contracts immediately without waiting on UI overhaul; avoids duplicating app shells or daemons; keeps incremental PRs < 1k LOC | +| C. Separate 40k–192k LOC frontend/daemon (`calli-workbench` / `apps/workbench`) | Rejected | Splits navigation, styling, proxy security, and daemon ownership; duplicates existing `ssh-host-catalog.ts` and `GoalAgentWorkPage`; large review surface | + +## 7. Safety, privacy, and compatibility + +- **Default-off parity:** Absence of L0 observation payloads keeps `ssh_host_catalog_v0` + output identical to `loopx/control_plane/status/ssh_host_catalog.py`. +- **Credential & path fail-closed:** `session_quota_fabric.ts` rejects any + SSH alias or quota `profile_id` / model string carrying `/Users/`, `/home/`, + `.ssh/`, `@`, `/`, `sk-`, `ghp_`, or `bearer`. +- **Unknown availability safety:** Missing/unknown quota observations force + `handover_eligible=false` and `disposition="no_handover_needed"`. + +## 8. Migration and rollback + +Existing `apps/presentation/dashboard` workflows continue unmodified. Each L0 +slice (`session_quota_fabric.ts`, optional backend endpoints, optional dashboard +drawer panels) is purely additive and reversible via standard commit revert with +no persisted schema migration required. + +## 9. Validation and acceptance + +| Claim | Evidence / Command | Required result | Exclusions / Boundary | +| --- | --- | --- | --- | +| Bilingual & RFC index integrity | `python3 scripts/check_rfc_bilingual.py` and `python3 scripts/generate_rfc_status_index.py --check` | Exit `0` | Does not verify runtime behavior | +| L0 TS type safety & digest boundary | `npm run typecheck:control-plane` and `node --test tests/control_plane_ts/content_digest_single_owner.test.ts` | Exit `0`, all pass | Static contract check only | +| L0 codecs, feature-off parity, handover fencing & privacy fail-closed | `node --test tests/control_plane_ts/session_quota_fabric.test.ts` | All cases pass | Unit-level fixtures; live SSH tunnel process remains M1/M2 | +| Vocabulary convergence & public scan | `python3 examples/semantic-vocabulary-drift-smoke.py` and `loopx check` | `ok` | Does not cover downstream packages | + +## 10. Operational contract + +Unknown SSH or quota state never elevates privileges or triggers background +handover. Surfacing remains read-only through `ssh_host_catalog_v0` and +Goal-scoped projections; failures emit deterministic typed errors. + +## 11. Normative delivery plan + +| Milestone | Shipped behavior | Entry gate | Exit evidence | Rollback | +| --- | --- | --- | --- | --- | +| **M0 Convergence RFC + L0 Contract** | Bilingual RFC (`session-and-quota-fabric-v0`) + `session_quota_fabric.ts` + TS unit tests | Baseline `31944d8354` | `session_quota_fabric.test.ts`, `docs-governance-smoke.py`, `semantic-vocabulary-drift-smoke.py` | Revert RFC & module | +| **M1 Attached API & Host Provider** | Generalize `codex_attached_api.py` `host_surface` routing + opt-in SSH probe wiring into `ssh_host_catalog_v0` | M0 merged | Feature-off parity test + seven SSH failure-code fixture tests | Disable provider flag | +| **M2 Single Goal Workbench UI & Handover Wire-up** | Embed host readiness, quota window badge, and Gate-bound handover trigger inside `GoalAgentWorkPage` (`apps/presentation/dashboard`) | M1 merged | Playwright desktop/narrow viewport smoke + visual evidence + turn-fence handoff integration test | Revert UI panel slice | + +## 12. Open decisions + +| Id | Question | Owner | Recommendation | Dependent milestone | +| --- | --- | --- | --- | --- | +| D1 | Exact generalization list for non-Codex `host_surface` names in `codex_attached_api.py` | Maintainers | Resolve dynamically from registered `agent_capabilities` host surfaces | M1 | +| D2 | Default `ask_before_switch` policy for quota handover | Maintainers | Default `true` (`user_gate_required`) until operator explicitly opts into fenced auto-switch | M2 | diff --git a/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md b/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md new file mode 100644 index 0000000000..e10caf9ad3 --- /dev/null +++ b/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md @@ -0,0 +1,135 @@ +# RFC:面向单一工作台收敛的 L0 会话与额度底座(v0) + +- **RFC 状态:** 已接受 +- **替代 / 关闭:** 无 +- **交付成熟度:** Partial。本基线已交付增量 L0 编解码与交接守卫模块(`session_quota_fabric.ts`);宿主运行时适配器与主工作台 UI 嵌入保留为后续分阶段切片。 +- **作者 / 负责人:** 架构收敛工作组;控制面归属、包边界及合并授权归属 LoopX 维护者 +- **创建日期:** 2026-11-17 +- **最近规范性修订:** 2026-11-17 +- **实现基线:** `31944d8354` +- **相关契约:** + [Agent 会话执行模式](agent-session-execution-modes-v0.zh-CN.md)、 + [桌面执行前端](desktop-execution-frontends-v0.zh-CN.md)、 + [单属主本地守护进程](single-owner-local-daemon-v0.md)、 + [Monorepo 分发拆分](monorepo-distribution-split-v0.zh-CN.md)、 + [整体路线图](loopx-overall-roadmap-v0.zh-CN.md)、 + [状态数据契约](../../status-data-contract.md)、 + [计算额度分配](../../quota-allocation.md)、 + [设计系统](../../development/design.md) +- **语言镜像:** [English](session-and-quota-fabric-v0.md) + +## 文档地图与维护契约 + +第 1–10 节定义稳定的设计与验收契约,第 11 节定义规范性交付计划,第 12 节记录待决问题(推荐方案在获维护者批准前不具备约束力)。附录之前不允许出现带日期的交付标题;历史检查点统一记入 [`ledger/`](ledger/README.zh-CN.md)。本中文版与 [英文原版](./session-and-quota-fabric-v0.md) 针对全部规范性条款保持严格语义镜像。 + +--- + +## 1. 决策摘要 + +1. **新增或收敛的权威边界。** 将多主机 SSH 就绪观测(`session_fabric_ssh_observation_v0`)、不透明 profile 额度窗口观测(`session_quota_window_observation_v0`)及围栏约束的交接评估(`governed_session_handover_proposal_v0`)抽离为独立的 L0 控制面契约(实现位于 [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts)),无需等待新建整套前端即可独立交付。 +2. **保持不变的边界。** `loopx-core` 继续唯一拥有 Goal、Todo、claim、lease、quota、Turn 与 Gate 状态写入权;`ssh_host_catalog_v0` 继续是权威 SSH 主机别名目录;`apps/presentation/dashboard` 中的单一 Goal 工作台继续是官方前端入口。 +3. **默认与开启边界。** 未启用 L0 观测时保持逐字节对等:`ssh_host_catalog_v0` 仍仅输出 `{ alias }`;额度状态为 `unknown`、或未通过 Turn/租约围栏及共享 Gate 确认时绝不自动切换执行者。 +4. **核心安全与前端收敛约束。** 阻止平行引入 4 万–19.2 万行规模的第二套前端应用(`apps/presentation/calli-workbench/`、`apps/workbench/`)及平行守护进程任务表;所有会话、机器、额度与分诊能力统一嵌入既有单一 Goal 工作台视图。 +5. **本 RFC 暂未批准的事项。** 不批准自动迁移凭据、隐式切换 `attached_host` <-> `managed_runtime` 模式、独立 Node Todo 守护进程表或未知额度状态触发扣额/切换。 + +## 2. 问题与动机 + +Calli/LooChat 系列 PR(#8778、#8782–#8784、#8843)反映出统一接入本地与 SSH 远端多 CLI 会话及额度感知切换的真实需求。但通过独立 4 万行乃至 19.2 万行(#8843 共 881 个文件)的新前端与独立 Node 守护进程(`apps/presentation/calli-workbench/`、`apps/workbench/`)推进,会直接造成产品与状态面分裂: + +- 用户被割裂在官方 Goal 工作台(`apps/presentation/dashboard`)与第二套互不连通的壳层界面之间,代理、CSS 变量与路由各自维护。 +- 主干既有的 `configured_ssh_host_aliases`(`ssh_host_catalog_v0`)、`/api/chat/codex-attached` 与 `GoalAgentWorkPage` 被重复造轮子,而非增量演进。 +- 守护进程自带的任务表、定时调度器与局部撤销逻辑会与 Core 的单写者租约及 Turn 围栏产生双权威竞态。 + +将 L0 主机/会话/额度底座与上层前端解耦,使 LoopX 可以先落地可独立测试的控制面契约,再将最小交互面板直接嵌入现有单一 Goal 工作台。 + +### 不变量 + +- **I1 单一主机与任务权威。** Goal/Todo/租约/Gate 状态仅由 `loopx-core` 写入;SSH 主机身份仅归 `ssh_host_catalog_v0` 所有。针对未在 `ssh_host_catalog_v0` 注册别名的 L0 观测一律 fail-closed 拒绝。 +- **I2 不透明额度隐私边界。** 额度窗口观测只承载不透明 `profile_id`,严禁包含邮箱、密钥、Bearer Token 或本机私人路径。 +- **I3 共享 Gate 单一确认。** 当 `ask_before_switch=true` 时,交接请求只产出共享 Inbox/Gate 投影上的 `user_gate_required`,绝不另建弹窗权威。 +- **I4 跨越交接的 Turn 与租约围栏。** 交接不得隐式改变 `attached_host` / `managed_runtime` 执行模式;必须同时满足 `current_turn_fenced=true` 与 `previous_lease_released=true` 才允许新 profile 申请租约。 +- **I5 关闭态严格对等。** 无 L0 观测时 `ssh_host_catalog_v0` 输出与现有基线完全一致;`unknown` 额度窗口始终输出 `no_handover_needed`。 + +## 3. 范围与非目标 + +### 范围内 + +- 在 `loopx/control_plane/collaboration/session_quota_fabric.ts` 落地零 I/O 的 TypeScript L0 类型化编解码、投影与交接评估契约。 +- 确立复用 `apps/presentation/dashboard` 单一 Goal 工作台、拒绝平行第二前端的架构收敛路线。 + +### 非目标 + +- 不引入独立的 `apps/workbench/`、`apps/presentation/calli-workbench/` 目录、Node SQLite 守护进程或第二套前端构建链。 +- 本 RFC 切片暂不直接修改 `loopx/presentation/codex_attached_api.py` 或在包内孵化常驻 OpenSSH 子进程监督器。 + +## 4. 现行系统契约(基线 `31944d8354`) + +- **SSH 目录:** [`ssh_host_catalog.py`](../../../loopx/control_plane/status/ssh_host_catalog.py) 在 `/ssh-hosts` 返回 `{ ok: true, schema_version: "ssh_host_catalog_v0", hosts: [{ alias }] }`。 +- **Dashboard SSH 客户端:** [`ssh-host-catalog.ts`](../../../apps/presentation/dashboard/src/data/ssh-host-catalog.ts) 已接入 `ssh_host_catalog_v0` 及 `/api/ssh-source/ensure`、`/api/ssh-source/goal-lifecycle`。 +- **挂接会话与 Goal 界面:** [`codex_attached_api.py`](../../../loopx/presentation/codex_attached_api.py) 当前在 `bound_conversations()` 过滤 `host_surface == "codex-app"`;[`attached-agent-conversations.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx) 与 [`goal-agent-work-page.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx) 已在同一 Goal 视图下承接挂接会话与托管会话。 +- **L0 契约模块(本基线已交付):** [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts) 提供严格解码、增量目录合并与交接守卫判断。 + +## 5. 目标架构 + +### 所有权与权威分工 + +| 层级 | 唯一负责人 | 契约 / 接入点 | +| --- | --- | --- | +| L0 SSH 与额度观测 | 实现 `session_quota_fabric.ts` 的可选宿主 Provider | 产出 `session_fabric_ssh_observation_v0` 与 `session_quota_window_observation_v0` | +| L1 任务、额度与交接围栏 | `loopx-core`(`control_plane/collaboration/`、`quota/`) | 通过 `evaluateGovernedSessionHandover` 校验并结合租约/Turn 围栏执行 | +| L1/L2 挂接接口泛化 | [`codex_attached_api.py`](../../../loopx/presentation/codex_attached_api.py) 后续切片 | 按已注册 `host_surface` 能力泛化,替代硬编码 `"codex-app"` | +| L3 单一 Goal 工作台 | `apps/presentation/dashboard` | 在既有 Goal 视图中嵌入机器切换、会话时间线、额度指示与 Gate 分诊抽屉 | + +### 状态模型与 Schema + +1. `session_fabric_ssh_observation_v0`:校验 `alias`、`connection_state`(`connected | degraded | disconnected | unknown`)、`failure_code`(严格限定 Calli 已验证的 7 个失败码 `no_ssh | host_key | auth | unreachable | ssh_failed | daemon_missing | forward_denied`,仅在 `degraded | disconnected` 时必填,其余状态必须为 `null`)、`checked_at` 与 `tunnel_latency_ms`。`projectSshHostCatalogPayload` 仅向已知别名增量附加 `observation`,无观测条目保持纯 `{ alias }`。 +2. `session_quota_window_observation_v0`:校验不透明 `profile_id`(拒绝 `@`、`/`、`.ssh/`、`sk-`、`ghp_`、`bearer`)、`availability`(`available | near_limit | exhausted | unknown`)、`used_ratio`(`unknown` 时强制为 `null`,其余必须在 `[0, 1]`)、`resets_at` 与 `eligible_models`。 +3. `governed_session_handover_proposal_v0`:禁止跨执行模式切换(`from_session_mode !== to_session_mode`)与同 profile 切换;在 `unknown` 或低于阈值时返回 `no_handover_needed`,开启询问时返回 `user_gate_required`,围栏或租约释放未完成时返回 `await_turn_fence`,仅当全部前置成立时返回 `ready_for_lease_reacquisition`。 + +## 6. 备选方案与架构取舍 + +直接回应 #8778、#8782–#8784 与 #8843 收敛评审中的路线抉择: + +| 方案 | 结论 | 架构权衡 | +| --- | --- | --- | +| A. 仅在既有视图零散打补丁 | 拒绝 | SSH 错误码与额度阈值逻辑散落在各钩子中,缺乏统一契约 | +| B. **先交付独立 L0 会话与额度底座 + 嵌入既有单一 Goal 工作台** | **选定** | 不等待前端大改即可先行交付可测核心契约;避免第二套前端与守护进程裂变,单次 PR 可控在数百行内 | +| C. 平行引入 4 万–19.2 万行新前端与守护进程(`calli-workbench` / `apps/workbench`) | 拒绝 | 造成导航、样式、代理边界与状态归属分裂;重复既有 `ssh-host-catalog.ts` 与 `GoalAgentWorkPage` 且评审面失控 | + +## 7. 安全性、隐私与兼容性 + +- **关闭态对等:** 无 L0 观测传入时,`ssh_host_catalog_v0` 输出与 `ssh_host_catalog.py` 完全一致。 +- **凭据与路径 fail-closed:** 任何包含 `/Users/`、`/home/`、`.ssh/`、`@`、`/`、`sk-`、`ghp_` 或 `bearer` 的标识或模型名在解码边界立即拒绝。 +- **未知额度保护:** `unknown` 窗口强制 `handover_eligible=false` 与 `no_handover_needed`。 + +## 8. 迁移与回滚 + +既有 `apps/presentation/dashboard` 流程零破坏。每个 L0 切片(`session_quota_fabric.ts`、可选后端路由、可选工作台抽屉)均属纯增量改动,无持久化迁移依赖,直接 `git revert` 即可完整回滚。 + +## 9. 验证与验收 + +| 声明 | 验证命令 / 证据 | 验收标准 | 适用边界与未覆盖项 | +| --- | --- | --- | --- | +| 双语与 RFC 索引一致性 | `python3 scripts/check_rfc_bilingual.py` 与 `python3 scripts/generate_rfc_status_index.py --check` | 退出码 `0` | 不代表运行时逻辑 | +| L0 TypeScript 类型与摘要边界 | `npm run typecheck:control-plane` 与 `node --test tests/control_plane_ts/content_digest_single_owner.test.ts` | 退出码 `0` 且全通过 | 静态检查范围 | +| L0 编解码、关闭态对等、围栏与隐私反例 | `node --test tests/control_plane_ts/session_quota_fabric.test.ts` | 全部用例通过 | 单元测试范围;真实 SSH 进程监督归 M1/M2 | +| 语义词表无漂移与公开边界扫描 | `python3 examples/semantic-vocabulary-drift-smoke.py` 与 `loopx check` | 返回 `ok` | 不替代下游真实后端联调 | + +## 10. 运维契约 + +SSH 或额度状态未知时绝不提升权限或触发后台切换;所有状态通过 `ssh_host_catalog_v0` 与 Goal 作用域投影只读暴露,非法输入稳定抛出类型化错误。 + +## 11. 规范性交付计划 + +| 里程碑 | 交付内容 | 进入门禁 | 退出证据 | 回滚方式 | +| --- | --- | --- | --- | --- | +| **M0 收敛 RFC + L0 契约底座** | 双语 RFC(`session-and-quota-fabric-v0`)+ `session_quota_fabric.ts` + 单元测试 | 基线 `31944d8354` | `session_quota_fabric.test.ts`、`docs-governance-smoke.py`、`semantic-vocabulary-drift-smoke.py` | 回滚 RFC 与模块 | +| **M1 挂接 API 泛化与主机 Provider** | 将 `codex_attached_api.py` `host_surface` 路由能力化并可选接入 `ssh_host_catalog_v0` 探活 | M0 合入 | 关闭态对等测试 + 7 种 SSH 失败码夹具测试 | 关闭 Provider 开关 | +| **M2 单一工作台 UI 嵌入与交接联调** | 在 `apps/presentation/dashboard` `GoalAgentWorkPage` 嵌入主机状态、额度徽标与 Gate 交接入口 | M1 合入 | Playwright 桌面/窄屏冒烟、视觉截图及 Turn 围栏交接集成测试 | 回滚 UI 面板切片 | + +## 12. 待决问题 + +| 编号 | 问题 | 负责人 | 推荐方案 | 依赖里程碑 | +| --- | --- | --- | --- | --- | +| D1 | `codex_attached_api.py` 对非 Codex `host_surface` 列表的泛化方式 | 维护者 | 从 Goal 已注册 `agent_capabilities` 的宿主面集合动态解析 | M1 | +| D2 | 额度交接 `ask_before_switch` 的默认策略 | 维护者 | 默认 `true`(走共享 Gate `user_gate_required`),经用户显式授权才开启围栏自动切换 | M2 | diff --git a/loopx/control_plane/collaboration/session_quota_fabric.ts b/loopx/control_plane/collaboration/session_quota_fabric.ts new file mode 100644 index 0000000000..08cdda7511 --- /dev/null +++ b/loopx/control_plane/collaboration/session_quota_fabric.ts @@ -0,0 +1,335 @@ +/** L0 Session & Quota Fabric additive codecs, read-only projections, and fence-bound handover checks. */ +import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; +import { + isStringLiteral, + optionalNonEmptyString, + requireBoolean, + requireJsonObject, + requireNonEmptyString, + requireStringArray, + requireStringLiteral, + type JsonObject, +} from "../runtime_decode.ts"; +import { parseIsoTimestamp } from "../runtime_timestamp.ts"; + +export const SESSION_FABRIC_SSH_OBSERVATION_SCHEMA = "session_fabric_ssh_observation_v0"; +export const SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA = "session_quota_window_observation_v0"; +export const GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA = "governed_session_handover_proposal_v0"; +export const GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA = "governed_session_handover_result_v0"; + +export const SESSION_FABRIC_SSH_CONNECTION_STATES = [ + "connected", + "degraded", + "disconnected", + "unknown", +] as const; + +export const SESSION_FABRIC_SSH_FAILURE_CODES = [ + "no_ssh", + "host_key", + "auth", + "unreachable", + "ssh_failed", + "daemon_missing", + "forward_denied", +] as const; + +export const SESSION_FABRIC_QUOTA_AVAILABILITIES = [ + "available", + "near_limit", + "exhausted", + "unknown", +] as const; + +export const SESSION_FABRIC_EXECUTION_MODES = ["managed_runtime", "attached_host"] as const; + +export const SESSION_FABRIC_HANDOVER_DISPOSITIONS = [ + "no_handover_needed", + "user_gate_required", + "await_turn_fence", + "ready_for_lease_reacquisition", +] as const; + +export type SshConnectionState = (typeof SESSION_FABRIC_SSH_CONNECTION_STATES)[number]; +export type SshFailureCode = (typeof SESSION_FABRIC_SSH_FAILURE_CODES)[number]; +export type QuotaWindowAvailability = (typeof SESSION_FABRIC_QUOTA_AVAILABILITIES)[number]; +export type SessionFabricExecutionMode = (typeof SESSION_FABRIC_EXECUTION_MODES)[number]; +export type HandoverDisposition = (typeof SESSION_FABRIC_HANDOVER_DISPOSITIONS)[number]; + +const SAFE_HOST_ALIAS = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/; +const OPAQUE_PROFILE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/; +const FORBIDDEN_SECRET_PATTERNS = ["/Users/", "/home/", ".ssh/", "sk-", "ghp_", "bearer "]; + +export interface SshHostObservation extends JsonObject { + schema_version: typeof SESSION_FABRIC_SSH_OBSERVATION_SCHEMA; + alias: string; + connection_state: SshConnectionState; + failure_code: SshFailureCode | null; + checked_at: string | null; + tunnel_latency_ms: number | null; +} + +export interface SessionQuotaWindowObservation extends JsonObject { + schema_version: typeof SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA; + profile_id: string; + availability: QuotaWindowAvailability; + used_ratio: number | null; + resets_at: string | null; + eligible_models: string[]; + handover_eligible: boolean; +} + +export interface GovernedSessionHandoverResult extends JsonObject { + schema_version: typeof GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA; + goal_id: string; + todo_id: string; + agent_id: string; + session_mode: SessionFabricExecutionMode; + from_profile_id: string; + to_profile_id: string; + availability: QuotaWindowAvailability; + used_ratio: number | null; + threshold_ratio: number; + disposition: HandoverDisposition; + gate_required: boolean; + turn_fence_satisfied: boolean; + ready_for_reacquisition: boolean; + reason: string; +} + +function assertPublicSafeText(value: string, label: string): string { + const trimmed = value.trim(); + const lowered = trimmed.toLowerCase(); + if (FORBIDDEN_SECRET_PATTERNS.some((pattern) => lowered.includes(pattern))) { + throw new EffectRuntimeRequestError(`${label} must not contain private paths or credentials`); + } + return trimmed; +} + +function requireHostAlias(value: unknown, label: string): string { + const alias = assertPublicSafeText(requireNonEmptyString(value, label), label); + if (alias.includes("..") || !SAFE_HOST_ALIAS.test(alias)) { + throw new EffectRuntimeRequestError(`${label} must be an explicit safe OpenSSH Host alias`); + } + return alias; +} + +function requireOpaqueProfileId(value: unknown, label: string): string { + const profileId = assertPublicSafeText(requireNonEmptyString(value, label), label); + if (profileId.includes("@") || profileId.includes("/") || !OPAQUE_PROFILE_ID.test(profileId)) { + throw new EffectRuntimeRequestError(`${label} must be an opaque profile identifier`); + } + return profileId; +} + +function optionalIsoTimestamp(value: unknown, label: string): string | null { + const raw = optionalNonEmptyString(value, label); + if (raw === null) return null; + const trimmed = assertPublicSafeText(raw, label); + if (parseIsoTimestamp(trimmed) === null) { + throw new EffectRuntimeRequestError(`${label} must be a valid ISO timestamp`); + } + return trimmed; +} + +export function decodeSshHostObservation(value: unknown): SshHostObservation { + const raw = requireJsonObject(value, "ssh_host_observation"); + if (raw.schema_version !== SESSION_FABRIC_SSH_OBSERVATION_SCHEMA) { + throw new EffectRuntimeRequestError("ssh_host_observation schema_version mismatch"); + } + const alias = requireHostAlias(raw.alias, "ssh_host_observation.alias"); + const connectionState = requireStringLiteral( + raw.connection_state, + SESSION_FABRIC_SSH_CONNECTION_STATES, + "ssh_host_observation.connection_state", + ); + const rawFailure = optionalNonEmptyString(raw.failure_code, "ssh_host_observation.failure_code"); + let failureCode: SshFailureCode | null = null; + if (connectionState === "degraded" || connectionState === "disconnected") { + if (rawFailure === null || !isStringLiteral(rawFailure.trim(), SESSION_FABRIC_SSH_FAILURE_CODES)) { + throw new EffectRuntimeRequestError( + "degraded or disconnected SSH host observations require a valid failure_code", + ); + } + failureCode = rawFailure.trim() as SshFailureCode; + } else if (rawFailure !== null) { + throw new EffectRuntimeRequestError( + "connected or unknown SSH host observations must not carry a failure_code", + ); + } + const latency = raw.tunnel_latency_ms ?? null; + if (latency !== null && (typeof latency !== "number" || !Number.isSafeInteger(latency) || latency < 0)) { + throw new EffectRuntimeRequestError("ssh_host_observation.tunnel_latency_ms must be a non-negative integer"); + } + return { + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias, + connection_state: connectionState, + failure_code: failureCode, + checked_at: optionalIsoTimestamp(raw.checked_at, "ssh_host_observation.checked_at"), + tunnel_latency_ms: latency, + }; +} + +/** Merge optional L0 readiness observations into `ssh_host_catalog_v0`. + * When no observations are supplied, host entries stay `{ alias }` only for feature-off parity. */ +export function projectSshHostCatalogPayload( + configuredAliases: readonly string[], + observations: readonly unknown[] = [], +): JsonObject { + const aliases: string[] = []; + const seenAliases = new Set(); + for (let index = 0; index < configuredAliases.length; index += 1) { + const alias = requireHostAlias(configuredAliases[index], `configured_aliases[${index}]`); + if (seenAliases.has(alias)) continue; + seenAliases.add(alias); + aliases.push(alias); + } + const byAlias = new Map(); + for (const item of observations) { + const observation = decodeSshHostObservation(item); + if (!seenAliases.has(observation.alias)) { + throw new EffectRuntimeRequestError( + `SSH observation target '${observation.alias}' is absent from ssh_host_catalog_v0`, + ); + } + if (byAlias.has(observation.alias)) { + throw new EffectRuntimeRequestError( + `duplicate SSH host observation for alias '${observation.alias}'`, + ); + } + byAlias.set(observation.alias, observation); + } + return { + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: aliases.map((alias) => { + const observation = byAlias.get(alias); + return observation ? { alias, observation } : { alias }; + }), + }; +} + +export function decodeSessionQuotaWindowObservation( + value: unknown, +): SessionQuotaWindowObservation { + const raw = requireJsonObject(value, "quota_window_observation"); + if (raw.schema_version !== SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA) { + throw new EffectRuntimeRequestError("quota_window_observation schema_version mismatch"); + } + const profileId = requireOpaqueProfileId(raw.profile_id, "quota_window_observation.profile_id"); + const availability = requireStringLiteral( + raw.availability, + SESSION_FABRIC_QUOTA_AVAILABILITIES, + "quota_window_observation.availability", + ); + let usedRatio: number | null = null; + if (availability === "unknown") { + if (raw.used_ratio !== null && raw.used_ratio !== undefined) { + throw new EffectRuntimeRequestError("unknown quota window must have used_ratio=null"); + } + } else { + if (typeof raw.used_ratio !== "number" || !Number.isFinite(raw.used_ratio) || + raw.used_ratio < 0 || raw.used_ratio > 1) { + throw new EffectRuntimeRequestError("quota_window_observation.used_ratio must be within [0, 1]"); + } + usedRatio = raw.used_ratio; + } + const eligibleModels: string[] = []; + const seenModels = new Set(); + for (const model of requireStringArray(raw.eligible_models ?? [], "quota_window_observation.eligible_models")) { + const clean = assertPublicSafeText(model, "quota_window_observation.eligible_models[]"); + if (!clean || seenModels.has(clean)) continue; + seenModels.add(clean); + eligibleModels.push(clean); + } + return { + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: profileId, + availability, + used_ratio: usedRatio, + resets_at: optionalIsoTimestamp(raw.resets_at, "quota_window_observation.resets_at"), + eligible_models: eligibleModels, + handover_eligible: availability === "near_limit" || availability === "exhausted", + }; +} + +/** Evaluate whether an observed profile quota window warrants a fenced handover proposal + * without executing any switch, acquiring leases, or implicitly changing execution mode. */ +export function evaluateGovernedSessionHandover( + value: unknown, +): GovernedSessionHandoverResult { + const raw = requireJsonObject(value, "governed_session_handover"); + if (raw.schema_version !== GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA) { + throw new EffectRuntimeRequestError("governed_session_handover schema_version mismatch"); + } + const goalId = assertPublicSafeText(requireNonEmptyString(raw.goal_id, "governed_session_handover.goal_id"), "goal_id"); + const todoId = assertPublicSafeText(requireNonEmptyString(raw.todo_id, "governed_session_handover.todo_id"), "todo_id"); + const agentId = assertPublicSafeText(requireNonEmptyString(raw.agent_id, "governed_session_handover.agent_id"), "agent_id"); + const fromProfile = requireOpaqueProfileId(raw.from_profile_id, "governed_session_handover.from_profile_id"); + const toProfile = requireOpaqueProfileId(raw.to_profile_id, "governed_session_handover.to_profile_id"); + if (fromProfile === toProfile) { + throw new EffectRuntimeRequestError("from_profile_id and to_profile_id must differ"); + } + const fromMode = requireStringLiteral( + raw.from_session_mode, + SESSION_FABRIC_EXECUTION_MODES, + "governed_session_handover.from_session_mode", + ); + const toMode = requireStringLiteral( + raw.to_session_mode, + SESSION_FABRIC_EXECUTION_MODES, + "governed_session_handover.to_session_mode", + ); + if (fromMode !== toMode) { + throw new EffectRuntimeRequestError("session handover cannot implicitly change execution mode"); + } + const observation = decodeSessionQuotaWindowObservation(raw.quota_observation); + if (observation.profile_id !== fromProfile) { + throw new EffectRuntimeRequestError("quota_observation.profile_id must match from_profile_id"); + } + const threshold = raw.threshold_ratio; + if (typeof threshold !== "number" || !Number.isFinite(threshold) || threshold <= 0 || threshold > 1) { + throw new EffectRuntimeRequestError("governed_session_handover.threshold_ratio must be in (0, 1]"); + } + const currentTurnFenced = requireBoolean(raw.current_turn_fenced, "governed_session_handover.current_turn_fenced"); + const previousLeaseReleased = requireBoolean(raw.previous_lease_released, "governed_session_handover.previous_lease_released"); + const askBeforeSwitch = requireBoolean(raw.ask_before_switch, "governed_session_handover.ask_before_switch"); + + const fenceSatisfied = currentTurnFenced && previousLeaseReleased; + let disposition: HandoverDisposition; + let reason: string; + if (observation.availability === "unknown" || (observation.used_ratio ?? 0) < threshold) { + disposition = "no_handover_needed"; + reason = observation.availability === "unknown" + ? "quota window is unknown; fail closed with no switch" + : "observed quota usage is below handover threshold"; + } else if (askBeforeSwitch) { + disposition = "user_gate_required"; + reason = "handover requires confirmation on the shared Goal Inbox/Gate projection"; + } else if (!fenceSatisfied) { + disposition = "await_turn_fence"; + reason = "current turn must reach its fence and release the prior lease before reacquisition"; + } else { + disposition = "ready_for_lease_reacquisition"; + reason = "prior turn fenced and lease released; target profile may reacquire the Todo lease"; + } + + return { + schema_version: GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA, + goal_id: goalId, + todo_id: todoId, + agent_id: agentId, + session_mode: fromMode, + from_profile_id: fromProfile, + to_profile_id: toProfile, + availability: observation.availability, + used_ratio: observation.used_ratio, + threshold_ratio: threshold, + disposition, + gate_required: disposition === "user_gate_required", + turn_fence_satisfied: fenceSatisfied, + ready_for_reacquisition: disposition === "ready_for_lease_reacquisition", + reason, + }; +} diff --git a/tests/control_plane_ts/session_quota_fabric.test.ts b/tests/control_plane_ts/session_quota_fabric.test.ts new file mode 100644 index 0000000000..87d70e92df --- /dev/null +++ b/tests/control_plane_ts/session_quota_fabric.test.ts @@ -0,0 +1,208 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { EffectRuntimeRequestError } from "../../loopx/control_plane/effect_runtime_errors.ts"; +import { + decodeSessionQuotaWindowObservation, + decodeSshHostObservation, + evaluateGovernedSessionHandover, + GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA, + projectSshHostCatalogPayload, + SESSION_FABRIC_SSH_FAILURE_CODES, + SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, +} from "../../loopx/control_plane/collaboration/session_quota_fabric.ts"; + +test("ssh_host_catalog_v0 preserves byte-identical shape when L0 observations are absent", () => { + const payload = projectSshHostCatalogPayload(["build-box", "gpu-1", "build-box"]); + assert.deepEqual(payload, { + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [{ alias: "build-box" }, { alias: "gpu-1" }], + }); + assert.deepEqual(Object.keys((payload.hosts as Record[])[0]), ["alias"]); +}); + +test("SSH observations accept all seven typed failure codes and fail closed on contradictions or unknown aliases", () => { + for (const code of SESSION_FABRIC_SSH_FAILURE_CODES) { + const decoded = decodeSshHostObservation({ + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias: "gpu-1", + connection_state: "disconnected", + failure_code: code, + checked_at: "2026-11-17T03:00:00Z", + tunnel_latency_ms: null, + }); + assert.equal(decoded.failure_code, code); + } + + const projected = projectSshHostCatalogPayload(["gpu-1", "idle-box"], [ + { + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias: "gpu-1", + connection_state: "connected", + failure_code: null, + checked_at: "2026-11-17T03:00:00Z", + tunnel_latency_ms: 14, + }, + ]); + const hosts = projected.hosts as Record[]; + assert.equal((hosts[0].observation as Record).tunnel_latency_ms, 14); + assert.deepEqual(hosts[1], { alias: "idle-box" }); + + assert.throws(() => decodeSshHostObservation({ + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias: "gpu-1", + connection_state: "connected", + failure_code: "unreachable", + checked_at: null, + tunnel_latency_ms: null, + }), EffectRuntimeRequestError); + + assert.throws(() => projectSshHostCatalogPayload(["gpu-1"], [ + { + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias: "phantom-host", + connection_state: "disconnected", + failure_code: "unreachable", + checked_at: null, + tunnel_latency_ms: null, + }, + ]), /absent from ssh_host_catalog_v0/); + + assert.throws(() => projectSshHostCatalogPayload(["../bad"]), EffectRuntimeRequestError); +}); + +test("quota window observations require opaque profile ids and unknown usage never triggers handover", () => { + assert.throws(() => decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "user@example.com", + availability: "near_limit", + used_ratio: 0.9, + resets_at: null, + eligible_models: [], + }), EffectRuntimeRequestError); + + assert.throws(() => decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-a", + availability: "unknown", + used_ratio: 0.95, + resets_at: null, + eligible_models: [], + }), EffectRuntimeRequestError); + + const unknownWindow = decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-a", + availability: "unknown", + used_ratio: null, + resets_at: null, + eligible_models: ["model-a", "model-a"], + }); + assert.equal(unknownWindow.handover_eligible, false); + assert.deepEqual(unknownWindow.eligible_models, ["model-a"]); + + const belowOrUnknown = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-a", + to_profile_id: "profile-b", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: unknownWindow, + threshold_ratio: 0.85, + current_turn_fenced: false, + previous_lease_released: false, + ask_before_switch: false, + }); + assert.equal(belowOrUnknown.disposition, "no_handover_needed"); + assert.equal(belowOrUnknown.ready_for_reacquisition, false); +}); + +test("governed handover enforces session mode preservation, shared Gate, and turn/lease fencing", () => { + const nearLimit = { + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-primary", + availability: "near_limit", + used_ratio: 0.92, + resets_at: "2026-11-17T06:00:00Z", + eligible_models: ["gpt-codex"], + }; + + assert.throws(() => evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "attached_host", + to_session_mode: "managed_runtime", + quota_observation: nearLimit, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }), /implicitly change execution mode/); + + const gated = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: nearLimit, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: true, + }); + assert.equal(gated.schema_version, GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA); + assert.equal(gated.disposition, "user_gate_required"); + assert.equal(gated.gate_required, true); + assert.equal(gated.ready_for_reacquisition, false); + + const unfenced = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: nearLimit, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: false, + ask_before_switch: false, + }); + assert.equal(unfenced.disposition, "await_turn_fence"); + assert.equal(unfenced.turn_fence_satisfied, false); + + const ready = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: nearLimit, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }); + assert.equal(ready.disposition, "ready_for_lease_reacquisition"); + assert.equal(ready.turn_fence_satisfied, true); + assert.equal(ready.ready_for_reacquisition, true); +}); From a88a364b6acc4da1c00ab5a0b13a7c5fed865212 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:08:12 +0800 Subject: [PATCH 2/2] fix(control-plane): address PR #8886 review findings Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../smoke/status-source-catalog-smoke.ts | 69 ++++- .../dashboard/src/data/ssh-host-catalog.ts | 33 ++- .../rfcs/session-and-quota-fabric-v0.md | 59 ++-- .../rfcs/session-and-quota-fabric-v0.zh-CN.md | 24 +- docs/reference/glossary.md | 41 +++ examples/semantic-vocabulary-drift-smoke.py | 4 +- loopx/chat_manager.py | 8 +- loopx/chat_store.py | 10 +- .../collaboration/session_quota_fabric.ts | 209 ++++++-------- .../session_quota_fabric_contract.ts | 202 ++++++++++++++ .../control_plane/effect_runtime_handlers.ts | 2 + .../control_plane/status/ssh_host_catalog.py | 39 ++- loopx/semantics/vocabulary_v0.json | 123 ++++++++- .../test_semantic_vocabulary_drift.py | 10 +- .../session_quota_fabric.test.ts | 254 ++++++++++++++++++ tests/test_status_server_ssh_hosts.py | 169 ++++++++++++ tsconfig.control-plane.json | 1 + 17 files changed, 1055 insertions(+), 202 deletions(-) create mode 100644 loopx/control_plane/collaboration/session_quota_fabric_contract.ts diff --git a/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts b/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts index e783f20df5..9392a0e319 100644 --- a/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts +++ b/apps/presentation/dashboard/smoke/status-source-catalog-smoke.ts @@ -116,10 +116,75 @@ equal(activeStatusSourceForUrl(added.catalog, null, added.source.statusUrl, base const configuredHosts = parseConfiguredSshHostCatalog({ ok: true, schema_version: "ssh_host_catalog_v0", - hosts: [{ alias: "remote-lab" }, { alias: "*.example" }, { alias: "remote-lab" }, { alias: "jump_box" }], + hosts: [{ alias: "remote-lab" }, { alias: "*.example" }, { alias: "remote-lab" }, { alias: "jump_box" }, { alias: "desk-box" }, { alias: "task-worker" }], }); equal(defaultConfiguredSshHostsUrl, "/ssh-hosts", "configured Host discovery stays on the active local Dashboard origin"); -deepEqual(configuredHosts.hosts, [{ alias: "remote-lab" }, { alias: "jump_box" }], "only explicit safe SSH aliases enter the browser catalog"); +deepEqual( + configuredHosts.hosts, + [{ alias: "remote-lab" }, { alias: "jump_box" }, { alias: "desk-box" }, { alias: "task-worker" }], + "only explicit safe SSH aliases enter the browser catalog and feature-off rows keep exact { alias } shape", +); + +const observedHosts = parseConfiguredSshHostCatalog({ + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "desk-box", + connection_state: "connected", + failure_code: null, + checked_at: "2026-11-20T00:00:00Z", + tunnel_latency_ms: 12, + }, + }, + { alias: "task-worker" }, + ], +}); +deepEqual( + observedHosts.hosts, + [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "desk-box", + connection_state: "connected", + failure_code: null, + checked_at: "2026-11-20T00:00:00Z", + tunnel_latency_ms: 12, + }, + }, + { alias: "task-worker" }, + ], + "optional validated L0 SSH observations round-trip without altering unobserved entries", +); + +let invalidObservationRejected = false; +try { + parseConfiguredSshHostCatalog({ + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [ + { + alias: "desk-box", + observation: { + schema_version: "session_fabric_ssh_observation_v0", + alias: "other-host", + connection_state: "connected", + failure_code: null, + checked_at: null, + tunnel_latency_ms: null, + }, + }, + ], + }); +} catch { + invalidObservationRejected = true; +} +assert(invalidObservationRejected, "mismatched or invalid SSH observations fail closed"); const configuredDraft = configuredSshTunnelDraft("remote-lab", "8876"); assert("command" in configuredDraft, "a configured Host and valid local port produce a tunnel draft"); equal(configuredDraft.command, "ssh -N -L 8876:127.0.0.1:8766 remote-lab", "the UI generates one exact OpenSSH command"); diff --git a/apps/presentation/dashboard/src/data/ssh-host-catalog.ts b/apps/presentation/dashboard/src/data/ssh-host-catalog.ts index e761c18942..5075089ee3 100644 --- a/apps/presentation/dashboard/src/data/ssh-host-catalog.ts +++ b/apps/presentation/dashboard/src/data/ssh-host-catalog.ts @@ -1,7 +1,15 @@ +import { + decodeSshHostObservationWith, + isSafeHostAlias, + type SshHostObservation, +} from "../../../../../loopx/control_plane/collaboration/session_quota_fabric_contract.js"; +import { parseIsoTimestamp } from "../../../../../loopx/control_plane/runtime_timestamp.js"; + export const defaultConfiguredSshHostsUrl = "/ssh-hosts"; export type ConfiguredSshHost = { alias: string; + observation?: SshHostObservation; }; export type ConfiguredSshHostCatalog = { @@ -9,10 +17,8 @@ export type ConfiguredSshHostCatalog = { schemaVersion: "ssh_host_catalog_v0"; }; -const safeAliasPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/; - export function isConfiguredSshHostAlias(value: unknown): value is string { - return typeof value === "string" && safeAliasPattern.test(value.trim()); + return isSafeHostAlias(value); } export function parseConfiguredSshHostCatalog(value: unknown): ConfiguredSshHostCatalog { @@ -24,12 +30,25 @@ export function parseConfiguredSshHostCatalog(value: unknown): ConfiguredSshHost throw new Error("SSH Host 列表协议不兼容,请更新本机 LoopX 服务。"); } const seen = new Set(); - const hosts = payload.hosts.flatMap((value) => { - if (!value || typeof value !== "object" || Array.isArray(value)) return []; - const alias = String((value as Record).alias ?? "").trim(); + const hosts = payload.hosts.flatMap((item): ConfiguredSshHost[] => { + if (!item || typeof item !== "object" || Array.isArray(item)) return []; + const record = item as Record; + const alias = String(record.alias ?? "").trim(); if (!isConfiguredSshHostAlias(alias) || seen.has(alias)) return []; seen.add(alias); - return [{ alias }]; + if (record.observation === undefined || record.observation === null) { + return [{ alias }]; + } + const observation = decodeSshHostObservationWith(record.observation, { + fail: (message) => { + throw new Error(`SSH Host observation 无效:${message}`); + }, + parseTimestamp: parseIsoTimestamp, + }); + if (observation.alias !== alias) { + throw new Error(`SSH Host observation 别名不匹配:${observation.alias} !== ${alias}`); + } + return [{ alias, observation }]; }); return { hosts, schemaVersion: "ssh_host_catalog_v0" }; } diff --git a/docs/architecture/rfcs/session-and-quota-fabric-v0.md b/docs/architecture/rfcs/session-and-quota-fabric-v0.md index 781e0076a8..7bd9d20528 100644 --- a/docs/architecture/rfcs/session-and-quota-fabric-v0.md +++ b/docs/architecture/rfcs/session-and-quota-fabric-v0.md @@ -2,11 +2,11 @@ - **RFC status:** Accepted - **Supersedes / closes:** none -- **Delivery maturity:** Partial. The additive L0 codecs and handover guard (`session_quota_fabric.ts`) ship on this baseline; host runtime adapters and dashboard UI composition remain staged follow-on slices. +- **Delivery maturity:** Partial. The additive L0 codecs, zero-import frontend/control-plane contract (`session_quota_fabric_contract.ts`), `effect_runtime_handlers.ts` registrations, optional `ssh_host_catalog_v0` observation pass-through, and handover guard (`session_quota_fabric.ts`) ship on this baseline; host runtime adapters and dashboard UI composition remain staged follow-on slices. - **Authors / owners:** Architecture convergence workgroup; control-plane ownership, package boundaries, and merge authorization belong to LoopX maintainers - **Created:** 2026-11-17 -- **Last normative revision:** 2026-11-17 -- **Implementation baseline:** `31944d8354` +- **Last normative revision:** 2026-11-20 +- **Implementation baseline:** `45c015ffd9` - **Related contracts:** [Agent session execution modes](agent-session-execution-modes-v0.md), [Desktop execution frontends](desktop-execution-frontends-v0.md), @@ -111,12 +111,18 @@ single Goal Workbench. - Bypassing `loopx/presentation/codex_attached_api.py` ownership boundaries or shipping concrete OpenSSH child-process supervisors inside this RFC slice. -## 4. Current-system contract (baseline `31944d8354`) +## 4. Current-system contract (baseline `45c015ffd9`) - **SSH catalog:** [`ssh_host_catalog.py`](../../../loopx/control_plane/status/ssh_host_catalog.py) - serves `/ssh-hosts` with `{ ok: true, schema_version: "ssh_host_catalog_v0", hosts: [{ alias }] }`. + serves `/ssh-hosts` with `{ ok: true, schema_version: "ssh_host_catalog_v0", hosts: [{ alias }] }` + and exposes an optional `project_ssh_host_catalog` / `observations` helper + wired through `effect_runtime_handlers.ts` while leaving the default + no-observation output byte-identical. - **Dashboard SSH client:** [`ssh-host-catalog.ts`](../../../apps/presentation/dashboard/src/data/ssh-host-catalog.ts) - already parses `ssh_host_catalog_v0` and invokes `/api/ssh-source/ensure` and + reuses `isSafeHostAlias` (`SAFE_HOST_ALIAS`) and `decodeSshHostObservationWith` + from [`session_quota_fabric_contract.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts), + preserving optional validated `observation` metadata when present and bare + `{ alias }` entries when absent, and invokes `/api/ssh-source/ensure` and `/api/ssh-source/goal-lifecycle`. - **Attached sessions & Goal UI:** [`codex_attached_api.py`](../../../loopx/presentation/codex_attached_api.py) @@ -124,9 +130,14 @@ single Goal Workbench. while [`attached-agent-conversations.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx) and [`goal-agent-work-page.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx) render bound attached and managed conversations inside one Goal view. -- **L0 contract module (delivered in this baseline):** +- **L0 contract & semantic registration (delivered in this baseline):** [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts) - provides zero-I/O validated projections and handover state transitions. + and [`session_quota_fabric_contract.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts) + provide zero-I/O validated projections and handover state transitions + registered under `effect_runtime_handlers.ts` (`collaboration.session_fabric.project_ssh_host_catalog`, + `collaboration.session_fabric.evaluate_governed_session_handover`) and + converged in [`vocabulary_v0.json`](../../../loopx/semantics/vocabulary_v0.json) + (reusing canonical `session_mode` owned by `loopx/chat_store.py`). ## 5. Proposed architecture @@ -149,15 +160,18 @@ single Goal Workbench. observations strictly to known `ssh_host_catalog_v0` aliases and leaves un-observed hosts as bare `{ alias }`. 2. `session_quota_window_observation_v0`: validates opaque `profile_id` - (forbidding `@`, `/`, `.ssh/`, `sk-`, `ghp_`, `bearer`), `availability` + (forbidding `@`, `/`, private paths, and boundary-anchored credential prefixes + such as `sk-...`, `ghp_...`, `github_pat_...`, `Bearer ...`), `availability` (`available | near_limit | exhausted | unknown`), `used_ratio` (`[0, 1]` or - strictly `null` when `unknown`), `resets_at`, and `eligible_models`. + strictly `null` when `unknown`), `resets_at`, and `eligible_models`, deriving + `handover_eligible` strictly for `near_limit` and `exhausted`. 3. `governed_session_handover_proposal_v0`: rejects cross-mode switches (`from_session_mode !== to_session_mode`), rejects `from_profile_id === to_profile_id`, - returns `no_handover_needed` when `unknown` or below `threshold_ratio`, - `user_gate_required` when `ask_before_switch=true`, `await_turn_fence` when - fencing/release is incomplete, and `ready_for_lease_reacquisition` only when - all preconditions hold. + returns `no_handover_needed` when `!observation.handover_eligible` (`unknown` + or `available`) or when `availability === "near_limit"` below `threshold_ratio`, + evaluates `exhausted` regardless of `used_ratio`, returns `user_gate_required` + when `ask_before_switch=true`, `await_turn_fence` when fencing/release is + incomplete, and `ready_for_lease_reacquisition` only when all preconditions hold. ## 6. Alternatives and design choices @@ -173,11 +187,16 @@ Directly answers open convergence review question D1/D2 across #8778, #8782–#8 - **Default-off parity:** Absence of L0 observation payloads keeps `ssh_host_catalog_v0` output identical to `loopx/control_plane/status/ssh_host_catalog.py`. -- **Credential & path fail-closed:** `session_quota_fabric.ts` rejects any - SSH alias or quota `profile_id` / model string carrying `/Users/`, `/home/`, - `.ssh/`, `@`, `/`, `sk-`, `ghp_`, or `bearer`. -- **Unknown availability safety:** Missing/unknown quota observations force - `handover_eligible=false` and `disposition="no_handover_needed"`. +- **Credential & path fail-closed:** `session_quota_fabric_contract.ts` / + `session_quota_fabric.ts` rejects private home/SSH paths (`/Users/`, `/home/`, + `/private/`, `~/`, `.ssh/`) and boundary-anchored credential prefixes (`sk-...`, + `sk_live_...`, `ghp_...`, `github_pat_...`, `Bearer ...`) without falsely + rejecting valid OpenSSH host aliases or identifiers such as `desk-box`, + `task-worker`, `disk-01`, or `kiosk-2`. +- **Unknown and available window safety:** Missing/unknown and `available` + quota observations force `handover_eligible=false` and + `disposition="no_handover_needed"`, while `exhausted` remains handover-eligible + even if `used_ratio < threshold_ratio`. ## 8. Migration and rollback @@ -205,7 +224,7 @@ Goal-scoped projections; failures emit deterministic typed errors. | Milestone | Shipped behavior | Entry gate | Exit evidence | Rollback | | --- | --- | --- | --- | --- | -| **M0 Convergence RFC + L0 Contract** | Bilingual RFC (`session-and-quota-fabric-v0`) + `session_quota_fabric.ts` + TS unit tests | Baseline `31944d8354` | `session_quota_fabric.test.ts`, `docs-governance-smoke.py`, `semantic-vocabulary-drift-smoke.py` | Revert RFC & module | +| **M0 Convergence RFC + L0 Contract** | Bilingual RFC (`session-and-quota-fabric-v0`) + `session_quota_fabric_contract.ts` / `session_quota_fabric.ts` + `effect_runtime_handlers.ts` wiring + `ssh_host_catalog.py` / `ssh-host-catalog.ts` pass-through + `vocabulary_v0.json` registration | Baseline `45c015ffd9` | `session_quota_fabric.test.ts`, `status-source-catalog-smoke.ts`, `test_status_server_ssh_hosts.py`, `docs-governance-smoke.py`, `test_semantic_vocabulary_drift.py` | Revert RFC, registration & L0 handlers | | **M1 Attached API & Host Provider** | Generalize `codex_attached_api.py` `host_surface` routing + opt-in SSH probe wiring into `ssh_host_catalog_v0` | M0 merged | Feature-off parity test + seven SSH failure-code fixture tests | Disable provider flag | | **M2 Single Goal Workbench UI & Handover Wire-up** | Embed host readiness, quota window badge, and Gate-bound handover trigger inside `GoalAgentWorkPage` (`apps/presentation/dashboard`) | M1 merged | Playwright desktop/narrow viewport smoke + visual evidence + turn-fence handoff integration test | Revert UI panel slice | diff --git a/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md b/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md index e10caf9ad3..adb0a5b742 100644 --- a/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md +++ b/docs/architecture/rfcs/session-and-quota-fabric-v0.zh-CN.md @@ -2,11 +2,11 @@ - **RFC 状态:** 已接受 - **替代 / 关闭:** 无 -- **交付成熟度:** Partial。本基线已交付增量 L0 编解码与交接守卫模块(`session_quota_fabric.ts`);宿主运行时适配器与主工作台 UI 嵌入保留为后续分阶段切片。 +- **交付成熟度:** Partial。本基线已交付增量 L0 编解码、零导入前后端共享契约(`session_quota_fabric_contract.ts`)、`effect_runtime_handlers.ts` 注册入口、可选 `ssh_host_catalog_v0` 观测透传及交接守卫模块(`session_quota_fabric.ts`);宿主运行时适配器与主工作台 UI 嵌入保留为后续分阶段切片。 - **作者 / 负责人:** 架构收敛工作组;控制面归属、包边界及合并授权归属 LoopX 维护者 - **创建日期:** 2026-11-17 -- **最近规范性修订:** 2026-11-17 -- **实现基线:** `31944d8354` +- **最近规范性修订:** 2026-11-20 +- **实现基线:** `45c015ffd9` - **相关契约:** [Agent 会话执行模式](agent-session-execution-modes-v0.zh-CN.md)、 [桌面执行前端](desktop-execution-frontends-v0.zh-CN.md)、 @@ -62,12 +62,12 @@ Calli/LooChat 系列 PR(#8778、#8782–#8784、#8843)反映出统一接入 - 不引入独立的 `apps/workbench/`、`apps/presentation/calli-workbench/` 目录、Node SQLite 守护进程或第二套前端构建链。 - 本 RFC 切片暂不直接修改 `loopx/presentation/codex_attached_api.py` 或在包内孵化常驻 OpenSSH 子进程监督器。 -## 4. 现行系统契约(基线 `31944d8354`) +## 4. 现行系统契约(基线 `45c015ffd9`) -- **SSH 目录:** [`ssh_host_catalog.py`](../../../loopx/control_plane/status/ssh_host_catalog.py) 在 `/ssh-hosts` 返回 `{ ok: true, schema_version: "ssh_host_catalog_v0", hosts: [{ alias }] }`。 -- **Dashboard SSH 客户端:** [`ssh-host-catalog.ts`](../../../apps/presentation/dashboard/src/data/ssh-host-catalog.ts) 已接入 `ssh_host_catalog_v0` 及 `/api/ssh-source/ensure`、`/api/ssh-source/goal-lifecycle`。 +- **SSH 目录:** [`ssh_host_catalog.py`](../../../loopx/control_plane/status/ssh_host_catalog.py) 在 `/ssh-hosts` 返回 `{ ok: true, schema_version: "ssh_host_catalog_v0", hosts: [{ alias }] }`,并通过经 `effect_runtime_handlers.ts` 路由的可选 `project_ssh_host_catalog` / `observations` 助手保持无观测态输出逐字节不变。 +- **Dashboard SSH 客户端:** [`ssh-host-catalog.ts`](../../../apps/presentation/dashboard/src/data/ssh-host-catalog.ts) 复用 [`session_quota_fabric_contract.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts) 中的 `isSafeHostAlias`(`SAFE_HOST_ALIAS`)与 `decodeSshHostObservationWith`,在存在观测时保留经校验的 `observation`,缺失时保持纯 `{ alias }`,并调用 `/api/ssh-source/ensure`、`/api/ssh-source/goal-lifecycle`。 - **挂接会话与 Goal 界面:** [`codex_attached_api.py`](../../../loopx/presentation/codex_attached_api.py) 当前在 `bound_conversations()` 过滤 `host_surface == "codex-app"`;[`attached-agent-conversations.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/attached-agent-conversations.tsx) 与 [`goal-agent-work-page.tsx`](../../../apps/presentation/dashboard/src/features/personal-workspace/goal-agent-work-page.tsx) 已在同一 Goal 视图下承接挂接会话与托管会话。 -- **L0 契约模块(本基线已交付):** [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts) 提供严格解码、增量目录合并与交接守卫判断。 +- **L0 契约模块与语义注册(本基线已交付):** [`session_quota_fabric.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric.ts) 与 [`session_quota_fabric_contract.ts`](../../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts) 提供严格解码、增量目录合并与交接守卫判断,已注册至 `effect_runtime_handlers.ts`(`collaboration.session_fabric.project_ssh_host_catalog`、`collaboration.session_fabric.evaluate_governed_session_handover`)并纳入 [`vocabulary_v0.json`](../../../loopx/semantics/vocabulary_v0.json)(复用 `loopx/chat_store.py` 的权威 `session_mode`)。 ## 5. 目标架构 @@ -83,8 +83,8 @@ Calli/LooChat 系列 PR(#8778、#8782–#8784、#8843)反映出统一接入 ### 状态模型与 Schema 1. `session_fabric_ssh_observation_v0`:校验 `alias`、`connection_state`(`connected | degraded | disconnected | unknown`)、`failure_code`(严格限定 Calli 已验证的 7 个失败码 `no_ssh | host_key | auth | unreachable | ssh_failed | daemon_missing | forward_denied`,仅在 `degraded | disconnected` 时必填,其余状态必须为 `null`)、`checked_at` 与 `tunnel_latency_ms`。`projectSshHostCatalogPayload` 仅向已知别名增量附加 `observation`,无观测条目保持纯 `{ alias }`。 -2. `session_quota_window_observation_v0`:校验不透明 `profile_id`(拒绝 `@`、`/`、`.ssh/`、`sk-`、`ghp_`、`bearer`)、`availability`(`available | near_limit | exhausted | unknown`)、`used_ratio`(`unknown` 时强制为 `null`,其余必须在 `[0, 1]`)、`resets_at` 与 `eligible_models`。 -3. `governed_session_handover_proposal_v0`:禁止跨执行模式切换(`from_session_mode !== to_session_mode`)与同 profile 切换;在 `unknown` 或低于阈值时返回 `no_handover_needed`,开启询问时返回 `user_gate_required`,围栏或租约释放未完成时返回 `await_turn_fence`,仅当全部前置成立时返回 `ready_for_lease_reacquisition`。 +2. `session_quota_window_observation_v0`:校验不透明 `profile_id`(拒绝 `@`、`/`、私人路径及边界锚定凭据前缀 `sk-...`、`ghp_...`、`github_pat_...`、`Bearer ...`)、`availability`(`available | near_limit | exhausted | unknown`)、`used_ratio`(`unknown` 时强制为 `null`,其余必须在 `[0, 1]`)、`resets_at` 与 `eligible_models`,并仅对 `near_limit` 与 `exhausted` 置 `handover_eligible=true`。 +3. `governed_session_handover_proposal_v0`:禁止跨执行模式切换(`from_session_mode !== to_session_mode`)与同 profile 切换;当 `!observation.handover_eligible`(`unknown` 或 `available`)或 `near_limit` 低于 `threshold_ratio` 时返回 `no_handover_needed`,`exhausted` 无论 `used_ratio` 均进入交接门控;开启询问时返回 `user_gate_required`,围栏或租约释放未完成时返回 `await_turn_fence`,仅当全部前置成立时返回 `ready_for_lease_reacquisition`。 ## 6. 备选方案与架构取舍 @@ -99,8 +99,8 @@ Calli/LooChat 系列 PR(#8778、#8782–#8784、#8843)反映出统一接入 ## 7. 安全性、隐私与兼容性 - **关闭态对等:** 无 L0 观测传入时,`ssh_host_catalog_v0` 输出与 `ssh_host_catalog.py` 完全一致。 -- **凭据与路径 fail-closed:** 任何包含 `/Users/`、`/home/`、`.ssh/`、`@`、`/`、`sk-`、`ghp_` 或 `bearer` 的标识或模型名在解码边界立即拒绝。 -- **未知额度保护:** `unknown` 窗口强制 `handover_eligible=false` 与 `no_handover_needed`。 +- **凭据与路径 fail-closed:** `session_quota_fabric_contract.ts` / `session_quota_fabric.ts` 在解码边界拒绝私人路径(`/Users/`、`/home/`、`/private/`、`~/`、`.ssh/`)与边界锚定的凭据前缀(`sk-...`、`sk_live_...`、`ghp_...`、`github_pat_...`、`Bearer ...`),同时正常放行 `desk-box`、`task-worker`、`disk-01`、`kiosk-2` 等合法 OpenSSH 别名与标识。 +- **未知与可用额度保护:** `unknown` 与 `available` 窗口强制 `handover_eligible=false` 与 `no_handover_needed`,而 `exhausted` 即使 `used_ratio < threshold_ratio` 仍保持交接资格。 ## 8. 迁移与回滚 @@ -123,7 +123,7 @@ SSH 或额度状态未知时绝不提升权限或触发后台切换;所有状 | 里程碑 | 交付内容 | 进入门禁 | 退出证据 | 回滚方式 | | --- | --- | --- | --- | --- | -| **M0 收敛 RFC + L0 契约底座** | 双语 RFC(`session-and-quota-fabric-v0`)+ `session_quota_fabric.ts` + 单元测试 | 基线 `31944d8354` | `session_quota_fabric.test.ts`、`docs-governance-smoke.py`、`semantic-vocabulary-drift-smoke.py` | 回滚 RFC 与模块 | +| **M0 收敛 RFC + L0 契约底座** | 双语 RFC(`session-and-quota-fabric-v0`)+ `session_quota_fabric_contract.ts` / `session_quota_fabric.ts` + `effect_runtime_handlers.ts` 接入 + `ssh_host_catalog.py` / `ssh-host-catalog.ts` 透传 + `vocabulary_v0.json` 词表登记 | 基线 `45c015ffd9` | `session_quota_fabric.test.ts`、`status-source-catalog-smoke.ts`、`test_status_server_ssh_hosts.py`、`docs-governance-smoke.py`、`test_semantic_vocabulary_drift.py` | 回滚 RFC、登记与 L0 处理器 | | **M1 挂接 API 泛化与主机 Provider** | 将 `codex_attached_api.py` `host_surface` 路由能力化并可选接入 `ssh_host_catalog_v0` 探活 | M0 合入 | 关闭态对等测试 + 7 种 SSH 失败码夹具测试 | 关闭 Provider 开关 | | **M2 单一工作台 UI 嵌入与交接联调** | 在 `apps/presentation/dashboard` `GoalAgentWorkPage` 嵌入主机状态、额度徽标与 Gate 交接入口 | M1 合入 | Playwright 桌面/窄屏冒烟、视觉截图及 Turn 围栏交接集成测试 | 回滚 UI 面板切片 | diff --git a/docs/reference/glossary.md b/docs/reference/glossary.md index 68dda6aa90..03a06daff7 100644 --- a/docs/reference/glossary.md +++ b/docs/reference/glossary.md @@ -175,6 +175,47 @@ Legal scheduler host state transition. - typescript: [`SCHEDULER_HOST_TRANSITIONS`](../../loopx/control_plane/scheduler/state_transition_rules.ts). - Values / 值: `apply_required`, `host_match_ack_required`, `recorded_failure_suppressed`, `settled`. +## session_fabric_handover_disposition + +Fence-bound governed session handover evaluation verdict returned without executing switches or acquiring leases. + +- Tier / 层级: `cross_runtime`; status / 状态: `canonical`. +- typescript: [`SESSION_FABRIC_HANDOVER_DISPOSITIONS`](../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts). +- Values / 值: `no_handover_needed`, `user_gate_required`, `await_turn_fence`, `ready_for_lease_reacquisition`. + +## session_fabric_quota_availability + +Opaque-profile quota window availability state decoded fail-closed by L0 session fabric. + +- Tier / 层级: `cross_runtime`; status / 状态: `canonical`. +- typescript: [`SESSION_FABRIC_QUOTA_AVAILABILITIES`](../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts). +- Values / 值: `available`, `near_limit`, `exhausted`, `unknown`. + +## session_fabric_ssh_connection_state + +Read-only L0 SSH host readiness state attached optionally to ssh_host_catalog_v0 entries. + +- Tier / 层级: `cross_runtime`; status / 状态: `canonical`. +- typescript: [`SESSION_FABRIC_SSH_CONNECTION_STATES`](../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts). +- Values / 值: `connected`, `degraded`, `disconnected`, `unknown`. + +## session_fabric_ssh_failure_code + +Typed SSH readiness failure reason required on degraded or disconnected L0 SSH host observations. + +- Tier / 层级: `cross_runtime`; status / 状态: `canonical`. +- typescript: [`SESSION_FABRIC_SSH_FAILURE_CODES`](../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts). +- Values / 值: `no_ssh`, `host_key`, `auth`, `unreachable`, `ssh_failed`, `daemon_missing`, `forward_denied`. + +## session_mode + +Explicit, non-implicitly-switchable execution ownership mode of a LoopX agent session binding. + +- Tier / 层级: `cross_runtime`; status / 状态: `canonical`. +- python: [`CHAT_SESSION_MODES`](../../loopx/chat_store.py). +- typescript: [`SESSION_MODES`](../../loopx/control_plane/collaboration/session_quota_fabric_contract.ts). +- Values / 值: `managed_runtime`, `attached_host`. + ## settlement_binding_kind How a settlement step binds to its receipt. diff --git a/examples/semantic-vocabulary-drift-smoke.py b/examples/semantic-vocabulary-drift-smoke.py index 69e07e9cde..651fe2ca62 100755 --- a/examples/semantic-vocabulary-drift-smoke.py +++ b/examples/semantic-vocabulary-drift-smoke.py @@ -191,8 +191,8 @@ # anchor. A `<=` comparison would let every tightening below the anchor be undone # silently; that is the gap the anchor exists to close. COVERAGE_ANCHOR = { - "vocabularies": 29, - "owner_symbols": 56, + "vocabularies": 34, + "owner_symbols": 62, "literal_scan_fields": 1, "projections": 1, "relations": 9, diff --git a/loopx/chat_manager.py b/loopx/chat_manager.py index f31e03d86c..1e9033fb4f 100644 --- a/loopx/chat_manager.py +++ b/loopx/chat_manager.py @@ -56,8 +56,7 @@ CodexChatAgentError, ) from .chat_store import ( - CHAT_SESSION_MODE_ATTACHED, - CHAT_SESSION_MODE_MANAGED, + CHAT_SESSION_MODES, RESUMABLE_SESSION_STATES, ) @@ -639,10 +638,7 @@ def manager_connection_executor_endpoint( MANAGER_CHANNEL_SESSION_MODE_SOURCE_READBACK = "session_readback" MANAGER_CHANNEL_SESSION_MODE_SOURCE_UNBOUND = "unbound" MANAGER_CHANNEL_SESSION_MODE_SOURCE_UNRECOGNIZED = "unrecognized" -MANAGER_CHANNEL_SESSION_MODES = ( - CHAT_SESSION_MODE_MANAGED, - CHAT_SESSION_MODE_ATTACHED, -) +MANAGER_CHANNEL_SESSION_MODES = CHAT_SESSION_MODES def manager_channel_session_mode_readback( diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 64fff16914..47cb28d4bf 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -46,8 +46,9 @@ CHAT_EVENT_SCHEMA_VERSION = "loopx_chat_event_v1" CHAT_MESSAGE_SCHEMA_VERSION = "loopx_chat_message_v1" CHAT_INGRESS_SCHEMA_VERSION = "loopx_chat_ingress_receipt_v1" -CHAT_SESSION_MODE_MANAGED = "managed_runtime" -CHAT_SESSION_MODE_ATTACHED = "attached_host" +CHAT_SESSION_MODES = ("managed_runtime", "attached_host") +CHAT_SESSION_MODE_MANAGED = CHAT_SESSION_MODES[0] +CHAT_SESSION_MODE_ATTACHED = CHAT_SESSION_MODES[1] RESUMABLE_SESSION_STATES = {"ready", "busy", "stale", "resuming"} TERMINAL_TURN_STATES = {"completed", "interrupted", "timed_out", "failed"} TERMINAL_EVENT_KINDS = {"turn.completed", "turn.failed", "turn.interrupted"} @@ -297,10 +298,7 @@ def create_session( or normalized_mode != CHAT_SESSION_MODE_MANAGED ): raise ValueError("codex_home must be an absolute managed Codex home") - if normalized_mode not in { - CHAT_SESSION_MODE_MANAGED, - CHAT_SESSION_MODE_ATTACHED, - }: + if normalized_mode not in CHAT_SESSION_MODES: raise ValueError("session_mode must be managed_runtime or attached_host") normalized_host_surface = ( _opaque_id(host_surface, field="host_surface") if host_surface else None diff --git a/loopx/control_plane/collaboration/session_quota_fabric.ts b/loopx/control_plane/collaboration/session_quota_fabric.ts index 08cdda7511..086b766821 100644 --- a/loopx/control_plane/collaboration/session_quota_fabric.ts +++ b/loopx/control_plane/collaboration/session_quota_fabric.ts @@ -1,7 +1,6 @@ /** L0 Session & Quota Fabric additive codecs, read-only projections, and fence-bound handover checks. */ import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { - isStringLiteral, optionalNonEmptyString, requireBoolean, requireJsonObject, @@ -11,107 +10,65 @@ import { type JsonObject, } from "../runtime_decode.ts"; import { parseIsoTimestamp } from "../runtime_timestamp.ts"; +import { + assertPublicSafeFabricText, + decodeSshHostObservationWith, + GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA, + isSafeHostAlias, + requireSafeHostAlias, + SAFE_HOST_ALIAS, + SESSION_FABRIC_HANDOVER_DISPOSITIONS, + SESSION_FABRIC_QUOTA_AVAILABILITIES, + SESSION_FABRIC_SSH_CONNECTION_STATES, + SESSION_FABRIC_SSH_FAILURE_CODES, + SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + SESSION_MODES, + SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + type GovernedSessionHandoverResult, + type HandoverDisposition, + type QuotaWindowAvailability, + type SessionMode, + type SessionQuotaWindowObservation, + type SshConnectionState, + type SshFailureCode, + type SshHostObservation, +} from "./session_quota_fabric_contract.ts"; -export const SESSION_FABRIC_SSH_OBSERVATION_SCHEMA = "session_fabric_ssh_observation_v0"; -export const SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA = "session_quota_window_observation_v0"; -export const GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA = "governed_session_handover_proposal_v0"; -export const GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA = "governed_session_handover_result_v0"; - -export const SESSION_FABRIC_SSH_CONNECTION_STATES = [ - "connected", - "degraded", - "disconnected", - "unknown", -] as const; - -export const SESSION_FABRIC_SSH_FAILURE_CODES = [ - "no_ssh", - "host_key", - "auth", - "unreachable", - "ssh_failed", - "daemon_missing", - "forward_denied", -] as const; - -export const SESSION_FABRIC_QUOTA_AVAILABILITIES = [ - "available", - "near_limit", - "exhausted", - "unknown", -] as const; - -export const SESSION_FABRIC_EXECUTION_MODES = ["managed_runtime", "attached_host"] as const; - -export const SESSION_FABRIC_HANDOVER_DISPOSITIONS = [ - "no_handover_needed", - "user_gate_required", - "await_turn_fence", - "ready_for_lease_reacquisition", -] as const; - -export type SshConnectionState = (typeof SESSION_FABRIC_SSH_CONNECTION_STATES)[number]; -export type SshFailureCode = (typeof SESSION_FABRIC_SSH_FAILURE_CODES)[number]; -export type QuotaWindowAvailability = (typeof SESSION_FABRIC_QUOTA_AVAILABILITIES)[number]; -export type SessionFabricExecutionMode = (typeof SESSION_FABRIC_EXECUTION_MODES)[number]; -export type HandoverDisposition = (typeof SESSION_FABRIC_HANDOVER_DISPOSITIONS)[number]; +export { + GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA, + isSafeHostAlias, + SAFE_HOST_ALIAS, + SESSION_FABRIC_HANDOVER_DISPOSITIONS, + SESSION_FABRIC_QUOTA_AVAILABILITIES, + SESSION_FABRIC_SSH_CONNECTION_STATES, + SESSION_FABRIC_SSH_FAILURE_CODES, + SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + SESSION_MODES, + SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + type GovernedSessionHandoverResult, + type HandoverDisposition, + type QuotaWindowAvailability, + type SessionMode, + type SessionQuotaWindowObservation, + type SshConnectionState, + type SshFailureCode, + type SshHostObservation, +}; -const SAFE_HOST_ALIAS = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/; const OPAQUE_PROFILE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/; -const FORBIDDEN_SECRET_PATTERNS = ["/Users/", "/home/", ".ssh/", "sk-", "ghp_", "bearer "]; - -export interface SshHostObservation extends JsonObject { - schema_version: typeof SESSION_FABRIC_SSH_OBSERVATION_SCHEMA; - alias: string; - connection_state: SshConnectionState; - failure_code: SshFailureCode | null; - checked_at: string | null; - tunnel_latency_ms: number | null; -} - -export interface SessionQuotaWindowObservation extends JsonObject { - schema_version: typeof SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA; - profile_id: string; - availability: QuotaWindowAvailability; - used_ratio: number | null; - resets_at: string | null; - eligible_models: string[]; - handover_eligible: boolean; -} -export interface GovernedSessionHandoverResult extends JsonObject { - schema_version: typeof GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA; - goal_id: string; - todo_id: string; - agent_id: string; - session_mode: SessionFabricExecutionMode; - from_profile_id: string; - to_profile_id: string; - availability: QuotaWindowAvailability; - used_ratio: number | null; - threshold_ratio: number; - disposition: HandoverDisposition; - gate_required: boolean; - turn_fence_satisfied: boolean; - ready_for_reacquisition: boolean; - reason: string; +function failFabricRequest(message: string): never { + throw new EffectRuntimeRequestError(message); } function assertPublicSafeText(value: string, label: string): string { - const trimmed = value.trim(); - const lowered = trimmed.toLowerCase(); - if (FORBIDDEN_SECRET_PATTERNS.some((pattern) => lowered.includes(pattern))) { - throw new EffectRuntimeRequestError(`${label} must not contain private paths or credentials`); - } - return trimmed; + return assertPublicSafeFabricText(value, label, failFabricRequest); } function requireHostAlias(value: unknown, label: string): string { - const alias = assertPublicSafeText(requireNonEmptyString(value, label), label); - if (alias.includes("..") || !SAFE_HOST_ALIAS.test(alias)) { - throw new EffectRuntimeRequestError(`${label} must be an explicit safe OpenSSH Host alias`); - } - return alias; + return requireSafeHostAlias(value, label, failFabricRequest); } function requireOpaqueProfileId(value: unknown, label: string): string { @@ -133,42 +90,10 @@ function optionalIsoTimestamp(value: unknown, label: string): string | null { } export function decodeSshHostObservation(value: unknown): SshHostObservation { - const raw = requireJsonObject(value, "ssh_host_observation"); - if (raw.schema_version !== SESSION_FABRIC_SSH_OBSERVATION_SCHEMA) { - throw new EffectRuntimeRequestError("ssh_host_observation schema_version mismatch"); - } - const alias = requireHostAlias(raw.alias, "ssh_host_observation.alias"); - const connectionState = requireStringLiteral( - raw.connection_state, - SESSION_FABRIC_SSH_CONNECTION_STATES, - "ssh_host_observation.connection_state", - ); - const rawFailure = optionalNonEmptyString(raw.failure_code, "ssh_host_observation.failure_code"); - let failureCode: SshFailureCode | null = null; - if (connectionState === "degraded" || connectionState === "disconnected") { - if (rawFailure === null || !isStringLiteral(rawFailure.trim(), SESSION_FABRIC_SSH_FAILURE_CODES)) { - throw new EffectRuntimeRequestError( - "degraded or disconnected SSH host observations require a valid failure_code", - ); - } - failureCode = rawFailure.trim() as SshFailureCode; - } else if (rawFailure !== null) { - throw new EffectRuntimeRequestError( - "connected or unknown SSH host observations must not carry a failure_code", - ); - } - const latency = raw.tunnel_latency_ms ?? null; - if (latency !== null && (typeof latency !== "number" || !Number.isSafeInteger(latency) || latency < 0)) { - throw new EffectRuntimeRequestError("ssh_host_observation.tunnel_latency_ms must be a non-negative integer"); - } - return { - schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, - alias, - connection_state: connectionState, - failure_code: failureCode, - checked_at: optionalIsoTimestamp(raw.checked_at, "ssh_host_observation.checked_at"), - tunnel_latency_ms: latency, - }; + return decodeSshHostObservationWith(value, { + fail: failFabricRequest, + parseTimestamp: parseIsoTimestamp, + }); } /** Merge optional L0 readiness observations into `ssh_host_catalog_v0`. @@ -210,6 +135,23 @@ export function projectSshHostCatalogPayload( }; } +export function projectSshHostCatalogRequest(value: unknown): JsonObject { + const raw = requireJsonObject(value, "ssh_host_catalog_projection_request"); + const configuredAliases = requireStringArray( + raw.configured_aliases, + "ssh_host_catalog_projection_request.configured_aliases", + ); + const observations = raw.observations === undefined || raw.observations === null + ? [] + : raw.observations; + if (!Array.isArray(observations)) { + throw new EffectRuntimeRequestError( + "ssh_host_catalog_projection_request.observations must be an array", + ); + } + return projectSshHostCatalogPayload(configuredAliases, observations); +} + export function decodeSessionQuotaWindowObservation( value: unknown, ): SessionQuotaWindowObservation { @@ -273,12 +215,12 @@ export function evaluateGovernedSessionHandover( } const fromMode = requireStringLiteral( raw.from_session_mode, - SESSION_FABRIC_EXECUTION_MODES, + SESSION_MODES, "governed_session_handover.from_session_mode", ); const toMode = requireStringLiteral( raw.to_session_mode, - SESSION_FABRIC_EXECUTION_MODES, + SESSION_MODES, "governed_session_handover.to_session_mode", ); if (fromMode !== toMode) { @@ -299,11 +241,14 @@ export function evaluateGovernedSessionHandover( const fenceSatisfied = currentTurnFenced && previousLeaseReleased; let disposition: HandoverDisposition; let reason: string; - if (observation.availability === "unknown" || (observation.used_ratio ?? 0) < threshold) { + if (!observation.handover_eligible) { disposition = "no_handover_needed"; reason = observation.availability === "unknown" ? "quota window is unknown; fail closed with no switch" - : "observed quota usage is below handover threshold"; + : "observed quota window is available; no handover needed"; + } else if (observation.availability === "near_limit" && (observation.used_ratio ?? 0) < threshold) { + disposition = "no_handover_needed"; + reason = "observed quota usage is below handover threshold"; } else if (askBeforeSwitch) { disposition = "user_gate_required"; reason = "handover requires confirmation on the shared Goal Inbox/Gate projection"; diff --git a/loopx/control_plane/collaboration/session_quota_fabric_contract.ts b/loopx/control_plane/collaboration/session_quota_fabric_contract.ts new file mode 100644 index 0000000000..619ca61771 --- /dev/null +++ b/loopx/control_plane/collaboration/session_quota_fabric_contract.ts @@ -0,0 +1,202 @@ +/** Shared zero-import L0 Session & Quota Fabric wire constants, closed vocabularies, and pure SSH observation codecs. */ + +export const SESSION_FABRIC_SSH_OBSERVATION_SCHEMA = "session_fabric_ssh_observation_v0"; +export const SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA = "session_quota_window_observation_v0"; +export const GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA = "governed_session_handover_proposal_v0"; +export const GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA = "governed_session_handover_result_v0"; + +export const SESSION_MODES = ["managed_runtime", "attached_host"] as const; + +export const SESSION_FABRIC_SSH_CONNECTION_STATES = [ + "connected", + "degraded", + "disconnected", + "unknown", +] as const; + +export const SESSION_FABRIC_SSH_FAILURE_CODES = [ + "no_ssh", + "host_key", + "auth", + "unreachable", + "ssh_failed", + "daemon_missing", + "forward_denied", +] as const; + +export const SESSION_FABRIC_QUOTA_AVAILABILITIES = [ + "available", + "near_limit", + "exhausted", + "unknown", +] as const; + +export const SESSION_FABRIC_HANDOVER_DISPOSITIONS = [ + "no_handover_needed", + "user_gate_required", + "await_turn_fence", + "ready_for_lease_reacquisition", +] as const; + +export type SessionMode = (typeof SESSION_MODES)[number]; +export type SshConnectionState = (typeof SESSION_FABRIC_SSH_CONNECTION_STATES)[number]; +export type SshFailureCode = (typeof SESSION_FABRIC_SSH_FAILURE_CODES)[number]; +export type QuotaWindowAvailability = (typeof SESSION_FABRIC_QUOTA_AVAILABILITIES)[number]; +export type HandoverDisposition = (typeof SESSION_FABRIC_HANDOVER_DISPOSITIONS)[number]; + +/** Canonical TypeScript owner for safe explicit OpenSSH Host aliases (`ssh_host_catalog_v0`). */ +export const SAFE_HOST_ALIAS = /^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/; + +const FORBIDDEN_CREDENTIAL_OR_PATH_PATTERNS: readonly RegExp[] = [ + /(?:\/(?:Users|home|private|tmp|var)\/|~[\\/]|[A-Za-z]:[\\/]|\\\\[A-Za-z0-9_.-]+\\|\.ssh[\\/])/i, + /(? { + schema_version: typeof SESSION_FABRIC_SSH_OBSERVATION_SCHEMA; + alias: string; + connection_state: SshConnectionState; + failure_code: SshFailureCode | null; + checked_at: string | null; + tunnel_latency_ms: number | null; +} + +export interface SessionQuotaWindowObservation extends Record { + schema_version: typeof SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA; + profile_id: string; + availability: QuotaWindowAvailability; + used_ratio: number | null; + resets_at: string | null; + eligible_models: string[]; + handover_eligible: boolean; +} + +export interface GovernedSessionHandoverResult extends Record { + schema_version: typeof GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA; + goal_id: string; + todo_id: string; + agent_id: string; + session_mode: SessionMode; + from_profile_id: string; + to_profile_id: string; + availability: QuotaWindowAvailability; + used_ratio: number | null; + threshold_ratio: number; + disposition: HandoverDisposition; + gate_required: boolean; + turn_fence_satisfied: boolean; + ready_for_reacquisition: boolean; + reason: string; +} + +export function isSafeHostAlias(value: unknown): value is string { + if (typeof value !== "string") return false; + const trimmed = value.trim(); + return Boolean(trimmed) && !trimmed.includes("..") && SAFE_HOST_ALIAS.test(trimmed); +} + +export function assertPublicSafeFabricText( + value: string, + label: string, + fail: (message: string) => never, +): string { + const trimmed = value.trim(); + if (FORBIDDEN_CREDENTIAL_OR_PATH_PATTERNS.some((pattern) => pattern.test(trimmed))) { + throw fail(`${label} must not contain private paths or credentials`); + } + return trimmed; +} + +export function requireSafeHostAlias( + value: unknown, + label: string, + fail: (message: string) => never, +): string { + if (typeof value !== "string" || !value.trim()) { + throw fail(`${label} must be a non-empty string`); + } + const alias = assertPublicSafeFabricText(value, label, fail); + if (!isSafeHostAlias(alias)) { + throw fail(`${label} must be an explicit safe OpenSSH Host alias`); + } + return alias; +} + +export function decodeSshHostObservationWith( + value: unknown, + options: { + fail: (message: string) => never; + parseTimestamp: (raw: string) => Date | null; + }, +): SshHostObservation { + const { fail, parseTimestamp } = options; + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw fail("ssh_host_observation must be an object"); + } + const raw = value as Record; + if (raw.schema_version !== SESSION_FABRIC_SSH_OBSERVATION_SCHEMA) { + throw fail("ssh_host_observation schema_version mismatch"); + } + const alias = requireSafeHostAlias(raw.alias, "ssh_host_observation.alias", fail); + const rawConnectionState = raw.connection_state; + if (typeof rawConnectionState !== "string" || !rawConnectionState.trim()) { + throw fail("ssh_host_observation.connection_state must be a non-empty string"); + } + if (!(SESSION_FABRIC_SSH_CONNECTION_STATES as readonly string[]).includes(rawConnectionState)) { + throw fail("ssh_host_observation.connection_state is unsupported"); + } + const connectionState = rawConnectionState as SshConnectionState; + + let rawFailure: string | null = null; + const rawFailureCode = raw.failure_code; + if (rawFailureCode !== null && rawFailureCode !== undefined && rawFailureCode !== "") { + if (typeof rawFailureCode !== "string" || !rawFailureCode.trim()) { + throw fail("ssh_host_observation.failure_code must be a non-empty string"); + } + rawFailure = rawFailureCode.trim(); + } + + let failureCode: SshFailureCode | null = null; + if (connectionState === "degraded" || connectionState === "disconnected") { + if (rawFailure === null || !(SESSION_FABRIC_SSH_FAILURE_CODES as readonly string[]).includes(rawFailure)) { + throw fail("degraded or disconnected SSH host observations require a valid failure_code"); + } + failureCode = rawFailure as SshFailureCode; + } else if (rawFailure !== null) { + throw fail("connected or unknown SSH host observations must not carry a failure_code"); + } + + const rawLatency = raw.tunnel_latency_ms ?? null; + let latency: number | null = null; + if (rawLatency !== null) { + if (typeof rawLatency !== "number" || !Number.isSafeInteger(rawLatency) || rawLatency < 0) { + throw fail("ssh_host_observation.tunnel_latency_ms must be a non-negative integer"); + } + latency = rawLatency; + } + + let checkedAt: string | null = null; + const rawCheckedAt = raw.checked_at; + if (rawCheckedAt !== null && rawCheckedAt !== undefined && rawCheckedAt !== "") { + if (typeof rawCheckedAt !== "string" || !rawCheckedAt.trim()) { + throw fail("ssh_host_observation.checked_at must be a non-empty string"); + } + const cleanCheckedAt = assertPublicSafeFabricText(rawCheckedAt, "ssh_host_observation.checked_at", fail); + if (parseTimestamp(cleanCheckedAt) === null) { + throw fail("ssh_host_observation.checked_at must be a valid ISO timestamp"); + } + checkedAt = cleanCheckedAt; + } + + return { + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias, + connection_state: connectionState, + failure_code: failureCode, + checked_at: checkedAt, + tunnel_latency_ms: latency, + }; +} diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 6fbe7ec4ab..87f3798f23 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -697,6 +697,8 @@ export function createEffectRuntimeHandlers( ["collaboration.result.attachment_refs", lazyHandler(() => import("./collaboration/result_publication.ts"), ({resultAttachmentRefs}) => resultAttachmentRefs)], ["collaboration.result.delivery_ready", lazyHandler(() => import("./collaboration/result_publication.ts"), ({collaborationResultDeliveryReady}) => collaborationResultDeliveryReady)], ["collaboration.peer_host_route.select", lazyHandler(() => import("./collaboration/peer_route_selection.ts"), ({selectObservedPeerHostRoute}) => selectObservedPeerHostRoute)], + ["collaboration.session_fabric.project_ssh_host_catalog", lazyHandler(() => import("./collaboration/session_quota_fabric.ts"), ({projectSshHostCatalogRequest}) => projectSshHostCatalogRequest)], + ["collaboration.session_fabric.evaluate_governed_session_handover", lazyHandler(() => import("./collaboration/session_quota_fabric.ts"), ({evaluateGovernedSessionHandover}) => evaluateGovernedSessionHandover)], ["runtime.background.project", lazyHandler(() => import("./runtime/background_services.ts"), ({projectBackgroundServices}) => projectBackgroundServices)], ["runtime.execution_identity.codex", lazyHandler(() => import("./runtime/execution_identity.ts"), ({readCodexExecutionIdentity}) => readCodexExecutionIdentity)], ["runtime.execution_identity.match", lazyHandler(() => import("./runtime/execution_identity.ts"), ({matchExecutionDeclaration}) => matchExecutionDeclaration)], diff --git a/loopx/control_plane/status/ssh_host_catalog.py b/loopx/control_plane/status/ssh_host_catalog.py index 8d43a324d7..509f05e78d 100644 --- a/loopx/control_plane/status/ssh_host_catalog.py +++ b/loopx/control_plane/status/ssh_host_catalog.py @@ -1,9 +1,11 @@ from __future__ import annotations +from collections.abc import Mapping, Sequence import glob from pathlib import Path import re import shlex +from typing import cast SSH_HOST_CATALOG_SCHEMA_VERSION = "ssh_host_catalog_v0" @@ -64,7 +66,11 @@ def visit(candidate: Path) -> None: if directive != "host": continue for alias in parts[1:]: - if not _SAFE_HOST_ALIAS.fullmatch(alias) or alias in seen_aliases: + if ( + not _SAFE_HOST_ALIAS.fullmatch(alias) + or ".." in alias + or alias in seen_aliases + ): continue seen_aliases.add(alias) aliases.append(alias) @@ -76,8 +82,37 @@ def visit(candidate: Path) -> None: return aliases -def ssh_host_catalog_payload(config_path: Path | None = None) -> dict[str, object]: +def project_ssh_host_catalog( + configured_aliases: Sequence[str], + observations: Sequence[Mapping[str, object]] | None = None, +) -> dict[str, object]: + """Project `ssh_host_catalog_v0` with optional L0 SSH observations via the TypeScript owner.""" + + from ..effect_runtime import EffectRuntimeRejected, effect_runtime_result + + try: + return cast( + dict[str, object], + effect_runtime_result( + "collaboration.session_fabric.project_ssh_host_catalog", + { + "configured_aliases": list(configured_aliases), + "observations": [dict(item) for item in (observations or ())], + }, + ), + ) + except EffectRuntimeRejected as exc: + raise ValueError(str(exc)) from exc + + +def ssh_host_catalog_payload( + config_path: Path | None = None, + *, + observations: Sequence[Mapping[str, object]] | None = None, +) -> dict[str, object]: aliases = configured_ssh_host_aliases(config_path) + if observations: + return project_ssh_host_catalog(aliases, observations) return { "ok": True, "schema_version": SSH_HOST_CATALOG_SCHEMA_VERSION, diff --git a/loopx/semantics/vocabulary_v0.json b/loopx/semantics/vocabulary_v0.json index 5e165bbee1..37ee53ac50 100644 --- a/loopx/semantics/vocabulary_v0.json +++ b/loopx/semantics/vocabulary_v0.json @@ -13,7 +13,7 @@ "formal_model": { "schema_version": "loopx_semantic_formal_model_v0", "universes": { - "vocabularies": "V: registered vocabulary identifiers; Producers(V) ⊆ V is exactly the subset declaring a producers key (including compatibility-only entries with an empty list). Kernel(V) ⊆ Producers(V). Producers(V) contains 6 vocabularies: 5 kernel and 1 outside the kernel tier. The 23 cross_runtime vocabularies outside Producers(V) are unverified.", + "vocabularies": "V: registered vocabulary identifiers; Producers(V) ⊆ V is exactly the subset declaring a producers key (including compatibility-only entries with an empty list). Kernel(V) ⊆ Producers(V). Producers(V) contains 6 vocabularies: 5 kernel and 1 outside the kernel tier. The 28 cross_runtime vocabularies outside Producers(V) are unverified.", "values": "U(v): ambient runtime values; S(v): registered admitted values", "sites": "L: source locations that define, produce, consume, interpret, pass through, project, or persist values", "scopes": "Scope: global or bounded_context(context_id); ScopeDeclarations are the forked names the registry declares as bounded contexts", @@ -73,25 +73,25 @@ "invariants": [ { "id": "F1_producer_closedness", - "statement": "∀v ∈ Producers(V): Produced_scan(v) ⊆ S(v) ⊆ U(v), where Produced_scan(v) is the production the fixed forms observe inside the code-owned scan reach. Producers(V) contains 6 vocabularies: 5 kernel and 1 outside the kernel tier. The 23 cross_runtime vocabularies outside Producers(V) are unverified. Production outside the scan reach is unverified rather than proven closed.", + "statement": "∀v ∈ Producers(V): Produced_scan(v) ⊆ S(v) ⊆ U(v), where Produced_scan(v) is the production the fixed forms observe inside the code-owned scan reach. Producers(V) contains 6 vocabularies: 5 kernel and 1 outside the kernel tier. The 28 cross_runtime vocabularies outside Producers(V) are unverified. Production outside the scan reach is unverified rather than proven closed.", "enforcement": "m0_5", "evidence": "bounded production-form AST scan over the PRODUCER_ROOTS/PRODUCER_FILES reach in loopx/semantics/production.py; check_producers visits only vocabularies that declare producers, and validate_production claims no whole-program closedness; unresolved dynamic sites are reported, not treated as proven safe", "domain": { "quantifies_over": "vocabularies[producers].producers", "verified": 6, - "registered": 29, + "registered": 34, "evidence_bound": "producer_scan_reach" } }, { "id": "F2_canonical_value_liveness", - "statement": "∀v ∈ Producers(V): Canonical(v) ⊆ Produced_scan(v) ∪ CompatibilityOnly(v). Producers(V) contains 6 vocabularies: 5 kernel and 1 outside the kernel tier. The 23 cross_runtime vocabularies outside Producers(V) are unverified. Liveness outside the walked set is not proven.", + "statement": "∀v ∈ Producers(V): Canonical(v) ⊆ Produced_scan(v) ∪ CompatibilityOnly(v). Producers(V) contains 6 vocabularies: 5 kernel and 1 outside the kernel tier. The 28 cross_runtime vocabularies outside Producers(V) are unverified. Liveness outside the walked set is not proven.", "enforcement": "m0_5", "evidence": "every value of a vocabulary in Producers(V) has a producer recognised inside the scan reach, an executable input witness, or an explicit compatibility-only reason; a value whose only producer lies outside the reach would be reported as dead, not silently accepted", "domain": { "quantifies_over": "vocabularies[producers].producers", "verified": 6, - "registered": 29, + "registered": 34, "evidence_bound": "producer_scan_reach" } }, @@ -103,7 +103,7 @@ "domain": { "quantifies_over": "vocabularies[*]", "verified": 0, - "registered": 29, + "registered": 34, "evidence_bound": "inventory_only" } }, @@ -170,8 +170,8 @@ } }, "coverage_floor": { - "vocabularies": 29, - "owner_symbols": 56, + "vocabularies": 34, + "owner_symbols": 62, "literal_scan_fields": 1, "projections": 1, "relations": 9, @@ -1017,6 +1017,113 @@ "historical_only": "A standalone SQLite copy passed its bounded offline structural integrity check, but its bytes have not been adopted by a current domain owner. Restored provider identities and leases remain historical data.", "unknown": "No supported owner inventory exists for remaining v0 state, or a component failed format, availability, qualified-runtime or owner-read validation. Unknown never becomes readable merely because archive or file hashes matched." } + }, + "session_mode": { + "meaning": "Explicit, non-implicitly-switchable execution ownership mode of a LoopX agent session binding.", + "tier": "cross_runtime", + "status": "canonical", + "owners": { + "python": "loopx/chat_store.py::CHAT_SESSION_MODES", + "typescript": "loopx/control_plane/collaboration/session_quota_fabric_contract.ts::SESSION_MODES" + }, + "values": [ + "managed_runtime", + "attached_host" + ], + "value_notes": { + "managed_runtime": "Default execution mode in loopx/chat_store.py when creating a LoopX-owned runtime session; preserved across governed session handover without implicit mode switching.", + "attached_host": "Explicitly bound execution mode when attaching an external host session with a non-empty host_surface in loopx/chat_store.py; preserved across governed session handover without implicit mode switching." + } + }, + "session_fabric_ssh_connection_state": { + "meaning": "Read-only L0 SSH host readiness state attached optionally to ssh_host_catalog_v0 entries.", + "tier": "cross_runtime", + "status": "canonical", + "owners": { + "python": null, + "typescript": "loopx/control_plane/collaboration/session_quota_fabric_contract.ts::SESSION_FABRIC_SSH_CONNECTION_STATES" + }, + "values": [ + "connected", + "degraded", + "disconnected", + "unknown" + ], + "value_notes": { + "connected": "Supplied by an SSH host observation when the tunnel and remote host check succeeded; requires failure_code to be null.", + "degraded": "Supplied by an SSH host observation when the host or tunnel is partially reachable or impaired; requires a non-null failure_code from session_fabric_ssh_failure_code.", + "disconnected": "Supplied by an SSH host observation when the SSH tunnel or host check failed to connect; requires a non-null failure_code from session_fabric_ssh_failure_code.", + "unknown": "Supplied by an SSH host observation when readiness has not been established; requires failure_code to be null and grants no connection guarantee." + } + }, + "session_fabric_ssh_failure_code": { + "meaning": "Typed SSH readiness failure reason required on degraded or disconnected L0 SSH host observations.", + "tier": "cross_runtime", + "status": "canonical", + "owners": { + "python": null, + "typescript": "loopx/control_plane/collaboration/session_quota_fabric_contract.ts::SESSION_FABRIC_SSH_FAILURE_CODES" + }, + "values": [ + "no_ssh", + "host_key", + "auth", + "unreachable", + "ssh_failed", + "daemon_missing", + "forward_denied" + ], + "value_notes": { + "no_ssh": "Emitted on a degraded or disconnected observation when the OpenSSH client binary is unavailable on the host.", + "host_key": "Emitted on a degraded or disconnected observation when SSH host-key verification failed.", + "auth": "Emitted on a degraded or disconnected observation when SSH authentication was rejected.", + "unreachable": "Emitted on a degraded or disconnected observation when the target SSH host could not be reached over the network.", + "ssh_failed": "Emitted on a degraded or disconnected observation when the SSH transport exited with a generic connection failure.", + "daemon_missing": "Emitted on a degraded or disconnected observation when the remote LoopX daemon or status endpoint is absent.", + "forward_denied": "Emitted on a degraded or disconnected observation when SSH port forwarding to the loopback target was denied." + } + }, + "session_fabric_quota_availability": { + "meaning": "Opaque-profile quota window availability state decoded fail-closed by L0 session fabric.", + "tier": "cross_runtime", + "status": "canonical", + "owners": { + "python": null, + "typescript": "loopx/control_plane/collaboration/session_quota_fabric_contract.ts::SESSION_FABRIC_QUOTA_AVAILABILITIES" + }, + "values": [ + "available", + "near_limit", + "exhausted", + "unknown" + ], + "value_notes": { + "available": "Decoded on a quota window observation with remaining capacity; sets handover_eligible=false and causes evaluateGovernedSessionHandover to return no_handover_needed.", + "near_limit": "Decoded on a quota window observation approaching exhaustion; sets handover_eligible=true so evaluateGovernedSessionHandover enters gating/fencing when used_ratio >= threshold_ratio.", + "exhausted": "Decoded on a depleted quota window observation; sets handover_eligible=true so evaluateGovernedSessionHandover enters gating/fencing regardless of used_ratio.", + "unknown": "Decoded on an unverified quota window observation (requires used_ratio=null); forces handover_eligible=false and causes evaluateGovernedSessionHandover to fail closed with no_handover_needed." + } + }, + "session_fabric_handover_disposition": { + "meaning": "Fence-bound governed session handover evaluation verdict returned without executing switches or acquiring leases.", + "tier": "cross_runtime", + "status": "canonical", + "owners": { + "python": null, + "typescript": "loopx/control_plane/collaboration/session_quota_fabric_contract.ts::SESSION_FABRIC_HANDOVER_DISPOSITIONS" + }, + "values": [ + "no_handover_needed", + "user_gate_required", + "await_turn_fence", + "ready_for_lease_reacquisition" + ], + "value_notes": { + "no_handover_needed": "Returned by evaluateGovernedSessionHandover when observation.handover_eligible is false (unknown or available) or when availability is near_limit with used_ratio below threshold_ratio.", + "user_gate_required": "Returned by evaluateGovernedSessionHandover when handover is warranted and ask_before_switch=true, routing confirmation to the shared Goal Inbox/Gate projection.", + "await_turn_fence": "Returned by evaluateGovernedSessionHandover when handover is warranted, ask_before_switch=false, and either current_turn_fenced or previous_lease_released is false.", + "ready_for_lease_reacquisition": "Returned by evaluateGovernedSessionHandover when handover is warranted, ask_before_switch=false, and both current_turn_fenced and previous_lease_released are true." + } } }, "relations": { diff --git a/tests/architecture/test_semantic_vocabulary_drift.py b/tests/architecture/test_semantic_vocabulary_drift.py index 62a4922ab2..1ffa05fc33 100644 --- a/tests/architecture/test_semantic_vocabulary_drift.py +++ b/tests/architecture/test_semantic_vocabulary_drift.py @@ -607,7 +607,7 @@ def test_generated_domain_accepts_true_kernel_comparison() -> None: # Recovery registers one additional cross-runtime vocabulary without # claiming a qualified producer scan for its offline observations. assert "state_recovery_component_state" not in domain.walked - assert domain.outside_by_tier == (("cross_runtime", 23),) + assert domain.outside_by_tier == (("cross_runtime", 28),) def test_canonical_domain_rejects_old_kernel_only_universe() -> None: @@ -631,7 +631,7 @@ def test_domain_membership_change_requires_regenerated_prose() -> None: with pytest.raises(smoke["Drift"], match="canonical producer-domain projection"): smoke["check_formal_model"](registry["formal_model"], registry) projected = smoke["producer_domain_prose"](registry) - assert "24 cross_runtime" in projected["F1_producer_closedness.statement"] + assert "29 cross_runtime" in projected["F1_producer_closedness.statement"] assert "5 kernel and 0 outside" in projected["universes.vocabularies"] @@ -777,7 +777,7 @@ def test_adding_a_vocabulary_forces_the_declared_domain_to_move() -> None: "meaning": "probe", "tier": "cross_runtime", "status": "canonical", "owners": {"python": None, "typescript": None}, "values": ["probe_value"], } - with pytest.raises(smoke["Drift"], match="the registry holds 30"): + with pytest.raises(smoke["Drift"], match="the registry holds 35"): smoke["check_formal_model"](registry["formal_model"], registry) @@ -997,8 +997,8 @@ def test_retired_lease_registry_entry_cannot_return_as_fake_compatibility(): def test_native_lifecycle_relation_keeps_the_live_owner_and_verification_boundary(): smoke = runpy.run_path(str(SMOKE)) registry = smoke['load_registry']() - assert registry['coverage_floor']['vocabularies'] == 29 - assert registry['coverage_floor']['owner_symbols'] == 56 + assert registry['coverage_floor']['vocabularies'] == 34 + assert registry['coverage_floor']['owner_symbols'] == 62 assert registry['coverage_floor']['relations'] == 9 relation = next(row for row in registry['relations']['subsets'] if row['name'] == 'task_lease_lifecycle_decision_operation') diff --git a/tests/control_plane_ts/session_quota_fabric.test.ts b/tests/control_plane_ts/session_quota_fabric.test.ts index 87d70e92df..da85a1945a 100644 --- a/tests/control_plane_ts/session_quota_fabric.test.ts +++ b/tests/control_plane_ts/session_quota_fabric.test.ts @@ -2,15 +2,22 @@ import assert from "node:assert/strict"; import test from "node:test"; import { EffectRuntimeRequestError } from "../../loopx/control_plane/effect_runtime_errors.ts"; +import { + createEffectRuntimeHandlers, + dispatchEffectRuntimeMethod, +} from "../../loopx/control_plane/effect_runtime_handlers.ts"; import { decodeSessionQuotaWindowObservation, decodeSshHostObservation, evaluateGovernedSessionHandover, GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, GOVERNED_SESSION_HANDOVER_RESULT_SCHEMA, + isSafeHostAlias, projectSshHostCatalogPayload, + SAFE_HOST_ALIAS, SESSION_FABRIC_SSH_FAILURE_CODES, SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + SESSION_MODES, SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, } from "../../loopx/control_plane/collaboration/session_quota_fabric.ts"; @@ -24,6 +31,90 @@ test("ssh_host_catalog_v0 preserves byte-identical shape when L0 observations ar assert.deepEqual(Object.keys((payload.hosts as Record[])[0]), ["alias"]); }); +test("valid OpenSSH aliases and identifiers containing sk- substrings are allowed while real secret prefixes and paths fail closed", () => { + const validAliases = ["desk-box", "task-worker", "disk-01", "kiosk-2", "flask-api"]; + for (const alias of validAliases) { + assert.equal(isSafeHostAlias(alias), true); + assert.equal(SAFE_HOST_ALIAS.test(alias), true); + } + const catalog = projectSshHostCatalogPayload(validAliases); + assert.deepEqual(catalog.hosts, validAliases.map((alias) => ({ alias }))); + + const safeWindow = decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "task-worker", + availability: "near_limit", + used_ratio: 0.91, + resets_at: null, + eligible_models: ["desk-box-model", "deepseek-chat", "kiosk-2"], + }); + assert.equal(safeWindow.profile_id, "task-worker"); + assert.deepEqual(safeWindow.eligible_models, ["desk-box-model", "deepseek-chat", "kiosk-2"]); + + const safeHandover = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "task-worker-goal", + todo_id: "todo_desk-box", + agent_id: "kiosk-2-agent", + from_profile_id: "task-worker", + to_profile_id: "disk-01", + from_session_mode: SESSION_MODES[0], + to_session_mode: SESSION_MODES[0], + quota_observation: safeWindow, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }); + assert.equal(safeHandover.disposition, "ready_for_lease_reacquisition"); + + const secretInputs = [ + "sk-" + "12345678", + "sk-" + "proj-abcdef12", + "sk-" + "ant-abcdef12", + "sk-" + "live-abcdef12", + "sk-" + "test-abcdef12", + "sk_" + "live_abcdef12", + "ghp" + "_abcdef12", + "github_pat" + "_abcdef12", + ]; + for (const secret of secretInputs) { + assert.throws(() => projectSshHostCatalogPayload([secret]), EffectRuntimeRequestError); + assert.throws(() => decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: secret, + availability: "near_limit", + used_ratio: 0.9, + resets_at: null, + eligible_models: [], + }), EffectRuntimeRequestError); + assert.throws(() => decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-a", + availability: "near_limit", + used_ratio: 0.9, + resets_at: null, + eligible_models: [secret], + }), EffectRuntimeRequestError); + } + + for (const unsafeText of [ + "Bearer " + "fixture1234", + "/" + "Users/fixture/key", + "/" + "home/fixture/key", + "~/.ssh" + "/id_ed25519", + ]) { + assert.throws(() => decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-a", + availability: "near_limit", + used_ratio: 0.9, + resets_at: null, + eligible_models: [unsafeText], + }), EffectRuntimeRequestError); + } +}); + test("SSH observations accept all seven typed failure codes and fail closed on contradictions or unknown aliases", () => { for (const code of SESSION_FABRIC_SSH_FAILURE_CODES) { const decoded = decodeSshHostObservation({ @@ -123,6 +214,90 @@ test("quota window observations require opaque profile ids and unknown usage nev assert.equal(belowOrUnknown.ready_for_reacquisition, false); }); +test("governed handover enforces observation.handover_eligible and availability counterfactuals", () => { + // Counterfactual 1: available window with high used_ratio must stay no_handover_needed. + const availableHighRatio = decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-primary", + availability: "available", + used_ratio: 0.95, + resets_at: null, + eligible_models: ["gpt-codex"], + }); + assert.equal(availableHighRatio.handover_eligible, false); + const availableResult = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: availableHighRatio, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }); + assert.equal(availableResult.disposition, "no_handover_needed"); + assert.equal(availableResult.ready_for_reacquisition, false); + + // Counterfactual 2: exhausted window with low used_ratio must still enter handover gating/fencing. + const exhaustedLowRatio = decodeSessionQuotaWindowObservation({ + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-primary", + availability: "exhausted", + used_ratio: 0.5, + resets_at: "2026-11-17T06:00:00Z", + eligible_models: ["gpt-codex"], + }); + assert.equal(exhaustedLowRatio.handover_eligible, true); + const exhaustedReady = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: exhaustedLowRatio, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }); + assert.equal(exhaustedReady.disposition, "ready_for_lease_reacquisition"); + assert.equal(exhaustedReady.ready_for_reacquisition, true); + + // Counterfactual 3: near_limit below threshold_ratio must stay no_handover_needed. + const nearLimitBelow = evaluateGovernedSessionHandover({ + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-primary", + to_profile_id: "profile-secondary", + from_session_mode: "managed_runtime", + to_session_mode: "managed_runtime", + quota_observation: { + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-primary", + availability: "near_limit", + used_ratio: 0.85, + resets_at: null, + eligible_models: ["gpt-codex"], + }, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }); + assert.equal(nearLimitBelow.disposition, "no_handover_needed"); + assert.equal(nearLimitBelow.ready_for_reacquisition, false); +}); + test("governed handover enforces session mode preservation, shared Gate, and turn/lease fencing", () => { const nearLimit = { schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, @@ -206,3 +381,82 @@ test("governed handover enforces session mode preservation, shared Gate, and tur assert.equal(ready.turn_fence_satisfied, true); assert.equal(ready.ready_for_reacquisition, true); }); + +test("effect_runtime_handlers dispatches registered session_fabric operations", async () => { + const handlers = createEffectRuntimeHandlers({ fingerprint: "fabric-test", requestShutdown() {} }); + + const featureOff = await dispatchEffectRuntimeMethod( + handlers, + "collaboration.session_fabric.project_ssh_host_catalog", + { configured_aliases: ["desk-box", "task-worker"] }, + ); + assert.deepEqual(featureOff, { + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [{ alias: "desk-box" }, { alias: "task-worker" }], + }); + + const featureOn = await dispatchEffectRuntimeMethod( + handlers, + "collaboration.session_fabric.project_ssh_host_catalog", + { + configured_aliases: ["desk-box", "task-worker"], + observations: [ + { + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias: "desk-box", + connection_state: "degraded", + failure_code: "daemon_missing", + checked_at: "2026-11-20T00:00:00Z", + tunnel_latency_ms: 42, + }, + ], + }, + ); + assert.deepEqual(featureOn, { + ok: true, + schema_version: "ssh_host_catalog_v0", + hosts: [ + { + alias: "desk-box", + observation: { + schema_version: SESSION_FABRIC_SSH_OBSERVATION_SCHEMA, + alias: "desk-box", + connection_state: "degraded", + failure_code: "daemon_missing", + checked_at: "2026-11-20T00:00:00Z", + tunnel_latency_ms: 42, + }, + }, + { alias: "task-worker" }, + ], + }); + + const handover = await dispatchEffectRuntimeMethod( + handlers, + "collaboration.session_fabric.evaluate_governed_session_handover", + { + schema_version: GOVERNED_SESSION_HANDOVER_PROPOSAL_SCHEMA, + goal_id: "demo-goal", + todo_id: "todo_sample01", + agent_id: "antigravity", + from_profile_id: "profile-a", + to_profile_id: "profile-b", + from_session_mode: "attached_host", + to_session_mode: "attached_host", + quota_observation: { + schema_version: SESSION_QUOTA_WINDOW_OBSERVATION_SCHEMA, + profile_id: "profile-a", + availability: "exhausted", + used_ratio: 0.4, + resets_at: null, + eligible_models: ["gpt-codex"], + }, + threshold_ratio: 0.9, + current_turn_fenced: true, + previous_lease_released: true, + ask_before_switch: false, + }, + ); + assert.equal((handover as Record).disposition, "ready_for_lease_reacquisition"); +}); diff --git a/tests/test_status_server_ssh_hosts.py b/tests/test_status_server_ssh_hosts.py index 2543504156..444a81eb40 100644 --- a/tests/test_status_server_ssh_hosts.py +++ b/tests/test_status_server_ssh_hosts.py @@ -3,12 +3,22 @@ import http.client import json from pathlib import Path +import re import threading +import pytest + from loopx.chat_server import ChatHTTPServer, ChatRequestHandler +from loopx.control_plane.effect_runtime import ( + EffectRuntimeRejected, + effect_runtime_result, +) from loopx.control_plane.status.ssh_host_catalog import ( SSH_HOST_CATALOG_PATH, + _SAFE_HOST_ALIAS, configured_ssh_host_aliases, + project_ssh_host_catalog, + ssh_host_catalog_payload, ) from loopx.status_server import DEFAULT_SSH_HOSTS_PATH, StatusHTTPServer, StatusRequestHandler @@ -148,3 +158,162 @@ def test_packaged_chat_ssh_hosts_rejects_non_loopback_origin(tmp_path: Path) -> assert response.status == 403 assert payload["ok"] is False + + +def test_ssh_host_catalog_feature_off_parity_and_sk_substring_aliases( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + def _unexpected_runtime(*_args: object, **_kwargs: object) -> object: + raise AssertionError("feature-off ssh_host_catalog_payload must not start effect_runtime") + + monkeypatch.setattr( + "loopx.control_plane.effect_runtime.effect_runtime_result", + _unexpected_runtime, + ) + ssh_dir = tmp_path / ".ssh" + ssh_dir.mkdir(parents=True) + config = ssh_dir / "config" + config.write_text( + "Host desk-box task-worker disk-01 kiosk-2 bad..alias\n HostName 192.0.2.20\n", + encoding="utf-8", + ) + + expected = { + "ok": True, + "schema_version": "ssh_host_catalog_v0", + "hosts": [ + {"alias": "desk-box"}, + {"alias": "task-worker"}, + {"alias": "disk-01"}, + {"alias": "kiosk-2"}, + ], + } + assert ssh_host_catalog_payload(config) == expected + assert ssh_host_catalog_payload(config, observations=[]) == expected + + contract_ts = ( + Path(__file__).resolve().parents[1] + / "loopx/control_plane/collaboration/session_quota_fabric_contract.ts" + ).read_text(encoding="utf-8") + match = re.search(r"export const SAFE_HOST_ALIAS = /([^/]+)/;", contract_ts) + assert match is not None + assert match.group(1) == _SAFE_HOST_ALIAS.pattern + + +def test_ssh_host_catalog_observation_round_trip_and_handover_handler(tmp_path: Path) -> None: + ssh_dir = tmp_path / ".ssh" + ssh_dir.mkdir(parents=True) + config = ssh_dir / "config" + config.write_text("Host desk-box task-worker\n", encoding="utf-8") + + projected = ssh_host_catalog_payload( + config, + observations=[ + { + "schema_version": "session_fabric_ssh_observation_v0", + "alias": "desk-box", + "connection_state": "disconnected", + "failure_code": "unreachable", + "checked_at": "2026-11-20T00:00:00Z", + "tunnel_latency_ms": None, + } + ], + ) + assert projected == { + "ok": True, + "schema_version": "ssh_host_catalog_v0", + "hosts": [ + { + "alias": "desk-box", + "observation": { + "schema_version": "session_fabric_ssh_observation_v0", + "alias": "desk-box", + "connection_state": "disconnected", + "failure_code": "unreachable", + "checked_at": "2026-11-20T00:00:00Z", + "tunnel_latency_ms": None, + }, + }, + {"alias": "task-worker"}, + ], + } + + with pytest.raises(ValueError, match="absent from ssh_host_catalog_v0"): + project_ssh_host_catalog( + ["desk-box"], + [ + { + "schema_version": "session_fabric_ssh_observation_v0", + "alias": "phantom-box", + "connection_state": "connected", + "failure_code": None, + "checked_at": None, + "tunnel_latency_ms": 5, + } + ], + ) + + handover = effect_runtime_result( + "collaboration.session_fabric.evaluate_governed_session_handover", + { + "schema_version": "governed_session_handover_proposal_v0", + "goal_id": "demo-goal", + "todo_id": "todo_sample01", + "agent_id": "antigravity", + "from_profile_id": "profile-a", + "to_profile_id": "profile-b", + "from_session_mode": "managed_runtime", + "to_session_mode": "managed_runtime", + "quota_observation": { + "schema_version": "session_quota_window_observation_v0", + "profile_id": "profile-a", + "availability": "available", + "used_ratio": 0.95, + "resets_at": None, + "eligible_models": ["gpt-codex"], + }, + "threshold_ratio": 0.9, + "current_turn_fenced": True, + "previous_lease_released": True, + "ask_before_switch": False, + }, + ) + assert handover["disposition"] == "no_handover_needed" + assert handover["ready_for_reacquisition"] is False + + handover_exhausted = effect_runtime_result( + "collaboration.session_fabric.evaluate_governed_session_handover", + { + "schema_version": "governed_session_handover_proposal_v0", + "goal_id": "demo-goal", + "todo_id": "todo_sample01", + "agent_id": "antigravity", + "from_profile_id": "profile-a", + "to_profile_id": "profile-b", + "from_session_mode": "attached_host", + "to_session_mode": "attached_host", + "quota_observation": { + "schema_version": "session_quota_window_observation_v0", + "profile_id": "profile-a", + "availability": "exhausted", + "used_ratio": 0.5, + "resets_at": None, + "eligible_models": ["gpt-codex"], + }, + "threshold_ratio": 0.9, + "current_turn_fenced": True, + "previous_lease_released": True, + "ask_before_switch": False, + }, + ) + assert handover_exhausted["disposition"] == "ready_for_lease_reacquisition" + assert handover_exhausted["ready_for_reacquisition"] is True + + with pytest.raises(ValueError, match="credentials"): + project_ssh_host_catalog(["sk-" + "proj-abcdef12"]) + + with pytest.raises(EffectRuntimeRejected, match="credentials"): + effect_runtime_result( + "collaboration.session_fabric.project_ssh_host_catalog", + {"configured_aliases": ["sk-" + "proj-abcdef12"]}, + ) diff --git a/tsconfig.control-plane.json b/tsconfig.control-plane.json index febde3aafc..1d5f29eecc 100644 --- a/tsconfig.control-plane.json +++ b/tsconfig.control-plane.json @@ -130,6 +130,7 @@ "tests/control_plane_ts/direction_authority.test.ts", "tests/control_plane_ts/direction_baseline.test.ts", "tests/control_plane_ts/material_wave_ranking.test.ts", + "tests/control_plane_ts/session_quota_fabric.test.ts", "tests/control_plane_ts/zcode*.test.ts" ] }