diff --git a/docs/architecture/rfcs/README.md b/docs/architecture/rfcs/README.md index ba2f0db398..2c4dc69334 100644 --- a/docs/architecture/rfcs/README.md +++ b/docs/architecture/rfcs/README.md @@ -263,6 +263,21 @@ 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 (`peer_coordination.ts`) and M1 conditional + default-on `<=300 B` Turn-envelope digest (`peer_coordination_digest.ts`) + implemented; M2–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`, and automatically injects cursor-deduplicated + `peer_coordination_digest` (`<=300 B` including field key; omitted at `0 B` + when single-agent, unchanged, or opted out) into `TurnEnvelope` on + `loopx quota should-run`. 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..9e9777b321 --- /dev/null +++ b/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.md @@ -0,0 +1,178 @@ +# 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 + M1 conditional default-on Turn-envelope digest shipped; M2–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 autonomous goal-oriented awareness and bilateral handshakes.** Keep explicit claim/lease/inbox owners unchanged (`shared_goal_alignment_v0`, `peer_agent_directory_v0`, `manager-inbox`), while shipping both bounded pull-side discovery (M0) and conditional default-on Turn-envelope digests (`peer_coordination_digest`, `<=300 B` serialized delta including field key, `~75 tokens` / `<0.04%` of a 200K context window; omitted at `0 B` when inactive) so specialized peers on one Goal discover urgent collisions, verification needs, or idle work without manual CLI pulls or human relays. +4. **Separate shipped M0+M1 read-only discovery from future M2–M3 write/host extensions.** M0 (`loopx shared-goal-alignment` / `goal-alignment`) and M1 conditional default-on Turn-envelope digests (`loopx quota should-run` -> `TurnEnvelope`, with explicit `off` opt-out retained for frozen benchmark baselines) require zero manual opt-in on normal product paths; cooldown-gated bilateral inbox handshakes (M2) and host-neutral Antigravity/non-Codex observer adapters (M3) remain follow-up slices gated by their own acceptance evidence. Note that `0 B` serialized omission delta when inactive is distinct from live runtime context-tax measurement against the `<5%` budget. +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, conditional default-on bounded Turn-envelope digest injection (M1, `<=300 B`), 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):** On-demand or pre-amendment pull via `loopx shared-goal-alignment --goal-id --agent-id ` recomputes full `peer_frontiers` and `collaboration_opportunities` (including `shared_domain_synergy`) over canonical `file_v0`/`sqlite_v0` snapshots. +- **M1 (Shipped — conditional default-on):** Normal `loopx quota should-run` Turns automatically invoke TS `peer_coordination_digest.ts` without manual opt-in. When the Goal has `>= 2` registered agents AND unseen qualifying `opportunity_id`s relative to the recipient's live Turn cursor (`peer-coordination-cursors/.json`), `TurnEnvelope` (`v0` / `v1`) embeds `peer_coordination_digest` (`schema: "peer_digest_v0"`, `read_only: true`, `grants_authority: false`) capped strictly at `<=300 B` serialized JSON delta (including `,"peer_coordination_digest":` field key overhead). Busy Turns surface only `shared_target_collision_risk` (`"collision"`) and `peer_verification_needed` (`"verify"`); idle Turns (`caller_lanes == []`) surface `peer_verification_needed` (`"verify"`) and high-priority `peer_unleased_lane_attention` (`"unleased"`). Read-only `--dry-run` previews may display `peer_coordination_digest` without creating or advancing the persistent cursor. Single-agent Goals, empty qualifying sets, unchanged cursors, scheduler-suppressed skip/observation states, and explicit `off` overrides (`coordination.peer_coordination_digest: "off"` or `LOOPX_PEER_COORDINATION_DIGEST=off`) omit the field (`0 B` serialized delta). Live non-preview non-skipped Turns record only actually surfaced item IDs plus still-active previously seen IDs in the cursor (so truncated `omitted > 0` items remain unseen for subsequent Turns while resolved IDs are pruned). +- **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`, and conditional M1 Turn digests without single-agent bloat | `uv run --extra test python -m pytest tests/control_plane/test_shared_goal_alignment.py tests/control_plane/test_shared_goal_alignment_cli.py tests/control_plane/test_peer_coordination_digest.py tests/control_plane/test_cli_output_budget.py` | All parametrized File+SQLite, CLI, TurnEnvelope, cursor-dedup, and `0 B` baseline output-budget assertions pass | Single-host canonical snapshots; no M2 handshake or M3 host daemon 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** | Conditional default-on Turn-envelope `peer_coordination_digest` (`<=300 B` incl. key, `0 B` omitted when inactive/unchanged, busy/idle filtering, live cursor commit & prune, explicit `off` override) | Canonical `file_v0`/`sqlite_v0` snapshot + `TurnEnvelope` v0/v1 integration | TS `peer_coordination_digest.test.ts` + File/SQLite `test_peer_coordination_digest.py` + zero baseline `cli-output-budget` regression (`canary premerge`) | Set `coordination.peer_coordination_digest="off"` or revert M1 wiring | +| **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 (Resolved — 2026-11-27, Turn-envelope default path & filtering — M1):** M1 requires **no manual opt-in** on normal product paths (`loopx quota should-run` -> `TurnEnvelope`). When `>= 2` registered agents share a Goal and unseen qualifying `opportunity_id`s exist relative to the cursor, emit `peer_coordination_digest` (`<=300 B` serialized delta including field key): busy Turns include only `shared_target_collision_risk` + `peer_verification_needed`; idle Turns include `peer_verification_needed` + high-priority `peer_unleased_lane_attention`. Read-only `--dry-run` previews may display the digest without mutating the cursor, whereas live non-preview non-skipped Turns record only actually surfaced item IDs plus still-active previously seen IDs (leaving omitted items unseen). Single-agent Goals, zero new qualifying opportunities, unchanged cursors, skipped/scheduler-observation modes, and explicit `off` settings omit the field (`0 B`). `shared_domain_synergy` remains pull-only via `shared-goal-alignment` / `goal-alignment`. Live runtime `<5%` control-plane tax remains verified explicitly (serialized `0 B` omission does not waive benchmark runtime verification). +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+M1 shipped cleanly on the updated PR branch (`peer_coordination.ts` + `peer_coordination_digest.ts` + `TurnEnvelope` v0/v1 wiring; subsequent M2–M3 checkpoint ledgers may open under `ledger/`). + +## 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 | +| 2026-11-27 | Resolve D1 & ship M1 conditional default-on `peer_coordination_digest` (`<=300 B`, `0 B` omitted when inactive, busy/idle filtering, cursor auto-prune, explicit `off` escape hatch) | User-approved direction ("为啥仍需要主动调用…路径能足够自动和智能么") + maintainer PR review | Require manual per-Goal opt-in flag (`opt-in` default-off) or pull-only CLI | §§1, 3, 5, 9, 11, 12 | + +## 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 | Clean PR worktree | `tests/control_plane_ts/shared_goal_alignment.test.ts` & `tests/control_plane/test_shared_goal_alignment*.py` | Pass in local worktree | Synthetic temp fixtures | +| E2 | M1 automatic Turn-envelope digest (`<=300 B`), cursor dedup/prune, explicit opt-out, and zero baseline CLI output regression across `file_v0`/`sqlite_v0` | Clean PR worktree | `tests/control_plane_ts/peer_coordination_digest.test.ts`, `tests/control_plane/test_peer_coordination_digest.py`, & `test_cli_output_budget.py` | Pass in local worktree | Synthetic temp fixtures; live `<5%` multi-agent benchmark telemetry stays scoped separately | + +## 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..1fe70ce10b --- /dev/null +++ b/docs/architecture/rfcs/goal-oriented-multi-agent-coordination-v0.zh-CN.md @@ -0,0 +1,174 @@ +# RFC:面向目标的多 Agent 自主协同协议(v0) + +- **RFC 状态:** 已接受 +- **替代 / 关闭:** 无 +- **交付成熟度:** Partial(M0 只读同目标 Peer 前沿与协同机会投影 + M1 Turn 信封条件式默认摘要已实现;M2–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` 各自的所有权,同时落地有界拉取式发现(M0)与 Turn 信封条件式默认摘要(`peer_coordination_digest`,包含字段键在内的序列化增量严格 `<=300 B`,约 `75` tokens / 不足 200K 上下文窗口的 `0.04%`;非激活或游标未变时省略为 `0 B`),使同 Goal 下异构专长 Agent 无需手动拉取 CLI 或人类中转即可及时感知冲突、独立验收需求或空闲可接续通道。 +4. **将已落地的 M0+M1 只读发现与后续 M2–M3 写入/宿主扩展解耦。** M0(`loopx shared-goal-alignment` / `goal-alignment`)与 M1 条件式默认 Turn 信封摘要(`loopx quota should-run` -> `TurnEnvelope`,同时保留面向冻结评测基线的显式 `off` 关闭开关)在普通产品路径上零手动开启成本;带冷却窗的双向握手(M2)与宿主中立的 Antigravity/非 Codex 路由观测配置(M3)仍各自受其退出验收门禁约束。注意无信号时的 `0 B` 仅描述序列化省略增量,不等价于 `<5%` 控制面上下文开销红线的运行时实测认证。 +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 信封条件式默认紧凑摘要(`<=300 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 `(及 amendment/plan 快照读取)在 `file_v0`/`sqlite_v0` 上按需计算完整的 `peer_frontiers` 与 `collaboration_opportunities`(含 `shared_domain_synergy`)。 +- **M1(已随本 PR 落地 — 条件式默认开启):** 普通 `loopx quota should-run` Turn 无需手动开启,自动调用 TS `peer_coordination_digest.ts`。仅当同 Goal 注册活跃 Agent `>= 2` 且相对接收者实盘 Turn 游标(`peer-coordination-cursors/.json`)出现新 `opportunity_id` 时,`TurnEnvelope`(`v0`/`v1`)才会嵌入 `peer_coordination_digest`(`schema: "peer_digest_v0"`、`read_only: true`、`grants_authority: false`),含 `,"peer_coordination_digest":` 字段键在内的序列化增量严格 `<=300 B`。繁忙 Turn 仅注入 `shared_target_collision_risk`(`"collision"`)与 `peer_verification_needed`(`"verify"`);空闲 Turn(`caller_lanes` 为空)注入 `peer_verification_needed`(`"verify"`)与高优 `peer_unleased_lane_attention`(`"unleased"`)。只读 `--dry-run` 预览在有合格信号时可显示该摘要,但绝不创建或推进持久游标;单 Agent、无合格新机会、游标未变、调度器跳过/观察状态或显式配置 `off`(`coordination.peer_coordination_digest: "off"` / `LOOPX_PEER_COORDINATION_DIGEST=off`)均整字段省略(`0 B`)。实盘非预览且未被跳过的 Turn 仅将本次**实际展示**的条目 ID 与仍然活跃的历史已读 ID 写入游标(被 `omitted` 截断的条目保留未读以便后续 Turn 继续透出,已消解条目自动清理)。 +- **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 与 M1 Turn 信封摘要一致且单 Agent 输出零回归 | `uv run --extra test python -m pytest tests/control_plane/test_shared_goal_alignment.py tests/control_plane/test_shared_goal_alignment_cli.py tests/control_plane/test_peer_coordination_digest.py tests/control_plane/test_cli_output_budget.py` | 全部 File/SQLite 参数化、CLI、TurnEnvelope、游标去重与 `0 B` 基线预算用例通过 | 单机 canonical 快照,不含 M2 握手或 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 信封条件式默认 `peer_coordination_digest`(含键 `<=300 B`,无新信号/单 Agent 省略 `0 B`,繁/闲分层过滤,实盘游标提交与清理,支持显式 `off`) | `file_v0`/`sqlite_v0` canonical 快照 + `TurnEnvelope` v0/v1 集成 | TS `peer_coordination_digest.test.ts` + File/SQLite `test_peer_coordination_digest.py` + `cli-output-budget` 零回归(`canary premerge`) | 配置 `coordination.peer_coordination_digest="off"` 或回退 M1 接线 | +| **M2** | 基于 `(opportunity_id, basis_digest)` 与冷却窗的双向 `manager-inbox` 握手 | M1 + 幂等评审通过 | 双端收件箱握手集成测试通过 | 关闭自动 offer 开关 | +| **M3** | 宿主中立路由观测适配器(覆盖 Antigravity 等非 Codex 宿主)与自主协同指标 | M2 + 宿主适配器开关 | 双 Agent 无人类中转协同实测通过 | 退回 `host_observer_unavailable` | + +## 12. 未决决策 + +1. **D1(已拍板 — 2026-11-27,M1 默认触发路径与信封暴露面):** 普通产品路径(`loopx quota should-run` -> `TurnEnvelope`)**无需手动开启** M1。当同一 Goal 注册活跃 Agent `>= 2` 且存在相对游标的新增合格 `opportunity_id` 时自动注入 `<=300 B`(含字段键)的 `peer_coordination_digest`:繁忙 Turn 仅纳入 `shared_target_collision_risk` 与 `peer_verification_needed`;空闲 Turn 纳入 `peer_verification_needed` 与高优 `peer_unleased_lane_attention`;只读 `--dry-run` 预览可显示摘要但不写入游标,实盘非预览且非跳过 Turn 仅确认实际展示条目及仍活跃历史条目(使截断省略条目可在后续 Turn 透出并自动清理已消解条目);单 Agent、无新合格信号、游标未变、跳过/调度观察模式与显式 `off` 关闭配置均整字段省略(`0 B`);`shared_domain_synergy` 保留通过 `shared-goal-alignment` / `goal-alignment` 按需拉取。控制面上下文开销 `<5%` 仍以端到端实测验收为准(序列化省略 `0 B` 不替代实测认证)。 +2. **D2(M2 拒绝冷却窗策略):** `decline` 后的默认冷却时长/revision 绑定规则应如何设定以避免同质打扰?**负责人:** `manager-inbox` owner。 +3. **D3(M3 Antigravity 宿主观测来源):** 应由签名本地守护进程端点还是应用侧租约文件提供存活观测?**负责人:** desktop/host owners。 + +--- + +## 附录 A:执行台账(非规范性) + +- M0+M1 已在更新后的 PR 分支一并落地(`peer_coordination.ts` + `peer_coordination_digest.ts` + `TurnEnvelope` v0/v1 接线;后续 M2–M3 检查点可于 `ledger/` 目录独立记录)。 + +## 附录 B:决策日志 + +| 日期 | 决策 | 所有者 / 批准 | 备选方案 | 变更的规范章节 | +| --- | --- | --- | --- | --- | +| 2026-11-27 | 采用基于 `shared_goal_alignment_v0` 的 M0 增量投影并复用 TS `evaluateQuotaSchedulingWriteScopesOverlap` | 待维护者 PR 审批 | 独立建表与独立 RPC | 第 1–11 节 | +| 2026-11-27 | 收口 D1 并落地 M1 条件式默认 `peer_coordination_digest`(`<=300 B`、无激活信号省略 `0 B`、繁/闲分层、游标自动清理与显式 `off` 退出通道) | 用户确认方向(“为啥仍需要主动调用……路径能足够自动和智能么”)+ 待维护者 PR 评审 | 维持默认关闭手动开启开关或仅限手动 CLI 拉取 | 第 1、3、5、9、11、12 节 | + +## 附录 C:证据登记表 + +| 证据 ID | 声明 | 基线 / 环境 | 产物或命令 | 结果 | 隐私 / 有效性边界 | +| --- | --- | --- | --- | --- | --- | +| E1 | TS 与 File/SQLite 对齐一致性及 M0 协同机会单测全过 | 清洁 PR 工作树 | `tests/control_plane_ts/shared_goal_alignment.test.ts` 与 `tests/control_plane/test_shared_goal_alignment*.py` | 本地工作树全过 | 临时测试夹具,不含真实私密状态 | +| E2 | M1 Turn 信封自动摘要(`<=300 B`)、游标去重/清理、显式关闭与 `file_v0`/`sqlite_v0` 下 CLI 基线预算零回归 | 清洁 PR 工作树 | `tests/control_plane_ts/peer_coordination_digest.test.ts`、`tests/control_plane/test_peer_coordination_digest.py` 与 `test_cli_output_budget.py` | 本地工作树全过 | 临时测试夹具;多 Agent 实测 `<5%` 上下文税单独统计 | + +## 附录 D:被拒绝或替代的方案 + +- **Python 侧自建匹配启发式逻辑:** 已拒绝。对齐投影与写域/仓库规范化已在 TypeScript 侧拥有权威 owner,在 Python 复制规则必然引发双端语义漂移。 + +## 附录 E:事故与评审教训 + +- 实际长期多 Agent 协作卡点往往不在缺乏点对点发信通道,而在于跨 Agent 互相看不见对方的领域/范围/验收需求(整数计数黑盒)与异构宿主缺少轻量路由观测,迫使人类不断充当人工路由器;通过有界只读结构化投影可从根本上消除这类人为中转负担。 diff --git a/loopx/cli_commands/quota.py b/loopx/cli_commands/quota.py index 9b10e7109a..c5c4c17b60 100644 --- a/loopx/cli_commands/quota.py +++ b/loopx/cli_commands/quota.py @@ -275,6 +275,40 @@ def _prepare_quota_result_context( ) +def _turn_peer_digest_delivery_callback( + payload: Mapping[str, object], + args: argparse.Namespace, + *, + preview: bool, + preflight_failed: bool, + closeout_unavailable: bool, + context: QuotaCommandContext | None, + registry_path: Path, + heartbeat_turn_id: str | None, +) -> Callable[[Mapping[str, object]], None]: + """Create post-delivery cursor commit callback bound to the emitted channel view.""" + from ..control_plane.goals.peer_coordination_digest_source import ( + maybe_commit_turn_peer_coordination_cursor, + ) + + turn_id = heartbeat_turn_id or getattr(args, "turn_instance_id", None) + return lambda delivered: maybe_commit_turn_peer_coordination_cursor( + payload, + quota_command=args.quota_command, + preview=preview, + scheduler_observation=bool(getattr(args, "scheduler_observation", False)), + preflight_failed=preflight_failed, + closeout_unavailable=closeout_unavailable, + status_payload=context.status_payload if context is not None else None, + registry_path=registry_path, + runtime_root=context.runtime_root if context is not None else None, + goal_id=args.goal_id, + agent_id=args.agent_id, + delivered_payload=delivered, + turn_instance_id=turn_id, + ) + + def _emit_quota_result( payload: dict[str, object], args: argparse.Namespace, @@ -286,6 +320,7 @@ def _emit_quota_result( capture_directory: Path | None, detail_sections: frozenset[str], print_payload: PrintPayload, + on_delivered: Callable[[Mapping[str, object]], None] | None = None, ) -> int: from .quota_result_delivery import emit_quota_result @@ -300,6 +335,7 @@ def _emit_quota_result( capture_directory=capture_directory, detail_sections=detail_sections, print_payload=print_payload, + on_delivered=on_delivered, ) @@ -738,4 +774,14 @@ def _execute_quota_command( capture_directory=capture_directory, detail_sections=detail_sections, print_payload=print_payload, + on_delivered=_turn_peer_digest_delivery_callback( + payload, + args, + preview=preview, + preflight_failed=action_selection_preflight_failed, + closeout_unavailable=closeout_query_unavailable, + context=context, + registry_path=registry_path, + heartbeat_turn_id=heartbeat_turn_id, + ), ) diff --git a/loopx/cli_commands/quota_context_reader.py b/loopx/cli_commands/quota_context_reader.py index a9bcf9c962..09ce22df2f 100644 --- a/loopx/cli_commands/quota_context_reader.py +++ b/loopx/cli_commands/quota_context_reader.py @@ -277,7 +277,8 @@ def _validate_pinned_selection(selection: dict[str, Any]) -> None: def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, Any] | None = None, next_page_bytes: int | None = None, next_page_output_bytes: int | None = None, - reader_argv: list[str] | None = None) -> dict[str, Any]: + reader_argv: list[str] | None = None, + delivery_proof: dict[str, Any] | None = None) -> dict[str, Any]: """Bounded local IO over immutable JSON. Verify the complete byte digest on every page. The cursor addresses bytes @@ -453,12 +454,29 @@ def read_context_capture(args: argparse.Namespace, *, presentation: dict[str, An reference_file, bound_route = None, None if offset > len(raw) or (offset < len(raw) and raw[offset] & 0xC0 == 0x80): raise ValueError("capture offset is outside the file or not a UTF-8 boundary; use the returned next offset") - return _capture_page(path, raw, digest, offset=offset, size=size, + page = _capture_page(path, raw, digest, offset=offset, size=size, output_limit=output_limit, instruction=bool(context_dir), presentation=presentation, next_page_bytes=next_page_bytes, next_page_output_bytes=next_page_output_bytes, select=selectors, selection_sha256=selection_digest, list_fields=list_fields, list_depth=list_depth, initial_read=initial_read, reference_file=reference_file, reader_argv=reader_argv, compact_reader=bound_route is not None) + if delivery_proof is not None and page.get("ok") is True: + from ..control_plane.goals.peer_coordination_digest_source import ( + prove_page_delivered_peer_digest, + ) + + delivered_digest = prove_page_delivered_peer_digest( + payload, + raw=raw, + content=str(page.get("content") or ""), + offset=int(page["offset"]), + list_fields=list_fields, + is_selection=selectors is not None or initial_read, + ) + if delivered_digest is not None: + delivery_proof["delivered_digest"] = delivered_digest + delivery_proof["captured_payload"] = payload + return page except (OSError, ValueError, RecursionError, EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc: # Recovery is presentation-only: keep failures separate from quota's # collection error path and retain the existing receipt/capture. @@ -721,7 +739,8 @@ def budgeted_ready_opening(navigation: dict[str, Any], plan: dict[str, Any], def _bounded_initial_read(navigation: dict[str, Any], plan: dict[str, Any], *, page_bytes: int, output_bytes: int, reader_argv: list[str] | None, attach_page: bool = True, remaining_reference: Path | None = None, - ordinary_page: dict[str, Any] | None = None) -> dict[str, Any] | None: + ordinary_page: dict[str, Any] | None = None, + delivery_proof: dict[str, Any] | None = None) -> dict[str, Any] | None: """Try the typed opening and keep the remainder pinned to the same capture.""" if "opening" not in plan or "first_read_command" not in navigation: return None @@ -763,14 +782,33 @@ def command(reference: Path) -> str: "and its next_command cursor through the remaining initial context. Both views pin the same capture. " "EOF does not establish retention, authority or freshness.") page["navigation"] = navigation - return page if len(_native_output_bytes(page)) <= output_bytes else None + if len(_native_output_bytes(page)) > output_bytes: + return None + if delivery_proof is not None: + from ..control_plane.goals.peer_coordination_digest_source import ( + prove_page_delivered_peer_digest, + ) + + delivered_digest = prove_page_delivered_peer_digest( + document, + raw=content, + content=str(page.get("content") or ""), + offset=int(page["offset"]), + list_fields=False, + is_selection=True, + ) + if delivered_digest is not None: + delivery_proof["delivered_digest"] = delivered_digest + delivery_proof["captured_payload"] = document + return page except (OSError, ValueError): return None # The same-capture ordinary reader is already available. def _saved_context_read_page(args: argparse.Namespace, navigation: dict[str, Any], *, initial_reference: str | None, initial_read_plan: dict[str, Any] | None, - output_limit: int | None, reader_argv: list[str]) -> dict[str, Any]: + output_limit: int | None, reader_argv: list[str], + delivery_proof: dict[str, Any] | None = None) -> dict[str, Any]: """Use the ordinary verified reader; the first page and navigation share its output budget.""" recovery = navigation["recovery"] pinned = initial_reference if args.initial_read else None @@ -780,13 +818,15 @@ def _saved_context_read_page(args: argparse.Namespace, navigation: dict[str, Any "capture_sha256": None if reference else recovery["sha256"], "max_page_output_bytes": output_limit, "codex_context_dir": None, "codex_context_root": None, "initial_read": bool(args.initial_read and not pinned)}) - page = read_context_capture(read_args, presentation={"navigation": navigation}, reader_argv=reader_argv) + page = read_context_capture(read_args, presentation={"navigation": navigation}, reader_argv=reader_argv, + delivery_proof=delivery_proof) if page["ok"]: if (pinned and initial_read_plan and output_limit is not None and not page["eof"] and "previously_delivered_fields" not in page and (opening := _bounded_initial_read(navigation, initial_read_plan, page_bytes=args.page_bytes if args.page_bytes is not None else output_limit, - output_bytes=output_limit, reader_argv=reader_argv, ordinary_page=page)) is not None): + output_bytes=output_limit, reader_argv=reader_argv, ordinary_page=page, + delivery_proof=delivery_proof)) is not None): return opening # Keep the already-budgeted page and cursor ahead of recovery metadata. page["navigation"] = page.pop("navigation") diff --git a/loopx/cli_commands/quota_native_context.py b/loopx/cli_commands/quota_native_context.py index d7f771bcf8..5dea9c056c 100644 --- a/loopx/cli_commands/quota_native_context.py +++ b/loopx/cli_commands/quota_native_context.py @@ -6,6 +6,7 @@ import os import stat import subprocess +import sys import tempfile from collections.abc import Callable from contextlib import AbstractContextManager, nullcontext @@ -91,6 +92,7 @@ def _saved_context_transport_failure( def project_saved_context_capture( args: argparse.Namespace, *, hook_session: str | None = None, registry_path: Path | None = None, runtime_root_arg: str | None = None, + delivery_proof: dict[str, Any] | None = None, ) -> dict[str, Any]: """Present an immutable already-decided quota capture. @@ -217,7 +219,10 @@ def authority_refusal(error: Exception) -> dict[str, Any]: with publication_guard(): if saved_page: return _saved_context_read_page(args, navigation, initial_reference=None, - initial_read_plan=None, output_limit=output_limit, reader_argv=reader_argv) + initial_read_plan=None, output_limit=output_limit, reader_argv=reader_argv, + delivery_proof=delivery_proof) + if delivery_proof is not None and isinstance(navigation, dict): + delivery_proof["captured_payload"] = payload return navigation except NativeRecoveryLeaseUnavailable as exc: return authority_refusal(exc) @@ -339,7 +344,10 @@ def authority_refusal(error: Exception) -> dict[str, Any]: with nullcontext() if native_prepared else publication_guard(): if saved_page: return _saved_context_read_page(args, navigation, initial_reference=initial_reference, - initial_read_plan=initial_read_plan, output_limit=output_limit, reader_argv=reader_argv) + initial_read_plan=initial_read_plan, output_limit=output_limit, reader_argv=reader_argv, + delivery_proof=delivery_proof) + if delivery_proof is not None and isinstance(navigation, dict): + delivery_proof["captured_payload"] = payload return navigation except NativeRecoveryLeaseUnavailable as exc: return authority_refusal(exc) @@ -613,16 +621,58 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca ) return _handle_context_hook(args, activation=activation) if args.quota_command == "context-project": - payload = project_saved_context_capture(args, registry_path=registry_path, runtime_root_arg=runtime_root_arg) + from ..control_plane.goals.peer_coordination_digest_source import ( + maybe_commit_captured_peer_coordination_cursor, + ) + + delivery_proof: dict[str, Any] = {} + payload = project_saved_context_capture( + args, + registry_path=registry_path, + runtime_root_arg=runtime_root_arg, + delivery_proof=delivery_proof, + ) print_payload(payload, args.format, lambda value: str(value.get("command", value.get("reason", "")))) + sys.stdout.flush() + if payload.get("ok") is True: + try: + maybe_commit_captured_peer_coordination_cursor( + args, + emitted_payload=payload, + delivery_proof=delivery_proof, + registry_path=registry_path, + runtime_root_arg=runtime_root_arg, + ) + except Exception: # noqa: BLE001 - best-effort cursor commit never blocks delivered projection. + pass return 0 if payload["ok"] else 1 if args.quota_command == "context-read": from ..command_invocation import current_loopx_cli_argv + from ..control_plane.goals.peer_coordination_digest_source import ( + maybe_commit_captured_peer_coordination_cursor, + ) # Presentation recovery reads the original capture, never current Goal # state. In particular it must not evaluate a guard or append a receipt. - payload = quota_capture.read_context_capture(args, reader_argv=current_loopx_cli_argv()) + delivery_proof = {} + payload = quota_capture.read_context_capture( + args, + reader_argv=current_loopx_cli_argv(), + delivery_proof=delivery_proof, + ) print_payload(payload, args.format, lambda value: str(value.get("content", value.get("reason", "")))) + sys.stdout.flush() + if payload.get("ok") is True: + try: + maybe_commit_captured_peer_coordination_cursor( + args, + emitted_payload=payload, + delivery_proof=delivery_proof, + registry_path=registry_path, + runtime_root_arg=runtime_root_arg, + ) + except Exception: # noqa: BLE001 - best-effort cursor commit never blocks delivered readback. + pass return 0 if payload["ok"] else 1 if args.quota_command == "replan-view": return handle_replan_view(args, print_payload) diff --git a/loopx/cli_commands/quota_result_delivery.py b/loopx/cli_commands/quota_result_delivery.py index 145ac4bebb..82bbfcbc40 100644 --- a/loopx/cli_commands/quota_result_delivery.py +++ b/loopx/cli_commands/quota_result_delivery.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import sys from collections.abc import Callable, Mapping from pathlib import Path from typing import TYPE_CHECKING, Any @@ -91,8 +92,15 @@ def _emit_and_prune_result( context: QuotaCommandContext | None, capture_directory: Path | None, exit_code: int, + on_delivered: Callable[[Mapping[str, object]], None] | None = None, ) -> int: print_payload(payload, args.format, renderer) + if exit_code == 0 and on_delivered is not None: + sys.stdout.flush() + try: + on_delivered(payload) + except Exception: # noqa: BLE001 - best-effort cursor commit never breaks delivered output. + pass try: _prune_ephemeral_context_delivery( args, @@ -231,6 +239,7 @@ def emit_quota_result( capture_directory: Path | None, detail_sections: frozenset[str], print_payload: PrintPayload, + on_delivered: Callable[[Mapping[str, object]], None] | None = None, ) -> int: """Capture the full decision before projecting and printing the CLI view.""" capture_sha256: str | None = None @@ -255,6 +264,7 @@ def record_capture(decision: dict[str, object], digest: str | None) -> None: detail_sections=detail_sections, print_payload=print_payload, record_capture=record_capture, + on_delivered=on_delivered, ) except Exception as exc: # noqa: BLE001 - publication cannot revoke a durable guard. receipt = payload.get("heartbeat_receipt") @@ -288,6 +298,7 @@ def _publish_quota_result( detail_sections: frozenset[str], print_payload: PrintPayload, record_capture: Callable[[dict[str, object], str | None], None], + on_delivered: Callable[[Mapping[str, object]], None] | None = None, ) -> int: from ..command_invocation import current_loopx_cli_argv @@ -457,6 +468,7 @@ def _publish_quota_result( context=context, capture_directory=capture_directory, exit_code=0, + on_delivered=on_delivered, ) if ( payload.get("ok") is False @@ -582,4 +594,5 @@ def _publish_quota_result( context=context, capture_directory=capture_directory, exit_code=0 if succeeded else 1, + on_delivered=on_delivered, ) 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/cli_runtime.py b/loopx/cli_runtime.py index d874b804f1..a53960f156 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -127,9 +127,9 @@ def print_payload( if fmt == "json": # JSON is the machine contract; retain every value and remove only # presentation whitespace. Human-readable output remains Markdown. - print(report_json_text(payload)) + print(report_json_text(payload), flush=True) else: - print(markdown_renderer(payload)) + print(markdown_renderer(payload), flush=True) def add_subcommand_format(arg_parser: argparse.ArgumentParser) -> None: diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index b0e94dd470..c4c8b57891 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -362,6 +362,7 @@ export function createEffectRuntimeHandlers( ["goal.checkpoint_read_context.inspect_replay", lazyHandler(() => import("./goals/checkpoint_commit.ts"), ({inspectCheckpointReplay}) => inspectCheckpointReplay)], ["goal.vision_wait.project", lazyHandler(() => import("./goals/vision_wait_coverage.ts"), ({projectGoalVisionWaitState}) => projectGoalVisionWaitState)], ["goal.shared_goal_alignment.project", lazyHandler(() => import("./goals/shared_goal_alignment.ts"), ({projectSharedGoalAlignment}) => projectSharedGoalAlignment)], + ["goal.peer_coordination_digest.project", lazyHandler(() => import("./goals/peer_coordination_digest.ts"), ({projectPeerCoordinationDigest}) => projectPeerCoordinationDigest)], ["goal.operator_actions.project", lazyHandler(() => import("./goals/operator_actions.ts"), ({projectGoalOperatorActions}) => projectGoalOperatorActions)], ["goal.activation.migrate", lazyHandler(() => import("./goals/activation_migration.ts"), ({migrateGoalActivationMetadata}) => migrateGoalActivationMetadata)], ["goal.amendment.execute", lazyHandler(() => import("./goals/goal_amendment_authority.ts"), ({goalAmendmentLocal}) => goalAmendmentLocal)], 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/peer_coordination_digest.ts b/loopx/control_plane/goals/peer_coordination_digest.ts new file mode 100644 index 0000000000..07b7ca770e --- /dev/null +++ b/loopx/control_plane/goals/peer_coordination_digest.ts @@ -0,0 +1,229 @@ +import type { JsonObject } from "../effect_program.ts"; +import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; +import { normalizeTodoAgent } from "../coordination/todo_agents.ts"; +import { + optionalNonEmptyString, + requireInteger, + requireJsonObject, + requireNonEmptyString, + requireStringArray, +} from "../runtime_decode.ts"; +import { + decodeCallerLanes, + decodePeerFrontiers, + projectPeerCoordination, + type CollaborationOpportunity, + type CollaborationOpportunityKind, +} from "./peer_coordination.ts"; +import { sharedGoalWorkFacts } from "./shared_goal_work.ts"; + +export const PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION = "peer_coordination_digest_request_v0"; +export const PEER_COORDINATION_DIGEST_PROJECTION_SCHEMA_VERSION = "peer_coordination_digest_projection_v0"; +export const PEER_COORDINATION_DIGEST_SCHEMA_VERSION = "peer_digest_v0"; +export const PEER_COORDINATION_DIGEST_MAX_BYTES = 300; +export const PEER_COORDINATION_DIGEST_MIN_BYTES = 128; +export const PEER_COORDINATION_DIGEST_FIELD_OVERHEAD_BYTES = Buffer.byteLength( + ',"peer_coordination_digest":', + "utf8", +); + +const COMPACT_KIND: Partial> = { + shared_target_collision_risk: "collision", + peer_verification_needed: "verify", + peer_unleased_lane_attention: "unleased", +}; + +const GOAL_ID_SAFE_PATTERN = /^[^\\/\s]+$/; + +function serializedDeltaBytes(digest: JsonObject): number { + return PEER_COORDINATION_DIGEST_FIELD_OVERHEAD_BYTES + Buffer.byteLength(JSON.stringify(digest), "utf8"); +} + +function makeDigestEnvelope(items: readonly JsonObject[], omittedCount: number): JsonObject { + const digest: JsonObject = { + schema: PEER_COORDINATION_DIGEST_SCHEMA_VERSION, + read_only: true, + grants_authority: false, + items: [...items], + }; + if (omittedCount > 0) { + digest.omitted = omittedCount; + } + return digest; +} + +function compactDigestItem( + opp: CollaborationOpportunity, + compactKind: string, + includeMine: boolean, +): JsonObject { + const item: JsonObject = { + id: opp.opportunity_id, + kind: compactKind, + peer: opp.peer_agent_id, + todo: opp.peer_todo_id, + }; + if (includeMine && opp.caller_todo_id !== null) { + item.mine = opp.caller_todo_id; + } + return item; +} + +/** + * Project a conditional, default-on, cursor-deduplicated peer coordination digest + * bounded strictly to <= max_bytes (default 300 B including serialized field overhead). + * + * Returns `digest: null` (0 B serialized delta) when: + * - fewer than 2 registered agents share the Goal, + * - no qualifying high-signal opportunities exist for the caller's state (busy vs. idle), or + * - all qualifying opportunities were already surfaced in `seen_opportunity_ids`. + */ +export function projectPeerCoordinationDigest(value: unknown): JsonObject { + const request = requireJsonObject(value, "peer_coordination_digest request"); + const schema = requireNonEmptyString( + request.schema_version, + "peer_coordination_digest.schema_version", + ); + if (schema !== PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION) { + throw new EffectRuntimeRequestError( + `unsupported peer_coordination_digest.schema_version: ${schema}`, + ); + } + const goalId = requireNonEmptyString(request.goal_id, "peer_coordination_digest.goal_id"); + if (!GOAL_ID_SAFE_PATTERN.test(goalId) || goalId.includes("..")) { + throw new EffectRuntimeRequestError( + "peer_coordination_digest.goal_id must be a safe single-segment goal id", + ); + } + let agentId: string; + try { + agentId = normalizeTodoAgent(request.agent_id, "peer_coordination_digest.agent_id"); + } catch { + throw new EffectRuntimeRequestError( + "peer_coordination_digest.agent_id must be a public-safe agent id", + ); + } + const registeredAgentCount = requireInteger( + request.registered_agent_count, + "peer_coordination_digest.registered_agent_count", + ); + if (registeredAgentCount < 0) { + throw new EffectRuntimeRequestError( + "peer_coordination_digest.registered_agent_count must be non-negative", + ); + } + const seenOpportunityIds = request.seen_opportunity_ids === undefined + ? [] + : requireStringArray( + request.seen_opportunity_ids, + "peer_coordination_digest.seen_opportunity_ids", + ); + const rawMaxBytes = request.max_bytes === undefined + ? PEER_COORDINATION_DIGEST_MAX_BYTES + : requireInteger(request.max_bytes, "peer_coordination_digest.max_bytes"); + const maxBytes = Math.min( + PEER_COORDINATION_DIGEST_MAX_BYTES, + Math.max(PEER_COORDINATION_DIGEST_MIN_BYTES, rawMaxBytes), + ); + const observedAt = optionalNonEmptyString( + request.observed_at, + "peer_coordination_digest.observed_at", + ) ?? new Date().toISOString(); + + if (registeredAgentCount < 2) { + return { + schema_version: PEER_COORDINATION_DIGEST_PROJECTION_SCHEMA_VERSION, + goal_id: goalId, + agent_id: agentId, + digest: null, + active_opportunity_ids: [], + new_opportunity_ids: [], + displayed_opportunity_ids: [], + serialized_delta_bytes: 0, + }; + } + + const workFacts = sharedGoalWorkFacts(request.work_items, agentId, observedAt); + const callerLanes = decodeCallerLanes(workFacts.caller_lanes); + const peerFrontiers = decodePeerFrontiers(workFacts.peer_frontiers); + const coordination = projectPeerCoordination(callerLanes, peerFrontiers); + + const callerIdle = callerLanes.length === 0; + const qualifying = coordination.collaboration_opportunities.filter((opp) => { + if (callerIdle) { + return ( + opp.kind === "peer_verification_needed" + || opp.kind === "peer_unleased_lane_attention" + ); + } + return ( + opp.kind === "shared_target_collision_risk" + || opp.kind === "peer_verification_needed" + ); + }); + + const activeOpportunityIds = Array.from( + new Set(qualifying.map((opp) => opp.opportunity_id)), + ).sort((a, b) => a.localeCompare(b)); + + const seenSet = new Set(seenOpportunityIds); + const newOpportunities = qualifying.filter( + (opp) => !seenSet.has(opp.opportunity_id), + ); + + if (newOpportunities.length === 0) { + return { + schema_version: PEER_COORDINATION_DIGEST_PROJECTION_SCHEMA_VERSION, + goal_id: goalId, + agent_id: agentId, + digest: null, + active_opportunity_ids: activeOpportunityIds, + new_opportunity_ids: [], + displayed_opportunity_ids: [], + serialized_delta_bytes: 0, + }; + } + + const packed: JsonObject[] = []; + for (let index = 0; index < newOpportunities.length; index += 1) { + const opp = newOpportunities[index]; + const compactKind = COMPACT_KIND[opp.kind]; + if (!compactKind) continue; + const remainingAfter = newOpportunities.length - (index + 1); + const fullItem = compactDigestItem(opp, compactKind, true); + const fullCandidate = makeDigestEnvelope([...packed, fullItem], remainingAfter); + if (serializedDeltaBytes(fullCandidate) <= maxBytes) { + packed.push(fullItem); + continue; + } + if (opp.caller_todo_id !== null) { + const strippedItem = compactDigestItem(opp, compactKind, false); + const strippedCandidate = makeDigestEnvelope([...packed, strippedItem], remainingAfter); + if (serializedDeltaBytes(strippedCandidate) <= maxBytes) { + packed.push(strippedItem); + continue; + } + } + break; + } + + const omittedCount = newOpportunities.length - packed.length; + const digest = makeDigestEnvelope(packed, omittedCount); + const serializedBytes = serializedDeltaBytes(digest); + if (serializedBytes > maxBytes) { + throw new EffectRuntimeRequestError( + `peer_coordination_digest minimum envelope exceeds max_bytes (${serializedBytes} > ${maxBytes})`, + ); + } + + return { + schema_version: PEER_COORDINATION_DIGEST_PROJECTION_SCHEMA_VERSION, + goal_id: goalId, + agent_id: agentId, + digest, + active_opportunity_ids: activeOpportunityIds, + new_opportunity_ids: newOpportunities.map((opp) => opp.opportunity_id), + displayed_opportunity_ids: packed.map((item) => item.id as string), + serialized_delta_bytes: serializedBytes, + }; +} diff --git a/loopx/control_plane/goals/peer_coordination_digest_source.py b/loopx/control_plane/goals/peer_coordination_digest_source.py new file mode 100644 index 0000000000..ec57fe959d --- /dev/null +++ b/loopx/control_plane/goals/peer_coordination_digest_source.py @@ -0,0 +1,918 @@ +"""Turn-envelope adapter and cursor persistence for M1 peer coordination digest.""" + +from __future__ import annotations + +import json +import os +import re +import tempfile +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from ...paths import registry_project_root +from ..effect_runtime import EffectRuntimeRejected, effect_runtime_projection_result +from ..quota.decision_summary import quota_decision_agent_id +from ..quota.effective_action import EffectiveAction +from ..quota.effect_program import ReceiptBoundReplayPhase +from ..quota.goal_boundary import registry_goal_by_id +from ..todos.contract import normalize_todo_claimed_by +from .shared_goal_work_source import SharedGoalWorkSource, read_shared_goal_work_source + +PEER_COORDINATION_DIGEST_EFFECT_METHOD = "goal.peer_coordination_digest.project" +PEER_COORDINATION_DIGEST_REQUEST_SCHEMA = "peer_coordination_digest_request_v0" +PEER_COORDINATION_DIGEST_PROJECTION_SCHEMA = "peer_coordination_digest_projection_v0" +PEER_COORDINATION_DIGEST_SCHEMA = "peer_digest_v0" +PEER_COORDINATION_CURSOR_SCHEMA = "peer_coordination_cursor_v0" +PEER_COORDINATION_DIGEST_DISABLE_ENV = "LOOPX_PEER_COORDINATION_DIGEST" + +_SAFE_SEGMENT_RE = re.compile(r"^[^\\/\s]+$") +_DISABLED_TOKENS = frozenset({"0", "false", "off", "disabled", "no"}) +_SKIPPED_EFFECTIVE_ACTIONS = frozenset( + { + EffectiveAction.BLOCKED_WAIT.value, + EffectiveAction.THROTTLED_SKIP.value, + EffectiveAction.QUOTA_SKIP.value, + EffectiveAction.HEARTBEAT_SETTLED_SKIP.value, + EffectiveAction.MONITOR_QUIET_SKIP.value, + } +) + + +def _safe_single_segment(value: str, label: str) -> str: + text = str(value or "").strip() + if not text or not _SAFE_SEGMENT_RE.match(text) or ".." in text: + raise ValueError(f"{label} must be a safe single segment") + return text + + +def peer_coordination_cursor_path( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, +) -> Path: + """Return the runtime-scoped cursor file path for one registered Goal Agent.""" + + safe_goal = _safe_single_segment(goal_id, "goal_id") + normalized_agent = normalize_todo_claimed_by(agent_id) + if normalized_agent is None: + raise ValueError("agent_id must be a public-safe agent id") + safe_agent = _safe_single_segment(normalized_agent, "agent_id") + return ( + runtime_root.expanduser() + / "goals" + / safe_goal + / "peer-coordination-cursors" + / f"{safe_agent}.json" + ) + + +_MAX_DELIVERED_TURN_IDS = 32 + + +def _normalize_opportunity_ids(values: Sequence[str] | Any) -> list[str]: + if not isinstance(values, Sequence) or isinstance(values, (str, bytes)): + return [] + cleaned = { + str(item).strip() + for item in values + if isinstance(item, str) and str(item).strip() + } + return sorted(cleaned) + + +def _normalize_turn_ids(values: Sequence[str] | Any) -> list[str]: + if not isinstance(values, Sequence) or isinstance(values, (str, bytes)): + return [] + deduped: list[str] = [] + seen: set[str] = set() + for item in values: + if not isinstance(item, str): + continue + cleaned = item.strip() + if cleaned and cleaned not in seen: + seen.add(cleaned) + deduped.append(cleaned) + return deduped[-_MAX_DELIVERED_TURN_IDS:] + + +def read_peer_coordination_cursor_state( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, +) -> tuple[list[str], list[str]]: + """Read seen opportunity IDs and delivered Turn IDs; fail open if absent/corrupt.""" + + try: + path = peer_coordination_cursor_path( + runtime_root, goal_id=goal_id, agent_id=agent_id + ) + raw = path.read_text(encoding="utf-8") + payload = json.loads(raw) + except (OSError, ValueError): + return [], [] + if not isinstance(payload, Mapping): + return [], [] + if ( + payload.get("schema_version") != PEER_COORDINATION_CURSOR_SCHEMA + or payload.get("goal_id") != goal_id + ): + return [], [] + return ( + _normalize_opportunity_ids(payload.get("seen_opportunity_ids")), + _normalize_turn_ids(payload.get("delivered_turn_ids")), + ) + + +def read_peer_coordination_cursor( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, +) -> list[str]: + """Read previously surfaced opportunity IDs; fail open to ``[]`` if missing or corrupt.""" + + seen_ids, _turn_ids = read_peer_coordination_cursor_state( + runtime_root, goal_id=goal_id, agent_id=agent_id + ) + return seen_ids + + +def write_peer_coordination_cursor( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + seen_opportunity_ids: Sequence[str], + delivered_turn_ids: Sequence[str] | None = None, +) -> bool: + """Persist normalized seen IDs and delivered Turn IDs atomically, skipping no-op writes.""" + + normalized = _normalize_opportunity_ids(seen_opportunity_ids) + path = peer_coordination_cursor_path( + runtime_root, goal_id=goal_id, agent_id=agent_id + ) + existing_seen, existing_turns = read_peer_coordination_cursor_state( + runtime_root, goal_id=goal_id, agent_id=agent_id + ) + normalized_turns = ( + existing_turns + if delivered_turn_ids is None + else _normalize_turn_ids(delivered_turn_ids) + ) + if path.exists(): + if existing_seen == normalized and existing_turns == normalized_turns: + return False + elif not normalized and not normalized_turns: + return False + + normalized_agent = normalize_todo_claimed_by(agent_id) + if normalized_agent is None: + raise ValueError("agent_id must be a public-safe agent id") + path.parent.mkdir(parents=True, exist_ok=True) + record: dict[str, Any] = { + "schema_version": PEER_COORDINATION_CURSOR_SCHEMA, + "goal_id": goal_id, + "agent_id": normalized_agent, + "seen_opportunity_ids": normalized, + } + if normalized_turns: + record["delivered_turn_ids"] = normalized_turns + serialized = json.dumps(record, ensure_ascii=False, indent=2, sort_keys=True) + "\n" + fd, tmp_name = tempfile.mkstemp( + prefix=".peer-cursor-", suffix=".tmp", dir=str(path.parent) + ) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(serialized) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp_name, path) + finally: + Path(tmp_name).unlink(missing_ok=True) + return True + + +def peer_coordination_digest_disabled( + *, + registry_goal: Mapping[str, Any] | None = None, +) -> bool: + """Return True when frozen baselines or config explicitly disable Turn digest injection.""" + + env_val = os.environ.get(PEER_COORDINATION_DIGEST_DISABLE_ENV, "").strip().lower() + if env_val in _DISABLED_TOKENS: + return True + coordination = ( + registry_goal.get("coordination") + if isinstance(registry_goal, Mapping) + else None + ) + if not isinstance(coordination, Mapping): + return False + setting = coordination.get("peer_coordination_digest") + if setting is False: + return True + if isinstance(setting, str) and setting.strip().lower() in _DISABLED_TOKENS: + return True + return False + + +def resolve_goal_project_root( + *, + registry_goal: Mapping[str, Any] | None, + registry_path_value: Any, +) -> Path | None: + """Resolve the project root directory for reading canonical shared work snapshots.""" + + registry_path = ( + Path(str(registry_path_value)).expanduser() + if isinstance(registry_path_value, str) and registry_path_value.strip() + else None + ) + if isinstance(registry_goal, Mapping): + repo_raw = registry_goal.get("repo") + if isinstance(repo_raw, str) and repo_raw.strip(): + repo_path = Path(repo_raw.strip()).expanduser() + if repo_path.is_absolute(): + return repo_path + if registry_path is not None: + return (registry_project_root(registry_path) / repo_path).resolve() + if registry_path is not None: + return registry_project_root(registry_path) + return None + + +def project_turn_peer_coordination_digest( + *, + registry_goal: Mapping[str, Any] | None, + project: Path | None, + runtime_root: Path | None, + goal_id: str, + agent_id: str | None, + registered_agent_ids: Sequence[str], + work_source: SharedGoalWorkSource | None = None, + turn_instance_id: str | None = None, +) -> tuple[dict[str, Any] | None, list[str]]: + """Compute bounded M1 peer digest for a Turn; returns ``(None, [])`` when inactive.""" + + normalized_goal_id = str(goal_id or "").strip() + normalized_agent_id = normalize_todo_claimed_by(agent_id) + normalized_agents = [ + claimed + for candidate in registered_agent_ids + if (claimed := normalize_todo_claimed_by(candidate)) is not None + ] + if ( + not normalized_goal_id + or not normalized_agent_id + or len(set(normalized_agents)) < 2 + or normalized_agent_id not in normalized_agents + or runtime_root is None + or project is None + or not isinstance(registry_goal, Mapping) + or not registry_goal.get("id") + or peer_coordination_digest_disabled(registry_goal=registry_goal) + ): + return None, [] + + try: + source = work_source or read_shared_goal_work_source( + goal=dict(registry_goal), + project=project, + runtime_root=runtime_root, + ) + except (OSError, ValueError, FileNotFoundError): + return None, [] + if source.goal_id != normalized_goal_id: + return None, [] + + seen_ids, delivered_turn_ids = read_peer_coordination_cursor_state( + runtime_root, + goal_id=normalized_goal_id, + agent_id=normalized_agent_id, + ) + clean_turn_id = str(turn_instance_id or "").strip() + if clean_turn_id and clean_turn_id in delivered_turn_ids: + seen_ids = sorted(set(seen_ids)) + request = { + "schema_version": PEER_COORDINATION_DIGEST_REQUEST_SCHEMA, + "goal_id": normalized_goal_id, + "agent_id": normalized_agent_id, + "registered_agent_count": len(set(normalized_agents)), + "seen_opportunity_ids": seen_ids, + "work_items": source.items, + "observed_at": source.observed_at, + } + try: + result = effect_runtime_projection_result( + PEER_COORDINATION_DIGEST_EFFECT_METHOD, request + ) + if isinstance(result, Mapping): + return None, _normalize_opportunity_ids(result.get("active_opportunity_ids")) + except EffectRuntimeRejected: + return None, [] + return None, [] + request = { + "schema_version": PEER_COORDINATION_DIGEST_REQUEST_SCHEMA, + "goal_id": normalized_goal_id, + "agent_id": normalized_agent_id, + "registered_agent_count": len(set(normalized_agents)), + "seen_opportunity_ids": seen_ids, + "work_items": source.items, + "observed_at": source.observed_at, + } + try: + result = effect_runtime_projection_result( + PEER_COORDINATION_DIGEST_EFFECT_METHOD, request + ) + except EffectRuntimeRejected: + return None, [] + if not isinstance(result, Mapping) or ( + result.get("schema_version") != PEER_COORDINATION_DIGEST_PROJECTION_SCHEMA + or result.get("goal_id") != normalized_goal_id + or result.get("agent_id") != normalized_agent_id + ): + raise RuntimeError("TypeScript peer_coordination_digest shape mismatch") + active_ids = _normalize_opportunity_ids(result.get("active_opportunity_ids")) + digest_value = result.get("digest") + if digest_value is None: + return None, active_ids + if not isinstance(digest_value, Mapping) or ( + digest_value.get("schema") != PEER_COORDINATION_DIGEST_SCHEMA + or digest_value.get("read_only") is not True + or digest_value.get("grants_authority") is not False + ): + raise RuntimeError("TypeScript peer_coordination_digest payload shape mismatch") + return dict(digest_value), active_ids + + +def attach_turn_peer_coordination_digest( + payload: dict[str, Any], + *, + prepared: Any, + runtime_root: str | Path | None, + turn_instance_id: str | None = None, +) -> None: + """Attach bounded M1 digest to active should-run payload when eligible.""" + + registered_agent_ids = prepared.registered_agent_ids + settled_replay = ( + prepared.receipt_bound_replay_phase is ReceiptBoundReplayPhase.SETTLED + ) + if ( + len(registered_agent_ids) < 2 + or settled_replay + or payload.get("ok") is not True + or str(payload.get("effective_action") or "").strip() in _SKIPPED_EFFECTIVE_ACTIONS + ): + return + status_payload = prepared.status_payload + goal_id = prepared.safe_goal_id + agent_id = quota_decision_agent_id(payload) or prepared.requested_agent_id + runtime_path = Path(str(runtime_root)).expanduser() if runtime_root else None + registry_goal = registry_goal_by_id(status_payload).get(goal_id) + project = resolve_goal_project_root( + registry_goal=registry_goal, + registry_path_value=status_payload.get("registry"), + ) + receipt = payload.get("heartbeat_receipt") + receipt_turn_id = ( + str(receipt.get("turn_instance_id") or "").strip() + if isinstance(receipt, Mapping) + else "" + ) + effective_turn_id = str(turn_instance_id or receipt_turn_id or "").strip() or None + digest, _active_ids = project_turn_peer_coordination_digest( + registry_goal=registry_goal, + project=project, + runtime_root=runtime_path, + goal_id=goal_id, + agent_id=agent_id, + registered_agent_ids=registered_agent_ids, + turn_instance_id=effective_turn_id, + ) + if digest is not None: + payload["peer_coordination_digest"] = digest + + +def extract_delivered_peer_coordination_digest( + delivered_payload: Mapping[str, Any] | Any, +) -> Mapping[str, Any] | None: + """Extract an inline peer_coordination_digest from a delivered CLI payload, if present.""" + + if not isinstance(delivered_payload, Mapping): + return None + direct = delivered_payload.get("peer_coordination_digest") + if isinstance(direct, Mapping): + return direct + work_opening = delivered_payload.get("work_opening") + if isinstance(work_opening, Mapping): + nested = work_opening.get("peer_coordination_digest") + if isinstance(nested, Mapping): + return nested + if delivered_payload.get("schema_version") == "context_delivery_v1": + inner = delivered_payload.get("payload") + if isinstance(inner, Mapping): + nested = inner.get("peer_coordination_digest") + if isinstance(nested, Mapping): + return nested + return None + + +def displayed_opportunity_ids_from_digest(digest: Mapping[str, Any] | Any) -> list[str]: + """Return the exact opportunity IDs actually shown inline inside a rendered digest.""" + + if not isinstance(digest, Mapping): + return [] + items = digest.get("items") + if not isinstance(items, Sequence) or isinstance(items, (str, bytes)): + return [] + return _normalize_opportunity_ids( + [ + str(item.get("id") or "") + for item in items + if isinstance(item, Mapping) and isinstance(item.get("id"), str) + ] + ) + + +def commit_displayed_peer_coordination_cursor( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + active_opportunity_ids: Sequence[str], + displayed_opportunity_ids: Sequence[str], + turn_instance_id: str | None = None, +) -> bool: + """Advance cursor using only actually delivered IDs + still-active previously seen IDs.""" + + clean_turn_id = str(turn_instance_id or "").strip() + existing_seen_list, existing_turns = read_peer_coordination_cursor_state( + runtime_root, goal_id=goal_id, agent_id=agent_id + ) + if clean_turn_id and clean_turn_id in existing_turns: + return False + active_set = set(_normalize_opportunity_ids(active_opportunity_ids)) + displayed_set = set(_normalize_opportunity_ids(displayed_opportunity_ids)) & active_set + existing_seen = set(existing_seen_list) & active_set + next_seen = sorted(existing_seen | displayed_set) + try: + cursor_exists = peer_coordination_cursor_path( + runtime_root, goal_id=goal_id, agent_id=agent_id + ).exists() + except ValueError: + return False + next_turns = existing_turns + if clean_turn_id and (displayed_set or cursor_exists): + next_turns = _normalize_turn_ids([*existing_turns, clean_turn_id]) + return write_peer_coordination_cursor( + runtime_root, + goal_id=goal_id, + agent_id=agent_id, + seen_opportunity_ids=next_seen, + delivered_turn_ids=next_turns, + ) + + +def commit_recovered_peer_coordination_cursor( + runtime_root: Path, + *, + goal_id: str, + agent_id: str, + displayed_opportunity_ids: Sequence[str], + turn_instance_id: str | None = None, +) -> bool: + """Commit cursor idempotently after digest-verified recovery or readback.""" + + clean_turn_id = str(turn_instance_id or "").strip() + existing_seen_list, existing_turns = read_peer_coordination_cursor_state( + runtime_root, goal_id=goal_id, agent_id=agent_id + ) + displayed = _normalize_opportunity_ids(displayed_opportunity_ids) + next_seen = sorted(set(existing_seen_list) | set(displayed)) + next_turns = ( + _normalize_turn_ids([*existing_turns, clean_turn_id]) + if clean_turn_id and (next_seen or existing_turns) + else existing_turns + ) + if next_seen == existing_seen_list and next_turns == existing_turns: + return False + return write_peer_coordination_cursor( + runtime_root, + goal_id=goal_id, + agent_id=agent_id, + seen_opportunity_ids=next_seen, + delivered_turn_ids=next_turns, + ) + + +def maybe_commit_turn_peer_coordination_cursor( + payload: Mapping[str, Any], + *, + quota_command: str, + preview: bool, + scheduler_observation: bool, + preflight_failed: bool, + closeout_unavailable: bool, + status_payload: Mapping[str, Any] | None, + registry_path: Path, + runtime_root: Path | None, + goal_id: str | None, + agent_id: str | None, + delivered_payload: Mapping[str, Any] | None = None, + turn_instance_id: str | None = None, +) -> bool: + """Commit or prune the live non-preview Turn cursor only after channel delivery.""" + + if ( + quota_command != "should-run" + or preview + or scheduler_observation + or preflight_failed + or closeout_unavailable + or payload.get("ok") is not True + or status_payload is None + or runtime_root is None + or not goal_id + or not agent_id + or str(payload.get("effective_action") or "").strip() in _SKIPPED_EFFECTIVE_ACTIONS + ): + return False + + delivered_view: Mapping[str, Any] = ( + delivered_payload if delivered_payload is not None else payload + ) + if delivered_view.get("ok") is not True: + return False + + delivered_digest = extract_delivered_peer_coordination_digest(delivered_view) + original_had_digest = isinstance(payload.get("peer_coordination_digest"), Mapping) + is_deferred_wrapper = ( + delivered_view.get("schema_version") + in {"context_capture_navigation_v1", "context_delivery_v1"} + or ( + "capture_sha256" in delivered_view + and "interaction_contract" not in delivered_view + and "mode" not in delivered_view + ) + ) + if delivered_digest is None and (original_had_digest or is_deferred_wrapper): + return False + + registry_goal = registry_goal_by_id(status_payload).get(goal_id) + identity = payload.get("agent_identity") + registered_agents = ( + list(identity.get("registered_agents") or []) + if isinstance(identity, Mapping) + else [] + ) + if not registered_agents and isinstance(registry_goal, Mapping): + coordination = registry_goal.get("coordination") + if isinstance(coordination, Mapping): + registered_agents = list(coordination.get("registered_agents") or []) + normalized_agent = normalize_todo_claimed_by(agent_id) + normalized_agents = [ + claimed + for candidate in registered_agents + if (claimed := normalize_todo_claimed_by(candidate)) is not None + ] + if ( + normalized_agent is None + or len(set(normalized_agents)) < 2 + or normalized_agent not in normalized_agents + or not isinstance(registry_goal, Mapping) + or not registry_goal.get("id") + or peer_coordination_digest_disabled(registry_goal=registry_goal) + ): + return False + + displayed_ids = displayed_opportunity_ids_from_digest(delivered_digest) + digest_emitted = delivered_digest is not None + try: + cursor_file = peer_coordination_cursor_path( + runtime_root, goal_id=goal_id, agent_id=normalized_agent + ) + except ValueError: + return False + if not digest_emitted and not cursor_file.exists(): + return False + project = resolve_goal_project_root( + registry_goal=registry_goal, + registry_path_value=str(registry_path), + ) + if project is None: + return False + receipt = payload.get("heartbeat_receipt") + receipt_turn_id = ( + str(receipt.get("turn_instance_id") or "").strip() + if isinstance(receipt, Mapping) + else "" + ) + effective_turn_id = str(turn_instance_id or receipt_turn_id or "").strip() or None + _digest, active_ids = project_turn_peer_coordination_digest( + registry_goal=registry_goal, + project=project, + runtime_root=runtime_root, + goal_id=goal_id, + agent_id=normalized_agent, + registered_agent_ids=normalized_agents, + turn_instance_id=effective_turn_id, + ) + return commit_displayed_peer_coordination_cursor( + runtime_root, + goal_id=goal_id, + agent_id=normalized_agent, + active_opportunity_ids=active_ids, + displayed_opportunity_ids=displayed_ids, + turn_instance_id=effective_turn_id, + ) + + +def _skip_json_ws(text: str, pos: int) -> int: + while pos < len(text) and text[pos] in " \t\r\n": + pos += 1 + return pos + + +def _top_level_digest_byte_spans( + raw_text: str, expected_digest: Mapping[str, Any] +) -> list[tuple[int, int]]: + decoder = json.JSONDecoder() + pos = _skip_json_ws(raw_text, 0) + if pos >= len(raw_text) or raw_text[pos] != "{": + return [] + pos += 1 + spans: list[tuple[int, int]] = [] + expected = dict(expected_digest) + while pos < len(raw_text): + pos = _skip_json_ws(raw_text, pos) + if pos >= len(raw_text) or raw_text[pos] == "}": + break + if raw_text[pos] == ",": + pos = _skip_json_ws(raw_text, pos + 1) + if pos >= len(raw_text) or raw_text[pos] == "}": + break + key_start = pos + key, pos = decoder.raw_decode(raw_text, pos) + pos = _skip_json_ws(raw_text, pos) + if pos >= len(raw_text) or raw_text[pos] != ":": + break + pos = _skip_json_ws(raw_text, pos + 1) + val, val_end = decoder.raw_decode(raw_text, pos) + if key == "peer_coordination_digest" and isinstance(val, Mapping) and dict(val) == expected: + spans.append( + ( + len(raw_text[:key_start].encode("utf-8")), + len(raw_text[:val_end].encode("utf-8")), + ) + ) + pos = val_end + return spans + + +def _selection_digest_byte_spans( + raw_text: str, expected_digest: Mapping[str, Any] +) -> list[tuple[int, int]]: + decoder = json.JSONDecoder() + pos = _skip_json_ws(raw_text, 0) + if pos >= len(raw_text) or raw_text[pos] != "{": + return [] + pos += 1 + spans: list[tuple[int, int]] = [] + expected = dict(expected_digest) + while pos < len(raw_text): + pos = _skip_json_ws(raw_text, pos) + if pos >= len(raw_text) or raw_text[pos] == "}": + break + if raw_text[pos] == ",": + pos = _skip_json_ws(raw_text, pos + 1) + if pos >= len(raw_text) or raw_text[pos] == "}": + break + key, pos = decoder.raw_decode(raw_text, pos) + pos = _skip_json_ws(raw_text, pos) + if pos >= len(raw_text) or raw_text[pos] != ":": + break + pos = _skip_json_ws(raw_text, pos + 1) + if key != "selections": + _val, pos = decoder.raw_decode(raw_text, pos) + continue + if pos >= len(raw_text) or raw_text[pos] != "[": + break + arr_pos = pos + 1 + while arr_pos < len(raw_text): + arr_pos = _skip_json_ws(raw_text, arr_pos) + if arr_pos >= len(raw_text) or raw_text[arr_pos] == "]": + arr_pos += 1 + break + if raw_text[arr_pos] == ",": + arr_pos = _skip_json_ws(raw_text, arr_pos + 1) + if arr_pos >= len(raw_text) or raw_text[arr_pos] == "]": + arr_pos += 1 + break + elem_start = arr_pos + elem, elem_end = decoder.raw_decode(raw_text, elem_start) + if isinstance(elem, Mapping): + ptr = elem.get("pointer") + val = elem.get("value") + if ptr in ("/peer_coordination_digest", "/work_opening/peer_coordination_digest"): + if isinstance(val, Mapping) and dict(val) == expected: + spans.append( + ( + len(raw_text[:elem_start].encode("utf-8")), + len(raw_text[:elem_end].encode("utf-8")), + ) + ) + elif ptr in ("", "/work_opening") and isinstance(val, Mapping): + nested_spans = _top_level_digest_byte_spans( + raw_text[elem_start:elem_end], expected + ) + if not nested_spans: + # Handle wrapper object {"pointer":..., "value":{...}} by walking into "value" + val_match_pos = _skip_json_ws(raw_text, elem_start + 1) + while val_match_pos < elem_end: + val_match_pos = _skip_json_ws(raw_text, val_match_pos) + if raw_text[val_match_pos] == ",": + val_match_pos = _skip_json_ws(raw_text, val_match_pos + 1) + if raw_text[val_match_pos] == "}": + break + ekey, val_match_pos = decoder.raw_decode(raw_text, val_match_pos) + val_match_pos = _skip_json_ws(raw_text, val_match_pos) + if raw_text[val_match_pos] != ":": + break + val_match_pos = _skip_json_ws(raw_text, val_match_pos + 1) + if ekey == "value": + for s_start, s_end in _top_level_digest_byte_spans( + raw_text[val_match_pos:elem_end], expected + ): + spans.append( + ( + len(raw_text[: val_match_pos + s_start].encode("utf-8")), + len(raw_text[: val_match_pos + s_end].encode("utf-8")), + ) + ) + break + _ev, val_match_pos = decoder.raw_decode(raw_text, val_match_pos) + arr_pos = elem_end + pos = arr_pos + return spans + + +def prove_page_delivered_peer_digest( + source_payload: Mapping[str, Any] | Any, + *, + raw: bytes, + content: str, + offset: int, + list_fields: bool = False, + is_selection: bool = False, +) -> Mapping[str, Any] | None: + """Return expected digest iff this page's actual bytes cover the full digest object.""" + + if list_fields or not isinstance(source_payload, Mapping): + return None + expected_digest = extract_delivered_peer_coordination_digest(source_payload) + if expected_digest is None: + return None + content_bytes = content.encode("utf-8") + page_start = offset + page_end = offset + len(content_bytes) + if page_start < 0 or page_end > len(raw) or raw[page_start:page_end] != content_bytes: + return None + try: + raw_text = raw.decode("utf-8") + except UnicodeDecodeError: + return None + try: + spans = ( + _selection_digest_byte_spans(raw_text, expected_digest) + if is_selection + else _top_level_digest_byte_spans(raw_text, expected_digest) + ) + except (ValueError, json.JSONDecodeError): + return None + if any(page_start <= span_start and span_end <= page_end for span_start, span_end in spans): + return expected_digest + return None + + +def _resolve_captured_decision_for_readback( + args: Any, + *, + emitted_payload: Mapping[str, Any], +) -> Mapping[str, Any] | None: + """Resolve the digest-verified source capture for context-read / context-project.""" + + from ..turn_driver.codex_context import codex_context_directory, read_codex_context_reference + from ..turn_driver.decision_capture import ( + read_context_capture_file, + read_context_read_reference, + ) + + try: + reference_file = getattr(args, "reference_file", None) + value = getattr(args, "capture_file", None) + digest = getattr(args, "capture_sha256", None) + if reference_file: + _ref_path, ref_payload = read_context_read_reference(str(reference_file)) + value, digest = ref_payload.get("path"), ref_payload.get("sha256") + if not value and not digest: + context_dir = codex_context_directory( + directory=getattr(args, "codex_context_dir", None), + root=getattr(args, "codex_context_root", None), + ) + if context_dir: + value, digest = read_codex_context_reference( + context_dir, + goal_id=getattr(args, "goal_id", None), + agent_id=getattr(args, "agent_id", None), + ) + if isinstance(value, str) and value and isinstance(digest, str) and digest: + _path, _raw, captured = read_context_capture_file(value, digest) + return captured + except (OSError, ValueError): + return None + if extract_delivered_peer_coordination_digest(emitted_payload) is not None: + return emitted_payload + return None + + +def maybe_commit_captured_peer_coordination_cursor( + args: Any, + *, + emitted_payload: Mapping[str, Any], + captured_payload: Mapping[str, Any] | None = None, + delivery_proof: Mapping[str, Any] | None = None, + registry_path: Path | None = None, + runtime_root_arg: str | None = None, +) -> bool: + """Advance cursor idempotently only when output actually delivered the complete digest.""" + + if emitted_payload.get("ok") is not True or emitted_payload.get("list_fields") is True: + return False + inline_digest = extract_delivered_peer_coordination_digest(emitted_payload) + proved_digest = ( + delivery_proof.get("delivered_digest") + if isinstance(delivery_proof, Mapping) + and isinstance(delivery_proof.get("delivered_digest"), Mapping) + else None + ) + if inline_digest is None and proved_digest is None: + return False + source = ( + captured_payload + if isinstance(captured_payload, Mapping) + else ( + delivery_proof.get("captured_payload") + if isinstance(delivery_proof, Mapping) + and isinstance(delivery_proof.get("captured_payload"), Mapping) + else _resolve_captured_decision_for_readback(args, emitted_payload=emitted_payload) + ) + ) + if not isinstance(source, Mapping): + return False + if ( + source.get("ok") is not True + or source.get("dry_run") is True + or str(source.get("effective_action") or "").strip() in _SKIPPED_EFFECTIVE_ACTIONS + ): + return False + receipt = source.get("heartbeat_receipt") + if not isinstance(receipt, Mapping): + return False + event_id = str(receipt.get("event_id") or "").strip() + turn_id = str(receipt.get("turn_instance_id") or "").strip() + if not event_id or not turn_id: + return False + digest = extract_delivered_peer_coordination_digest(source) + if digest is None: + return False + goal_id = str(source.get("goal_id") or "").strip() + agent_id = quota_decision_agent_id(source) + if not goal_id or not agent_id: + return False + raw_runtime = source.get("runtime_root") or runtime_root_arg + runtime_path: Path | None = ( + Path(str(raw_runtime)).expanduser() + if isinstance(raw_runtime, (str, Path)) and str(raw_runtime).strip() + else None + ) + if runtime_path is None and registry_path is not None: + from ...history import load_registry + from ...paths import resolve_runtime_root + + try: + runtime_path = resolve_runtime_root(load_registry(registry_path), runtime_root_arg) + except (OSError, ValueError): + return False + if runtime_path is None: + return False + return commit_recovered_peer_coordination_cursor( + runtime_path, + goal_id=goal_id, + agent_id=agent_id, + displayed_opportunity_ids=displayed_opportunity_ids_from_digest(digest), + turn_instance_id=turn_id, + ) 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/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index 2b1c88173b..896c9b543a 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -1135,6 +1135,7 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly && typeof supportingSource?.path === "string" && typeof supportingSource.sha256 === "string" && typeof details?.instruction === "string" && details.instruction.length > 0; for (const field of decisionFields) include(field); + include("peer_coordination_digest"); // A staged replan has already replaced inline acceptance with a pinned // review reader. Deliver its first action and ordering without writeback. const replan = object(context.replan_action_packet); diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index a7fad2628d..d2dfb393e3 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -39,6 +39,7 @@ read_frontier_action, ) from ..goals.goal_frontier import AUTONOMOUS_REPLAN_REQUIRED_MODE +from ..goals.peer_coordination_digest_source import attach_turn_peer_coordination_digest from ..goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL from ..quota.decision_summary import ( quota_decision_agent_id, @@ -1797,6 +1798,8 @@ def _build_quota_should_run_payload( "interaction_contract": payload["interaction_contract"], "selection_context": action_selection_context(payload), }) + attach_turn_peer_coordination_digest(payload, prepared=prepared, turn_instance_id=turn_instance_id, + runtime_root=_interaction_runtime_root(runtime_root, prepared.status_payload)) return payload diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index ef365fe6f2..c26f53baa8 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -512,6 +512,8 @@ function actionProjection(payload: JsonObject, deferSettlement = true, precision } const orchestration = object(payload.task_orchestration_contract); if (Object.keys(orchestration).length > 0) projection.task_orchestration_contract = orchestration; + const peerDigest = object(payload.peer_coordination_digest); + if (Object.keys(peerDigest).length > 0) projection.peer_coordination_digest = peerDigest; const plan = responsePlan(interaction); if (plan) projection.response_plan = plan; return projection; @@ -737,6 +739,7 @@ export function turnEnvelopeActionSignatureDocument(value: unknown): JsonObject } if (Object.keys(object(envelope.agent_context)).length > 0) signature.agent_context = object(envelope.agent_context); if (Object.keys(object(envelope.work_context)).length > 0) signature.work_context = object(envelope.work_context); + if (Object.keys(object(envelope.peer_coordination_digest)).length > 0) signature.peer_coordination_digest = object(envelope.peer_coordination_digest); if (Object.keys(object(responsePlanValue)).length > 0) signature.response_plan = { ...object(responsePlanValue) }; return signature; } @@ -1469,6 +1472,8 @@ function readyWorkOpening(context: JsonObject): JsonObject | undefined { work_lane_contract: context.work_lane_contract, goal_boundary: context.goal_boundary, goal_acceptance: context.goal_acceptance, task_scope: context.task_scope, latest_run_recommended_action: context.latest_run_recommended_action, + ...(context.peer_coordination_digest !== undefined + ? { peer_coordination_digest: context.peer_coordination_digest } : {}), }); } diff --git a/loopx/control_plane/quota/turn_envelope_budget.ts b/loopx/control_plane/quota/turn_envelope_budget.ts index b7e2128c62..a09780c90c 100644 --- a/loopx/control_plane/quota/turn_envelope_budget.ts +++ b/loopx/control_plane/quota/turn_envelope_budget.ts @@ -16,6 +16,7 @@ const SECTION_FIELDS: Record = { boundary: "boundary", execution_policy: "boundary", writeback: "writeback", scheduler: "scheduler", contract_capsule: "contracts", agent_context: "context", work_context: "context", task_orchestration_contract: "context", + peer_coordination_digest: "context", }; function sectionBytes(envelope: JsonObject): Record { 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/loopx/presentation/renderers/turn_envelope_markdown.py b/loopx/presentation/renderers/turn_envelope_markdown.py index 41770f9a96..795c63b1f3 100644 --- a/loopx/presentation/renderers/turn_envelope_markdown.py +++ b/loopx/presentation/renderers/turn_envelope_markdown.py @@ -82,6 +82,14 @@ def render_turn_envelope_markdown(payload: dict[str, Any]) -> str: f"- within_budget: `{compaction.get('within_budget')}`", *turn_envelope_budget_warning_lines(payload), ] + if isinstance(payload.get("peer_coordination_digest"), dict): + digest = payload["peer_coordination_digest"] + items = digest.get("items") or [] + lines.append( + f"- peer_coordination_digest: items={len(items)}" + + (f" omitted={digest.get('omitted')}" if digest.get("omitted") else "") + + f" read_only={digest.get('read_only')}" + ) if isinstance(payload.get("work_context"), dict): lines.extend(work_context_lines(payload["work_context"])) return "\n".join(lines) diff --git a/tests/control_plane/test_peer_coordination_digest.py b/tests/control_plane/test_peer_coordination_digest.py new file mode 100644 index 0000000000..91bb075119 --- /dev/null +++ b/tests/control_plane/test_peer_coordination_digest.py @@ -0,0 +1,1081 @@ +"""End-to-end File & SQLite regression tests for M1 Turn-envelope peer_coordination_digest.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +from pathlib import Path +from typing import Any + +import pytest + +from canonical_authority_fixture import ( + advance_canonical_fixture_authority, + initialize_canonical_authority, + isolate_sqlite_runtime, +) +from loopx.cli import main as cli_main +from loopx.control_plane.coordination.runtime_shadow import build_todo_runtime_shadow_projection +from loopx.control_plane.goals.peer_coordination_digest_source import ( + commit_displayed_peer_coordination_cursor, + peer_coordination_cursor_path, + read_peer_coordination_cursor, + read_peer_coordination_cursor_state, +) +from loopx.control_plane.quota.turn_envelope import assert_complete_turn_decision +from loopx.control_plane.todos.todo_summary import canonical_todo_read_record, structured_todo_item + + +GOAL_ID = "goal-m1-digest" + + +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, + ) + ) + + +def _write_m1_fixture( + root: Path, + *, + agents: tuple[str, ...], + todos: list[dict[str, object]], + provider: str, + coordination_extra: dict[str, Any] | None = None, +) -> dict[str, Path]: + project = root / "project" + runtime = root / "runtime" + state_file = project / ".codex" / "goals" / GOAL_ID / "ACTIVE_GOAL_STATE.md" + state_file.parent.mkdir(parents=True, exist_ok=True) + state_file.write_text( + "---\nstatus: active\nupdated_at: 2026-11-27T05:00:00+00:00\n---\n\n# M1 Fixture\n\n## Agent Todo\n\n", + encoding="utf-8", + ) + registry_path = project / ".loopx" / "registry.json" + registry_path.parent.mkdir(parents=True, exist_ok=True) + coordination: dict[str, Any] = { + "agent_model": "peer_v1", + "registered_agents": list(agents), + "agent_profiles": { + agent_id: { + "schema_version": "agent_profile_v1", + "profile_role": "fixture", + "scope": "public test", + } + for agent_id in agents + }, + "write_scope": ["loopx/**"], + } + if coordination_extra: + coordination.update(coordination_extra) + registry_path.write_text( + json.dumps( + { + "schema_version": 1, + "common_runtime_root": str(runtime), + "goals": [ + { + "id": GOAL_ID, + "domain": "control_plane", + "status": "active", + "repo": str(project), + "state_file": str(state_file.relative_to(project)), + "adapter": { + "kind": "fixture_connected_delivery_v0", + "status": "connected-delivery", + }, + "quota": {"compute": 1.0, "window_hours": 24}, + "coordination": coordination, + } + ], + }, + ensure_ascii=False, + indent=2, + ) + + "\n", + encoding="utf-8", + ) + projection = build_todo_runtime_shadow_projection(goal_id=GOAL_ID, todos=todos) + initialize_canonical_authority( + runtime, GOAL_ID, projection, state_path=state_file, provider=provider + ) + return { + "project": project, + "runtime": runtime, + "registry": registry_path, + "state_file": state_file, + } + + +def _run_should_run( + *, + registry: Path, + runtime: Path, + agent_id: str, + extra_args: tuple[str, ...] = (), +) -> tuple[int, dict[str, Any]]: + argv = [ + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + agent_id, + "--context-delivery", + "off", + *extra_args, + ] + buf = io.StringIO() + saved_thread = os.environ.pop("CODEX_THREAD_ID", None) + try: + with contextlib.redirect_stdout(buf): + code = cli_main(argv) + finally: + if saved_thread is not None: + os.environ["CODEX_THREAD_ID"] = saved_thread + return code, json.loads(buf.getvalue()) + + +def _sample_multi_agent_todos(*, include_second_verify: bool = False) -> list[dict[str, object]]: + todos = [ + _canonical_record( + todo_id="todo_a_work", + text="[P0] Verify PR slice on turn envelope", + 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_b_collide", + text="[P0] Refactor turn envelope allocation", + 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_b_unleased", + text="[P0] Fix unleased scheduler corner", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + task_repository="git:github.com/loopx-project/loopx", + target_key="scheduler", + required_write_scopes=["loopx/control_plane/scheduler/"], + claimed_by="agent-b", + priority="P0", + index=3, + ), + _canonical_record( + todo_id="todo_b_synergy", + text="[P2] Polish docs table", + status="open", + task_class="advancement_task", + action_kind="docs", + task_domain="control_plane", + task_repository="git:github.com/loopx-project/loopx", + target_key="docs", + required_write_scopes=["docs/architecture/"], + claimed_by="agent-b", + priority="P2", + index=4, + ), + ] + if include_second_verify: + todos.append( + _canonical_record( + todo_id="todo_b_verify_new", + text="[P1] Newly queued peer verification request", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="other_domain", + task_repository="git:github.com/loopx-project/loopx", + target_key="fresh-target", + completion_validation_required=True, + claimed_by="agent-b", + priority="P1", + index=5, + ) + ) + return todos + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_solo_goal_omits_digest_and_skips_cursor_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a",), + todos=[_sample_multi_agent_todos()[0]], + provider=provider, + ) + code, payload = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code == 0 and payload["ok"] is True + assert "peer_coordination_digest" not in payload + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + assert not cursor.exists() + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_automatic_turn_digest_cursor_lifecycle_and_prune( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + # Preview (--dry-run) shows the digest without creating or advancing cursor. + code, dry_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--dry-run",), + ) + assert code == 0 and dry_payload["ok"] is True + assert_complete_turn_decision(dry_payload) + assert not cursor.exists() + digest = dry_payload["peer_coordination_digest"] + assert digest["schema"] == "peer_digest_v0" + assert digest["read_only"] is True + assert digest["grants_authority"] is False + kinds = {item["kind"] for item in digest["items"]} + assert kinds <= {"collision", "verify"} + assert "unleased" not in kinds and "synergy" not in kinds + wire_bytes = len(',"peer_coordination_digest":'.encode("utf-8")) + len( + json.dumps(digest, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + ) + assert wire_bytes <= 300 + + # Live Turn #1 emits collision digest (with 1 omitted verify opp) and records only Turn 1's ID. + code1, live1 = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code1 == 0 and live1["ok"] is True + assert_complete_turn_decision(live1) + assert live1["peer_coordination_digest"] == digest + assert digest.get("omitted") == 1 + assert cursor.is_file() + cursor_after_t1 = json.loads(cursor.read_text(encoding="utf-8")) + assert len(cursor_after_t1["seen_opportunity_ids"]) == 1 + + # Live Turn #2 surfaces the previously omitted verify opportunity without losing it. + code2, live2 = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code2 == 0 and live2["ok"] is True + digest2 = live2["peer_coordination_digest"] + assert [item["kind"] for item in digest2["items"]] == ["verify"] + assert "omitted" not in digest2 + cursor_after_t2 = json.loads(cursor.read_text(encoding="utf-8")) + assert len(cursor_after_t2["seen_opportunity_ids"]) == 2 + + # Live Turn #3 (unchanged canonical frontier, all ops seen) omits field completely (0 B). + code2_quiet, live2_quiet = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code2_quiet == 0 and live2_quiet["ok"] is True + assert "peer_coordination_digest" not in live2_quiet + + # Newly added peer verification opportunity immediately surfaces ONLY the new item. + updated_projection = build_todo_runtime_shadow_projection( + goal_id=GOAL_ID, todos=_sample_multi_agent_todos(include_second_verify=True) + ) + advance_canonical_fixture_authority( + paths["runtime"], GOAL_ID, updated_projection, operation_id="op_add_second_verify" + ) + code3, live3 = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code3 == 0 and live3["ok"] is True + digest3 = live3["peer_coordination_digest"] + assert [item["todo"] for item in digest3["items"]] == ["todo_b_verify_new"] + + # When peer opportunities clear, live Turn omits digest and prunes cursor cleanly. + cleared_projection = build_todo_runtime_shadow_projection( + goal_id=GOAL_ID, todos=[_sample_multi_agent_todos()[0]] + ) + advance_canonical_fixture_authority( + paths["runtime"], GOAL_ID, cleared_projection, operation_id="op_clear_peer_opps" + ) + code4, live4 = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code4 == 0 and live4["ok"] is True + assert "peer_coordination_digest" not in live4 + cursor_data = json.loads(cursor.read_text(encoding="utf-8")) + assert cursor_data["seen_opportunity_ids"] == [] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_idle_specialist_discovers_peer_opportunities_automatically( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b", "agent-idle"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + code, payload = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-idle" + ) + assert code == 0 and payload["ok"] is True + digest = payload["peer_coordination_digest"] + kinds = {item["kind"] for item in digest["items"]} + assert kinds <= {"verify", "unleased"} + assert len(kinds) >= 1 + + +@pytest.mark.parametrize("mode", ["goal_config", "env_flag"]) +def test_explicit_off_escape_hatch_suppresses_digest( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + extra = {"peer_coordination_digest": "off"} if mode == "goal_config" else None + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider="file", + coordination_extra=extra, + ) + if mode == "env_flag": + monkeypatch.setenv("LOOPX_PEER_COORDINATION_DIGEST", "off") + code, payload = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code == 0 and payload["ok"] is True + assert "peer_coordination_digest" not in payload + + +def test_commit_displayed_cursor_records_only_displayed_and_active_seen(tmp_path: Path) -> None: + runtime = tmp_path / "runtime" + active = ["opp:1", "opp:2", "opp:3"] + assert ( + commit_displayed_peer_coordination_cursor( + runtime, + goal_id=GOAL_ID, + agent_id="agent-a", + active_opportunity_ids=active, + displayed_opportunity_ids=["opp:1"], + ) + is True + ) + assert read_peer_coordination_cursor(runtime, goal_id=GOAL_ID, agent_id="agent-a") == [ + "opp:1" + ] + + # When opp:2 becomes inactive while opp:1 was previously seen and opp:3 is displayed next, + # opp:2 is pruned and opp:1 + opp:3 remain recorded. + commit_displayed_peer_coordination_cursor( + runtime, + goal_id=GOAL_ID, + agent_id="agent-a", + active_opportunity_ids=["opp:1", "opp:3", "opp:4"], + displayed_opportunity_ids=["opp:3"], + ) + assert read_peer_coordination_cursor(runtime, goal_id=GOAL_ID, agent_id="agent-a") == [ + "opp:1", + "opp:3", + ] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_dry_run_non_mutating_and_omitted_opportunities_surface_across_turns( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + todos: list[dict[str, object]] = [ + _canonical_record( + todo_id="todo_a_verifier", + text="[P0] Verify peer slices cleanly", + status="open", + task_class="advancement_task", + action_kind="verify", + task_domain="control_plane", + task_repository="https://github.com/loopx-project/loopx.git", + target_key="peer-target", + required_write_scopes=["loopx/control_plane/goals/"], + claimed_by="agent-a", + priority="P0", + index=1, + ) + ] + long_todo_ids = [ + f"todo_overflow_{idx}_" + ("x" * 12) + for idx in range(3) + ] + for offset, todo_id in enumerate(long_todo_ids, start=2): + todos.append( + _canonical_record( + todo_id=todo_id, + text=f"[P0] Peer slice {offset} needing review", + status="open", + task_class="advancement_task", + action_kind="refactor", + task_domain="control_plane", + task_repository="git:github.com/loopx-project/loopx", + target_key=f"module-{offset}", + required_write_scopes=[f"loopx/control_plane/mod_{offset}/"], + completion_validation_required=True, + claimed_by="agent-b", + priority="P0", + index=offset, + ) + ) + + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=todos, + provider=provider, + ) + cursor_path = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + # Preview (--dry-run) may display the digest without creating or advancing the cursor. + dry_code, dry_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--dry-run",), + ) + assert dry_code == 0 and dry_payload["ok"] is True + assert "peer_coordination_digest" in dry_payload + assert not cursor_path.exists() + + seen_todo_ids: list[str] = [] + omitted_seen_on_first_turn = False + for turn in range(6): + code, payload = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert code == 0 and payload["ok"] is True + digest = payload.get("peer_coordination_digest") + if digest is None: + break + serialized_bytes = len( + json.dumps(digest, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + ) + assert serialized_bytes <= 300 + if turn == 0: + omitted_seen_on_first_turn = int(digest.get("omitted", 0)) >= 1 + turn_todos = [str(item["todo"]) for item in digest["items"]] + assert set(turn_todos).isdisjoint(set(seen_todo_ids)) + seen_todo_ids.extend(turn_todos) + recorded = read_peer_coordination_cursor( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + assert len(recorded) == len(seen_todo_ids) + + assert omitted_seen_on_first_turn + assert set(long_todo_ids).issubset(set(seen_todo_ids)) + + quiet_code, quiet_payload = _run_should_run( + registry=paths["registry"], runtime=paths["runtime"], agent_id="agent-a" + ) + assert quiet_code == 0 and quiet_payload["ok"] is True + assert "peer_coordination_digest" not in quiet_payload + + +def _run_quota_cli( + *, + registry: Path, + runtime: Path, + subcommand: str, + extra_args: tuple[str, ...] = (), +) -> tuple[int, dict[str, Any]]: + argv = [ + "--registry", + str(registry), + "--runtime-root", + str(runtime), + "--format", + "json", + "quota", + subcommand, + *extra_args, + ] + buf = io.StringIO() + saved_thread = os.environ.pop("CODEX_THREAD_ID", None) + try: + with contextlib.redirect_stdout(buf): + code = cli_main(argv) + finally: + if saved_thread is not None: + os.environ["CODEX_THREAD_ID"] = saved_thread + return code, json.loads(buf.getvalue()) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_capture_failure_preserves_cursor_and_same_turn_or_next_turn_recovers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + from loopx.control_plane.turn_driver import decision_capture + + with monkeypatch.context() as patch: + def _fail_capture(*_args: Any, **_kwargs: Any) -> str: + raise OSError("disk full") + + patch.setattr(decision_capture, "write_decision_capture", _fail_capture) + fail_code, fail_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=( + "--turn-instance-id", + "turn-cap-fail", + "--decision-output-dir", + str(tmp_path / "cap-fail"), + ), + ) + assert fail_code == 1 and fail_payload["ok"] is False + assert fail_payload["error_code"] == "quota_decision_transport_failed" + assert not cursor.exists() + + # Same Turn retries once capture path succeeds -> delivers collision and commits ONLY collision. + retry_code, retry_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=( + "--turn-instance-id", + "turn-cap-fail", + "--decision-output-dir", + str(tmp_path / "cap-retry"), + ), + ) + assert retry_code == 0 and retry_payload["ok"] is True + retry_digest = retry_payload["peer_coordination_digest"] + assert [item["kind"] for item in retry_digest["items"]] == ["collision"] + assert retry_digest.get("omitted") == 1 + seen_after_retry, turns_after_retry = read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + assert seen_after_retry == [retry_digest["items"][0]["id"]] + assert turns_after_retry == ["turn-cap-fail"] + + # Replaying the exact same Turn ID again stays idempotent (0 B, does not consume verify). + replay_code, replay_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=( + "--turn-instance-id", + "turn-cap-fail", + "--decision-output-dir", + str(tmp_path / "cap-replay"), + ), + ) + assert replay_code == 0 and replay_payload["ok"] is True + assert "peer_coordination_digest" not in replay_payload + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == (seen_after_retry, turns_after_retry) + + # Next normal Turn surfaces the previously omitted verify opportunity. + next_code, next_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--turn-instance-id", "turn-next"), + ) + assert next_code == 0 and next_payload["ok"] is True + next_digest = next_payload["peer_coordination_digest"] + assert [item["kind"] for item in next_digest["items"]] == ["verify"] + seen_after_next, turns_after_next = read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + assert len(seen_after_next) == 2 + assert turns_after_next == ["turn-cap-fail", "turn-next"] + + quiet_code2, quiet_payload2 = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--turn-instance-id", "turn-quiet"), + ) + assert quiet_code2 == 0 and quiet_payload2["ok"] is True + assert "peer_coordination_digest" not in quiet_payload2 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_delivery_failure_after_capture_preserves_cursor_and_context_read_recovers_idempotently( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + from loopx.cli_commands import quota_result_delivery + from loopx.control_plane.quota.error_codes import QuotaDecisionTransportError + + with monkeypatch.context() as patch: + def _fail_handoff(*_args: Any, **_kwargs: Any) -> Any: + raise QuotaDecisionTransportError("simulated handoff transport failure") + + patch.setattr(quota_result_delivery, "handoff_decision", _fail_handoff) + fail_code, fail_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=( + "--turn-instance-id", + "turn-handoff-fail", + "--decision-output-dir", + str(tmp_path / "cap-handoff"), + ), + ) + assert fail_code == 1 and fail_payload["ok"] is False + assert fail_payload["error_code"] == "quota_decision_transport_failed" + assert not cursor.exists() + captured_ref = fail_payload["captured_decision"] + + # Reading an unrelated pointer does NOT advance the peer digest cursor. + hb_code, hb_payload = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--select", + "/heartbeat_receipt", + ), + ) + assert hb_code == 0 and hb_payload["ok"] is True and hb_payload["eof"] is True + assert not cursor.exists() + + # Full same-decision recovery read delivers collision digest and commits ONLY collision + original Turn. + read1_code, read1_payload = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--page-bytes", + "65536", + "--max-page-output-bytes", + "65536", + ), + ) + assert read1_code == 0 and read1_payload["ok"] is True and read1_payload["eof"] is True + recovered_doc = json.loads(read1_payload["content"]) + collision_id = recovered_doc["peer_coordination_digest"]["items"][0]["id"] + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == ([collision_id], ["turn-handoff-fail"]) + + # Repeated readback of the same saved decision is idempotent (same bytes, no extra advancement). + read2_code, read2_payload = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--page-bytes", + "65536", + "--max-page-output-bytes", + "65536", + ), + ) + assert read2_code == 0 and read2_payload["ok"] is True + assert read2_payload["content"] == read1_payload["content"] + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == ([collision_id], ["turn-handoff-fail"]) + + # Subsequent normal Turn surfaces omitted verify item. + next_code, next_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--turn-instance-id", "turn-after-recovery"), + ) + assert next_code == 0 and next_payload["ok"] is True + assert [item["kind"] for item in next_payload["peer_coordination_digest"]["items"]] == ["verify"] + seen_after_next, turns_after_next = read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + assert len(seen_after_next) == 2 + assert turns_after_next == ["turn-handoff-fail", "turn-after-recovery"] + + # Late repeated readback on the old capture stays idempotent and never regresses cursor. + late_code, late_payload = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--select", + "/peer_coordination_digest", + ), + ) + assert late_code == 0 and late_payload["ok"] is True + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == (seen_after_next, turns_after_next) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_prepared_capture_reference_defers_cursor_until_selected_read_and_stdout_failure_preserves_cursor( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + cap_dir = tmp_path / "prepared-cap" + prep_code, prep_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=( + "--turn-instance-id", + "turn-prep", + "--decision-output-dir", + str(cap_dir), + "--prepared-capture-reference", + ), + ) + assert prep_code == 0 and prep_payload["ok"] is True + assert "peer_coordination_digest" not in prep_payload + assert not cursor.exists() + + sel_code, sel_payload = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + str(cap_dir / "decision.json"), + "--capture-sha256", + prep_payload["capture_sha256"], + "--select", + "/peer_coordination_digest", + ), + ) + assert sel_code == 0 and sel_payload["ok"] is True and sel_payload["eof"] is True + selections = json.loads(sel_payload["content"])["selections"] + collision_id = selections[0]["value"]["items"][0]["id"] + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == ([collision_id], ["turn-prep"]) + + # Stdout emission error never advances cursor either. + from loopx import cli_runtime + + with monkeypatch.context() as patch: + def _fail_print(*_args: Any, **_kwargs: Any) -> None: + raise OSError("broken pipe") + + patch.setattr(cli_runtime, "print_payload", _fail_print) + with pytest.raises(OSError, match="broken pipe"): + cli_main( + [ + "--registry", + str(paths["registry"]), + "--runtime-root", + str(paths["runtime"]), + "--format", + "json", + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--turn-instance-id", + "turn-stdout-fail", + "--context-delivery", + "off", + ] + ) + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == ([collision_id], ["turn-prep"]) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_buffered_stdout_flush_failure_preserves_cursor_and_next_turn_delivers( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + import sys + + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + class _BufferedBrokenPipeStdout: + def __init__(self) -> None: + self.buffered: list[str] = [] + self.delivered = bytearray() + + def write(self, data: str) -> int: + self.buffered.append(data) + return len(data) + + def flush(self) -> None: + raise BrokenPipeError("broken pipe on stdout flush") + + broken_stdout = _BufferedBrokenPipeStdout() + with monkeypatch.context() as patch: + patch.setattr(sys, "stdout", broken_stdout) + with pytest.raises(BrokenPipeError, match="broken pipe on stdout flush"): + cli_main( + [ + "--registry", + str(paths["registry"]), + "--runtime-root", + str(paths["runtime"]), + "--format", + "json", + "quota", + "should-run", + "--goal-id", + GOAL_ID, + "--agent-id", + "agent-a", + "--turn-instance-id", + "turn-buf-fail", + "--context-delivery", + "off", + ] + ) + assert len(broken_stdout.delivered) == 0 + assert not cursor.exists() + + # Subsequent live Turn must still surface the unseen collision opportunity. + next_code, next_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--turn-instance-id", "turn-buf-next"), + ) + assert next_code == 0 and next_payload["ok"] is True + next_digest = next_payload["peer_coordination_digest"] + assert [item["kind"] for item in next_digest["items"]] == ["collision"] + assert next_digest.get("omitted") == 1 + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == ([next_digest["items"][0]["id"]], ["turn-buf-next"]) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_tail_only_raw_and_selected_context_read_preserve_cursor_until_full_digest_delivered( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str +) -> None: + if provider == "sqlite": + isolate_sqlite_runtime(tmp_path, monkeypatch) + paths = _write_m1_fixture( + tmp_path, + agents=("agent-a", "agent-b"), + todos=_sample_multi_agent_todos(), + provider=provider, + ) + cursor = peer_coordination_cursor_path( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) + + from loopx.cli_commands import quota_result_delivery + from loopx.control_plane.quota.error_codes import QuotaDecisionTransportError + + with monkeypatch.context() as patch: + def _fail_handoff(*_args: Any, **_kwargs: Any) -> Any: + raise QuotaDecisionTransportError("simulated handoff transport failure") + + patch.setattr(quota_result_delivery, "handoff_decision", _fail_handoff) + fail_code, fail_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=( + "--turn-instance-id", + "turn-tail-fail", + "--decision-output-dir", + str(tmp_path / "cap-tail"), + ), + ) + assert fail_code == 1 and fail_payload["error_code"] == "quota_decision_transport_failed" + assert not cursor.exists() + captured_ref = fail_payload["captured_decision"] + raw_len = len(Path(captured_ref["path"]).read_bytes()) + + # 1. Bare capture tail-only page (1 byte, eof=True) must NOT advance cursor. + raw_tail_code, raw_tail = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--offset", + str(raw_len - 1), + ), + ) + assert raw_tail_code == 0 and raw_tail["ok"] is True and raw_tail["eof"] is True + assert len(raw_tail["content"].encode("utf-8")) == 1 + assert not cursor.exists() + + # 2. Explicit selection head chunk truncated before digest end (eof=False) must NOT advance cursor. + sel_head_code, sel_head = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--select", + "/peer_coordination_digest", + "--page-bytes", + "256", + "--offset", + "0", + ), + ) + assert sel_head_code == 0 and sel_head["ok"] is True and sel_head["eof"] is False + assert not cursor.exists() + + # 3. Jumping directly to the tail page of the explicit selection (1 byte, eof=True) must NOT advance cursor. + sel_total = int(sel_head["total_bytes"]) + sel_tail_code, sel_tail = _run_quota_cli( + registry=paths["registry"], + runtime=paths["runtime"], + subcommand="context-read", + extra_args=( + "--capture-file", + captured_ref["path"], + "--capture-sha256", + captured_ref["sha256"], + "--select", + "/peer_coordination_digest", + "--selection-sha256", + str(sel_head["selection_sha256"]), + "--offset", + str(sel_total - 1), + ), + ) + assert sel_tail_code == 0 and sel_tail["ok"] is True and sel_tail["eof"] is True + assert len(sel_tail["content"].encode("utf-8")) == 1 + assert not cursor.exists() + + # 4. Subsequent normal live Turn must STILL see the collision item. + next_code, next_payload = _run_should_run( + registry=paths["registry"], + runtime=paths["runtime"], + agent_id="agent-a", + extra_args=("--turn-instance-id", "turn-after-tail"), + ) + assert next_code == 0 and next_payload["ok"] is True + next_digest = next_payload["peer_coordination_digest"] + assert [item["kind"] for item in next_digest["items"]] == ["collision"] + assert next_digest.get("omitted") == 1 + assert read_peer_coordination_cursor_state( + paths["runtime"], goal_id=GOAL_ID, agent_id="agent-a" + ) == ([next_digest["items"][0]["id"]], ["turn-after-tail"]) 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/peer_coordination_digest.test.ts b/tests/control_plane_ts/peer_coordination_digest.test.ts new file mode 100644 index 0000000000..ef4c927b8e --- /dev/null +++ b/tests/control_plane_ts/peer_coordination_digest.test.ts @@ -0,0 +1,350 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + PEER_COORDINATION_DIGEST_FIELD_OVERHEAD_BYTES, + PEER_COORDINATION_DIGEST_MAX_BYTES, + PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + PEER_COORDINATION_DIGEST_SCHEMA_VERSION, + projectPeerCoordinationDigest, +} from "../../loopx/control_plane/goals/peer_coordination_digest.ts"; +import { + buildTurnEnvelope, + composeCompleteTurnDecision, + turnEnvelopeActionSignatureDocument, +} from "../../loopx/control_plane/quota/turn_envelope.ts"; +import { evaluateTurnEnvelope } from "../../loopx/control_plane/quota/turn_envelope.ts"; +import type { JsonObject } from "../../loopx/control_plane/effect_program.ts"; + +const OBSERVED_AT = "2026-11-27T05:00:00Z"; + +function multiAgentWorkItems() { + return [ + { + todo_id: "todo_caller_verify", + status: "open", + done: false, + task_class: "advancement_task", + claimed_by: "agent-a", + bound_agent: null, + priority: "P0", + 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/"], + completion_validation_required: false, + excluded_agents: [], + lease: { + schema_version: "task_lease_v0", + status: "active", + owner: "agent-a", + epoch: 1, + lease_version: 1, + expires_at: "2026-11-27T06:00:00Z", + }, + }, + { + todo_id: "todo_peer_collision_verify", + status: "open", + done: false, + task_class: "advancement_task", + claimed_by: "agent-b", + bound_agent: null, + priority: "P0", + 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, + excluded_agents: [], + lease: { + schema_version: "task_lease_v0", + status: "active", + owner: "agent-b", + epoch: 1, + lease_version: 1, + expires_at: "2026-11-27T06:00:00Z", + }, + }, + { + todo_id: "todo_peer_unleased_p0", + status: "open", + done: false, + task_class: "advancement_task", + claimed_by: "agent-b", + bound_agent: null, + priority: "P0", + action_kind: "refactor", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx", + target_key: "scheduler-hint", + required_write_scopes: ["loopx/control_plane/scheduler/"], + completion_validation_required: false, + excluded_agents: [], + lease: null, + }, + { + todo_id: "todo_peer_synergy_only", + status: "open", + done: false, + task_class: "advancement_task", + claimed_by: "agent-b", + bound_agent: null, + priority: "P2", + action_kind: "docs", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx", + target_key: "docs-sync", + required_write_scopes: ["docs/architecture/"], + completion_validation_required: false, + excluded_agents: [], + lease: null, + }, + ]; +} + +function minimalTurnPayload(overrides: JsonObject = {}): JsonObject { + return { + ok: true, + goal_id: "goal-coord", + decision: "run", + should_run: true, + effective_action: "normal_run", + state: "eligible", + reason: "ready to execute", + action_required: false, + open_count: 0, + normal_delivery_allowed: true, + agent_identity: { agent_id: "agent-a", registered_agents: ["agent-a", "agent-b"] }, + selected_todo: { todo_id: "todo_caller_verify", text: "Verify PR slice" }, + interaction_contract: { + schema_version: "loopx_interaction_contract_v0", + mode: "bounded_delivery", + user_channel: { action_required: false, notify: "DONT_NOTIFY", max_items: 0, actions: [], non_blocking: true }, + agent_channel: { + must_attempt: true, + delivery_allowed: true, + quiet_noop_allowed: false, + primary_action: "Verify PR slice", + required_reads: [], + work_context: { complete: true, selected_todo_ref: "selected_todo", instruction: "Read selected todo." }, + }, + cli_channel: { + spend_allowed_now: true, + spend_after_validation: true, + spend_policy: "normal", + next_cli_actions: ["loopx quota spend-slot --goal-id goal-coord"], + }, + }, + ...overrides, + }; +} + +test("single-agent goal emits null digest with 0 serialized delta bytes", () => { + const result = projectPeerCoordinationDigest({ + schema_version: PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + goal_id: "goal-solo", + agent_id: "agent-a", + registered_agent_count: 1, + work_items: multiAgentWorkItems(), + observed_at: OBSERVED_AT, + }); + assert.equal(result.digest, null); + assert.deepEqual(result.active_opportunity_ids, []); + assert.deepEqual(result.new_opportunity_ids, []); + assert.equal(result.serialized_delta_bytes, 0); +}); + +test("busy multi-agent Turn surfaces only collision & verify within 300 B and excludes unleased/synergy", () => { + const result = projectPeerCoordinationDigest({ + schema_version: PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + goal_id: "goal-coord", + agent_id: "agent-a", + registered_agent_count: 2, + work_items: multiAgentWorkItems(), + observed_at: OBSERVED_AT, + }); + const digest = result.digest as JsonObject; + assert.ok(digest !== null && typeof digest === "object"); + assert.equal(digest.schema, PEER_COORDINATION_DIGEST_SCHEMA_VERSION); + assert.equal(digest.read_only, true); + assert.equal(digest.grants_authority, false); + const serializedBytes = result.serialized_delta_bytes as number; + assert.ok(serializedBytes > 0 && serializedBytes <= PEER_COORDINATION_DIGEST_MAX_BYTES); + const actualWireBytes = PEER_COORDINATION_DIGEST_FIELD_OVERHEAD_BYTES + + Buffer.byteLength(JSON.stringify(digest), "utf8"); + assert.equal(serializedBytes, actualWireBytes); + + const items = digest.items as JsonObject[]; + const kinds = items.map((item) => item.kind); + assert.ok(kinds.includes("collision") || kinds.includes("verify")); + assert.ok(!kinds.includes("unleased")); + assert.ok(!kinds.includes("synergy")); + + const seenAll = projectPeerCoordinationDigest({ + schema_version: PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + goal_id: "goal-coord", + agent_id: "agent-a", + registered_agent_count: 2, + seen_opportunity_ids: result.active_opportunity_ids, + work_items: multiAgentWorkItems(), + observed_at: OBSERVED_AT, + }); + assert.equal(seenAll.digest, null); + assert.equal(seenAll.serialized_delta_bytes, 0); + assert.deepEqual(seenAll.new_opportunity_ids, []); +}); + +test("idle multi-agent caller discovers verify & unleased P0/P1 without synergy noise", () => { + const result = projectPeerCoordinationDigest({ + schema_version: PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + goal_id: "goal-coord", + agent_id: "agent-c", + registered_agent_count: 3, + work_items: multiAgentWorkItems(), + observed_at: OBSERVED_AT, + }); + const digest = result.digest as JsonObject; + assert.ok(digest !== null); + assert.ok((result.serialized_delta_bytes as number) <= PEER_COORDINATION_DIGEST_MAX_BYTES); + const activeCount = (result.active_opportunity_ids as string[]).length; + assert.equal(activeCount, 2); + const items = digest.items as JsonObject[]; + const kinds = new Set(items.map((item) => item.kind)); + assert.ok(kinds.has("verify") || kinds.has("unleased")); + assert.ok(!kinds.has("collision")); + assert.ok(!kinds.has("synergy")); +}); + +test("strict <= 300 B cap emits omitted count without breaking budget even on long ids", () => { + const longAgent = "agent_" + "x".repeat(48); + const longPeerTodo = "todo_" + "p".repeat(56); + const items = Array.from({ length: 5 }, (_, idx) => ({ + todo_id: `${longPeerTodo.slice(0, 60)}_${idx}`, + status: "open", + done: false, + task_class: "advancement_task", + claimed_by: longAgent, + bound_agent: null, + priority: "P0", + action_kind: "refactor", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx", + target_key: "shared-target", + required_write_scopes: ["loopx/control_plane/quota/"], + completion_validation_required: true, + excluded_agents: [], + lease: null, + })); + const result = projectPeerCoordinationDigest({ + schema_version: PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + goal_id: "goal-long", + agent_id: "agent-idle-observer", + registered_agent_count: 2, + work_items: items, + observed_at: OBSERVED_AT, + }); + const digest = result.digest as JsonObject; + assert.ok(digest !== null); + assert.ok((result.serialized_delta_bytes as number) <= PEER_COORDINATION_DIGEST_MAX_BYTES); + assert.ok(typeof digest.omitted === "number" && (digest.omitted as number) >= 1); + const digestItems = digest.items as JsonObject[]; + assert.deepEqual( + result.displayed_opportunity_ids, + digestItems.map((item) => item.id as string), + ); +}); + +test("omitted overflowing opportunities are not marked seen and surface on follow-up turns", () => { + const workItems = [0, 1, 2].map((idx) => ({ + todo_id: `todo_overflow_${idx}_` + "x".repeat(12), + status: "open", + done: false, + task_class: "advancement_task", + claimed_by: "agent-b", + bound_agent: null, + priority: "P0", + action_kind: "refactor", + task_domain: "control_plane", + task_repository: "git:github.com/loopx-project/loopx", + target_key: `module-${idx}`, + required_write_scopes: [`loopx/control_plane/mod_${idx}/`], + completion_validation_required: true, + excluded_agents: [], + lease: null, + })); + + const seen: string[] = []; + const displayedAll: string[] = []; + let expectedActiveIds: string[] = []; + let sawOmitted = false; + for (let turn = 0; turn < 10; turn += 1) { + const step = projectPeerCoordinationDigest({ + schema_version: PEER_COORDINATION_DIGEST_REQUEST_SCHEMA_VERSION, + goal_id: "goal-overflow", + agent_id: "agent-a", + registered_agent_count: 2, + work_items: workItems, + seen_opportunity_ids: seen, + observed_at: OBSERVED_AT, + }); + if (step.digest === null) break; + assert.ok((step.serialized_delta_bytes as number) <= PEER_COORDINATION_DIGEST_MAX_BYTES); + const stepDigest = step.digest as JsonObject; + const stepItems = stepDigest.items as JsonObject[]; + const stepDisplayed = step.displayed_opportunity_ids as string[]; + assert.deepEqual( + stepDisplayed, + stepItems.map((item) => item.id as string), + ); + assert.ok(stepDisplayed.length >= 1); + if (turn === 0) { + expectedActiveIds = [...(step.active_opportunity_ids as string[])]; + sawOmitted = typeof stepDigest.omitted === "number" && (stepDigest.omitted as number) >= 1; + assert.ok(stepDisplayed.length < expectedActiveIds.length); + } + for (const id of stepDisplayed) { + assert.ok(!seen.includes(id)); + seen.push(id); + displayedAll.push(id); + } + } + assert.ok(sawOmitted); + assert.ok(expectedActiveIds.length >= 3); + assert.deepEqual([...displayedAll].sort(), [...expectedActiveIds].sort()); +}); + +test("TurnEnvelope v0/v1 and progressive opening preserve peer_coordination_digest cleanly", () => { + const digest = { + schema: PEER_COORDINATION_DIGEST_SCHEMA_VERSION, + read_only: true, + grants_authority: false, + items: [{ id: "opp_0123456789abcdef", kind: "verify", peer: "agent-b", todo: "todo_peer_1" }], + }; + const withoutDigest = minimalTurnPayload(); + const withDigest = minimalTurnPayload({ peer_coordination_digest: digest }); + + const envWithout = buildTurnEnvelope({ payload: withoutDigest, scheduler_execution_args: "" }); + const envWith = buildTurnEnvelope({ payload: withDigest, scheduler_execution_args: "" }); + assert.equal((envWithout as JsonObject).peer_coordination_digest, undefined); + assert.deepEqual((envWith as JsonObject).peer_coordination_digest, digest); + assert.equal((envWith.action_signature as JsonObject).matches, true); + assert.deepEqual( + (turnEnvelopeActionSignatureDocument(envWith) as JsonObject).peer_coordination_digest, + digest, + ); + + const complete = composeCompleteTurnDecision({ payload: withDigest, scheduler_execution_args: "" }); + assert.deepEqual((complete as JsonObject).peer_coordination_digest, digest); + const selected = evaluateTurnEnvelope({ + operation: "context_select", + select: [""], + list_fields: true, + include_initial_read_plan: true, + context: complete, + }); + const selections = ((selected.initial_read_plan as JsonObject)?.selections ?? []) as JsonObject[]; + assert.ok(selections.some((entry) => entry.pointer === "/peer_coordination_digest")); +}); 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`); +});