diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md index ba2f0db398..5d5b47e81c 100644 --- a/docs/architecture/rfcs/README.md +++ b/docs/architecture/rfcs/README.md @@ -263,6 +263,18 @@ Paired diffs do not certify translation accuracy. governed commit policy/verifier, lease-impact handling and Stage 3+ qualification remain unshipped. Manager handoff consumes these boundaries; it does not provide another amendment writer. +- [Goal-Oriented Multi-Agent Peer Coordination v0](goal-oriented-multi-agent-coordination-v0.md) + ([中文版](goal-oriented-multi-agent-coordination-v0.zh-CN.md)) + - **Delivery on `main`:** M0 read-only peer frontier and collaboration + opportunity projection implemented (`peer_coordination.ts`); M1–M3 remain + unshipped. + - **Current boundary:** Projects bounded `peer_frontiers` and deterministic + `collaboration_opportunities` (`shared_target_collision_risk`, + `peer_verification_needed`, `peer_unleased_lane_attention`, + `shared_domain_synergy`, all with `grants_authority: false`) onto + `shared_goal_alignment_v0` from canonical `file_v0`/`sqlite_v0` snapshots. + Turn-envelope `<=400 B` digests (M1), cooldown-gated bilateral `manager-inbox` + handshakes (M2), and host-neutral live route observers (M3) remain open. - [Goal contract evolution and bounded working context v0](goal-contract-evolution-v0.md) ([中文版](goal-contract-evolution-v0.zh-CN.md)) - **Delivery on `main`:** Proposal only; existing objective revision and additive diff --git a/docs/architecture/rfcs/STATUS.md b/docs/architecture/rfcs/STATUS.md index 86b76ad7bc..a1d60044ec 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 (54) +## Accepted (55) | RFC | Header status | Supersedes / closes | Ledger | | --- | --- | --- | --- | @@ -42,6 +42,7 @@ appendix may keep dated history, but no dated log heading may precede it. | [RFC: Goal Direction Baseline (v0)](goal-direction-baseline-v0.md) | Accepted | none | — | | [Design follow-up: Goal continuity across restart and replacement](goal-immutability-coherence-defense-v0.md) | Accepted | none | — | | [Goal Instance Identity and Orphan Recovery (v0)](goal-instance-identity-and-orphan-recovery-v0.md) | Accepted | none | — | +| [RFC: Goal-Oriented Multi-Agent Peer Coordination (v0)](goal-oriented-multi-agent-coordination-v0.md) | Accepted | none | — | | [RFC: Persistent Goal outcome refinement (v0)](goal-outcome-refinement-v0.md) | Accepted | none | — | | [RFC: Goal-scoped Capability Portfolio and Connector Lifecycle (v0)](goal-scoped-capability-portfolio-v0.md) | Accepted | none | — | | [RFC: Per-Goal Usage, Token, and Cost Surfacing v0](goal-usage-token-cost-v0.md) | Accepted | none | — | diff --git a/docs/architecture/rfcs/STATUS.zh-CN.md b/docs/architecture/rfcs/STATUS.zh-CN.md index f519f7e11c..9cd3ee26d4 100644 --- a/docs/architecture/rfcs/STATUS.zh-CN.md +++ b/docs/architecture/rfcs/STATUS.zh-CN.md @@ -15,7 +15,7 @@ [English](STATUS.md) 与本文互为语义镜像。 -## 已接受 (54) +## 已接受 (55) | RFC | 头部状态 | 替代 / 关闭 | Ledger | | --- | --- | --- | --- | @@ -39,6 +39,7 @@ | [RFC:Goal Direction Baseline(目标方向基线)v0](goal-direction-baseline-v0.zh-CN.md) | 已接受 | 无 | — | | [后续设计:重启与实例替换中的 Goal 连续性](goal-immutability-coherence-defense-v0.zh-CN.md) | 已接受 | none | — | | [Goal 实例身份与孤儿状态恢复(v0)](goal-instance-identity-and-orphan-recovery-v0.zh-CN.md) | 已接受 | 无 | — | +| [RFC:面向目标的多 Agent 自主协同协议(v0)](goal-oriented-multi-agent-coordination-v0.zh-CN.md) | 已接受 | 无 | — | | [RFC:持久化 Goal 成果细化(v0)](goal-outcome-refinement-v0.zh-CN.md) | 已接受 | 无 | — | | [RFC:Goal 级能力组合与 Connector 生命周期(v0)](goal-scoped-capability-portfolio-v0.zh-CN.md) | 已接受 | 无 | — | | [RFC: Per-Goal Usage, Token, and Cost Surfacing v0](goal-usage-token-cost-v0.md) | 已接受 | none | — | diff --git a/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.md b/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.md new file mode 100644 index 0000000000..8fad5af7e3 --- /dev/null +++ b/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.md @@ -0,0 +1,176 @@ +# RFC: Goal-Oriented Multi-Agent Peer Coordination (v0) + +- **RFC status:** Accepted +- **Supersedes / closes:** none +- **Delivery maturity:** Partial (M0 read-only peer frontier and collaboration opportunity projection shipped; M1–M3 remain follow-up slices) +- **Authors / owners:** existing control-plane alignment, collaboration, and directory owners +- **Created:** 2026-11-27 +- **Last normative revision:** 2026-11-27 +- **Implementation baseline:** `50b4cc9de4` +- **Related contracts:** [Shared Goal Alignment and Governed Amendment Protocol](shared-goal-alignment-and-governed-amendment-v0.md), [Peer Agent Directory and Observation](../../reference/protocols/peer-agent-directory-and-observation-v0.md), [Capable Agent Manager and Semantic Work Handoff](capable-manager-semantic-handoff-v0.md), [Live Team Workspace](live-team-workspace-v0.md) +- **Language mirror:** [中文版](goal-oriented-multi-agent-coordination-v0.zh-CN.md) + +## Document map and maintenance contract + +Sections 1–10 define the durable design, safety, and acceptance contract. +Section 11 defines the normative delivery plan (starting from the M0 slice +shipped against `50b4cc9de4`). Section 12 lists unresolved design decisions for +M1–M3. Appendices record non-normative execution lineage and evidence. The English document and its [Chinese mirror](goal-oriented-multi-agent-coordination-v0.zh-CN.md) +are semantic mirrors; any discrepancy between the two is a defect. + +--- + +## 1. Decision summary + +1. **Make same-Goal peer frontiers discoverable without adding a new database or authority.** Extend `shared_goal_alignment_v0` additively with bounded `peer_frontiers` and `collaboration_opportunities` derived deterministically in a single TypeScript owner (`loopx/control_plane/goals/peer_coordination.ts`) from existing canonical Todos and task leases. +2. **Preserve zero-authority read projections (`grants_authority: false`).** Discovering a collision risk, an independent verification need, an unleased high-priority peer lane, or shared-domain synergy never transfers claims, overrides leases, edits Todos, or triggers auto-delivery on its own. +3. **Shift from human-relayed pull to bilateral goal-oriented handshakes.** Keep explicit claim/lease/inbox owners unchanged (`shared_goal_alignment_v0`, `peer_agent_directory_v0`, `manager-inbox`), while specifying a bounded pull-side discovery path and future opt-in Turn-envelope digest (`<=400 B`) so two specialized peers on one Goal (e.g., simplification vs. verification) can coordinate directly within the `<5%` control-plane context budget. +4. **Separate deterministic M0 from opt-in M1–M3 transport/host profiles.** M0 ships strictly in read-only alignment projection (`shared-goal-alignment` / `goal-alignment`); automatic Turn-envelope digests (M1), cooldown-gated bilateral offer/decline (M2), and host-neutral Antigravity/non-Codex observer adapters (M3) remain gated behind explicit acceptance evidence. +5. **This RFC does not approve** autonomous multi-agent self-merging, automatic Todo reassignment across owners, or unconditional Turn-envelope size growth. + +## 2. Problem and motivation + +When multiple specialist Agents share one LoopX Goal (for example, a microkernel/code-simplification Agent opening focused PRs while a benchmark/verification Agent validates efficiency gains and catches subtle regressions), today's coordination still falls back on a human operator to bridge the two sessions: + +- A user frequently has to tell Agent B: *"Agent A has some simplification PRs; go coordinate, verify, and polish them together."* +- Meanwhile, peers lack a pull-side view of which peer lanes already overlap in target/write-scope, need independent verification, or sit unleased on a high-priority lane. + +Five concrete structural gaps explain why spontaneous peer-to-peer coordination fails today: + +1. **Opaque scalar peer counts:** `shared_goal_alignment_v0` currently exposes only `other_agent_claimed_advancement_count` (an integer) and `peer_claimed_bound_todo_ids` (`bound_agent === caller`). Peer priorities, domains, repositories, `target_key`s, write scopes, and `completion_validation_required` flags stay hidden. +2. **Push-only inbox delivery without pull-side synergy matching:** `manager-inbox` works well once Sender A already knows exact Peer B and crafts a bespoke brief, yet neither agent can deterministically ask *"which active peer lane needs independent verification or touches my current domain right now?"* +3. **Collision blind spots prior to lease conflicts:** Two peers working on overlapping `required_write_scopes` or identical `target_key` only discover contention at hard lease/worktree failure time rather than via an advisory pre-edit signal. +4. **Context-budget hazard for peer awareness:** Naively dumping full peer work trees into Turn envelopes violates the `<5%` control-plane context tax invariant; discovery must be pull-first and tightly bounded (`MAX_PEER_FRONTIER_ITEMS = 12`, `MAX_COLLABORATION_OPPORTUNITIES = 8`), with deterministic cursor/ID deduplication. +5. **Asymmetric host reachability:** `resolve-peer-route` reports `unavailable (host_observer_unavailable)` for hosts without an implemented observer adapter (such as Antigravity desktop sessions vs. Codex app-server threads), forcing senders to degrade to unrouted inbox writes or manual prompt copy-paste. + +### Invariants + +- **Single state authority:** Peer coordination introduces zero parallel Todo tables, shadow claim files, or secondary intent stores; every field projects from canonical Todo/lease snapshots (`file_v0` / `sqlite_v0`). +- **Single semantic reducer:** One TypeScript module (`peer_coordination.ts`) defines eligibility, overlap matching, priority ordering, deduplication, and caps; Python/CLI callers are pure transport/formatting adapters. +- **Deterministic & authority-free outputs:** Identical input snapshots yield byte-identical sorted outputs and deterministic `opportunity_id`s, always carrying `grants_authority: false` and `read_only: true`. +- **Fail closed for caller authority, fail bounded for corrupt peer metadata:** Unreadable caller lease metadata continues to reject alignment projection; unreadable peer lease metadata yields `lease_active: null` rather than breaking the caller's read-only view. +- **Public-safe boundaries:** No private local paths, raw chat transcripts, or credentials appear in `peer_frontiers` or `collaboration_opportunities`. + +## 3. Scope and non-goals + +### In scope + +- Additive M0 extension of `shared_goal_alignment_v0` (`peer_frontiers`, `collaboration_opportunities`) computed by TypeScript and exposed via `loopx shared-goal-alignment` / `goal-alignment`. +- Normative protocol specification for pull-side matching, deterministic `opportunity_id` deduplication, bounded Turn-envelope digest integration (M1), cooldown-gated bilateral `manager-inbox` handshake (M2), and host-neutral route observation profiles (M3). + +### Non-goals + +- Replacing `shared_goal_intent_v0`, `goal_amendment_proposal_v0`, `task_lease`, or `peer_agent_directory_v0`. +- Granting agents unilateral claim-stealing, priority mutation, or self-merge permission. +- Adding host-specific chat polling loops or scraping desktop transcripts outside registered public-safe bindings. + +## 4. Current-system contract + +At baseline `50b4cc9de4`: + +- **Goal membership & directory (`loopx/control_plane/agents/directory.py`, `agent-directory`):** Projects registered agents, current Todo summary (`todo_id`, `status`, `claimed_by`, `title`), `stale_claim_hint`, and `peer_route`, without computing pair-wise work synergy, write-scope collisions, or verification requests. +- **Shared Goal alignment (`loopx/control_plane/goals/shared_goal_alignment.ts`, `shared_goal_work.ts`, `shared_goal_work_source.py`):** Reads one canonical snapshot (`canonical_todo_snapshot`), counts `current_agent_claimed_advancement_count`, `unclaimed_advancement_count`, and `other_agent_claimed_advancement_count`, checks caller leases and `peer_claimed_bound_todo_ids`, and returns `read_only: true`. It currently discards peer `task_domain`, `task_repository`, `target_key`, `required_write_scopes`, `completion_validation_required`, `priority`, and `lease_active`. +- **Execution orchestration (`loopx/control_plane/quota/peer_orchestration.ts`):** Handles task-scoped coordinator activation of `peer_agent_activation` lanes (`bound` / `executing`) when the caller holds coordinator capability, not equal-rank `peer_v1` horizontal discovery. +- **Write-scope overlap & repository identity (`work_items/task_lease_acquire_decision.ts`, `work_items/task_lease_repository.ts`, `todos/work_requirements.ts`):** Existing TS owners already normalize `task_repository`, normalize `required_write_scopes`, and test overlap (`evaluateQuotaSchedulingWriteScopesOverlap`, `repositoryScopesMayOverlap`). + +## 5. Proposed architecture + +### Ownership and authority + +`loopx/control_plane/goals/peer_coordination.ts` is the sole semantic owner of multi-agent goal-oriented matching projections. `shared_goal_work.ts` and `shared_goal_alignment.ts` compose it cleanly without re-implementing matching heuristics in Python. All writeback, lease acquisition, and inbox acceptance continue to run strictly through their existing owners (`todo claim`, `task-lease`, `manager-inbox`). + +### State model and schema + +`shared_goal_alignment_v0` retains all existing top-level fields identically and adds two read-only arrays (defaulting to `[]` when callers supply legacy preselected inputs): + +1. **`peer_frontiers`** (sorted by priority rank `P0..P4`, `agent_id`, `todo_id`; capped at `12`): + - `todo_id`, `agent_id`, `priority`, `action_kind`, `task_domain`, `task_repository`, `target_key`, `required_write_scopes`, `completion_validation_required`, `lease_active` (`true | false | null`). +2. **`collaboration_opportunities`** (sorted by severity rank -> peer priority -> `peer_todo_id` -> `caller_todo_id` -> `opportunity_id`; capped at `8`): + - `opportunity_id`: `"opp_" + sha256(canonical_json([kind, peer_agent_id, peer_todo_id, caller_todo_id ?? "", ...matched_on]))[0..16]` + - `kind`: one of: + - `shared_target_collision_risk` (`advisory_action: "deconflict_before_edit"`) — shared non-null `target_key` or overlapping `required_write_scopes` on compatible repositories. + - `peer_verification_needed` (`advisory_action: "offer_independent_verification"`) — `completion_validation_required === true` matching verifier `action_kind`, shared domain/repository, or an idle caller discovering verification demand. + - `peer_unleased_lane_attention` (`advisory_action: "inspect_peer_status_before_duplicating"`) — `lease_active === false` on high-priority (`P0`/`P1`) peer work matching the caller's domain/target (or idle caller discovery). + - `shared_domain_synergy` (`advisory_action: "align_with_peer_deliverable"`) — matching non-null `task_domain` across compatible repositories (suppressed on pairs already flagged as collision risks). + - `peer_agent_id`, `peer_todo_id`, `caller_todo_id` (`string | null`), `matched_on` (`string[]`), `advisory_action`, `grants_authority: false`. + +### Command and handshake lifecycle + +- **M0 (Shipped):** Passive pull via `loopx shared-goal-alignment --goal-id --agent-id ` recomputes `peer_frontiers` and `collaboration_opportunities` on demand over canonical `file_v0`/`sqlite_v0` snapshots. +- **M1 (Future opt-in):** Heartbeat / Turn envelope embeds a compact `<=400 B` cursor-deduplicated digest of top newly emerged `opportunity_id`s only when the digest changed since the agent's last seen cursor. +- **M2 (Future opt-in):** Structured `offer` / `accept` / `decline` handshake over `manager-inbox` keyed by `(opportunity_id, basis_digest)` with sender cooldown after decline or unreachable host route. + +### Provider or extension contract + +Logical alignment projection stays 100% provider-neutral. Host observers (Codex app-server, Antigravity desktop/daemon, IDE sidecars) expose live presence and submission handles through optional adapter profiles; absence of a live host observer only leaves `peer_route` in `host_observer_unavailable` while durable Todo/lease coordination and `manager-inbox` persistence continue uninterrupted. + +## 6. Alternatives and design choices + +1. **Rejected: Storing a separate "team coordination board" file or SQLite table.** Creates split-brain drift vs. canonical Todos/leases and requires dual-write synchronization. *Reopen only if* cross-Goal ephemeral rendezvous proves unrepresentable in canonical Todo metadata. +2. **Chosen: Additive fields on existing `shared_goal_alignment_v0` over existing TS scope/repo codecs.** Avoids creating a redundant CLI surface or duplicating glob/repository normalization, stays backwards-compatible with legacy callers, and preserves zero-cost read-only invariants. +3. **Rejected: Automatic peer interruption on every Todo change.** Causes thundering-herd prompt noise and blows the `<5%` context budget. Cursor-deduplicated M1 digests plus cooldowns avoid runaway chatter. + +## 7. Safety, privacy, and compatibility + +- **Default parity:** Existing `shared_goal_alignment` JSON callers receive identical top-level fields with `peer_frontiers` and `collaboration_opportunities` appended; legacy requests omitting `caller_lanes`/`peer_frontiers` receive `[]` safely. +- **Authority & write isolation:** Read projections enforce `read_only: true` and `grants_authority: false`; host prompts still require explicit lease/inbox gates before external writes or PR merges. +- **Public-safe filtering:** Only validated public identifiers (`todo_id`, `agent_id`, `task_domain`, `task_repository`, `target_key`, normalized relative write scopes) enter the projection; free-text prose notes and private paths remain excluded. +- **Downgrade/mixed versions:** Older Python/CLI readers ignore unknown additive keys cleanly; TS decoder checks `caller_lanes` and `peer_frontiers` strictly when supplied and falls back to `[]` when absent. + +## 8. Migration and rollback + +Not applicable for M0 beyond additive code rollback: M0 adds read-only fields with zero persistent schema migration or disk format change. Reverting the commit cleanly restores exact prior output. + +## 9. Validation and acceptance + +| Claim | Test or evidence | Required result | Boundary / exclusions | +| --- | --- | --- | --- | +| TS coordinator deterministically detects all 4 opportunity kinds, collision suppression, idle caller discovery, scope/repo boundaries, and caps | `node --experimental-strip-types --test tests/control_plane_ts/shared_goal_alignment.test.ts` | All TS unit assertions pass; zero regressions on 28 existing tests | Synthetic typed payloads; does not test SQLite I/O | +| Canonical `file_v0` and `sqlite_v0` snapshots project matching `peer_frontiers` & `collaboration_opportunities` without disk writes | `uv run --extra test python -m pytest tests/control_plane/test_shared_goal_alignment.py tests/control_plane/test_shared_goal_alignment_cli.py` | All parametrized File+SQLite & CLI assertions pass | Single-host canonical snapshots; no M1–M3 envelope wiring | +| Bilingual RFC index & governance stay valid | `python3 scripts/generate_rfc_status_index.py --check` & `python3 scripts/check_rfc_bilingual.py --base origin/main --head HEAD` | Exit `0` | Structural mirror parity only, not automated translation grading | + +## 10. Operational contract + +- **Bounded output:** At most `12` `peer_frontiers` and `8` `collaboration_opportunities` per call; CLI markdown renders compact tables/bullets sorted by severity. +- **Diagnosable failure:** Caller lease corruption continues failing closed (`EffectRuntimeRequestError`), while malformed peer lease records degrade locally to `lease_active: null` so peer errors never DoS unrelated agents. + +## 11. Normative delivery plan + +| Milestone | Shipped behavior | Entry gate | Exit evidence | Rollback | +| --- | --- | --- | --- | --- | +| **M0** | TS `peer_coordination.ts`, canonical `shared_goal_work_source.py` field forwarding, additive `shared_goal_alignment_v0` & CLI Markdown/JSON | Clean `origin/main` alignment baseline | TS + File/SQLite pytest + CLI + premerge canaries pass | Revert additive PR | +| **M1** | Opt-in compact `<=400 B` `peer_coordination_digest` in Turn/heartbeat envelope keyed by cursor | M0 merged + token budget ceiling verified | No Turn envelope regression (`<5%` control tax) + cursor dedup tests | Keep default-off flag false | +| **M2** | Bilateral `manager-inbox` offer/decline handshake keyed by `(opportunity_id, basis_digest)` with cooldown | M1 + exact-idempotency review | Multi-agent inbox handshake integration suite passes | Disable opt-in auto-offer | +| **M3** | Host-neutral observer profile (Antigravity/desktop alongside Codex) + multi-agent efficiency telemetry | M2 + host-adapter opt-in | Live dual-agent qualification without human intermediary | Retain `host_observer_unavailable` fallback | + +## 12. Open decisions + +1. **D1 (Turn-envelope opt-in threshold — M1):** Should `peer_coordination_digest` surface only `shared_target_collision_risk` + `peer_verification_needed` by default in M1 while keeping `shared_domain_synergy` pull-only via CLI? **Owner:** alignment/quota maintainers. +2. **D2 (Decline cooldown window — M2):** What default cooldown duration/epoch binding prevents repeated bilateral inbox offers on unchanged frontiers? **Owner:** `manager-inbox` maintainer. +3. **D3 (Antigravity route observer protocol — M3):** Should host presence come from a signed local daemon endpoint or per-app file lease projection? **Owner:** desktop/host maintainers. + +--- + +## Appendix A: Execution ledger (non-normative) + +- M0 baseline shipped on `50b4cc9de4` (see companion PR verification notes and subsequent ledger entries under `ledger/` if opened for M1+). + +## Appendix B: Decision log + +| Date | Decision | Owner / approval | Alternatives | Normative sections changed | +| --- | --- | --- | --- | --- | +| 2026-11-27 | Adopt M0 additive projection over `shared_goal_alignment_v0` reusing `evaluateQuotaSchedulingWriteScopesOverlap` | Pending maintainer PR review | Dedicated standalone `peer-synergy` table/RPC | §§1–11 | + +## Appendix C: Evidence registry + +| Evidence id | Claim | Baseline / environment | Artifact or command | Result | Privacy / validity boundary | +| --- | --- | --- | --- | --- | --- | +| E1 | TS + File/SQLite alignment parity and M0 peer coordination unit coverage | `50b4cc9de4` local worktree | `tests/control_plane_ts/shared_goal_alignment.test.ts` & `tests/control_plane/test_shared_goal_alignment*.py` | Pending post-edit run | Synthetic temp fixtures | + +## Appendix D: Rejected or superseded alternatives + +- **Python-side matching heuristics:** Rejected because `shared_goal_alignment.ts` and `task_lease_acquire_decision.ts` already own alignment and scope-overlap normalization in TypeScript; splitting matching rules into Python would reintroduce py/ts semantic drift. + +## Appendix E: Incident and review lessons + +- Multi-agent coordination failures in practice stem less from lack of raw inbox transport and more from invisible per-lane state (`other_agent_claimed_advancement_count` integer blindness) plus high host-route unavailability between heterogeneous agents, requiring manual human relays until made queryable and bounded. diff --git a/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.zh-CN.md b/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.zh-CN.md new file mode 100644 index 0000000000..3fd06661d5 --- /dev/null +++ b/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.zh-CN.md @@ -0,0 +1,172 @@ +# RFC:面向目标的多 Agent 自主协同协议(v0) + +- **RFC 状态:** 已接受 +- **替代 / 关闭:** 无 +- **交付成熟度:** Partial(M0 只读同目标 Peer 前沿与协同机会投影已实现;M1–M3 留待后续切片) +- **作者 / 负责人:** 既有控制面 alignment、collaboration 与 directory owners +- **创建:** 2026-11-27 +- **最近规范性修订:** 2026-11-27 +- **实现基线:** `50b4cc9de4` +- **相关契约:** [共享 Goal 对齐与受治理 Amendment 协议](shared-goal-alignment-and-governed-amendment-v0.zh-CN.md)、[Peer Agent Directory 与有界观测](../../reference/protocols/peer-agent-directory-and-observation-v0.md)、[有能力的 Agent Manager 与语义工作交接](capable-manager-semantic-handoff-v0.zh-CN.md)、[实时团队工作空间](live-team-workspace-v0.zh-CN.md) +- **语言镜像:** [English](goal-oriented-multi-agent-coordination-v0.md) + +## 文档结构与维护约定 + +第 1–10 节为持久的设计、安全与验收契约;第 11 节为规范性交付计划(起点为基于 `50b4cc9de4` 落地的 M0 切片);第 12 节记录 M1–M3 的未决决策;附录保留非规范性演进记录与证据索引。本中文版本与[英文版](goal-oriented-multi-agent-coordination-v0.md)互为语义镜像(semantic mirror),二者存在实质差异即为缺陷。 + +--- + +## 1. 决策摘要 + +1. **在不新增数据库或平行 authority 的前提下,让同一 Goal 下的 Peer 前沿结构化可发现。** 对 `shared_goal_alignment_v0` 做向后兼容的增量扩展,新增有界字段 `peer_frontiers` 与 `collaboration_opportunities`,由单一 TypeScript 语义所有者(`loopx/control_plane/goals/peer_coordination.ts`)基于现有 canonical Todo 与任务租约确定性计算。 +2. **严格守住“零授权只读投影”(`grants_authority: false`)。** 发现冲突风险、独立验证需求、高优无租约通道或同域协同机会,本身绝不转移 claim、越过租约、修改 Todo 或直接触发外部投递。 +3. **从“人肉传话 + 被动推信”演进为“面向目标的双向自主配合”。** 保留现有 `shared_goal_alignment_v0`、`peer_agent_directory_v0` 与 `manager-inbox` 各自的所有权,规范拉取式协同发现与后续可选 Turn 信封紧凑摘要(`<=400 B`),使同一 Goal 下的异构专长 Agent(如代码精简 Agent 与验证/评测 Agent)在控制面上下文税 `<5%` 约束内自主对齐配合。 +4. **将确定性 M0 与可选 M1–M3 传输/宿主扩展解耦。** M0 仅在只读对齐投影(`loopx shared-goal-alignment` / `goal-alignment`)落地;Turn 信封自动摘要(M1)、带冷却窗的双向 offer/decline 握手(M2)以及宿主中立的 Antigravity/非 Codex 路由观测配置(M3)均留待各自显式验收后启用。 +5. **本 RFC 明确不批准**自主多 Agent 自合并 PR、跨所有者自动改派 Todo 或无界膨胀 Turn 上下文信封。 + +## 2. 问题与动机 + +当多个分工不同的 Agent 围绕同一个 LoopX Goal 协作时(例如质量/精简重构 Agent 持续产出聚焦 PR,而验证/基准 Agent 负责独立评测、捕捉回归与效率归因),当前仍经常需要人类显式传话才能建立配合: + +- 用户不得不手动交代 Agent B:“Agent A 有一批简化 PR,你们协同验证和打磨一下”; +- 同时,各个 Peer 自身也缺乏“拉取式”的结构化视图来回答:谁和我碰到了同一个 `target_key` 或重叠 `required_write_scopes`、谁正在等待 `completion_validation_required` 独立验收、谁的高优通道已失去活跃租约。 + +根本原因在于五处结构性缺口: + +1. **纯标量 Peer 计数黑盒:** 现有 `shared_goal_alignment_v0` 仅向调用方返回 `other_agent_claimed_advancement_count`(一个整数)以及 `peer_claimed_bound_todo_ids`(仅限 `bound_agent === caller`)。其他 Peer 的优先级、`task_domain`、`task_repository`、`target_key`、`required_write_scopes` 与 `completion_validation_required` 完全不可见。 +2. **只有推式 `manager-inbox`,缺少拉式协同匹配:** `manager-inbox` 在“发送方已经明确知道找谁、要做什么”时有效,但无法在协同发起前回答“当前 Goal 下哪条 Peer 通道与我的域匹配或急需独立核验”。 +3. **写域/目标冲突后置暴露:** 两位 Agent 在相同 `target_key` 或重叠 `required_write_scopes` 上并行工作时,往往要到尝试抢锁或构建 worktree 冲突后才被动发现,缺少无副作用的事前避让提示。 +4. **上下文预算风险:** 直接把完整 Peer 工作树塞入每次 Turn 会击穿控制面 `<5%` 上下文预算红线;协同发现必须坚持按需拉取、严格封顶(`MAX_PEER_FRONTIER_ITEMS = 12`、`MAX_COLLABORATION_OPPORTUNITIES = 8`)并靠确定性 `opportunity_id` 去重。 +5. **异构宿主路由不对称:** 非 Codex 宿主(如 Antigravity 桌面会话)在未接入观测适配器时,`resolve-peer-route` 返回 `unavailable (host_observer_unavailable)`,发送方只能退化为离线收件箱写入或依赖人类中转。 + +### 不变量 + +- **单一状态来源:** 不新增第二套 Todo 表、影子 claim 文件或并行 intent 存储;一切投影严格源于 canonical Todo/lease 快照(`file_v0` / `sqlite_v0`)。 +- **单一语义归约器:** 仅由 `peer_coordination.ts` 一个 TypeScript 模块定义资格判定、写域与目标重叠计算、排序优先级、去重与截断上限;Python 与 CLI 只作参数传递与展示适配。 +- **确定性与零授权:** 相同输入快照必然输出完全一致的有序列表与 `opportunity_id`,每条结果均显式标注 `grants_authority: false` 与 `read_only: true`。 +- **自身失败闭环、同伴脏数据有界降级:** 调用方自身的租约损坏仍严格 fail-closed;Peer 的损坏租约记录安全降级为 `lease_active: null`,避免拖垮调用方的只读对齐视图。 +- **公开安全边界:** 不向 `peer_frontiers` 或 `collaboration_opportunities` 暴露本地私有路径、原始聊天记录或凭据。 + +## 3. 范围与非目标 + +### 范围内 + +- 对 `shared_goal_alignment_v0` 做增量 M0 扩展(`peer_frontiers`、`collaboration_opportunities`),由 TypeScript 计算并通过 `loopx shared-goal-alignment` / `goal-alignment` 输出。 +- 规范拉取式协同匹配规则、确定性 `opportunity_id` 去重、M1 Turn 信封紧凑摘要(`<=400 B`)、M2 冷却窗握手及 M3 宿主中立路由观测契约。 + +### 非目标 + +- 替代 `shared_goal_intent_v0`、`goal_amendment_proposal_v0`、`task_lease` 或 `peer_agent_directory_v0`。 +- 授予 Agent 跨所有者抢占 Todo、篡改优先级或未经授权自合并 PR 的权限。 +- 引入宿主特定聊天轮询或抓取未绑定会话原文。 + +## 4. 当前系统契约 + +基于基线 `50b4cc9de4`: + +- **Peer 目录(`loopx/control_plane/agents/directory.py` / `agent-directory`):** 聚合展示已注册 Agent、当前 Todo 概要、陈旧提示与路由候选,不计算成对写域冲突、域协同或验收需求匹配。 +- **共享 Goal 对齐(`shared_goal_alignment.ts` / `shared_goal_work.ts` / `shared_goal_work_source.py`):** 读取单一 `canonical_todo_snapshot` 并产出计数字段、caller 租约冲突与 `peer_claimed_bound_todo_ids`,目前丢弃 Peer 的 `priority`、`task_domain`、`task_repository`、`target_key`、`required_write_scopes`、`completion_validation_required` 与租约活跃度。 +- **协调激活投影(`peer_orchestration.ts`):** 处理具备 `peer_agent_activation` 能力的协调者对 `bound`/`executing` 子通道的激活准入,不解决同级 `peer_v1` 之间的横向自主配合。 +- **写域重叠与仓库标识(`task_lease_acquire_decision.ts`、`task_lease_repository.ts`、`work_requirements.ts`):** TS 侧已有成熟的仓库规范化与写域重叠函数(`evaluateQuotaSchedulingWriteScopesOverlap`、`repositoryScopesMayOverlap`)可直接复用。 + +## 5. 提案架构 + +### 所有权与权威边界 + +`loopx/control_plane/goals/peer_coordination.ts` 是面向目标 Peer 协同匹配投影的唯一语义所有者;`shared_goal_work.ts` 与 `shared_goal_alignment.ts` 仅负责组合调用,不在 Python 侧复制任何重叠或匹配规则。实际写入继续严格由既有 owner(`todo claim`、`task-lease`、`manager-inbox`)校验执行。 + +### 状态模型与模式 + +`shared_goal_alignment_v0` 保留全部既有顶层字段不变,增量新增两个只读数组(当旧调用方传入未携带新输入字段的历史请求时安全默认为空数组 `[]`): + +1. **`peer_frontiers`**(按 `P0..P4` 优先级、`agent_id`、`todo_id` 确定性排序,上限 `12` 条): + - `todo_id`、`agent_id`、`priority`、`action_kind`、`task_domain`、`task_repository`、`target_key`、`required_write_scopes`、`completion_validation_required`、`lease_active`(`true | false | null`)。 +2. **`collaboration_opportunities`**(按严重度等级 -> Peer 优先级 -> `peer_todo_id` -> `caller_todo_id` -> `opportunity_id` 排序,上限 `8` 条): + - `opportunity_id`:`"opp_" + sha256(canonical_json([kind, peer_agent_id, peer_todo_id, caller_todo_id ?? "", ...matched_on]))[0..16]` + - `kind`(四类闭合枚举): + - `shared_target_collision_risk`(`advisory_action: "deconflict_before_edit"`):仓库兼容前提下存在相同非空 `target_key` 或重叠 `required_write_scopes`。 + - `peer_verification_needed`(`advisory_action: "offer_independent_verification"`):Peer 设置了 `completion_validation_required === true`,且调用方具备验证类 `action_kind`(`verify`/`review`/`benchmark`/`evaluate`/`audit`)、同域/同库上下文,或处于空闲状态(`caller_lanes` 为空)发现待验证需求。 + - `peer_unleased_lane_attention`(`advisory_action: "inspect_peer_status_before_duplicating"`):高优(`P0`/`P1`)Peer 通道 `lease_active === false` 且与调用方存在同域/同目标交集(或空闲发现)。 + - `shared_domain_synergy`(`advisory_action: "align_with_peer_deliverable"`):相同非空 `task_domain` 且仓库兼容,但未在同一 `(caller_todo_id, peer_todo_id)` 对上触发碰撞预警。 + - `peer_agent_id`、`peer_todo_id`、`caller_todo_id`(`string | null`)、`matched_on`(`string[]`)、`advisory_action`、`grants_authority: false`。 + +### 命令与协同生命周期 + +- **M0(随本 PR 落地):** 通过 `loopx shared-goal-alignment --goal-id --agent-id ` 在 `file_v0`/`sqlite_v0` 上按需实时计算 `peer_frontiers` 与 `collaboration_opportunities`。 +- **M1(后续可选):** 在 Turn / heartbeat 信封中仅当游标对比发现新 `opportunity_id` 时嵌入 `<=400 B` 紧凑摘要。 +- **M2(后续可选):** 基于 `(opportunity_id, basis_digest)` 通过 `manager-inbox` 完成带冷却窗的 `offer` / `accept` / `decline` 握手,防止对拒绝或暂不可达 Peer 重复打扰。 + +### 扩展与宿主契约 + +核心匹配语义与宿主无关;Antigravity 或其他运行时通过可选宿主观测 profile 提供路由可达性,未启用时自动保守保留 `host_observer_unavailable`,但仍可依托持久 `manager-inbox` 与 canonical Todo/lease 完成协同对齐。 + +## 6. 备选方案与设计取舍 + +1. **拒绝:独立建立“团队协同看板”表/文件。** 极易与 canonical Todo/lease 发生双写分裂;仅当未来出现跨 Goal 瞬时握手需求无法表达时再重评。 +2. **采用:在既有 `shared_goal_alignment_v0` 上增量扩展,并复用 TS 既有写域重叠/仓库规范化组件。** 零重复轮子、对历史调用方完全兼容、天然受既有边界测试保护。 +3. **拒绝:任何 Todo 变动即无条件推送全员提示。** 会制造提示词风暴并突破 `<5%` 控制面开销上限;M1 游标去重 + M2 冷却窗从机制上抑制噪音。 + +## 7. 安全性、隐私与兼容性 + +- **默认等价性:** 既有 `shared_goal_alignment` 调用方所有旧字段语义不变;未传入 `caller_lanes`/`peer_frontiers` 的历史请求返回 `[]`。 +- **权限与写隔离:** 全程 `read_only: true` 且 `grants_authority: false`,任何外部写入或 PR 合并仍遵循原有明确授权门禁。 +- **公开安全:** 仅引用规范化公共标识与相对写域路径,不出现私有目录、凭证或聊天原文。 +- **版本兼容:** 增量为纯加性字段,旧读者安全忽略,TS 解码器仅在显式提供新字段时严格校验。 + +## 8. 迁移与回滚 + +M0 仅扩展只读投影输出,不改动磁盘持久化 schema 或迁移流程,回滚单笔提交即可完全恢复先前输出形态,无需导出迁移。 + +## 9. 验证与验收 + +| 声明 | 测试或证据 | 预期结果 | 边界 / 排除项 | +| --- | --- | --- | --- | +| TS 归约器准确产出 4 类协同机会、冲突抑制、空闲发现、写域/仓库判定与上限控制 | `node --experimental-strip-types --test tests/control_plane_ts/shared_goal_alignment.test.ts` | 新增与既有 `28` 项 TS 断言全数通过 | 内存合成载荷,不测磁盘 I/O | +| `file_v0` 与 `sqlite_v0` 真实快照与 CLI JSON/Markdown 输出严格零写入一致 | `uv run --extra test python -m pytest tests/control_plane/test_shared_goal_alignment.py tests/control_plane/test_shared_goal_alignment_cli.py` | 全部 File/SQLite 参数化及 CLI 用例通过 | 单机 canonical 快照,不含 M1–M3 | +| 双语 RFC 索引与校验规则通过 | `python3 scripts/generate_rfc_status_index.py --check` 与 `python3 scripts/check_rfc_bilingual.py --base origin/main --head HEAD` | 退出码 `0` | 校验双语结构成对变更,不代替人工译文审查 | + +## 10. 运维契约 + +- **输出有界:** 单次投影 `peer_frontiers <= 12`、`collaboration_opportunities <= 8`,CLI Markdown 按严重度有序渲染。 +- **可诊断降级:** 调用方租约报错照常 fail-closed;Peer 损坏租约降级为 `lease_active: null`,防止单个损坏条目阻断全组视角。 + +## 11. 规范性交付计划 + +| 里程碑 | 交付行为 | 准入条件 | 退出证据 | 回滚路径 | +| --- | --- | --- | --- | --- | +| **M0** | TS `peer_coordination.ts`、Python `shared_goal_work_source.py` 透传及 `shared_goal_alignment` / CLI 输出 | `origin/main` 基线干净 | TS + File/SQLite pytest + CLI + `canary premerge` 全过 | 回退本 PR | +| **M1** | 默认关闭的 Turn/heartbeat 信封 `<=400 B` 游标去重 `peer_coordination_digest` | M0 合入且验证 token 开销边界 | 控制面税 `<5%` 与游标去重单测通过 | 保持默认关闭 | +| **M2** | 基于 `(opportunity_id, basis_digest)` 与冷却窗的双向 `manager-inbox` 握手 | M1 + 幂等评审通过 | 双端收件箱握手集成测试通过 | 关闭自动 offer 开关 | +| **M3** | 宿主中立路由观测适配器(覆盖 Antigravity 等非 Codex 宿主)与自主协同指标 | M2 + 宿主适配器开关 | 双 Agent 无人类中转协同实测通过 | 退回 `host_observer_unavailable` | + +## 12. 未决决策 + +1. **D1(M1 信封默认暴露面):** M1 是否只在 Turn 信封主动提示 `shared_target_collision_risk` 与 `peer_verification_needed`,而把 `shared_domain_synergy` 保留为 CLI 拉取查询?**负责人:** alignment/quota owners。 +2. **D2(M2 拒绝冷却窗策略):** `decline` 后的默认冷却时长/revision 绑定规则应如何设定以避免同质打扰?**负责人:** `manager-inbox` owner。 +3. **D3(M3 Antigravity 宿主观测来源):** 应由签名本地守护进程端点还是应用侧租约文件提供存活观测?**负责人:** desktop/host owners。 + +--- + +## 附录 A:执行台账(非规范性) + +- M0 基线基于 `50b4cc9de4` 随同 M0 实现提交落地(后续 M1–M3 检查点于 `ledger/` 目录独立记录)。 + +## 附录 B:决策日志 + +| 日期 | 决策 | 所有者 / 批准 | 备选方案 | 变更的规范章节 | +| --- | --- | --- | --- | --- | +| 2026-11-27 | 采用基于 `shared_goal_alignment_v0` 的 M0 增量投影并复用 TS `evaluateQuotaSchedulingWriteScopesOverlap` | 待维护者 PR 审批 | 独立建表与独立 RPC | 第 1–11 节 | + +## 附录 C:证据登记表 + +| 证据 ID | 声明 | 基线 / 环境 | 产物或命令 | 结果 | 隐私 / 有效性边界 | +| --- | --- | --- | --- | --- | --- | +| E1 | TS 与 File/SQLite 对齐一致性及 M0 协同机会单测全过 | `50b4cc9de4` 本地工作树 | `tests/control_plane_ts/shared_goal_alignment.test.ts` 与 `tests/control_plane/test_shared_goal_alignment*.py` | 待编辑后实测验证 | 临时测试夹具,不含真实私密状态 | + +## 附录 D:被拒绝或替代的方案 + +- **Python 侧自建匹配启发式逻辑:** 已拒绝。对齐投影与写域/仓库规范化已在 TypeScript 侧拥有权威 owner,在 Python 复制规则必然引发双端语义漂移。 + +## 附录 E:事故与评审教训 + +- 实际长期多 Agent 协作卡点往往不在缺乏点对点发信通道,而在于跨 Agent 互相看不见对方的领域/范围/验收需求(整数计数黑盒)与异构宿主缺少轻量路由观测,迫使人类不断充当人工路由器;通过有界只读结构化投影可从根本上消除这类人为中转负担。 diff --git a/loopx/cli_commands/shared_goal_alignment.py b/loopx/cli_commands/shared_goal_alignment.py index 29d270ff67..00e4ca398a 100644 --- a/loopx/cli_commands/shared_goal_alignment.py +++ b/loopx/cli_commands/shared_goal_alignment.py @@ -92,6 +92,29 @@ def render_shared_goal_alignment_markdown(payload: dict[str, object]) -> str: f" - `{item.get('todo_id')}` " f"claim_required=`{item.get('claim_required_before_work')}`" ) + peer_frontiers = payload.get("peer_frontiers") + if isinstance(peer_frontiers, list) and peer_frontiers: + lines.append("- peer_frontiers:") + for peer in peer_frontiers: + if isinstance(peer, dict): + lines.append( + f" - `{peer.get('agent_id')}` `{peer.get('todo_id')}` " + f"priority=`{peer.get('priority')}` domain=`{peer.get('task_domain')}` " + f"target=`{peer.get('target_key')}` validation_required=`{peer.get('completion_validation_required')}` " + f"lease_active=`{peer.get('lease_active')}`" + ) + opportunities = payload.get("collaboration_opportunities") + if isinstance(opportunities, list) and opportunities: + lines.append("- collaboration_opportunities:") + for opp in opportunities: + if isinstance(opp, dict): + lines.append( + f" - `{opp.get('opportunity_id')}` `{opp.get('kind')}` " + f"peer=`{opp.get('peer_agent_id')}`:`{opp.get('peer_todo_id')}` " + f"caller_todo=`{opp.get('caller_todo_id')}` " + f"advisory_action=`{opp.get('advisory_action')}` " + f"grants_authority=`{opp.get('grants_authority')}`" + ) return "\n".join(lines) diff --git a/loopx/control_plane/goals/peer_coordination.ts b/loopx/control_plane/goals/peer_coordination.ts new file mode 100644 index 0000000000..c2f1f5ac76 --- /dev/null +++ b/loopx/control_plane/goals/peer_coordination.ts @@ -0,0 +1,556 @@ +import { createHash } from "node:crypto"; +import type { JsonObject } from "../effect_program.ts"; +import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; +import { normalizeTodoAgent } from "../coordination/todo_agents.ts"; +import { optionalNonEmptyString, requireBoolean, requireJsonObject } from "../runtime_decode.ts"; +import { normalizeTodoRepository } from "../todos/work_requirements.ts"; +import { + comparisonWriteScopes, + schedulingScopePairOverlaps, + schedulingScopeRoot, +} from "../work_items/task_lease_acquire_decision.ts"; +import { leaseWriteRepository } from "../work_items/task_lease_repository.ts"; +import { normalizeWriteScopes } from "../work_items/write_scope_codec.ts"; + +export const MAX_PEER_FRONTIER_ITEMS = 12; +export const MAX_COLLABORATION_OPPORTUNITIES = 8; + +export const COLLABORATION_OPPORTUNITY_KINDS = [ + "shared_target_collision_risk", + "peer_verification_needed", + "peer_unleased_lane_attention", + "shared_domain_synergy", +] as const; + +export const COLLABORATION_ADVISORY_ACTIONS = [ + "deconflict_before_edit", + "offer_independent_verification", + "inspect_peer_status_before_duplicating", + "align_with_peer_deliverable", +] as const; + +export type CollaborationOpportunityKind = (typeof COLLABORATION_OPPORTUNITY_KINDS)[number]; +export type CollaborationAdvisoryAction = (typeof COLLABORATION_ADVISORY_ACTIONS)[number]; + +const TODO_ID_PATTERN = /^todo_[a-z0-9_-]{3,64}$/; +const PRIORITY_RANK: Record = { P0: 0, P1: 1, P2: 2, P3: 3, P4: 4 }; +const VERIFIER_ACTION_KINDS = new Set(["verify", "review", "benchmark", "evaluate", "audit"]); +const OPPORTUNITY_KIND_RANK: Record = { + shared_target_collision_risk: 0, + peer_verification_needed: 1, + peer_unleased_lane_attention: 2, + shared_domain_synergy: 3, +}; + +export interface CallerLaneSummary extends JsonObject { + todo_id: string; + priority: string | null; + action_kind: string | null; + task_domain: string | null; + task_repository: string | null; + target_key: string | null; + required_write_scopes: string[]; + completion_validation_required: boolean; + lease_active: boolean | null; +} + +export interface PeerFrontierItem extends CallerLaneSummary { + agent_id: string; +} + +export interface CollaborationOpportunity extends JsonObject { + opportunity_id: string; + kind: CollaborationOpportunityKind; + peer_agent_id: string; + peer_todo_id: string; + caller_todo_id: string | null; + matched_on: string[]; + advisory_action: CollaborationAdvisoryAction; + grants_authority: false; +} + +export interface PeerCoordinationProjection { + peer_frontiers: PeerFrontierItem[]; + collaboration_opportunities: CollaborationOpportunity[]; +} + +function optionalLowerToken(value: unknown, label: string): string | null { + const token = optionalNonEmptyString(value, label); + return token === null ? null : token.trim().toLowerCase() || null; +} + +function optionalPriority(value: unknown, label: string): string | null { + const token = optionalNonEmptyString(value, label); + if (token === null) return null; + const upper = token.trim().toUpperCase(); + if (!(upper in PRIORITY_RANK)) { + throw new EffectRuntimeRequestError(`${label} must be P0..P4 or null`); + } + return upper; +} + +function optionalLeaseActive(value: unknown, label: string): boolean | null { + if (value === null || value === undefined) return null; + return requireBoolean(value, label); +} + +function decodeLaneBase(value: unknown, label: string): CallerLaneSummary { + const raw = requireJsonObject(value, label); + const todoId = (optionalNonEmptyString(raw.todo_id, `${label}.todo_id`) ?? "").trim().toLowerCase(); + if (!TODO_ID_PATTERN.test(todoId)) { + throw new EffectRuntimeRequestError(`${label}.todo_id must be a valid Todo id`); + } + return { + todo_id: todoId, + priority: optionalPriority(raw.priority, `${label}.priority`), + action_kind: optionalLowerToken(raw.action_kind, `${label}.action_kind`), + task_domain: optionalLowerToken(raw.task_domain, `${label}.task_domain`), + task_repository: normalizeTodoRepository(raw.task_repository, `${label}.task_repository`), + target_key: optionalNonEmptyString(raw.target_key, `${label}.target_key`), + required_write_scopes: normalizeWriteScopes(raw.required_write_scopes ?? []), + completion_validation_required: raw.completion_validation_required === undefined + ? false + : requireBoolean(raw.completion_validation_required, `${label}.completion_validation_required`), + lease_active: optionalLeaseActive(raw.lease_active, `${label}.lease_active`), + }; +} + +export function decodeCallerLanes(value: unknown): CallerLaneSummary[] { + if (value === undefined) return []; + if (!Array.isArray(value)) throw new EffectRuntimeRequestError("shared_goal_alignment.caller_lanes must be an array"); + return value.map((item, idx) => decodeLaneBase(item, `shared_goal_alignment.caller_lanes[${idx}]`)); +} + +export function decodePeerFrontiers(value: unknown): PeerFrontierItem[] { + if (value === undefined) return []; + if (!Array.isArray(value)) throw new EffectRuntimeRequestError("shared_goal_alignment.peer_frontiers must be an array"); + return value.map((item, idx) => { + const label = `shared_goal_alignment.peer_frontiers[${idx}]`; + const base = decodeLaneBase(item, label); + const raw = item as Record; + let agentId: string; + try { + agentId = normalizeTodoAgent(raw.agent_id, `${label}.agent_id`); + } catch { + throw new EffectRuntimeRequestError(`${label}.agent_id must be a public-safe agent id`); + } + return { ...base, agent_id: agentId }; + }); +} + +function priorityRank(priority: string | null): number { + return priority !== null && priority in PRIORITY_RANK ? PRIORITY_RANK[priority] : 50; +} + +function buildOpportunityId( + kind: CollaborationOpportunityKind, + peerAgentId: string, + peerTodoId: string, + callerTodoId: string | null, + matchedOn: readonly string[], +): string { + const payload = JSON.stringify([kind, peerAgentId, peerTodoId, callerTodoId ?? "", ...matchedOn]); + return `opp_${createHash("sha256").update(payload, "utf8").digest("hex").slice(0, 16)}`; +} + +function precomputedScopesOverlap(left: readonly string[], right: readonly string[]): boolean { + if (left.length === 0 || right.length === 0) return false; + return left.some((first) => right.some((second) => schedulingScopePairOverlaps(first, second))); +} + +interface IndexedCaller { + readonly idx: number; + readonly lane: CallerLaneSummary; + readonly repoLower: string | null; + readonly isVerifier: boolean; + readonly scopes: readonly string[]; + readonly scopeRoots: readonly string[][]; +} + +interface IndexedPeer { + readonly lane: PeerFrontierItem; + readonly priorityRank: number; + readonly repoLower: string | null; + readonly scopes: readonly string[]; + readonly scopeRoots: readonly string[][]; +} + +interface ScopeTrieNode { + exactOrPrefix: IndexedCaller[]; + descendants: IndexedCaller[]; + children: Map; +} + +function createScopeTrieNode(): ScopeTrieNode { + return { exactOrPrefix: [], descendants: [], children: new Map() }; +} + +function splitScopeRootSegments(scope: string): string[] { + if (scope === "*" || scope === "**" || scope === "./" || scope === ".") return []; + const root = schedulingScopeRoot(scope); + return root && root !== "." ? root.split("/") : []; +} + +function pushToMapArray(map: Map, key: K, value: V): void { + const existing = map.get(key); + if (existing !== undefined) existing.push(value); + else map.set(key, [value]); +} + +function buildCallerIndex(sortedCallers: readonly CallerLaneSummary[]) { + const byRepo = new Map(); + const globalRepoCallers: IndexedCaller[] = []; + const byTarget = new Map(); + const byDomain = new Map(); + const verifiers: IndexedCaller[] = []; + const scopeTrie = createScopeTrieNode(); + const globalScopeCallers: IndexedCaller[] = []; + + const callers: IndexedCaller[] = sortedCallers.map((lane, idx) => { + const repoLower = leaseWriteRepository(lane.task_repository)?.toLowerCase() ?? null; + const scopes = lane.required_write_scopes.length > 0 + ? comparisonWriteScopes(lane.required_write_scopes) + : []; + const scopeRoots = scopes.map(splitScopeRootSegments); + const entry: IndexedCaller = { + idx, + lane, + repoLower, + isVerifier: Boolean(lane.action_kind && VERIFIER_ACTION_KINDS.has(lane.action_kind)), + scopes, + scopeRoots, + }; + if (repoLower === null) globalRepoCallers.push(entry); + else pushToMapArray(byRepo, repoLower, entry); + if (lane.target_key) pushToMapArray(byTarget, lane.target_key, entry); + if (lane.task_domain) pushToMapArray(byDomain, lane.task_domain, entry); + if (entry.isVerifier) verifiers.push(entry); + if (scopes.length > 0) { + let addedGlobal = false; + for (const parts of scopeRoots) { + if (parts.length === 0) { + if (!addedGlobal) { + globalScopeCallers.push(entry); + addedGlobal = true; + } + continue; + } + let node = scopeTrie; + for (const seg of parts) { + node.descendants.push(entry); + let child = node.children.get(seg); + if (child === undefined) { + child = createScopeTrieNode(); + node.children.set(seg, child); + } + node = child; + } + node.exactOrPrefix.push(entry); + } + } + return entry; + }); + + return { callers, byRepo, globalRepoCallers, byTarget, byDomain, verifiers, scopeTrie, globalScopeCallers }; +} + +function repoCompatible(callerRepoLower: string | null, peerRepoLower: string | null): boolean { + return callerRepoLower === null || peerRepoLower === null || callerRepoLower === peerRepoLower; +} + +function scopeCandidateCallers( + index: ReturnType, + peer: IndexedPeer, +): IndexedCaller[] { + if (peer.scopes.length === 0) return []; + const seen = new Set(); + const add = (list: readonly IndexedCaller[]) => { + for (const c of list) { + if (repoCompatible(c.repoLower, peer.repoLower)) seen.add(c); + } + }; + add(index.globalScopeCallers); + for (const parts of peer.scopeRoots) { + if (parts.length === 0) { + // Rootless wildcard peer can overlap every caller that declares a scope. + return index.callers.filter((c) => c.scopes.length > 0 && repoCompatible(c.repoLower, peer.repoLower)); + } + let node: ScopeTrieNode | undefined = index.scopeTrie; + for (const seg of parts) { + if (node === undefined) break; + add(node.exactOrPrefix); + node = node.children.get(seg); + } + if (node !== undefined) { + add(node.exactOrPrefix); + add(node.descendants); + } + } + return [...seen]; +} + +function compareBuiltOpportunities( + a: CollaborationOpportunity, + b: CollaborationOpportunity, + peerRankByTodo: ReadonlyMap, +): number { + return OPPORTUNITY_KIND_RANK[a.kind] - OPPORTUNITY_KIND_RANK[b.kind] + || (peerRankByTodo.get(a.peer_todo_id) ?? 50) - (peerRankByTodo.get(b.peer_todo_id) ?? 50) + || a.peer_todo_id.localeCompare(b.peer_todo_id) + || (a.caller_todo_id ?? "").localeCompare(b.caller_todo_id ?? "") + || a.opportunity_id.localeCompare(b.opportunity_id); +} + +function collectBoundedOpportunities( + peersInOppOrder: readonly IndexedPeer[], + index: ReturnType, + peerRankByTodo: ReadonlyMap, + limit: number, +): CollaborationOpportunity[] { + const winners: CollaborationOpportunity[] = []; + const kindsInRankOrder: readonly CollaborationOpportunityKind[] = [ + "shared_target_collision_risk", + "peer_verification_needed", + "peer_unleased_lane_attention", + "shared_domain_synergy", + ]; + + for (const kind of kindsInRankOrder) { + const remaining = limit - winners.length; + if (remaining <= 0) break; + + const bucket: CollaborationOpportunity[] = []; + const seenInBucket = new Set(); + let cutoff: { rank: number; todoId: string } | null = null; + + for (const peer of peersInOppOrder) { + if (cutoff !== null && (peer.priorityRank > cutoff.rank || peer.lane.todo_id !== cutoff.todoId)) { + break; + } + + if (kind === "peer_verification_needed" && !peer.lane.completion_validation_required) continue; + if (kind === "peer_unleased_lane_attention" + && (peer.lane.lease_active !== false || (peer.lane.priority !== "P0" && peer.lane.priority !== "P1"))) continue; + if (kind === "shared_domain_synergy" && !peer.lane.task_domain) continue; + + let candidateCallers: IndexedCaller[]; + if (kind === "shared_target_collision_risk") { + const merged = new Set(); + if (peer.lane.target_key) { + for (const c of index.byTarget.get(peer.lane.target_key) ?? []) { + if (repoCompatible(c.repoLower, peer.repoLower)) merged.add(c); + } + } + for (const c of scopeCandidateCallers(index, peer)) { + merged.add(c); + } + candidateCallers = [...merged].sort((a, b) => a.idx - b.idx); + } else if (kind === "peer_verification_needed") { + const merged = new Set(); + for (const c of index.verifiers) { + if (repoCompatible(c.repoLower, peer.repoLower)) merged.add(c); + } + if (peer.lane.task_domain) { + for (const c of index.byDomain.get(peer.lane.task_domain) ?? []) { + if (repoCompatible(c.repoLower, peer.repoLower)) merged.add(c); + } + } + if (peer.repoLower !== null) { + for (const c of index.byRepo.get(peer.repoLower) ?? []) { + merged.add(c); + } + } + candidateCallers = [...merged].sort((a, b) => a.idx - b.idx); + } else if (kind === "peer_unleased_lane_attention") { + const merged = new Set(); + if (peer.lane.target_key) { + for (const c of index.byTarget.get(peer.lane.target_key) ?? []) { + if (repoCompatible(c.repoLower, peer.repoLower)) merged.add(c); + } + } + if (peer.lane.task_domain) { + for (const c of index.byDomain.get(peer.lane.task_domain) ?? []) { + if (repoCompatible(c.repoLower, peer.repoLower)) merged.add(c); + } + } + candidateCallers = [...merged].sort((a, b) => a.idx - b.idx); + } else { + candidateCallers = []; + for (const c of index.byDomain.get(peer.lane.task_domain!) ?? []) { + if (repoCompatible(c.repoLower, peer.repoLower)) candidateCallers.push(c); + } + } + + for (const caller of candidateCallers) { + const dedupKey = `${peer.lane.agent_id}|${peer.lane.todo_id}|${caller.lane.todo_id}`; + if (seenInBucket.has(dedupKey)) continue; + + const sameTarget = Boolean( + caller.lane.target_key && peer.lane.target_key && caller.lane.target_key === peer.lane.target_key, + ); + const sameDomain = Boolean( + caller.lane.task_domain && peer.lane.task_domain && caller.lane.task_domain === peer.lane.task_domain, + ); + const sameRepo = Boolean(caller.repoLower && peer.repoLower && caller.repoLower === peer.repoLower); + + if (kind === "shared_target_collision_risk") { + const signals: string[] = []; + if (sameTarget) signals.push("target_key"); + if (precomputedScopesOverlap(caller.scopes, peer.scopes)) signals.push("required_write_scopes"); + if (signals.length === 0) continue; + seenInBucket.add(dedupKey); + bucket.push(buildOpportunity(kind, "deconflict_before_edit", peer.lane, caller.lane.todo_id, signals)); + } else if (kind === "peer_verification_needed") { + if (!(caller.isVerifier || sameDomain || sameRepo)) continue; + const signals = ["completion_validation_required"]; + if (caller.isVerifier) signals.push("caller_verifier_action_kind"); + if (sameDomain) signals.push("task_domain"); + if (sameRepo) signals.push("task_repository"); + seenInBucket.add(dedupKey); + bucket.push(buildOpportunity(kind, "offer_independent_verification", peer.lane, caller.lane.todo_id, signals)); + } else if (kind === "peer_unleased_lane_attention") { + if (!(sameTarget || sameDomain)) continue; + const signals = ["lease_inactive"]; + if (sameTarget) signals.push("target_key"); + if (sameDomain) signals.push("task_domain"); + seenInBucket.add(dedupKey); + bucket.push(buildOpportunity(kind, "inspect_peer_status_before_duplicating", peer.lane, caller.lane.todo_id, signals)); + } else { + if (sameTarget || precomputedScopesOverlap(caller.scopes, peer.scopes)) continue; + const signals = ["task_domain"]; + if (sameRepo) signals.push("task_repository"); + seenInBucket.add(dedupKey); + bucket.push(buildOpportunity(kind, "align_with_peer_deliverable", peer.lane, caller.lane.todo_id, signals)); + } + } + + if (bucket.length >= remaining && cutoff === null) { + cutoff = { rank: peer.priorityRank, todoId: peer.lane.todo_id }; + } + } + + if (bucket.length > 0) { + bucket.sort((a, b) => compareBuiltOpportunities(a, b, peerRankByTodo)); + winners.push(...bucket.slice(0, remaining)); + } + } + return winners; +} + +function buildOpportunity( + kind: CollaborationOpportunityKind, + advisoryAction: CollaborationAdvisoryAction, + peer: PeerFrontierItem, + callerTodoId: string | null, + matchedOn: string[], +): CollaborationOpportunity { + return { + opportunity_id: buildOpportunityId(kind, peer.agent_id, peer.todo_id, callerTodoId, matchedOn), + kind, + peer_agent_id: peer.agent_id, + peer_todo_id: peer.todo_id, + caller_todo_id: callerTodoId, + matched_on: matchedOn, + advisory_action: advisoryAction, + grants_authority: false, + }; +} + +/** Deterministically project bounded same-Goal peer frontiers and coordination opportunities. */ +export function projectPeerCoordination( + callerLanes: readonly CallerLaneSummary[], + peerLanes: readonly PeerFrontierItem[], +): PeerCoordinationProjection { + const sortedCallers = [...callerLanes].sort((a, b) => a.todo_id.localeCompare(b.todo_id)); + const sortedPeers = [...peerLanes].sort( + (a, b) => priorityRank(a.priority) - priorityRank(b.priority) + || a.agent_id.localeCompare(b.agent_id) + || a.todo_id.localeCompare(b.todo_id), + ); + const peerRankByTodo = new Map(); + for (const lane of sortedPeers) { + peerRankByTodo.set(lane.todo_id, priorityRank(lane.priority)); + } + const indexedPeers: IndexedPeer[] = sortedPeers.map((lane) => { + const repoLower = leaseWriteRepository(lane.task_repository)?.toLowerCase() ?? null; + const scopes = lane.required_write_scopes.length > 0 + ? comparisonWriteScopes(lane.required_write_scopes) + : []; + return { + lane, + priorityRank: peerRankByTodo.get(lane.todo_id) ?? 50, + repoLower, + scopes, + scopeRoots: scopes.map(splitScopeRootSegments), + }; + }); + const peersInOppOrder = [...indexedPeers].sort( + (a, b) => a.priorityRank - b.priorityRank + || a.lane.todo_id.localeCompare(b.lane.todo_id) + || a.lane.agent_id.localeCompare(b.lane.agent_id), + ); + + if (sortedCallers.length === 0) { + const rawOpps: CollaborationOpportunity[] = []; + const seen = new Set(); + const addIdleBucket = (kind: "peer_verification_needed" | "peer_unleased_lane_attention") => { + let cutoff: { rank: number; todoId: string } | null = null; + const needed = MAX_COLLABORATION_OPPORTUNITIES - rawOpps.length; + if (needed <= 0) return; + let added = 0; + for (const peer of peersInOppOrder) { + if (cutoff !== null && (peer.priorityRank > cutoff.rank || peer.lane.todo_id !== cutoff.todoId)) break; + if (kind === "peer_verification_needed" && peer.lane.completion_validation_required) { + const key = `${kind}|${peer.lane.agent_id}|${peer.lane.todo_id}`; + if (!seen.has(key)) { + seen.add(key); + rawOpps.push(buildOpportunity( + kind, + "offer_independent_verification", + peer.lane, + null, + ["completion_validation_required", "idle_caller_discovery"], + )); + added += 1; + } + } else if (kind === "peer_unleased_lane_attention" + && peer.lane.lease_active === false && (peer.lane.priority === "P0" || peer.lane.priority === "P1")) { + const key = `${kind}|${peer.lane.agent_id}|${peer.lane.todo_id}`; + if (!seen.has(key)) { + seen.add(key); + rawOpps.push(buildOpportunity( + kind, + "inspect_peer_status_before_duplicating", + peer.lane, + null, + ["lease_inactive", "idle_caller_discovery"], + )); + added += 1; + } + } + if (added >= needed && cutoff === null) { + cutoff = { rank: peer.priorityRank, todoId: peer.lane.todo_id }; + } + } + }; + addIdleBucket("peer_verification_needed"); + addIdleBucket("peer_unleased_lane_attention"); + rawOpps.sort((a, b) => compareBuiltOpportunities(a, b, peerRankByTodo)); + return { + peer_frontiers: sortedPeers.slice(0, MAX_PEER_FRONTIER_ITEMS), + collaboration_opportunities: rawOpps.slice(0, MAX_COLLABORATION_OPPORTUNITIES), + }; + } + + const callerIndex = buildCallerIndex(sortedCallers); + const built = collectBoundedOpportunities( + peersInOppOrder, + callerIndex, + peerRankByTodo, + MAX_COLLABORATION_OPPORTUNITIES, + ); + return { + peer_frontiers: sortedPeers.slice(0, MAX_PEER_FRONTIER_ITEMS), + collaboration_opportunities: built.slice(0, MAX_COLLABORATION_OPPORTUNITIES), + }; +} diff --git a/loopx/control_plane/goals/shared_goal_alignment.py b/loopx/control_plane/goals/shared_goal_alignment.py index 7a883a6e03..6f7781f160 100644 --- a/loopx/control_plane/goals/shared_goal_alignment.py +++ b/loopx/control_plane/goals/shared_goal_alignment.py @@ -203,6 +203,8 @@ def _project_shared_goal_alignment( or result.get("agent_id") != normalized_agent_id or not isinstance(result.get("drift_facts"), list) or not isinstance(result.get("conflict_facts"), list) + or not isinstance(result.get("peer_frontiers"), list) + or not isinstance(result.get("collaboration_opportunities"), list) ): raise RuntimeError("TypeScript shared goal alignment shape mismatch") return dict(result) diff --git a/loopx/control_plane/goals/shared_goal_alignment.ts b/loopx/control_plane/goals/shared_goal_alignment.ts index 2a2ba35a4c..0f6dddcf05 100644 --- a/loopx/control_plane/goals/shared_goal_alignment.ts +++ b/loopx/control_plane/goals/shared_goal_alignment.ts @@ -1,5 +1,13 @@ import type { JsonObject } from "../effect_program.ts"; import { sharedGoalWorkFacts } from "./shared_goal_work.ts"; +import { + decodeCallerLanes, + decodePeerFrontiers, + projectPeerCoordination, + type CallerLaneSummary, + type CollaborationOpportunity, + type PeerFrontierItem, +} from "./peer_coordination.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { optionalNonEmptyString, @@ -119,6 +127,8 @@ export interface SharedGoalAlignmentRequest extends JsonObject { unclaimed_eligible: UnclaimedEligibleFacts[]; peer_claimed_bound_todo_ids: string[]; open_lane_replan_obligation_required: boolean; + caller_lanes?: CallerLaneSummary[]; + peer_frontiers?: PeerFrontierItem[]; } export interface SharedGoalAlignment extends JsonObject { @@ -134,6 +144,8 @@ export interface SharedGoalAlignment extends JsonObject { }>; drift_facts: SharedGoalAlignmentDriftFact[]; conflict_facts: SharedGoalAlignmentConflictFact[]; + peer_frontiers: PeerFrontierItem[]; + collaboration_opportunities: CollaborationOpportunity[]; read_only: true; } @@ -525,7 +537,7 @@ export function decodeSharedGoalAlignmentRequest( } const agentIdValue = agentId(request.agent_id, "shared_goal_alignment.agent_id"); if (request.work_items !== undefined) { - for (const key of ["claims", "frontier_counts", "unclaimed_eligible", "peer_claimed_bound_todo_ids"]) { + for (const key of ["claims", "frontier_counts", "unclaimed_eligible", "peer_claimed_bound_todo_ids", "caller_lanes", "peer_frontiers"]) { if (request[key] !== undefined) throw new EffectRuntimeRequestError("work_items cannot mix with preselected alignment facts"); } request = {...request, ...sharedGoalWorkFacts(request.work_items, agentIdValue, request.observed_at)}; @@ -555,12 +567,18 @@ export function decodeSharedGoalAlignmentRequest( claimedTodoIds, ), open_lane_replan_obligation_required: openLaneReplanObligationRequired, + caller_lanes: decodeCallerLanes(request.caller_lanes), + peer_frontiers: decodePeerFrontiers(request.peer_frontiers), }; } /** Project one read-only per-Agent alignment view from typed facts. */ export function projectSharedGoalAlignment(value: unknown): SharedGoalAlignment { const request = decodeSharedGoalAlignmentRequest(value); + const coordination = projectPeerCoordination( + request.caller_lanes ?? [], + request.peer_frontiers ?? [], + ); return { schema_version: SHARED_GOAL_ALIGNMENT_SCHEMA_VERSION, goal_id: request.goal_id, @@ -580,6 +598,7 @@ export function projectSharedGoalAlignment(value: unknown): SharedGoalAlignment request.peer_claimed_bound_todo_ids, request.open_lane_replan_obligation_required, ), + ...coordination, read_only: true, }; } diff --git a/loopx/control_plane/goals/shared_goal_work.ts b/loopx/control_plane/goals/shared_goal_work.ts index 5c653e99fb..dcc7ce44a2 100644 --- a/loopx/control_plane/goals/shared_goal_work.ts +++ b/loopx/control_plane/goals/shared_goal_work.ts @@ -2,9 +2,84 @@ import type { JsonObject } from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { requireJsonObject, optionalNonEmptyString, requireStringArray } from "../runtime_decode.ts"; -import { leaseIsActive, leaseEpoch, TaskLeaseAcquireError } from "../work_items/task_lease_acquire.ts"; +import { + TASK_LEASE_SCHEMA_VERSION, + leaseIsActive, + leaseEpoch, + leaseVersion, + TaskLeaseAcquireError, + type LeaseRecord, +} from "../work_items/task_lease_acquire.ts"; +import { parseIsoTimestamp } from "../runtime_timestamp.ts"; import { normalizeTodoAgent } from "../coordination/todo_agents.ts"; import { AuthorityStoreProtocolError } from "../coordination/authority_store_codec.ts"; +import { normalizeWriteScopes } from "../work_items/write_scope_codec.ts"; +import { normalizeTodoRepository } from "../todos/work_requirements.ts"; + +function laneFields(item: JsonObject, leaseActive: boolean | null): JsonObject { + const priority = optionalNonEmptyString(item.priority, "priority"); + const normalizedPriority = priority && /^p[0-4]$/iu.test(priority.trim()) ? priority.trim().toUpperCase() : null; + const actionKind = optionalNonEmptyString(item.action_kind, "action_kind"); + const taskDomain = optionalNonEmptyString(item.task_domain, "task_domain"); + return { + todo_id: String(item.todo_id), + priority: normalizedPriority, + action_kind: actionKind ? actionKind.trim().toLowerCase() : null, + task_domain: taskDomain ? taskDomain.trim().toLowerCase() : null, + task_repository: normalizeTodoRepository(item.task_repository, "task_repository"), + target_key: optionalNonEmptyString(item.target_key, "target_key"), + required_write_scopes: normalizeWriteScopes(item.required_write_scopes ?? []), + completion_validation_required: item.completion_validation_required === true, + lease_active: leaseActive, + }; +} + +/** Validate active lease credentials symmetrically for callers and peers. */ +function activeLeaseDetails( + lease: JsonObject | null, + now: Date, +): { owner: string; epoch: number } | null { + if (!leaseIsActive(lease, now)) return null; + return { + owner: normalizeTodoAgent(lease?.owner, "active task lease owner"), + epoch: leaseEpoch(lease), + }; +} + +/** + * Validate active or released `task_lease_v0` credentials using canonical + * task-lease rules so unknown schemas or corrupt status/fields degrade that + * peer lane to `null` instead of masquerading as unleased (`false`). + */ +function parseKnownTaskLease(lease: JsonObject): LeaseRecord { + if (lease.schema_version !== TASK_LEASE_SCHEMA_VERSION) { + throw new TaskLeaseAcquireError("unknown task lease schema_version", "corrupt_lease"); + } + if (lease.status !== "active" && lease.status !== "released") { + throw new TaskLeaseAcquireError("unknown task lease status", "corrupt_lease"); + } + if ( + lease.expires_at !== undefined && lease.expires_at !== null + && (typeof lease.expires_at !== "string" || parseIsoTimestamp(lease.expires_at) === null) + ) { + throw new TaskLeaseAcquireError("lease expires_at must be a valid timestamp", "corrupt_lease"); + } + normalizeTodoAgent(lease.owner, "active task lease owner"); + leaseEpoch(lease); + leaseVersion(lease); + return lease as LeaseRecord; +} + +function peerLeaseActive(item: JsonObject, now: Date): boolean | null { + if (item.lease_read_error != null) return null; + if (item.lease == null) return false; + try { + const lease = parseKnownTaskLease(requireJsonObject(item.lease, "peer claim lease")); + return activeLeaseDetails(lease, now) !== null; + } catch { + return null; + } +} export function sharedGoalWorkFacts(value: unknown, agent: string, observedAt: unknown): JsonObject { if (typeof observedAt !== "string" || !Number.isFinite(Date.parse(observedAt))) { @@ -40,31 +115,35 @@ export function sharedGoalWorkFacts(value: unknown, agent: string, observedAt: u if (claim && claim !== agent) peers.push(item); else if (!excluded) (claim ? current : unclaimed).push(item); } + const activeCallerLease = new Map(); + const claims = current.map((item) => { + if (item.lease_read_error != null) { + throw new EffectRuntimeRequestError(`cannot read selected claim lease: ${item.todo_id}`); + } + const lease = item.lease == null ? null : requireJsonObject(item.lease, "claim lease"); + let details: { owner: string; epoch: number } | null = null; + try { + details = activeLeaseDetails(lease, now); + } catch (error) { + if (error instanceof AuthorityStoreProtocolError) { + throw new EffectRuntimeRequestError("active task lease has no valid owner"); + } + if (error instanceof TaskLeaseAcquireError) { + throw new EffectRuntimeRequestError(error.message); + } + throw error; + } + const epoch = details?.epoch ?? null; + const owner = details?.owner ?? null; + activeCallerLease.set(String(item.todo_id), details !== null); + return {todo_id: item.todo_id, claimed_by: item.claimed_by, lease_epoch: epoch, lease_owner: owner}; + }); return { frontier_counts: {current_agent_claimed_advancement_count: current.length, unclaimed_advancement_count: unclaimed.length, other_agent_claimed_advancement_count: peers.length}, - claims: current.map((item) => { - if (item.lease_read_error != null) { - throw new EffectRuntimeRequestError(`cannot read selected claim lease: ${item.todo_id}`); - } - const lease = item.lease == null ? null : requireJsonObject(item.lease, "claim lease"); - let epoch: number | null = null, owner: string | null = null; - try { - if (leaseIsActive(lease, now)) { - owner = normalizeTodoAgent(lease?.owner, "active task lease owner"); - epoch = leaseEpoch(lease); - } - } catch (error) { - if (error instanceof AuthorityStoreProtocolError) { - throw new EffectRuntimeRequestError("active task lease has no valid owner"); - } - if (error instanceof TaskLeaseAcquireError) { - throw new EffectRuntimeRequestError(error.message); - } - throw error; - } - return {todo_id: item.todo_id, claimed_by: item.claimed_by, lease_epoch: epoch, lease_owner: owner}; - }), + claims, + caller_lanes: current.map((item) => laneFields(item, activeCallerLease.get(String(item.todo_id)) ?? false)), + peer_frontiers: peers.map((item) => ({agent_id: item.claimed_by, ...laneFields(item, peerLeaseActive(item, now))})), unclaimed_eligible: unclaimed.map((item) => ({todo_id: item.todo_id, task_class: "advancement_task"})), peer_claimed_bound_todo_ids: peers.filter((item) => item.bound_agent === agent).map((item) => item.todo_id), goal_todo_inventory: inventory, diff --git a/loopx/control_plane/goals/shared_goal_work_source.py b/loopx/control_plane/goals/shared_goal_work_source.py index a53b234d8c..9b904c03dc 100644 --- a/loopx/control_plane/goals/shared_goal_work_source.py +++ b/loopx/control_plane/goals/shared_goal_work_source.py @@ -11,6 +11,16 @@ from ...registry import resolve_state_file from ..coordination.local_authority import canonical_todo_summary_fields, read_canonical_todos_if_promoted from ..todos.contract import normalize_todo_excluded_agents +from ..todos.todo_semantics import todo_priority_parts + + +def _canonical_lane_priority(source: dict[str, Any]) -> str | None: + raw = str(source.get("priority") or "").strip().upper() + if raw in {"P0", "P1", "P2", "P3", "P4"}: + return raw + parsed, _ = todo_priority_parts(str(source.get("text") or "")) + token = str(parsed or "").strip().upper()[:2] + return token if token in {"P0", "P1", "P2", "P3", "P4"} else None @dataclass(frozen=True) @@ -43,7 +53,10 @@ def read_shared_goal_work_source(*, goal: dict[str, Any], project: Path, items = [] for source in summary.get("items") or []: item = {key: source.get(key) for key in ("todo_id", "status", "done", "task_class", - "archive_state", "claimed_by", "bound_agent", "resume_when", "resume_ready", "action_kind")} + "archive_state", "claimed_by", "bound_agent", "resume_when", "resume_ready", + "action_kind", "task_domain", "task_repository", "target_key", + "required_write_scopes", "completion_validation_required")} + item["priority"] = _canonical_lane_priority(source) item["excluded_agents"] = normalize_todo_excluded_agents(source.get("excluded_agents")) item["lease"] = None todo_id = item["todo_id"] diff --git a/loopx/control_plane/work_items/task_lease_acquire_decision.ts b/loopx/control_plane/work_items/task_lease_acquire_decision.ts index f9cff44c9f..9d5fe719bc 100644 --- a/loopx/control_plane/work_items/task_lease_acquire_decision.ts +++ b/loopx/control_plane/work_items/task_lease_acquire_decision.ts @@ -498,7 +498,7 @@ export function evaluateTaskLeaseWriteScopesOverlap(value: unknown): JsonObject } /** Literal segments before the first wildcard, folded for comparison. */ -function schedulingScopeRoot(scope: string): string { +export function schedulingScopeRoot(scope: string): string { const parts: string[] = []; for (const part of scope.replace(/^\/+|\/+$/gu, "").split("/")) { if (part.includes("*") || part.includes("?") || part.includes("[")) break; @@ -507,7 +507,7 @@ function schedulingScopeRoot(scope: string): string { return caseFold(parts.join("/")); } -function schedulingScopePairOverlaps(left: string, right: string): boolean { +export function schedulingScopePairOverlaps(left: string, right: string): boolean { if (scopePairOverlaps(left, right)) return true; const leftRoot = schedulingScopeRoot(left); const rightRoot = schedulingScopeRoot(right); diff --git a/tests/control_plane/test_shared_goal_alignment.py b/tests/control_plane/test_shared_goal_alignment.py index f4233ae1a4..74766a80f7 100644 --- a/tests/control_plane/test_shared_goal_alignment.py +++ b/tests/control_plane/test_shared_goal_alignment.py @@ -910,3 +910,388 @@ def test_registered_method_rejects_an_illegal_request() -> None: }, ) assert excinfo.value.error_kind == "request_rejected" + + +def _canonical_record(**fields: object) -> dict[str, object]: + raw = { + "role": "agent", + "source_section": "Agent Todo", + "archive_state": "active", + "done": False, + **fields, + } + return canonical_todo_read_record( + structured_todo_item( + raw, + role="agent", + source_section="Agent Todo", + archive_state="active", + text_limit=None, + ) + ) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_canonical_snapshot_projects_peer_coordination_opportunities( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_caller_verify", + text="[P0] Independently verify simplification slice", + status="open", + task_class="advancement_task", + action_kind="verify", + task_domain="control_plane", + task_repository="https://github.com/loopx-project/loopx.git", + target_key="turn-envelope", + required_write_scopes=["loopx/control_plane/quota/"], + claimed_by="agent-a", + priority="P0", + index=1, + ), + _canonical_record( + todo_id="todo_peer_slim", + text="[P0] Slim Turn-envelope context payload", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + task_repository="git:github.com/loopx-project/loopx", + target_key="turn-envelope", + required_write_scopes=["loopx/control_plane/quota/turn_envelope.ts"], + completion_validation_required=True, + claimed_by="agent-b", + priority="P0", + index=2, + ), + _canonical_record( + todo_id="todo_peer_synergy", + text="[P1] Trim redundant alignment helpers", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + task_repository="git:github.com/loopx-project/loopx", + required_write_scopes=["loopx/control_plane/agents/"], + claimed_by="agent-b", + priority="P1", + index=3, + ), + ] + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + initialize_canonical_authority( + paths["runtime"], GOAL_ID, projection, state_path=paths["state_file"], provider=provider + ) + + result = project_shared_goal_alignment( + goal_id=GOAL_ID, + agent_id="agent-a", + project=paths["project"], + registry_path=paths["registry"], + runtime_root=paths["runtime"], + ) + assert result["read_only"] is True + assert [p["todo_id"] for p in result["peer_frontiers"]] == ["todo_peer_slim", "todo_peer_synergy"] + assert all(p["lease_active"] is False for p in result["peer_frontiers"]) + kinds = [opp["kind"] for opp in result["collaboration_opportunities"]] + assert kinds == [ + "shared_target_collision_risk", + "peer_verification_needed", + "peer_unleased_lane_attention", + "peer_unleased_lane_attention", + "shared_domain_synergy", + ] + assert all(opp["grants_authority"] is False for opp in result["collaboration_opportunities"]) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_idle_caller_discovers_peer_verification_demand( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_peer_needs_verify", + text="[P0] Verify open-core split PR", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="microkernel", + completion_validation_required=True, + claimed_by="agent-b", + priority="P0", + index=1, + ) + ] + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + initialize_canonical_authority( + paths["runtime"], GOAL_ID, projection, state_path=paths["state_file"], provider=provider + ) + result = project_shared_goal_alignment( + goal_id=GOAL_ID, + agent_id="agent-a", + project=paths["project"], + registry_path=paths["registry"], + runtime_root=paths["runtime"], + ) + assert result["frontier_counts"]["current_agent_claimed_advancement_count"] == 0 + opps = result["collaboration_opportunities"] + assert [opp["kind"] for opp in opps] == [ + "peer_verification_needed", + "peer_unleased_lane_attention", + ] + assert all(opp["peer_todo_id"] == "todo_peer_needs_verify" for opp in opps) + assert all(opp["caller_todo_id"] is None for opp in opps) + assert all(opp["grants_authority"] is False for opp in opps) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_corrupt_peer_lease_epoch_and_owner_degrade_to_null_while_caller_rejects( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + + peer_root = tmp_path / "peer_case" + peer_paths = _write_fixture(peer_root, todo_specs=[], canonical=False) + peer_todos = [ + _canonical_record( + todo_id="todo_peer_epoch_zero", + text="[P0] Peer with zero lease epoch", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + claimed_by="agent-b", + priority="P0", + index=1, + ), + _canonical_record( + todo_id="todo_peer_bad_owner", + text="[P0] Peer with empty lease owner", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + claimed_by="agent-b", + priority="P0", + index=2, + ), + _canonical_record( + todo_id="todo_peer_valid_lease", + text="[P0] Peer with valid active lease", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + claimed_by="agent-b", + priority="P0", + index=3, + ), + ] + peer_projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=peer_todos) + peer_projection["leases"] = [ + { + "schema_version": "task_lease_v0", + "goal_id": GOAL_ID, + "todo_id": "todo_peer_epoch_zero", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-b", + "lease_epoch": 0, + "version": 1, + }, + { + "schema_version": "task_lease_v0", + "goal_id": GOAL_ID, + "todo_id": "todo_peer_bad_owner", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "", + "lease_epoch": 2, + "version": 1, + }, + { + "schema_version": "task_lease_v0", + "goal_id": GOAL_ID, + "todo_id": "todo_peer_valid_lease", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-b", + "lease_epoch": 2, + "version": 1, + }, + ] + initialize_canonical_authority( + peer_paths["runtime"], GOAL_ID, peer_projection, state_path=peer_paths["state_file"], provider=provider + ) + + result = project_shared_goal_alignment( + goal_id=GOAL_ID, + agent_id="agent-a", + project=peer_paths["project"], + registry_path=peer_paths["registry"], + runtime_root=peer_paths["runtime"], + ) + by_id = {item["todo_id"]: item for item in result["peer_frontiers"]} + assert by_id["todo_peer_epoch_zero"]["lease_active"] is None + assert by_id["todo_peer_bad_owner"]["lease_active"] is None + assert by_id["todo_peer_valid_lease"]["lease_active"] is True + assert result["collaboration_opportunities"] == [] + + # Binding the same epoch=0 lease to the caller fails closed. + caller_root = tmp_path / "caller_case" + if provider == "sqlite": + isolate_sqlite_runtime(caller_root, monkeypatch) + caller_paths = _write_fixture(caller_root, todo_specs=[], canonical=False) + caller_todos = [ + _canonical_record( + todo_id="todo_caller_epoch_zero", + text="[P0] Caller with zero lease epoch", + status="open", + task_class="advancement_task", + action_kind="run", + claimed_by="agent-a", + priority="P0", + index=1, + ), + ] + caller_projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=caller_todos) + caller_projection["leases"] = [ + { + "schema_version": "task_lease_v0", + "goal_id": GOAL_ID, + "todo_id": "todo_caller_epoch_zero", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-a", + "lease_epoch": 0, + "version": 1, + } + ] + initialize_canonical_authority( + caller_paths["runtime"], GOAL_ID, caller_projection, state_path=caller_paths["state_file"], provider=provider + ) + with pytest.raises(ValueError, match="lease epoch"): + project_shared_goal_alignment( + goal_id=GOAL_ID, + agent_id="agent-a", + project=caller_paths["project"], + registry_path=caller_paths["registry"], + runtime_root=caller_paths["runtime"], + ) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_unrecognized_peer_lease_schema_degrades_to_null_without_false_unleased_attention( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_peer_unknown_schema", + text="[P0] Peer with unrecognized lease schema_version", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + claimed_by="agent-b", + priority="P0", + index=1, + ), + _canonical_record( + todo_id="todo_peer_released_known", + text="[P1] Peer with valid released lease", + status="open", + task_class="advancement_task", + action_kind="code", + task_domain="control_plane", + claimed_by="agent-b", + priority="P1", + index=2, + ), + ] + unknown_projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + unknown_projection["leases"] = [ + { + "schema_version": "task_lease_v99", + "goal_id": GOAL_ID, + "todo_id": "todo_peer_unknown_schema", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-b", + "lease_epoch": 2, + "version": 1, + }, + { + "schema_version": "task_lease_v0", + "goal_id": GOAL_ID, + "todo_id": "todo_peer_released_known", + "status": "released", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-b", + "lease_epoch": 2, + "version": 1, + }, + ] + initialize_canonical_authority( + paths["runtime"], GOAL_ID, unknown_projection, state_path=paths["state_file"], provider=provider + ) + degraded = project_shared_goal_alignment( + goal_id=GOAL_ID, + agent_id="agent-a", + project=paths["project"], + registry_path=paths["registry"], + runtime_root=paths["runtime"], + ) + by_id = {item["todo_id"]: item for item in degraded["peer_frontiers"]} + assert by_id["todo_peer_unknown_schema"]["lease_active"] is None + assert by_id["todo_peer_released_known"]["lease_active"] is False + assert [opp["peer_todo_id"] for opp in degraded["collaboration_opportunities"]] == [ + "todo_peer_released_known" + ] + + # Switching the exact fixture record back to supported task_lease_v0 reports lease_active=True. + restored_root = tmp_path / "restored" + if provider == "sqlite": + isolate_sqlite_runtime(restored_root, monkeypatch) + restored_paths = _write_fixture(restored_root, todo_specs=[], canonical=False) + restored_projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + restored_projection["leases"] = [ + {**unknown_projection["leases"][0], "schema_version": "task_lease_v0"}, + unknown_projection["leases"][1], + ] + initialize_canonical_authority( + restored_paths["runtime"], + GOAL_ID, + restored_projection, + state_path=restored_paths["state_file"], + provider=provider, + ) + restored = project_shared_goal_alignment( + goal_id=GOAL_ID, + agent_id="agent-a", + project=restored_paths["project"], + registry_path=restored_paths["registry"], + runtime_root=restored_paths["runtime"], + ) + restored_by_id = {item["todo_id"]: item for item in restored["peer_frontiers"]} + assert restored_by_id["todo_peer_unknown_schema"]["lease_active"] is True + assert restored_by_id["todo_peer_released_known"]["lease_active"] is False diff --git a/tests/control_plane/test_shared_goal_alignment_cli.py b/tests/control_plane/test_shared_goal_alignment_cli.py index d73dc8b6f0..bd754cb703 100644 --- a/tests/control_plane/test_shared_goal_alignment_cli.py +++ b/tests/control_plane/test_shared_goal_alignment_cli.py @@ -309,3 +309,280 @@ def test_cli_preserves_selected_canonical_basis_without_display(tmp_path, monkey assert payload["frontier_basis"] == {"basis_source": "unbound", "based_on_state_event_sequence": None, "last_agent_event_id": None} assert not state_file.exists() + + +@pytest.mark.parametrize("fmt", ["json", "markdown"]) +def test_cli_surfaces_peer_frontiers_and_collaboration_opportunities( + tmp_path: Path, capsys: pytest.CaptureFixture[str], fmt: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + from tests.control_plane.test_shared_goal_alignment import _canonical_record + + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_verify", + text="[P0] Verify peer PR", + status="open", + task_class="advancement_task", + action_kind="verify", + task_domain="control_plane", + claimed_by="agent-a", + priority="P0", + index=1, + ), + _canonical_record( + todo_id="todo_slim", + text="[P0] Simplify envelope", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + completion_validation_required=True, + claimed_by="agent-b", + priority="P0", + index=2, + ), + ] + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + initialize_canonical_authority( + paths["runtime"], GOAL_ID, projection, state_path=paths["state_file"], provider="file" + ) + code, payload, stdout = _run_alignment_cli( + capsys, + paths["registry"], + "shared-goal-alignment", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--project", + str(paths["project"]), + "--format", + fmt, + ) + assert code == 0 + if fmt == "json": + assert len(payload["peer_frontiers"]) == 1 + assert any(o["kind"] == "peer_verification_needed" for o in payload["collaboration_opportunities"]) + else: + assert "- peer_frontiers:" in stdout + assert "- collaboration_opportunities:" in stdout + assert "peer_verification_needed" in stdout + assert "grants_authority=`False`" in stdout + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_cli_idle_caller_single_p0_peer_surfaces_verification_and_unleased_attention( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + from tests.control_plane.test_shared_goal_alignment import _canonical_record + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_single_p0_peer", + text="[P0] Needs independent verification and is unleased", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + completion_validation_required=True, + claimed_by="agent-b", + priority="P0", + index=1, + ) + ] + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + initialize_canonical_authority( + paths["runtime"], GOAL_ID, projection, state_path=paths["state_file"], provider=provider + ) + code, payload, _ = _run_alignment_cli( + capsys, + paths["registry"], + "shared-goal-alignment", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--project", + str(paths["project"]), + "--format", + "json", + ) + assert code == 0, payload + assert payload["peer_frontiers"][0]["lease_active"] is False + assert [opp["kind"] for opp in payload["collaboration_opportunities"]] == [ + "peer_verification_needed", + "peer_unleased_lane_attention", + ] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_cli_corrupt_peer_lease_epoch_zero_returns_null_while_caller_rejects( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + from tests.control_plane.test_shared_goal_alignment import _canonical_record + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_corrupt_peer_lease", + text="[P0] Peer with epoch zero lease", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + claimed_by="agent-b", + priority="P0", + index=1, + ) + ] + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + projection["leases"] = [ + { + "schema_version": "task_lease_v0", + "goal_id": GOAL_ID, + "todo_id": "todo_corrupt_peer_lease", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-b", + "lease_epoch": 0, + "version": 1, + } + ] + initialize_canonical_authority( + paths["runtime"], GOAL_ID, projection, state_path=paths["state_file"], provider=provider + ) + code, payload, _ = _run_alignment_cli( + capsys, + paths["registry"], + "shared-goal-alignment", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--project", + str(paths["project"]), + "--format", + "json", + ) + assert code == 0, payload + assert payload["peer_frontiers"][0]["lease_active"] is None + assert payload["collaboration_opportunities"] == [] + + # Same corrupt epoch=0 lease read from caller fails closed on CLI too. + caller_code, caller_payload, _ = _run_alignment_cli( + capsys, + paths["registry"], + "shared-goal-alignment", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-b", + "--project", + str(paths["project"]), + "--format", + "json", + ) + assert caller_code == 1 + assert caller_payload["ok"] is False + assert "lease epoch" in caller_payload["error"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_cli_unrecognized_peer_lease_schema_returns_null_without_false_unleased_attention( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], provider: str +) -> None: + from canonical_authority_fixture import initialize_canonical_authority, isolate_sqlite_runtime + from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection + from tests.control_plane.test_shared_goal_alignment import _canonical_record + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_fixture(tmp_path, todo_specs=[], canonical=False) + todos = [ + _canonical_record( + todo_id="todo_unknown_schema_peer", + text="[P0] Peer with unrecognized lease schema_version", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + claimed_by="agent-b", + priority="P0", + index=1, + ) + ] + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + projection["leases"] = [ + { + "schema_version": "task_lease_v99", + "goal_id": GOAL_ID, + "todo_id": "todo_unknown_schema_peer", + "status": "active", + "expires_at": "2099-01-01T00:00:00Z", + "owner": "agent-b", + "lease_epoch": 2, + "version": 1, + } + ] + initialize_canonical_authority( + paths["runtime"], GOAL_ID, projection, state_path=paths["state_file"], provider=provider + ) + code, payload, _ = _run_alignment_cli( + capsys, + paths["registry"], + "shared-goal-alignment", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--project", + str(paths["project"]), + "--format", + "json", + ) + assert code == 0, payload + assert payload["peer_frontiers"][0]["lease_active"] is None + assert payload["collaboration_opportunities"] == [] + + # Same fixture updated to known task_lease_v0 flips lease_active to True. + restored_root = tmp_path / "restored" + if provider == "sqlite": + isolate_sqlite_runtime(restored_root, monkeypatch) + restored_paths = _write_fixture(restored_root, todo_specs=[], canonical=False) + restored_projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + restored_projection["leases"] = [{**projection["leases"][0], "schema_version": "task_lease_v0"}] + initialize_canonical_authority( + restored_paths["runtime"], + GOAL_ID, + restored_projection, + state_path=restored_paths["state_file"], + provider=provider, + ) + ok_code, ok_payload, _ = _run_alignment_cli( + capsys, + restored_paths["registry"], + "shared-goal-alignment", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--project", + str(restored_paths["project"]), + "--format", + "json", + ) + assert ok_code == 0, ok_payload + assert ok_payload["peer_frontiers"][0]["lease_active"] is True + assert ok_payload["collaboration_opportunities"] == [] diff --git a/tests/control_plane_ts/shared_goal_alignment.test.ts b/tests/control_plane_ts/shared_goal_alignment.test.ts index dcfa85fd2b..caf05ffd24 100644 --- a/tests/control_plane_ts/shared_goal_alignment.test.ts +++ b/tests/control_plane_ts/shared_goal_alignment.test.ts @@ -1,10 +1,21 @@ import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; import test from "node:test"; +import { + MAX_COLLABORATION_OPPORTUNITIES, + MAX_PEER_FRONTIER_ITEMS, + projectPeerCoordination, + type CallerLaneSummary, + type CollaborationOpportunity, + type PeerFrontierItem, +} from "../../loopx/control_plane/goals/peer_coordination.ts"; import { SHARED_GOAL_ALIGNMENT_SCHEMA_VERSION, projectSharedGoalAlignment, } from "../../loopx/control_plane/goals/shared_goal_alignment.ts"; +import { evaluateQuotaSchedulingWriteScopesOverlap } from "../../loopx/control_plane/work_items/task_lease_acquire_decision.ts"; +import { repositoryScopesMayOverlap } from "../../loopx/control_plane/work_items/task_lease_repository.ts"; const DIGEST = "sha256:" + "a".repeat(64); @@ -613,3 +624,623 @@ test("a non-boolean open lane replan flag is rejected", () => { /open_lane_replan_obligation_required/, ); }); + +test("work_items project deterministic peer_frontiers, all four opportunity kinds, and idle discovery", () => { + const workRequest = (agentId: string, workItems: unknown[]) => ({ + schema_version: "shared_goal_alignment_request_v0", + goal_id: "personal-loopx-maintenance", + agent_id: agentId, + source_basis: { + revision_basis: "canonical_todo_snapshot", + state_event_basis_sequence: 0, + source_basis_digest: DIGEST, + state_updated_at: null, + todo_basis: { + source_authority: "sqlite_v0", + provider_revision: "sqlite:rev:1", + records_sha256: "b".repeat(64), + }, + }, + frontier_basis: { + basis_source: "unbound", + based_on_state_event_sequence: null, + last_agent_event_id: null, + }, + work_items: workItems, + observed_at: "2026-11-27T01:00:00Z", + open_lane_replan_obligation_required: false, + }); + + const sharedWork = [ + { + todo_id: "todo_caller_verify", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "edgebench-analysis", + priority: "P0", + action_kind: "verify", + task_domain: "control_plane", + task_repository: "https://github.com/loopx-project/loopx.git", + target_key: "quota-envelope", + required_write_scopes: ["loopx/control_plane/quota/"], + completion_validation_required: false, + lease: { + schema_version: "task_lease_v0", + owner: "edgebench-analysis", + lease_epoch: 1, + expires_at: "2026-11-27T04:00:00Z", + }, + }, + { + todo_id: "todo_peer_slim", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "antigravity", + priority: "P0", + action_kind: "refactor", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx", + target_key: "quota-envelope", + required_write_scopes: ["loopx/control_plane/quota/turn_envelope.ts"], + completion_validation_required: true, + lease: null, + }, + { + todo_id: "todo_peer_bench_domain", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "antigravity", + priority: "P2", + action_kind: "code", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx", + target_key: "hosts-consolidation", + required_write_scopes: ["loopx/hosts/"], + completion_validation_required: false, + lease: null, + }, + { + todo_id: "todo_other_repo", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "value-scout", + priority: "P1", + action_kind: "code", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx-cloud", + target_key: "quota-envelope", + required_write_scopes: ["loopx/control_plane/quota/"], + completion_validation_required: false, + lease: null, + }, + ]; + + const active = projectSharedGoalAlignment(workRequest("edgebench-analysis", sharedWork)); + assert.equal(active.read_only, true); + assert.equal(active.peer_frontiers.length, 3); + assert.equal(active.peer_frontiers[0].todo_id, "todo_peer_slim"); + assert.equal(active.peer_frontiers[0].lease_active, false); + + const kinds = active.collaboration_opportunities.map((o) => o.kind); + assert.deepEqual(kinds, [ + "shared_target_collision_risk", + "peer_verification_needed", + "peer_unleased_lane_attention", + "shared_domain_synergy", + ]); + for (const opp of active.collaboration_opportunities) { + assert.equal(opp.grants_authority, false); + assert.match(String(opp.opportunity_id), /^opp_[0-9a-f]{16}$/); + } + assert.ok(!active.collaboration_opportunities.some((o) => o.peer_todo_id === "todo_other_repo")); + // Collision pair suppresses redundant shared_domain_synergy on todo_peer_slim, + // while keeping shared_domain_synergy on todo_peer_bench_domain. + const synergy = active.collaboration_opportunities.find((o) => o.kind === "shared_domain_synergy"); + assert.equal(synergy?.peer_todo_id, "todo_peer_bench_domain"); + + const idle = projectSharedGoalAlignment(workRequest("review-a", sharedWork)); + assert.equal(idle.frontier_counts.current_agent_claimed_advancement_count, 0); + const idleVer = idle.collaboration_opportunities.find((o) => o.kind === "peer_verification_needed"); + assert.equal(idleVer?.caller_todo_id, null); + assert.deepEqual(idleVer?.matched_on, ["completion_validation_required", "idle_caller_discovery"]); + assert.deepEqual( + idle.collaboration_opportunities + .filter((o) => o.peer_todo_id === "todo_peer_slim") + .map((o) => o.kind), + ["peer_verification_needed", "peer_unleased_lane_attention"], + ); +}); + +test("corrupt peer lease degrades safely to lease_active null and caps peer outputs", () => { + const peers = Array.from({ length: 15 }, (_, idx) => ({ + todo_id: `todo_peer_${String(idx).padStart(2, "0")}`, + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "agent-b", + priority: "P0", + action_kind: "code", + task_domain: "kernel", + required_write_scopes: ["loopx/control_plane/"], + completion_validation_required: true, + lease_read_error: idx === 0 ? "corrupt peer lease" : null, + lease: null, + })); + const res = projectSharedGoalAlignment({ + ...baseRequest(), + claims: undefined, + frontier_counts: undefined, + unclaimed_eligible: undefined, + peer_claimed_bound_todo_ids: undefined, + work_items: peers, + observed_at: "2026-11-27T01:00:00Z", + }); + assert.equal(res.peer_frontiers.length, 12); + assert.equal(res.peer_frontiers[0].lease_active, null); + assert.equal(res.collaboration_opportunities.length, 8); +}); + +test("corrupt active peer lease epoch or owner degrades to lease_active null without false unleased attention", () => { + const makePeer = (todoId: string, lease: unknown) => ({ + todo_id: todoId, + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "agent-b", + priority: "P0", + action_kind: "code", + task_domain: "kernel", + completion_validation_required: false, + lease, + }); + + const res = projectSharedGoalAlignment({ + ...baseRequest(), + claims: undefined, + frontier_counts: undefined, + unclaimed_eligible: undefined, + peer_claimed_bound_todo_ids: undefined, + work_items: [ + makePeer("todo_peer_epoch_zero", { + schema_version: "task_lease_v0", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 0, + version: 1, + }), + makePeer("todo_peer_bad_owner", { + schema_version: "task_lease_v0", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + owner: "", + lease_epoch: 2, + version: 1, + }), + makePeer("todo_peer_missing_owner", { + schema_version: "task_lease_v0", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + lease_epoch: 2, + version: 1, + }), + makePeer("todo_peer_valid_active", { + schema_version: "task_lease_v0", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 2, + version: 1, + }), + makePeer("todo_peer_released", { + schema_version: "task_lease_v0", + status: "released", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 2, + version: 1, + }), + ], + observed_at: "2026-11-27T01:00:00Z", + }); + + const byTodo = new Map(res.peer_frontiers.map((p) => [p.todo_id, p])); + assert.equal(byTodo.get("todo_peer_epoch_zero")?.lease_active, null); + assert.equal(byTodo.get("todo_peer_bad_owner")?.lease_active, null); + assert.equal(byTodo.get("todo_peer_missing_owner")?.lease_active, null); + assert.equal(byTodo.get("todo_peer_valid_active")?.lease_active, true); + assert.equal(byTodo.get("todo_peer_released")?.lease_active, false); + // Only the genuinely unleased (released) peer should emit peer_unleased_lane_attention. + assert.deepEqual( + res.collaboration_opportunities.map((o) => [o.kind, o.peer_todo_id]), + [["peer_unleased_lane_attention", "todo_peer_released"]], + ); +}); + +test("idle caller emits both verification and unleased attention for a single P0/P1 peer", () => { + const mkIdleReq = (lease: unknown, priority = "P0") => ({ + ...baseRequest(), + claims: undefined, + frontier_counts: undefined, + unclaimed_eligible: undefined, + peer_claimed_bound_todo_ids: undefined, + work_items: [ + { + todo_id: "todo_single_peer", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "agent-b", + priority, + action_kind: "refactor", + task_domain: "control_plane", + completion_validation_required: true, + lease, + }, + ], + observed_at: "2026-11-27T01:00:00Z", + }); + + const unleased = projectSharedGoalAlignment(mkIdleReq(null, "P0")); + assert.deepEqual( + unleased.collaboration_opportunities.map((o) => o.kind), + ["peer_verification_needed", "peer_unleased_lane_attention"], + ); + assert.ok(unleased.collaboration_opportunities.every((o) => o.caller_todo_id === null)); + + const leased = projectSharedGoalAlignment(mkIdleReq({ + schema_version: "task_lease_v0", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 1, + version: 1, + }, "P0")); + assert.deepEqual( + leased.collaboration_opportunities.map((o) => o.kind), + ["peer_verification_needed"], + ); +}); + +test("unknown lease schema_version or invalid status degrades only that peer to lease_active null", () => { + const mkReq = (lease: unknown) => ({ + ...baseRequest(), + claims: undefined, + frontier_counts: undefined, + unclaimed_eligible: undefined, + peer_claimed_bound_todo_ids: undefined, + work_items: [ + { + todo_id: "todo_peer_unknown_schema", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "agent-b", + priority: "P0", + action_kind: "code", + task_domain: "control_plane", + completion_validation_required: false, + lease, + }, + { + todo_id: "todo_peer_absent_lease", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "agent-c", + priority: "P1", + action_kind: "code", + task_domain: "control_plane", + completion_validation_required: false, + lease: null, + }, + { + todo_id: "todo_peer_expired_known", + status: "open", + done: false, + task_class: "advancement_task", + archive_state: "active", + claimed_by: "agent-d", + priority: "P1", + action_kind: "code", + task_domain: "control_plane", + completion_validation_required: false, + lease: { + schema_version: "task_lease_v0", + status: "active", + expires_at: "2020-01-01T00:00:00Z", + owner: "agent-d", + lease_epoch: 1, + version: 1, + }, + }, + ], + observed_at: "2026-11-27T01:00:00Z", + }); + + for (const invalidLease of [ + { + schema_version: "task_lease_v99", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 1, + version: 1, + }, + { + schema_version: "task_lease_v0", + status: "suspended", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 1, + version: 1, + }, + { + schema_version: "task_lease_v0", + status: "released", + expires_at: "bad-timestamp", + owner: "agent-b", + lease_epoch: 1, + version: 1, + }, + { + owner: "agent-b", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + }, + ]) { + const res = projectSharedGoalAlignment(mkReq(invalidLease)); + const byId = new Map(res.peer_frontiers.map((p) => [p.todo_id, p])); + assert.equal(byId.get("todo_peer_unknown_schema")?.lease_active, null); + assert.equal(byId.get("todo_peer_absent_lease")?.lease_active, false); + assert.equal(byId.get("todo_peer_expired_known")?.lease_active, false); + assert.ok( + !res.collaboration_opportunities.some((o) => o.peer_todo_id === "todo_peer_unknown_schema"), + "uninterpretable peer lease must not emit peer_unleased_lane_attention", + ); + assert.ok( + res.collaboration_opportunities.some( + (o) => o.kind === "peer_unleased_lane_attention" && o.peer_todo_id === "todo_peer_absent_lease", + ), + ); + } + + // Switching the exact fixture record back to task_lease_v0 yields lease_active === true. + const valid = projectSharedGoalAlignment(mkReq({ + schema_version: "task_lease_v0", + status: "active", + expires_at: "2099-01-01T00:00:00Z", + owner: "agent-b", + lease_epoch: 1, + version: 1, + })); + const validById = new Map(valid.peer_frontiers.map((p) => [p.todo_id, p])); + assert.equal(validById.get("todo_peer_unknown_schema")?.lease_active, true); +}); + +function referencePeerCoordination( + callerLanes: readonly CallerLaneSummary[], + peerLanes: readonly PeerFrontierItem[], +) { + const rankMap: Record = { P0: 0, P1: 1, P2: 2, P3: 3, P4: 4 }; + const pRank = (p: string | null) => (p !== null && p in rankMap ? rankMap[p] : 50); + const kindRank: Record = { + shared_target_collision_risk: 0, + peer_verification_needed: 1, + peer_unleased_lane_attention: 2, + shared_domain_synergy: 3, + }; + const verifiers = new Set(["verify", "review", "benchmark", "evaluate", "audit"]); + const oppId = (kind: string, peerAgent: string, peerTodo: string, callerTodo: string | null, matched: string[]) => + `opp_${createHash("sha256").update(JSON.stringify([kind, peerAgent, peerTodo, callerTodo ?? "", ...matched]), "utf8").digest("hex").slice(0, 16)}`; + + const sortedCallers = [...callerLanes].sort((a, b) => a.todo_id.localeCompare(b.todo_id)); + const sortedPeers = [...peerLanes].sort( + (a, b) => pRank(a.priority) - pRank(b.priority) + || a.agent_id.localeCompare(b.agent_id) + || a.todo_id.localeCompare(b.todo_id), + ); + const peerRankByTodo = new Map(sortedPeers.map((p) => [p.todo_id, pRank(p.priority)])); + const raw: CollaborationOpportunity[] = []; + if (sortedCallers.length === 0) { + for (const peer of sortedPeers) { + if (peer.completion_validation_required) { + const matched = ["completion_validation_required", "idle_caller_discovery"]; + raw.push({ + opportunity_id: oppId("peer_verification_needed", peer.agent_id, peer.todo_id, null, matched), + kind: "peer_verification_needed", peer_agent_id: peer.agent_id, peer_todo_id: peer.todo_id, + caller_todo_id: null, matched_on: matched, advisory_action: "offer_independent_verification", grants_authority: false, + }); + } + if (peer.lease_active === false && (peer.priority === "P0" || peer.priority === "P1")) { + const matched = ["lease_inactive", "idle_caller_discovery"]; + raw.push({ + opportunity_id: oppId("peer_unleased_lane_attention", peer.agent_id, peer.todo_id, null, matched), + kind: "peer_unleased_lane_attention", peer_agent_id: peer.agent_id, peer_todo_id: peer.todo_id, + caller_todo_id: null, matched_on: matched, advisory_action: "inspect_peer_status_before_duplicating", grants_authority: false, + }); + } + } + } else { + for (const caller of sortedCallers) { + for (const peer of sortedPeers) { + const repoCompat = repositoryScopesMayOverlap(caller.task_repository, peer.task_repository); + const sameTarget = Boolean(caller.target_key && peer.target_key && caller.target_key === peer.target_key); + const scopeHit = repoCompat && caller.required_write_scopes.length > 0 && peer.required_write_scopes.length > 0 + && evaluateQuotaSchedulingWriteScopesOverlap({ + left: [...caller.required_write_scopes], + right: [...peer.required_write_scopes], + }).overlap === true; + const sameDomain = Boolean(caller.task_domain && peer.task_domain && caller.task_domain === peer.task_domain); + const sameRepo = Boolean( + caller.task_repository && peer.task_repository + && caller.task_repository.toLowerCase() === peer.task_repository.toLowerCase(), + ); + const cSignals: string[] = []; + if (repoCompat && sameTarget) cSignals.push("target_key"); + if (scopeHit) cSignals.push("required_write_scopes"); + if (cSignals.length > 0) { + raw.push({ + opportunity_id: oppId("shared_target_collision_risk", peer.agent_id, peer.todo_id, caller.todo_id, cSignals), + kind: "shared_target_collision_risk", peer_agent_id: peer.agent_id, peer_todo_id: peer.todo_id, + caller_todo_id: caller.todo_id, matched_on: cSignals, advisory_action: "deconflict_before_edit", grants_authority: false, + }); + } + const isVer = Boolean(caller.action_kind && verifiers.has(caller.action_kind)); + if (peer.completion_validation_required && repoCompat && (isVer || sameDomain || sameRepo)) { + const matched = ["completion_validation_required"]; + if (isVer) matched.push("caller_verifier_action_kind"); + if (sameDomain) matched.push("task_domain"); + if (sameRepo) matched.push("task_repository"); + raw.push({ + opportunity_id: oppId("peer_verification_needed", peer.agent_id, peer.todo_id, caller.todo_id, matched), + kind: "peer_verification_needed", peer_agent_id: peer.agent_id, peer_todo_id: peer.todo_id, + caller_todo_id: caller.todo_id, matched_on: matched, advisory_action: "offer_independent_verification", grants_authority: false, + }); + } + if (peer.lease_active === false && (peer.priority === "P0" || peer.priority === "P1") && repoCompat && (sameTarget || sameDomain)) { + const matched = ["lease_inactive"]; + if (sameTarget) matched.push("target_key"); + if (sameDomain) matched.push("task_domain"); + raw.push({ + opportunity_id: oppId("peer_unleased_lane_attention", peer.agent_id, peer.todo_id, caller.todo_id, matched), + kind: "peer_unleased_lane_attention", peer_agent_id: peer.agent_id, peer_todo_id: peer.todo_id, + caller_todo_id: caller.todo_id, matched_on: matched, advisory_action: "inspect_peer_status_before_duplicating", grants_authority: false, + }); + } + if (cSignals.length === 0 && repoCompat && sameDomain) { + const matched = ["task_domain"]; + if (sameRepo) matched.push("task_repository"); + raw.push({ + opportunity_id: oppId("shared_domain_synergy", peer.agent_id, peer.todo_id, caller.todo_id, matched), + kind: "shared_domain_synergy", peer_agent_id: peer.agent_id, peer_todo_id: peer.todo_id, + caller_todo_id: caller.todo_id, matched_on: matched, advisory_action: "align_with_peer_deliverable", grants_authority: false, + }); + } + } + } + } + const deduped = new Map(); + for (const opp of raw) { + const k = `${opp.kind}|${opp.peer_agent_id}|${opp.peer_todo_id}|${opp.caller_todo_id ?? ""}`; + if (!deduped.has(k)) deduped.set(k, opp); + } + const opps = [...deduped.values()].sort( + (a, b) => kindRank[a.kind] - kindRank[b.kind] + || (peerRankByTodo.get(a.peer_todo_id) ?? 50) - (peerRankByTodo.get(b.peer_todo_id) ?? 50) + || a.peer_todo_id.localeCompare(b.peer_todo_id) + || (a.caller_todo_id ?? "").localeCompare(b.caller_todo_id ?? "") + || a.opportunity_id.localeCompare(b.opportunity_id), + ); + return { + peer_frontiers: sortedPeers.slice(0, MAX_PEER_FRONTIER_ITEMS), + collaboration_opportunities: opps.slice(0, MAX_COLLABORATION_OPPORTUNITIES), + }; +} + +test("bounded indexed projectPeerCoordination matches exhaustive reference parity across globs, ties, and 160x160 scale", () => { + const scopesPool = [ + [], + ["loopx/control_plane/goals/shared_goal_work.ts"], + ["loopx/control_plane/goals/*.ts"], + ["loopx/control_plane/**"], + ["LoopX/Control_Plane/Goals/"], + ["loopx/a*.ts"], + ["*.md"], + ["./"], + ["packages/dsh-loopx-plugin/src/driver.ts"], + ["docs/architecture/rfcs/"], + ]; + const repos = [null, "git:github.com/loopx-project/loopx", "git:github.com/loopx-project/loopx-cloud"]; + const domains = [null, "control_plane", "microkernel", "docs"]; + const targets = [null, "quota", "hosts", "fold"]; + const priorities = ["P0", "P1", "P2", null]; + const actions = ["code", "verify", "review", "refactor"]; + const leaseStates: (boolean | null)[] = [true, false, null]; + + let seed = 0x9502cafe; + const nextInt = (max: number) => { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return seed % max; + }; + + for (let trial = 0; trial < 50; trial += 1) { + const numCallers = trial % 7 === 0 ? 0 : 1 + nextInt(18); + const numPeers = 1 + nextInt(22); + const callers: CallerLaneSummary[] = Array.from({ length: numCallers }, (_, i) => ({ + todo_id: `todo_c_${i}`, + priority: priorities[nextInt(priorities.length)], + action_kind: actions[nextInt(actions.length)], + task_domain: domains[nextInt(domains.length)], + task_repository: repos[nextInt(repos.length)], + target_key: targets[nextInt(targets.length)], + required_write_scopes: scopesPool[nextInt(scopesPool.length)], + completion_validation_required: nextInt(2) === 1, + lease_active: leaseStates[nextInt(leaseStates.length)], + })); + const peers: PeerFrontierItem[] = Array.from({ length: numPeers }, (_, i) => ({ + // Include occasional tied peer_todo_id across different agent_ids to exercise opportunity_id tie-breaks. + todo_id: `todo_p_${i > 0 && nextInt(8) === 0 ? i - 1 : i}`, + agent_id: `agent-${nextInt(5)}`, + priority: priorities[nextInt(priorities.length)], + action_kind: actions[nextInt(actions.length)], + task_domain: domains[nextInt(domains.length)], + task_repository: repos[nextInt(repos.length)], + target_key: targets[nextInt(targets.length)], + required_write_scopes: scopesPool[nextInt(scopesPool.length)], + completion_validation_required: nextInt(2) === 1, + lease_active: leaseStates[nextInt(leaseStates.length)], + })); + + assert.deepEqual( + projectPeerCoordination(callers, peers), + referencePeerCoordination(callers, peers), + `parity mismatch on trial ${trial}`, + ); + } + + // Large 160x160 scale parity + bounded wall-time regression guard (disjoint + dense cases). + const largeCallers: CallerLaneSummary[] = Array.from({ length: 160 }, (_, i) => ({ + todo_id: `todo_c_${String(i).padStart(3, "0")}`, + priority: "P0", + action_kind: i === 150 ? "verify" : "code", + task_domain: `dom_${i % 10}`, + task_repository: "git:github.com/loopx-project/loopx", + target_key: `tgt_c_${i}`, + required_write_scopes: [`loopx/c_mod_${i}/file.ts`], + completion_validation_required: false, + lease_active: true, + })); + const largePeers: PeerFrontierItem[] = Array.from({ length: 160 }, (_, i) => ({ + agent_id: `agent-${i}`, + todo_id: `todo_p_${String(i).padStart(3, "0")}`, + priority: i % 2 === 0 ? "P0" : "P1", + action_kind: "refactor", + task_domain: `dom_${i % 10}`, + task_repository: "git:github.com/loopx-project/loopx", + target_key: i === 155 ? "tgt_c_12" : `tgt_p_${i}`, + required_write_scopes: [`loopx/p_mod_${i}/sub.ts`], + completion_validation_required: true, + lease_active: false, + })); + + const expectedLarge = referencePeerCoordination(largeCallers, largePeers); + const t0 = performance.now(); + const actualLarge = projectPeerCoordination(largeCallers, largePeers); + const elapsedMs = performance.now() - t0; + assert.deepEqual(actualLarge, expectedLarge); + assert.ok(elapsedMs < 25, `expected <25ms for 160x160 projection, got ${elapsedMs.toFixed(2)}ms`); +});