From 0133c9b3e851fa2cb5432fea8773734acd0ab3cf Mon Sep 17 00:00:00 2001 From: Bastian Huppertz <29781772+BastiHu@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:54:29 +0000 Subject: [PATCH 01/11] fix(fleet): expose measured ledger and runtime facts Read owed and awaited Exchanges and sender delivery alarms with the Fleet snapshot. Derive runtime, dispatch problems and labeled activity from the existing live raw shell, with one shared local threshold deadline and explicit missing-fact reasons. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex --- FORK.md | 4 +- apps/server/src/j5/a2a/ClientReadsService.ts | 14 +- .../server/src/j5/a2a/ReadChangeFeeds.test.ts | 32 +- apps/server/src/j5/a2a/ReadChangeFeeds.ts | 12 +- apps/server/src/j5/a2a/clientReadBatches.ts | 10 + apps/server/src/j5/a2a/fleetFacts.test.ts | 205 +++++++++++ apps/server/src/j5/a2a/fleetFacts.ts | 105 ++++++ apps/server/src/j5/a2a/fleetRead.ts | 80 +++- .../j5/run-observability/QueuedRunWatchdog.ts | 3 +- docs/j5/product/features/fleet-page.md | 4 +- packages/client-runtime/package.json | 4 + .../client-runtime/src/j5/fleetFacts.test.ts | 348 ++++++++++++++++++ packages/client-runtime/src/j5/fleetFacts.ts | 205 +++++++++++ packages/contracts/src/j5.ts | 10 +- packages/contracts/src/j5/fleet.ts | 72 ++++ 15 files changed, 1074 insertions(+), 34 deletions(-) create mode 100644 apps/server/src/j5/a2a/clientReadBatches.ts create mode 100644 apps/server/src/j5/a2a/fleetFacts.test.ts create mode 100644 apps/server/src/j5/a2a/fleetFacts.ts create mode 100644 packages/client-runtime/src/j5/fleetFacts.test.ts create mode 100644 packages/client-runtime/src/j5/fleetFacts.ts create mode 100644 packages/contracts/src/j5/fleet.ts diff --git a/FORK.md b/FORK.md index 910ec17211fc6..fb82e4b7f960b 100644 --- a/FORK.md +++ b/FORK.md @@ -163,6 +163,8 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 33. Artifacts (PR #109, corrected 2026-09-14). Storage is server-owned application data, never the repository: `apps/server/src/j5/artifacts/ArtifactWorkspace.ts` keeps one directory per project under `/artifacts//`, so there is no Git exclusion and no per-thread folder. Production decorates the existing `RunFinalizationObserver` with J5-owned `ArtifactRunFinalizationObserver.ts` (wrapped in turn by the handoff observer), preserving both upstream refresh methods (`refreshAfterTurn` is now `(projectId) => Effect`; the decorators pass it through unchanged, nesting handoff → artifact → upstream). It reads the settled projection to export the final proposed plan to the project's `plan.md`; no observer argument extension is needed. `apps/server/src/j5/a2a/J5AuthenticatedRoutes.ts` appends the authenticated, project-addressed artifact read route to the sole J5 aggregate; the list is the RPC `j5.artifacts.list` (case 64). The operate-scoped permanent delete is the RPC `j5.artifacts.delete` in the J5 artifact group, served by J5-owned `ArtifactDeletion.ts` (case 64). Deletion uses non-recursive platform filesystem removal and adds no runtime dependency or packaging seam. Successful deletion reconciles a matching saved-agent handoff to `missing` and publishes the normal handoff refresh; reconciliation stays best-effort because the file has already been deleted and cannot be rolled back. The artifact change stream is a J5 RPC group, `J5ArtifactRpcGroup` in `packages/contracts/src/j5/artifacts.ts`, merged into `WsRpcGroup` in `packages/contracts/src/rpc.ts` beside the persona group (one appended `.merge`); `apps/server/src/auth/RpcAuthorization.ts` spreads its scopes, its handlers from J5-owned `apps/server/src/j5/artifacts/artifactRpc.ts` are served through case 58's `layerJ5WsRpc`, and `packages/client-runtime/src/rpc/client.ts` names its tag in the subscription-tag union. `apps/web/src/components/sidebar/SidebarChrome.tsx` adds the Artifacts footer item, and case 6's `isSidebarUtilityPage` entry gives `/artifacts` its Back behavior; `rightPanelStore.ts`, `RightPanelTabs.tsx`, and `ChatView.tsx` add a project-scoped singleton right-panel surface that reuses the J5-owned artifact view, and upstream's `components/chat/RightPanelSurfaceContent.tsx`, which holds the surface switch since upstream moved it out of `ChatView.tsx`, renders it in a `case "artifacts"` from an `artifactsProjectId` prop that `ChatView.tsx` passes (the switch has no default, so a lost case leaves the tab blank and no check fails); `rightPanelStore` storage version is 15 (J5 13 + upstream 14), and its version-agnostic migration drops `plan`/`agents` and normalizes `artifacts`. `ChatMarkdown.tsx` recognizes workspace-relative `artifacts/` file references, gives them distinct presentation, and routes their primary action to that surface with the referenced artifact selected. J5's instructions (case 8) carry one planning-document placement bullet. The MCP `j5_write_artifact`, `j5_read_artifact`, and `j5_list_artifacts` tools (`apps/server/src/mcp/toolkits/artifacts/`, `ArtifactMcpService.ts`) are registered by case 2's `layerJ5Toolkits`. The route, client, project page, filesystem policy, path classifier, previews, and change subscription otherwise live in J5-owned files. The generated `apps/web/src/routeTree.gen.ts` delta is not hand-authored. On every rebase, keep plan export and post-delete handoff reconciliation best-effort so neither can poison a completed operation, preserve the finalization observer's original refresh behavior, and keep one shared project namespace. 34. Issue #105's cross-environment reads for the project ledger and the human inbox (read models merge in the client; authority stays on each server, per [`docs/j5/product/cross-device.md`](docs/j5/product/cross-device.md)): `packages/contracts/src/environment.ts` adds three optional capability keys beside upstream's existing optional capabilities: `j5ProjectLedger`, which gates every J5 read, and `j5Squadrons` and `j5HumanInbox`, the two keys a J5 server reported while its ledger was keyed by Squadron. `apps/server/src/environment/ServerEnvironment.ts` (with its test) spreads J5-owned `J5_LEDGER_CAPABILITIES` (`packages/contracts/src/j5.ts`) into its descriptor: `j5ProjectLedger` true and the two older keys false. A server that does not report `j5ProjectLedger` true is shown as unsupported in the Inbox, Fleet, Crew, peer and playbook views, which send it no reads; the sidebar's row reads, the archive preflight and the artifact list still ask it and get "Unknown request tag", as they got a 404 before. An older J5 server, which reports `j5Squadrons` true, is refused at connection (case 56). `packages/contracts/package.json` adds the `./j5` export for J5-owned `packages/contracts/src/j5.ts`; `packages/client-runtime/package.json` appends six `./j5/*` exports for the J5-owned read-source, HTTP, and merge modules under `packages/client-runtime/src/j5/`. Those modules reuse upstream's environment registry and per-environment query atoms. `packages/client-runtime/src/state/environmentHttpAuth.ts` exposes `executeAuthenticatedEnvironmentRawHttpRequest` for the one J5 route a client still calls, the read of an artifact's content (case 64 moved every other read onto the socket); it and upstream's typed-group `executeAuthenticatedEnvironmentHttpRequest` both sit on upstream's `executeEnvironmentRequest`, the one credential/retry implementation, and start their relay DPoP root spans through one helper. That core keeps a `url(httpBaseUrl)` callback, which the raw helper passes as is; the typed wrapper builds it from upstream's contract URL builder, so a typed caller signs the URL the client sends. This keeps cookie, bearer, and relay DPoP with one refresh-and-retry shared without assigning J5 routes to an unrelated upstream API group, and no J5 read falls back to the primary environment. The upstream mount that remains (`CommandPalette.logic.ts`'s thread value, `thread::`) carries the environment beside the id so two environments' rows never collide; no new mount or door is added. Environment labels appear only once a read model spans more than one environment. The draft's Squadron environment lock went with the draft chip (the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): `ChatView.tsx`'s three environment-selection doors are upstream's again. Native mobile screens are deferred. On every rebase, verify the capability keys stay optional, the J5 request helper still goes through the shared authenticated transport, and the scoped identities survive in each recorded mount. + + Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read. Keep this subpath on upstream sync. Cases 10, 11 and 12 are retired, so no launch policy remains to verify here. Client permission guards (Jackson's 2026-10-08 decision 23; [#506](https://github.com/Jacksondr5/j5code/issues/506)). J5's protected actions are registered with upstream's guard and its controls read the guard's answer, as upstream's own do: case 64. A session without the operate scope cannot use Crew approve and decline, Crew runtime answers, Stop and Archive crew, Inbox answers, artifact delete, the playbook and persona library mutations or the skill mutations; peering needs `access:write`. The server remains the authority in every case. @@ -411,7 +413,7 @@ migrations after upstream migrations. The client's reads followed (step 3 of the issue, Jackson's 2026-10-11 go-ahead), by upstream's own rule: a small read is a socket query, and a large, compressible payload goes over HTTP (upstream's comment on its pull-request diff route in `environmentHttp.ts`). `packages/contracts/src/rpc.ts` gains one more `.merge(J5ClientReadRpcGroup)`: the Inbox list and open count, Crew proposals, Crew runtime requests, Crew memberships, the Fleet, spawned children, the archive preflight, participant identities and the peer list. The three playbook reads join `J5PlaybookRpcGroup` and the artifact list joins `J5ArtifactRpcGroup`. All need read scope, except the peer list, which needs `access:read` as its route did; none is guarded, because a guarded method cannot back a query. `ClientReadsService` serves them through `apps/server/src/j5/a2a/clientReadRpc.ts`, and `playbooks/WorkspacePlaybooks.ts` resolves the workspace a playbook request names for its read, export, delete and rename. Their routes are removed with no overlap, as the actions' were. On the client each is upstream's `createEnvironmentRpcQueryAtomFamily` or, for a one-off read, `createEnvironmentRpcCommand`; the per-route probe for a missing route is gone (case 34), and a server too old to have a read shows "This view needs a newer server." - Those reads are told when to run again by one change stream per environment, in place of the foreground timers they ran on ([#182](https://github.com/Jacksondr5/j5code/issues/182), the other half of step 3). `j5.reads.subscribeChanges` is a stream RPC in `J5ClientReadRpcGroup` with read scope. It carries five counters and never what changed: `inbox`, `crew`, `fleet`, `runtimeRequests` and `peers`, the whole record each time, starting with where they stand, so a client that reconnects sees a counter that moved while it was away. They restart with the server. J5-owned `apps/server/src/j5/a2a/ReadChanges.ts` holds them, as one layer object shared by reference in `runtimeLayer.ts` between the writers and the socket handler (it joins `J5WsRpcServices` in `apps/server/src/j5/wsRpc.ts`, so `ws.ts` is not edited), and coalesces a burst of writes into one message. `ReadChangeFeeds.ts` moves them from what the server already publishes: the ledger's committed events move `inbox` when an Exchange closes or is dropped and when a message to a person is delivered, cancelled or fails, `fleet` on every participant event and on an Exchange opening, closing or being dropped, and `peers` on a send to a peer server and on every delivery outcome (an outcome does not say whether its message waited for a peer), since the peer list counts each peer's waiting messages; the playbook store's revision moves `fleet`; the peer registry's `subscribeListChanges` moves `peers` after each write the peer list shows (a peer recorded, rotated, adopted or removed, a heartbeat, a changed last error or name, and a session issued for a peer, which `PeerAdminService` tells it of), and stays apart from the `subscribeChanges` the pollers follow, so a heartbeat reconciles no poller; and the orchestration event store moves `runtimeRequests` on `runtime-request.updated`, on an approval request among the `turn-item.updated` events, and on a thread being archived, unarchived or deleted. Two writers move a counter themselves: `SpawnCompositionService.recordFacts` moves `fleet`, because a placement on a thread that is already registered commits no ledger event, and `layerNotifying` in `AgentCrewProposalService.ts` and `AgentCrewInstanceService.ts` (the layers the server runs) moves `crew` after each write to a proposal, a Crew or its seats. On the client, `packages/client-runtime/src/rpc/client.ts` names the tag in `EnvironmentSubscriptionRpcTag` (its import and one union member, beside the artifact and playbook tags), and each read in `packages/client-runtime/src/j5/state.ts` names its counters as upstream's `refreshTrigger`, the pattern of `createLinkedPullRequestSummaryAtomFamily`: the Inbox list and open count follow `inbox`, Crew proposals `crew`, Crew runtime requests `crew` and `runtimeRequests`, the Fleet `crew` and `fleet`, and the peer list `peers`. A mounted read holds the subscription open, so a server that does not report `j5ProjectLedger`, whose reads are not made once its config has loaded (case 34), is not left subscribed to. The sidebar's Crew chips and spawned children are batched commands and not queries, so `createFleetRowRefresher` in `apps/web/src/j5/fleet/fleet.logic.ts` re-reads them after each roster read a moved counter caused: the chips on `crew`, the children on `crew` or `fleet`, for case 23's involved rows. None of these reads runs on a timer, and neither do the playbook reads, which follow the playbook store's own revision (`j5.playbooks.subscribeChanges`, case 45). That revision moves on each run mutation and resolved or targeted hand-off, on a definition renamed or deleted through the store, on a read that cancelled a run whose owner is gone (and on no other read, or each read would cause the next), and on a change on disk to the YAML an active run is shown from: J5-owned `apps/server/src/j5/playbooks/PlaybookDefinitionWatch.ts` follows the revision, watches each directory that holds an active run's definition, and stops when the directory's last run ends, so a server with no active run holds no file handle for it. A watch that fails or ends is not started again until its directory has no active run. Still without a signal: a renamed project; a playbook YAML file no active run uses, which the library reads each time it is opened; a peer's session revoked or expired in the auth database by another path; and a playbook directory deleted or replaced under an active run, whose watch is lost. Each of these views reads again when the tab is focused or shown, which also covers a server too old to have the stream. On rebase, keep `ReadChanges` one instance for every writer and the handler, and move a counter only after the write it reports has committed. + Those reads are told when to run again by one change stream per environment, in place of the foreground timers they ran on ([#182](https://github.com/Jacksondr5/j5code/issues/182), the other half of step 3). `j5.reads.subscribeChanges` is a stream RPC in `J5ClientReadRpcGroup` with read scope. It carries five counters and never what changed: `inbox`, `crew`, `fleet`, `runtimeRequests` and `peers`, the whole record each time, starting with where they stand, so a client that reconnects sees a counter that moved while it was away. They restart with the server. J5-owned `apps/server/src/j5/a2a/ReadChanges.ts` holds them, as one layer object shared by reference in `runtimeLayer.ts` between the writers and the socket handler (it joins `J5WsRpcServices` in `apps/server/src/j5/wsRpc.ts`, so `ws.ts` is not edited), and coalesces a burst of writes into one message. `ReadChangeFeeds.ts` moves them from what the server already publishes: the ledger's committed events move `inbox` when an Exchange closes or is dropped and when a message to a person is delivered, cancelled or fails, `fleet` on every participant event and on an Exchange opening, closing or being dropped, and `fleet` on an alarmed delivery failure or a cancellation; `peers` moves on a send to a peer server and on every delivery outcome (an outcome does not say whether its message waited for a peer), since the peer list counts each peer's waiting messages; the playbook store's revision moves `fleet`; the peer registry's `subscribeListChanges` moves `peers` after each write the peer list shows (a peer recorded, rotated, adopted or removed, a heartbeat, a changed last error or name, and a session issued for a peer, which `PeerAdminService` tells it of), and stays apart from the `subscribeChanges` the pollers follow, so a heartbeat reconciles no poller; and the orchestration event store moves `runtimeRequests` on `runtime-request.updated`, on an approval request among the `turn-item.updated` events, and on a thread being archived, unarchived or deleted. Two writers move a counter themselves: `SpawnCompositionService.recordFacts` moves `fleet`, because a placement on a thread that is already registered commits no ledger event, and `layerNotifying` in `AgentCrewProposalService.ts` and `AgentCrewInstanceService.ts` (the layers the server runs) moves `crew` after each write to a proposal, a Crew or its seats. On the client, `packages/client-runtime/src/rpc/client.ts` names the tag in `EnvironmentSubscriptionRpcTag` (its import and one union member, beside the artifact and playbook tags), and each read in `packages/client-runtime/src/j5/state.ts` names its counters as upstream's `refreshTrigger`, the pattern of `createLinkedPullRequestSummaryAtomFamily`: the Inbox list and open count follow `inbox`, Crew proposals `crew`, Crew runtime requests `crew` and `runtimeRequests`, the Fleet `crew` and `fleet`, and the peer list `peers`. A mounted read holds the subscription open, so a server that does not report `j5ProjectLedger`, whose reads are not made once its config has loaded (case 34), is not left subscribed to. The sidebar's Crew chips and spawned children are batched commands and not queries, so `createFleetRowRefresher` in `apps/web/src/j5/fleet/fleet.logic.ts` re-reads them after each roster read a moved counter caused: the chips on `crew`, the children on `crew` or `fleet`, for case 23's involved rows. None of these reads runs on a timer, and neither do the playbook reads, which follow the playbook store's own revision (`j5.playbooks.subscribeChanges`, case 45). That revision moves on each run mutation and resolved or targeted hand-off, on a definition renamed or deleted through the store, on a read that cancelled a run whose owner is gone (and on no other read, or each read would cause the next), and on a change on disk to the YAML an active run is shown from: J5-owned `apps/server/src/j5/playbooks/PlaybookDefinitionWatch.ts` follows the revision, watches each directory that holds an active run's definition, and stops when the directory's last run ends, so a server with no active run holds no file handle for it. A watch that fails or ends is not started again until its directory has no active run. Still without a signal: a renamed project; a playbook YAML file no active run uses, which the library reads each time it is opened; a peer's session revoked or expired in the auth database by another path; and a playbook directory deleted or replaced under an active run, whose watch is lost. Each of these views reads again when the tab is focused or shown, which also covers a server too old to have the stream. On rebase, keep `ReadChanges` one instance for every writer and the handler, and move a counter only after the write it reports has committed. Two things stay on HTTP for a client. Reading one artifact's content (`POST /api/j5/artifacts/read`) can be megabytes, up to the 5 MB artifact limit and a third more as base64, so it keeps case 34's request helper as that helper's only caller. `GET /api/j5/a2a/peers` stays for the `j5 a2a peer list` CLI and calls `PeerAdminService.list`, as the RPC does. diff --git a/apps/server/src/j5/a2a/ClientReadsService.ts b/apps/server/src/j5/a2a/ClientReadsService.ts index 49b95cd346cd5..f71376df080ed 100644 --- a/apps/server/src/j5/a2a/ClientReadsService.ts +++ b/apps/server/src/j5/a2a/ClientReadsService.ts @@ -24,6 +24,7 @@ import { A2AArchiveFacts } from "./ArchiveFactsService.ts"; import { makeCrewMembershipsRead } from "./crewMembershipsRead.ts"; import { projectCrewProposal } from "./crewProposalProjection.ts"; import { CrewRuntimeRequestService } from "./CrewRuntimeRequestService.ts"; +import { clientReadBatches } from "./clientReadBatches.ts"; import { makeFleetRead } from "./fleetRead.ts"; import { type A2AHumanInboxError, A2AHumanInbox } from "./HumanInboxService.ts"; import { A2ALedger } from "./LedgerService.ts"; @@ -93,20 +94,9 @@ interface QueryPlanRow { readonly detail: string; } -/** Leaves headroom under SQLite's bind-parameter ceiling for viewport-sized reads. */ -export const CLIENT_READ_PARTICIPANT_BATCH_SIZE = 900; - const uniqueInFirstOccurrenceOrder = (values: ReadonlyArray) => Array.from(new Set(values)); -const batchesOf = (values: ReadonlyArray) => { - const batches: Array> = []; - for (let index = 0; index < values.length; index += CLIENT_READ_PARTICIPANT_BATCH_SIZE) { - batches.push(values.slice(index, index + CLIENT_READ_PARTICIPANT_BATCH_SIZE)); - } - return batches; -}; - const unknownIdentity = (): DisplayIdentity => ({ kind: "unknown" }); const toIdentity = (row: IdentityRow | undefined): DisplayIdentity => { @@ -307,7 +297,7 @@ export const layer: Layer.Layer< const uniqueParticipantIds = uniqueInFirstOccurrenceOrder(input.participantIds); if (uniqueParticipantIds.length === 0) return { entries: [] }; const rows: Array = []; - for (const participantIdBatch of batchesOf(uniqueParticipantIds)) { + for (const participantIdBatch of clientReadBatches(uniqueParticipantIds)) { rows.push(...(yield* participantIdentityRows(sql, participantIdBatch))); // Machine senders have no thread; their display name is their registered name. rows.push( diff --git a/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts b/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts index 45a3593f37c0f..3acd2a79091c1 100644 --- a/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts +++ b/apps/server/src/j5/a2a/ReadChangeFeeds.test.ts @@ -54,10 +54,36 @@ it("maps each ledger event to the reads it puts out of date", () => { "message.delivery_failed", ] as const) { // An outcome does not say whether its message waited for a peer, so each moves the peer list. - assert.deepStrictEqual(changed(kind, person), ["inbox", "peers"], kind); - assert.deepStrictEqual(changed(kind, agent), ["peers"], kind); + assert.deepStrictEqual( + changed(kind, person), + kind === "message.cancelled" ? ["inbox", "fleet", "peers"] : ["inbox", "peers"], + kind, + ); + assert.deepStrictEqual( + changed(kind, agent), + kind === "message.cancelled" ? ["fleet", "peers"] : ["peers"], + kind, + ); // An event that names no receiver is counted rather than missed. - assert.deepStrictEqual(changed(kind, null), ["inbox", "peers"], kind); + assert.deepStrictEqual( + changed(kind, null), + kind === "message.cancelled" ? ["inbox", "fleet", "peers"] : ["inbox", "peers"], + kind, + ); + } + for (const receiver of [person, agent, null]) { + assert.deepStrictEqual( + readsChangedByLedgerEvent( + ledgerEvent("message.delivery_failed", receiver, { alarmed: true }), + ), + receiver === agent ? ["fleet", "peers"] : ["inbox", "fleet", "peers"], + ); + assert.deepStrictEqual( + readsChangedByLedgerEvent( + ledgerEvent("message.delivery_failed", receiver, { alarmed: false }), + ), + receiver === agent ? ["peers"] : ["inbox", "peers"], + ); } for (const kind of ["message.sent", "message.received", "silence.notice"] as const) assert.deepStrictEqual(changed(kind, person), [], kind); diff --git a/apps/server/src/j5/a2a/ReadChangeFeeds.ts b/apps/server/src/j5/a2a/ReadChangeFeeds.ts index 9bad178d6803b..5cf763616a414 100644 --- a/apps/server/src/j5/a2a/ReadChangeFeeds.ts +++ b/apps/server/src/j5/a2a/ReadChangeFeeds.ts @@ -46,12 +46,22 @@ export const readsChangedByLedgerEvent = ( return ["inbox", "fleet"]; case "exchange.opened": return ["fleet"]; + // Fleet changes only when an alarm appears or is cancelled; an alarm is never retried. // The peer list counts the messages waiting for each peer. An outcome does not say whether // its message was for a peer, so each one counts while this server has a peer; the daemon // below drops `peers` while it has none. - case "message.delivered": case "message.cancelled": + return reachesPerson(event) ? ["inbox", "fleet", "peers"] : ["fleet", "peers"]; case "message.delivery_failed": + if ( + typeof event.payload === "object" && + event.payload !== null && + "alarmed" in event.payload && + event.payload.alarmed === true + ) + return reachesPerson(event) ? ["inbox", "fleet", "peers"] : ["fleet", "peers"]; + return reachesPerson(event) ? ["inbox", "peers"] : ["peers"]; + case "message.delivered": return reachesPerson(event) ? ["inbox", "peers"] : ["peers"]; case "message.sent": return sentToPeer(event) ? ["peers"] : []; diff --git a/apps/server/src/j5/a2a/clientReadBatches.ts b/apps/server/src/j5/a2a/clientReadBatches.ts new file mode 100644 index 0000000000000..a4826495e3a5c --- /dev/null +++ b/apps/server/src/j5/a2a/clientReadBatches.ts @@ -0,0 +1,10 @@ +/** Leaves headroom under SQLite's bind ceiling for the other fields in a client read. */ +const PARTICIPANT_BATCH_SIZE = 900; + +export const clientReadBatches = (values: ReadonlyArray) => { + const batches: Array> = []; + for (let index = 0; index < values.length; index += PARTICIPANT_BATCH_SIZE) { + batches.push(values.slice(index, index + PARTICIPANT_BATCH_SIZE)); + } + return batches; +}; diff --git a/apps/server/src/j5/a2a/fleetFacts.test.ts b/apps/server/src/j5/a2a/fleetFacts.test.ts new file mode 100644 index 0000000000000..8a901827d5a8d --- /dev/null +++ b/apps/server/src/j5/a2a/fleetFacts.test.ts @@ -0,0 +1,205 @@ +import { assert, it } from "@effect/vitest"; +import { ThreadId } from "@t3tools/contracts"; +import * as Layer from "effect/Layer"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; + +import { runMigrations } from "../../persistence/Migrations.ts"; +import { runJ5A2AMigrations } from "./Migrations.ts"; +import { A2ALedger } from "./LedgerService.ts"; +import { ParticipantPlacementService } from "./PlacementService.ts"; +import { AgentCrewInstanceService } from "./AgentCrewInstanceService.ts"; +import { PlaybookCrewRelay } from "../playbooks/PlaybookCrewRelay.ts"; +import { CREW_ALERT_EXCHANGE_PREFIX } from "./crewFailureAlert.ts"; +import { makeFleetRead } from "./fleetRead.ts"; +import { LedgerProjectId, ParticipantId } from "./contracts.ts"; +import type { ParticipantPlacementView } from "./placementContracts.ts"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; + +const database = NodeSqliteClient.layer({ filename: ":memory:" }); +const sender = "agent:sender"; +const receiver = "agent:receiver"; +const at = "2026-10-19T10:00:00.000Z"; + +it.effect( + "reads both ask directions across projects and keeps local/remote alarms on their sender", + () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + for (const project of ["p", "other"]) + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES (${project}, ${at})`; + const exchange = Effect.fnUntraced(function* ( + id: string, + project: string, + from: string, + to: string, + ) { + yield* sql`INSERT INTO j5_a2a_exchange ( + project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at + ) VALUES (${project}, ${id}, ${from}, ${to}, 'open', ${id}, 1, ${at}, ${at})`; + }); + yield* exchange("outgoing", "p", sender, receiver); + yield* exchange("incoming", "other", "human:operator", sender); + const alarm = Effect.fnUntraced(function* ( + id: string, + channel: string, + exchangeId: string | null, + remote: string | null = null, + status = "alarmed", + receiverId = receiver, + ) { + yield* sql`INSERT INTO j5_a2a_delivery ( + project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, correlation_id, message_text, status, attempts, last_error, + created_at, updated_at, envelope_channel, receiver_environment_id + ) VALUES ('p', ${id}, ${id}, 1, ${sender}, ${receiverId}, 'p', ${exchangeId}, + ${exchangeId === null ? "none" : "followup"}, ${id}, 'hello', ${status}, 3, 'transport unavailable', + ${at}, ${at}, ${channel}, ${remote})`; + }); + const platformExchange = `${CREW_ALERT_EXCHANGE_PREFIX}crew/run`; + yield* exchange(platformExchange, "p", sender, "human:operator"); + yield* alarm("platform-alert", "peer", platformExchange, null, "alarmed", "human:operator"); + yield* alarm("local-ask", "peer", "outgoing"); + yield* alarm("remote-ask", "peer", "outgoing", "remote-env"); + yield* alarm("plain", "peer", null); + yield* alarm("silence", "silence_notice", null); + yield* alarm("lifecycle", "lifecycle_notice", null); + yield* alarm("retry", "peer", null, null, "retry_scheduled"); + yield* alarm("delivered", "peer", null, null, "delivered"); + const read = () => + readFleetLedgerFacts(sql, "p", [sender, receiver], (id) => + id === receiver ? "Receiver" : null, + ); + const before = yield* read(); + assert.equal(before.owed.get(sender)?.length, 1); + assert.equal(before.owed.get(receiver)?.length, 1); + assert.deepStrictEqual(before.awaited.get(sender), [ + { + exchangeId: "outgoing", + counterpartyId: receiver, + counterpartyName: "Receiver", + intent: "outgoing", + openedAt: at, + }, + ]); + assert.deepStrictEqual( + before.problems + .get(sender) + ?.map( + (problem) => + problem.kind === "delivery-failed" && [problem.messageId, problem.exchangeOpen], + ), + [ + ["local-ask", true], + ["plain", false], + ["remote-ask", true], + ], + ); + assert.isUndefined(before.problems.get(receiver)); + yield* sql`UPDATE j5_a2a_exchange SET status = 'closed' WHERE exchange_id = 'outgoing'`; + const closed = yield* read(); + assert.isUndefined(closed.awaited.get(sender)); + assert.equal(closed.problems.get(sender)?.length, 3); + assert.isTrue( + closed.problems + .get(sender)! + .every((problem) => problem.kind === "delivery-failed" && !problem.exchangeOpen), + ); + yield* sql`UPDATE j5_a2a_delivery SET status = 'cancelled' WHERE message_id = 'local-ask'`; + assert.equal((yield* read()).problems.get(sender)?.length, 2); + assert.equal( + (yield* readFleetLedgerFacts(sql, "other", [sender], () => null)).problems.size, + 0, + ); + yield* sql`INSERT INTO j5_a2a_human_person + (person_id, is_local_operator, created_at, kind, display_name, name_key) + VALUES ('human:operator', 1, ${at}, 'member', 'Operator', 'operator')`; + const participant = (id: string, project: string): ParticipantPlacementView => ({ + projectId: LedgerProjectId.make(project), + participantId: ParticipantId.make(id), + participant: { + kind: "agent", + id: ParticipantId.make(id), + threadId: ThreadId.make(id), + }, + threadId: ThreadId.make(id), + provenance: { kind: "unrecorded" }, + placementParentId: null, + }); + yield* sql`INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + active_provider_thread_id, created_at, updated_at, archived_at, deleted_at, payload_json + ) VALUES (${receiver}, 'other', 'Remote receiver', 'codex', 'full-access', 'default', + NULL, ${at}, ${at}, NULL, NULL, '{}')`; + const fleetRead = yield* makeFleetRead.pipe( + Effect.provide( + Layer.mergeAll( + Layer.mock(A2ALedger)({ + listProjectLedgers: () => + Effect.succeed([ + { id: LedgerProjectId.make("p"), name: "P", createdAt: at }, + { id: LedgerProjectId.make("other"), name: "Other", createdAt: at }, + ]), + }), + Layer.mock(ParticipantPlacementService)({ + listParticipants: (project) => + Effect.succeed([ + project === "p" ? participant(sender, "p") : participant(receiver, "other"), + ]), + }), + Layer.mock(AgentCrewInstanceService)({ listForProject: () => Effect.succeed([]) }), + Layer.mock(PlaybookCrewRelay)({}), + ), + ), + ); + const snapshot = yield* fleetRead(false); + assert.equal(snapshot.asOf, "1970-01-01T00:00:00.000Z"); + assert.equal(snapshot.projects[0]?.agents[0]?.facts?.asks.owed.length, 1); + assert.equal( + snapshot.projects[0]?.agents[0]?.facts?.asks.owed[0]?.counterpartyName, + "Operator", + ); + assert.equal(snapshot.projects[0]?.agents[0]?.facts?.problems.length, 2); + assert.deepStrictEqual( + snapshot.projects[0]?.agents[0]?.facts?.problems.map( + (problem) => problem.kind === "delivery-failed" && problem.receiverName, + ), + ["Remote receiver", "Remote receiver"], + ); + }).pipe(Effect.provide(database)), +); + +it.effect( + "reads beyond SQLite's unbatched bind limit without duplicating cross-project Exchanges", + () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + const agents = Array.from({ length: 17_000 }, (_, index) => `agent:${index}`); + for (const project of ["p", "other"]) { + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES (${project}, ${at})`; + yield* sql`INSERT INTO j5_a2a_exchange ( + project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at + ) VALUES (${project}, 'shared', ${agents[0]!}, ${agents[900]!}, 'open', ${project}, 1, ${at}, ${at})`; + } + for (const id of [agents[0]!, agents.at(-1)!]) { + yield* sql`INSERT INTO j5_a2a_delivery ( + project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, correlation_id, message_text, status, attempts, last_error, + created_at, updated_at, envelope_channel + ) VALUES ('p', ${id}, ${id}, 1, ${id}, 'agent:remote', 'other', NULL, + 'none', ${id}, 'hello', 'alarmed', 3, 'transport unavailable', ${at}, ${at}, 'peer')`; + } + // Binding these ids in both directions together would exceed SQLite's 32,766 variable ceiling. + const facts = yield* readFleetLedgerFacts(sql, "p", agents, () => null); + assert.equal(facts.awaited.get(agents[0]!)?.length, 2); + assert.equal(facts.owed.get(agents[900]!)?.length, 2); + assert.equal(facts.problems.get(agents[0]!)?.length, 1); + assert.equal(facts.problems.get(agents.at(-1)!)?.length, 1); + assert.isNull(facts.awaited.get(agents[0]!)?.[0]?.counterpartyName); + }).pipe(Effect.provide(database)), +); diff --git a/apps/server/src/j5/a2a/fleetFacts.ts b/apps/server/src/j5/a2a/fleetFacts.ts new file mode 100644 index 0000000000000..b767182ac6837 --- /dev/null +++ b/apps/server/src/j5/a2a/fleetFacts.ts @@ -0,0 +1,105 @@ +import type { FleetAgentFacts, FleetProblem } from "@t3tools/contracts/j5"; +import * as Effect from "effect/Effect"; +import type * as SqlClient from "effect/sql/SqlClient"; + +import { CREW_ALERT_EXCHANGE_PREFIX } from "./crewFailureAlert.ts"; +import { clientReadBatches } from "./clientReadBatches.ts"; + +type Ask = FleetAgentFacts["asks"]["owed"][number]; +type ExchangeRow = { + readonly project_id: string; + readonly exchange_id: string; + readonly sender_id: string; + readonly receiver_id: string; + readonly intent: string; + readonly created_at: string; +}; +type AlarmRow = { + readonly sender_id: string; + readonly receiver_id: string; + readonly message_id: string; + readonly updated_at: string; + readonly last_error: string | null; + readonly exchange_open: number; +}; + +/** Both directions span project boundaries: the Exchange lives with its sender. */ +export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* ( + sql: SqlClient.SqlClient, + projectId: string, + agentIds: ReadonlyArray, + nameOf: (id: string) => string | null, +) { + const owed = new Map>(); + const awaited = new Map>(); + const problems = new Map>(); + if (agentIds.length === 0) return { owed, awaited, problems }; + const batches = clientReadBatches([...new Set(agentIds)]); + const exchanges = new Map>(); + for (const batch of batches) { + for (const column of ["sender_id", "receiver_id"]) { + const rows = yield* sql` + SELECT project_id, exchange_id, sender_id, receiver_id, intent, created_at + FROM j5_a2a_exchange + WHERE status = 'open' AND ${sql(column)} IN ${sql.in(batch)} + AND exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`} + `; + for (const row of rows) { + const projectExchanges = exchanges.get(row.project_id) ?? new Map(); + projectExchanges.set(row.exchange_id, row); + exchanges.set(row.project_id, projectExchanges); + } + } + } + const orderedExchanges = [...exchanges.values()] + .flatMap((rows) => [...rows.values()]) + .toSorted( + (left, right) => + left.created_at.localeCompare(right.created_at) || + left.exchange_id.localeCompare(right.exchange_id) || + left.project_id.localeCompare(right.project_id), + ); + for (const row of orderedExchanges) { + const ask = (counterpartyId: string): Ask => ({ + exchangeId: row.exchange_id, + counterpartyId, + counterpartyName: nameOf(counterpartyId), + intent: row.intent, + openedAt: row.created_at, + }); + const senderAsks = awaited.get(row.sender_id) ?? []; + senderAsks.push(ask(row.receiver_id)); + awaited.set(row.sender_id, senderAsks); + const receiverAsks = owed.get(row.receiver_id) ?? []; + receiverAsks.push(ask(row.sender_id)); + owed.set(row.receiver_id, receiverAsks); + } + // `peer` is the authored envelope channel, including local delivery. Platform notices have + // their own channels and must never surface as an agent's problem (Fleet AC24). + for (const batch of batches) { + const alarms = yield* sql` + SELECT d.sender_id, d.receiver_id, d.message_id, d.updated_at, d.last_error, + EXISTS (SELECT 1 FROM j5_a2a_exchange e WHERE e.project_id = d.project_id + AND e.exchange_id = d.exchange_id AND e.status = 'open') AS exchange_open + FROM j5_a2a_delivery d + WHERE d.project_id = ${projectId} AND d.sender_id IN ${sql.in(batch)} + AND d.status = 'alarmed' AND d.envelope_channel = 'peer' + AND (d.exchange_id IS NULL OR d.exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`}) + ORDER BY d.sent_seq, d.message_id + `; + for (const row of alarms) { + const senderProblems = problems.get(row.sender_id) ?? []; + senderProblems.push({ + kind: "delivery-failed", + messageId: row.message_id, + receiverId: row.receiver_id, + receiverName: nameOf(row.receiver_id), + at: row.updated_at, + reason: row.last_error, + exchangeOpen: row.exchange_open === 1, + }); + problems.set(row.sender_id, senderProblems); + } + } + return { owed, awaited, problems }; +}); diff --git a/apps/server/src/j5/a2a/fleetRead.ts b/apps/server/src/j5/a2a/fleetRead.ts index eea4706ade006..97673851b6d06 100644 --- a/apps/server/src/j5/a2a/fleetRead.ts +++ b/apps/server/src/j5/a2a/fleetRead.ts @@ -1,3 +1,4 @@ +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as J5Contracts from "@t3tools/contracts/j5"; import * as SqlClient from "effect/sql/SqlClient"; @@ -7,6 +8,9 @@ import { AgentCrewInstanceService, type AgentCrewInstance } from "./AgentCrewIns import { A2ALedger } from "./LedgerService.ts"; import { ParticipantPlacementService } from "./PlacementService.ts"; import { LedgerProjectId, isOutsideAgentParticipantId } from "./contracts.ts"; +import { listRegisteredHumanPersonNames } from "./HumanPersonRegistry.ts"; +import { clientReadBatches } from "./clientReadBatches.ts"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; import { outsideAgentNameRows } from "./outsideAgentNames.ts"; import type { ParticipantPlacementView } from "./placementContracts.ts"; @@ -23,6 +27,7 @@ export const projectFleetProject = (input: { readonly participants: ReadonlyArray; readonly crews: ReadonlyArray; readonly openAsks: ReadonlyMap; + readonly facts?: ReadonlyMap; /** Each live Crew's active playbook run, by Crew id. */ readonly playbookRuns?: ReadonlyMap; /** The label of each outside agent that spawned one of the participants, by its id. */ @@ -62,6 +67,9 @@ export const projectFleetProject = (input: { placementParentId: crew.captainParticipantId, crew: seatByParticipant.get(member.participantId) ?? null, openAsks: 0, + ...(input.facts === undefined + ? {} + : { facts: { asks: { owed: [], awaited: [] }, problems: [] } }), })), ); return { @@ -97,6 +105,9 @@ export const projectFleetProject = (input: { : {}), crew: seatByParticipant.get(row.participantId) ?? null, openAsks: input.openAsks.get(row.participantId) ?? 0, + ...(input.facts?.has(row.participantId) + ? { facts: input.facts.get(row.participantId)! } + : {}), })), ...unrecordedSeats, ], @@ -130,8 +141,7 @@ export const projectFleetProject = (input: { /** * The Roster read (SB6): every project with its active agents, placement parents, Crew seats, - * and the count of open asks each agent owes. Status and last activity come from the client's - * thread state, so this read carries only what the ledger knows. Unknowns stay unknown. + * and open Exchanges and delivery alarms. Runtime facts stay on the live shell stream. */ export const makeFleetRead = Effect.gen(function* () { const ledger = yield* A2ALedger; @@ -143,20 +153,39 @@ export const makeFleetRead = Effect.gen(function* () { Effect.gen(function* () { const projects = yield* ledger.listProjectLedgers(); const result: Array = []; + const participantsByProject = new Map>(); + const names = yield* listRegisteredHumanPersonNames(sql); for (const project of projects) { const participants = yield* placements.listParticipants(project.id); + participantsByProject.set(project.id, participants); + for (const row of participants) { + if ("displayName" in row.participant && typeof row.participant.displayName === "string") + names.set(row.participantId, row.participant.displayName); + } + } + const agents = [...participantsByProject.values()] + .flat() + .filter((row) => row.threadId !== null); + const threadIds = [ + ...new Set(agents.flatMap((row) => (row.threadId === null ? [] : [row.threadId]))), + ]; + const threadNames = new Map(); + for (const batch of clientReadBatches(threadIds)) { + const titles = yield* sql<{ readonly thread_id: string; readonly title: string }>` + SELECT thread_id, title FROM orchestration_v2_projection_threads + WHERE thread_id IN ${sql.in(batch)} + `; + for (const row of titles) threadNames.set(row.thread_id, row.title); + } + for (const row of agents) { + const title = row.threadId === null ? undefined : threadNames.get(row.threadId); + if (title !== undefined) names.set(row.participantId, title); + } + for (const project of projects) { + const participants = participantsByProject.get(project.id)!; const agentIds = participants .filter((row) => row.participant.kind === "agent") .map((row) => row.participantId); - const openAsks = new Map(); - if (agentIds.length > 0) { - const rows = yield* sql<{ readonly receiver_id: string; readonly count: number }>` - SELECT receiver_id, COUNT(*) AS count FROM j5_a2a_exchange - WHERE status = 'open' AND receiver_id IN ${sql.in([...agentIds])} - GROUP BY receiver_id - `; - for (const row of rows) openAsks.set(row.receiver_id, Number(row.count)); - } const outsideSpawnerIds = [ ...new Set( participants.flatMap((row) => @@ -170,9 +199,30 @@ export const makeFleetRead = Effect.gen(function* () { const outsideAgentNames = new Map( (outsideSpawnerIds.length === 0 ? [] - : yield* outsideAgentNameRows(sql, outsideSpawnerIds) + : yield* Effect.forEach(clientReadBatches(outsideSpawnerIds), (batch) => + outsideAgentNameRows(sql, batch), + ).pipe(Effect.map((batches) => batches.flat())) ).map((row) => [row.participant_id, row.display_name] as const), ); + const ledgerFacts = yield* readFleetLedgerFacts( + sql, + project.id, + agentIds, + (id) => names.get(id) ?? outsideAgentNames.get(id) ?? null, + ); + const facts = new Map( + agentIds.map((id) => [ + id, + { + asks: { + owed: ledgerFacts.owed.get(id) ?? [], + awaited: ledgerFacts.awaited.get(id) ?? [], + }, + problems: ledgerFacts.problems.get(id) ?? [], + }, + ]), + ); + const openAsks = new Map(agentIds.map((id) => [id, ledgerFacts.owed.get(id)?.length ?? 0])); // Retired Crews carry rosters and briefs; only the page that shows them pays for them. const projectCrews = (yield* crews.listForProject(project.id)).filter( (crew) => includeRetired || crew.archivedAt === null, @@ -187,11 +237,15 @@ export const makeFleetRead = Effect.gen(function* () { participants, crews: projectCrews, openAsks, + facts, playbookRuns, outsideAgentNames, }), ); } - return { projects: result } satisfies FleetResponse; + return { + projects: result, + asOf: DateTime.formatIso(yield* DateTime.now), + } satisfies FleetResponse; }); }); diff --git a/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts b/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts index 6f3cec4c7437b..48ff0dd9c9f8b 100644 --- a/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts +++ b/apps/server/src/j5/run-observability/QueuedRunWatchdog.ts @@ -3,6 +3,7 @@ import { type OrchestrationV2Run, type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; +import { FLEET_DISPATCH_THRESHOLD_MS } from "@t3tools/contracts/j5"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -21,7 +22,7 @@ import { import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import { forkParked } from "../../serverActivation.ts"; -export const QUEUED_RUN_WATCHDOG_DELAY_MS = 5 * 60 * 1000; +export const QUEUED_RUN_WATCHDOG_DELAY_MS = FLEET_DISPATCH_THRESHOLD_MS; export const QUEUED_RUN_WATCHDOG_POLL_MS = 60 * 1000; export const QUEUED_RUN_WATCHDOG_MAX_CANDIDATES = 100; diff --git a/docs/j5/product/features/fleet-page.md b/docs/j5/product/features/fleet-page.md index c1c348d150c0d..f3a9418404da7 100644 --- a/docs/j5/product/features/fleet-page.md +++ b/docs/j5/product/features/fleet-page.md @@ -75,7 +75,7 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### The four facts -15. Status shows the runtime's own fact: Working, Waiting, Approval, Input or Failed; "Waiting to start · Nm" takes precedence while a run has been requested and not dispatched; "Idle since ⟨time⟩" appears only when nothing is active and no background work remains. +15. Status shows the runtime's own fact: Working, Waiting, Approval, Input or Failed; "Waiting to start · Nm" takes precedence while a run has been requested and not dispatched and no other run is in progress; a follow-up queued behind an active run keeps that active run's status. "Idle since ⟨time⟩" appears only when nothing is active and no background work holds completion; a non-holding command such as a dev server does not prevent Idle. 16. Read and snooze bookkeeping (upstream's Woke and Done) is not a status and does not appear. 17. Silence notices are not shown on the page; the age of an open ask is the visible fact. 18. Open asks show two counts, "Owes N" for open asks the agent must answer and "Awaiting N" for open asks it is waiting on, with a hover list of counterparty, intent and age; a follow-up joined to an open Exchange counts once. @@ -84,7 +84,7 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### Problems and the badge -21. A row's measured problems are a failed latest run, a delivery alarm, and a run that has waited past the dispatch threshold; the row lists every one it has. +21. A row's measured problems are a failed latest run, a delivery alarm, and a requested run that has waited past the dispatch threshold with no other run in progress; the row lists every one it has. 22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). 23. The badge counts agents that have at least one measured problem across every project the page reads; an agent counts once however many problems it has, unknowns never count, and the badge never counts open asks to the person or silence notices. 24. A delivery alarm counts toward the badge only while the Exchange it belongs to is open; an alarm on a plain message is shown on the row and never counted; a failed delivery of a platform-authored notice is neither shown nor counted. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fc319d0ceb421..0d419f852d532 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -375,6 +375,10 @@ "types": "./src/j5/http.ts", "default": "./src/j5/http.ts" }, + "./j5/fleetFacts": { + "types": "./src/j5/fleetFacts.ts", + "default": "./src/j5/fleetFacts.ts" + }, "./j5/state": { "types": "./src/j5/state.ts", "default": "./src/j5/state.ts" diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts new file mode 100644 index 0000000000000..6338a86b04d78 --- /dev/null +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -0,0 +1,348 @@ +import { describe, expect, it, vi, afterEach } from "vite-plus/test"; +import { RunId, RuntimeRequestId, type OrchestrationV2ThreadShell } from "@t3tools/contracts"; +import { + FleetResponse, + FLEET_DISPATCH_THRESHOLD_MS, + type FleetAgentFacts, +} from "@t3tools/contracts/j5"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; +import { Atom, AtomRegistry } from "effect/reactivity"; + +import { v2ThreadShell } from "../state/orchestrationV2TestFixtures.ts"; +import { createFleetFactsAtom, deriveFleetFacts, type FleetFactRow } from "./fleetFacts.ts"; + +const decodeFleet = Schema.decodeUnknownSync(FleetResponse); + +const at = "2026-10-19T10:00:00.000Z"; +const now = Date.parse(at); +const date = DateTime.makeUnsafe(at); +const ledger: FleetAgentFacts = { asks: { owed: [], awaited: [] }, problems: [] }; +const shell = (changes: Partial = {}): OrchestrationV2ThreadShell => ({ + ...v2ThreadShell, + latestRunId: RunId.make("r"), + status: "starting", + latestRunRequestedAt: date, + latestRunStartedAt: null, + latestRunCompletedAt: null, + activityRunStatus: "starting", + pendingBackgroundTasks: [], + ...changes, +}); +const derive = (source: OrchestrationV2ThreadShell | undefined, clock = now) => + deriveFleetFacts({ shell: source, ledger, now: clock }); + +afterEach(() => vi.useRealTimers()); + +describe("Fleet runtime measurements", () => { + it("crosses the exact dispatch boundary once and recovers immediately when dispatched", () => { + const before = derive(shell(), now + FLEET_DISPATCH_THRESHOLD_MS - 1); + expect(before.facts.runtime).toMatchObject({ status: "waiting-to-start" }); + expect(before.nextDeadline).toBe(now + FLEET_DISPATCH_THRESHOLD_MS); + expect(before.facts.problems).toEqual([]); + const due = derive(shell(), now + FLEET_DISPATCH_THRESHOLD_MS); + expect(due.facts.problems).toEqual([{ kind: "dispatch-overdue", runId: "r", at }]); + expect(due.nextDeadline).toBeUndefined(); + expect(derive(shell(), now + 900_000).nextDeadline).toBeUndefined(); + const dispatched = derive( + shell({ status: "running", activityRunStatus: "running", latestRunStartedAt: date }), + now + 900_000, + ); + expect(dispatched.facts.runtime).toMatchObject({ status: "working" }); + expect(dispatched.facts.problems).toEqual([]); + }); + + it("preserves raw runtime activity when an older shell omits activityRunStatus", () => { + const source = shell({ + status: "running", + activeRunId: RunId.make("r"), + latestRunStartedAt: date, + activityRunStatus: undefined, + }); + expect(derive(source).facts.runtime).toMatchObject({ + state: "known", + status: "working", + settled: false, + }); + expect(derive({ ...source, status: "waiting" }).facts.runtime).toMatchObject({ + status: "waiting", + }); + expect(derive({ ...source, status: "preparing" }).facts.runtime).toMatchObject({ + status: "waiting", + }); + }); + + it("gives undispatched work precedence over approval, then follows input and background state", () => { + const pending = { + id: RuntimeRequestId.make("approval"), + kind: "command" as const, + createdAt: date, + }; + expect(derive(shell({ pendingRuntimeRequest: pending })).facts.runtime).toMatchObject({ + status: "waiting-to-start", + }); + const started = shell({ + latestRunStartedAt: date, + activityRunStatus: "running", + status: "running", + pendingRuntimeRequest: pending, + }); + expect(derive(started).facts.runtime).toMatchObject({ status: "approval" }); + expect( + derive({ ...started, pendingRuntimeRequest: { ...pending, kind: "user_input" } }).facts + .runtime, + ).toMatchObject({ status: "input" }); + expect( + derive( + shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + pendingBackgroundTasks: [{ kind: "background_task", taskId: "background" }], + settledAt: date, + }), + ).facts.runtime, + ).toMatchObject({ status: "waiting", settled: false }); + expect( + derive( + shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + settledAt: date, + }), + ).facts.runtime, + ).toMatchObject({ status: "idle", since: at, settled: true }); + }); + + it("leaves queued follow-ups behind another run Working, Approval or Input without a deadline", () => { + const queued = shell({ + status: "queued", + activeRunId: RunId.make("earlier"), + activityRunStatus: "running", + }); + const overdueClock = now + FLEET_DISPATCH_THRESHOLD_MS * 2; + expect(derive(queued, overdueClock)).toMatchObject({ + facts: { runtime: { status: "working" }, problems: [] }, + }); + expect(derive(queued, overdueClock).nextDeadline).toBeUndefined(); + const pending = { + id: RuntimeRequestId.make("request"), + kind: "command" as const, + createdAt: date, + }; + expect( + derive({ ...queued, pendingRuntimeRequest: pending }, overdueClock).facts.runtime, + ).toMatchObject({ status: "approval" }); + expect( + derive({ ...queued, pendingRuntimeRequest: { ...pending, kind: "user_input" } }, overdueClock) + .facts.runtime, + ).toMatchObject({ status: "input" }); + expect( + derive({ ...queued, activityRunStatus: "waiting", activeRunId: null }, overdueClock), + ).toMatchObject({ facts: { runtime: { status: "waiting" }, problems: [] } }); + const alone = shell({ status: "queued", activeRunId: null, activityRunStatus: null }); + expect(derive(alone, now + FLEET_DISPATCH_THRESHOLD_MS - 1).facts.problems).toEqual([]); + expect(derive(alone, now + FLEET_DISPATCH_THRESHOLD_MS).facts.problems).toEqual([ + { kind: "dispatch-overdue", runId: "r", at }, + ]); + }); + + it("lets non-holding commands remain idle and reports holding background work as Waiting", () => { + const completed = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }); + expect( + derive({ ...completed, pendingBackgroundTasks: [{ kind: "command", taskId: "dev-server" }] }) + .facts.runtime, + ).toMatchObject({ status: "idle", since: at }); + for (const kind of ["subagent", "monitor", "background_task"] as const) { + expect( + derive({ ...completed, pendingBackgroundTasks: [{ kind, taskId: "work" }] }).facts.runtime, + ).toMatchObject({ status: "waiting", settled: false }); + } + }); + + it("clears failed-latest-run when a healthy latest run replaces it", () => { + const failed = shell({ + status: "failed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }); + expect(derive(failed).facts.problems).toEqual([{ kind: "failed-run", runId: "r", at }]); + expect(derive({ ...failed, latestRunCompletedAt: null }).facts.problems).toEqual([ + { kind: "failed-run", runId: "r", at: null }, + ]); + expect( + derive({ ...failed, status: "completed", latestRunCompletedAt: null }).facts.runtime, + ).toMatchObject({ + state: "unknown", + reason: "The latest run has no measured completion time.", + }); + expect(derive({ ...failed, status: "completed" }).facts.problems).toEqual([]); + expect(derive({ ...failed, status: "completed" }).facts.runtime).toMatchObject({ + status: "idle", + }); + }); + + it("ignores bookkeeping updatedAt and labels the latest measured event", () => { + const source = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + updatedAt: DateTime.makeUnsafe(now + 60_000), + settledAt: DateTime.makeUnsafe(now + 60_000), + }); + expect(derive(source).facts.lastActivity).toEqual({ state: "known", label: "Turn ended", at }); + expect(derive({ ...source, latestRunCompletedAt: undefined }).facts.lastActivity).toEqual({ + state: "unknown", + reason: "This environment does not report run timestamps.", + }); + }); + + it("keeps known delivery facts when runtime is missing and leaves old ledger facts absent", () => { + const alarm = { + kind: "delivery-failed" as const, + messageId: "m", + receiverId: "other", + receiverName: null, + at, + reason: "offline", + exchangeOpen: true, + }; + const missing = deriveFleetFacts({ + shell: undefined, + ledger: { ...ledger, problems: [alarm] }, + now, + }); + expect(missing.facts.runtime.state).toBe("unknown"); + expect(missing.facts.problems).toEqual([alarm]); + const old = decodeFleet({ + projects: [ + { + id: "p", + title: "P", + crews: [], + agents: [ + { + participantId: "a", + threadId: "t", + displayName: null, + origin: "human", + placementParentId: null, + crew: null, + openAsks: 4, + }, + ], + }, + ], + }); + expect(old.asOf).toBeUndefined(); + expect(old.projects[0]!.agents[0]!.facts).toBeUndefined(); + expect( + deriveFleetFacts({ shell: shell(), ledger: old.projects[0]!.agents[0]!.facts, now }).facts + .asks, + ).toBeUndefined(); + }); +}); + +it("shares one local deadline across consumers, clears stale/removed rows, and never rereads ledger", () => { + vi.useFakeTimers(); + vi.setSystemTime(now); + const rows = Atom.make>([ + { key: "env-a:a", shell: shell(), ledger, live: true }, + { + key: "env-b:a", + shell: shell({ latestRunRequestedAt: DateTime.makeUnsafe(now + 1_000) }), + ledger, + live: true, + }, + ]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); + const callback = vi.fn(); + const first = registry.subscribe(facts, callback, { immediate: true }); + const second = registry.subscribe(facts, callback, { immediate: true }); + vi.advanceTimersByTime(0); + const timerCount = vi.getTimerCount(); + expect(timerCount).toBe(1); + const unchanged = registry.get(facts).get("env-a:a"); + registry.set( + rows, + registry + .get(rows) + .map((row) => + row.key === "env-b:a" ? { ...row, shell: { ...row.shell!, title: "Renamed" } } : row, + ), + ); + expect(registry.get(facts).get("env-a:a")).toBe(unchanged); + vi.advanceTimersByTime(FLEET_DISPATCH_THRESHOLD_MS); + expect(registry.get(facts).get("env-a:a")!.problems).toHaveLength(1); + expect(registry.get(facts).get("env-b:a")!.problems).toHaveLength(0); + expect(vi.getTimerCount()).toBe(1); + registry.set( + rows, + registry.get(rows).map((row) => ({ ...row, live: false })), + ); + vi.advanceTimersByTime(0); + expect(vi.getTimerCount()).toBe(0); + registry.set(rows, []); + expect(registry.get(facts).size).toBe(0); + first(); + second(); + registry.dispose(); +}); + +it("does not advance offline dispatch facts when unrelated live rows change", () => { + vi.useFakeTimers(); + vi.setSystemTime(now); + const alarm = { + kind: "delivery-failed" as const, + messageId: "m", + receiverId: "other", + receiverName: null, + at, + reason: "offline", + exchangeOpen: true, + }; + const rows = Atom.make>([ + { key: "offline:a", shell: shell(), ledger: { ...ledger, problems: [alarm] }, live: true }, + { key: "cached:a", shell: shell(), ledger, live: false }, + ]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); + const stop = registry.subscribe(facts, () => {}, { immediate: true }); + registry.set( + rows, + registry.get(rows).map((row) => ({ ...row, live: false })), + ); + vi.advanceTimersByTime(FLEET_DISPATCH_THRESHOLD_MS * 2); + registry.set(rows, [ + ...registry.get(rows), + { + key: "live:a", + shell: shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }), + ledger, + live: true, + }, + ]); + const stale = registry.get(facts).get("offline:a")!; + expect(stale.runtime).toMatchObject({ state: "known", status: "waiting-to-start" }); + expect(stale.lastActivity.state).toBe("known"); + expect(stale.problems).toEqual([alarm]); + expect(registry.get(facts).get("cached:a")?.runtime.state).toBe("unknown"); + stop(); + registry.dispose(); +}); diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts new file mode 100644 index 0000000000000..a905a2ee9b335 --- /dev/null +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -0,0 +1,205 @@ +import type { OrchestrationV2ThreadShell } from "@t3tools/contracts"; +import { + FLEET_DISPATCH_THRESHOLD_MS, + type FleetAgentFacts, + type FleetRuntimeFact, + type FleetActivityFact, + type FleetProblem, +} from "@t3tools/contracts/j5"; +import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; +import * as Equal from "effect/Equal"; +import * as Option from "effect/Option"; +import { Atom } from "effect/reactivity"; +import * as DateTime from "effect/DateTime"; + +const iso = (value: DateTime.Utc | null | undefined) => + value == null ? null : DateTime.formatIso(value); + +export interface FleetDerivedFacts { + readonly runtime: FleetRuntimeFact; + readonly asks: FleetAgentFacts["asks"] | undefined; + readonly lastActivity: FleetActivityFact; + readonly problems: ReadonlyArray; +} + +export const deriveFleetFacts = (input: { + readonly shell: OrchestrationV2ThreadShell | undefined; + readonly ledger: FleetAgentFacts | undefined; + readonly now: number; +}): { readonly facts: FleetDerivedFacts; readonly nextDeadline?: number } => { + const { shell } = input; + const problems = [...(input.ledger?.problems ?? [])]; + const asks = input.ledger?.asks; + if (shell === undefined) { + const unknown = { + state: "unknown" as const, + reason: "This environment has no readable thread shell.", + }; + return { facts: { runtime: unknown, lastActivity: unknown, asks, problems } }; + } + const missingRunTimes = + shell.latestRunId !== null && + (shell.latestRunRequestedAt === undefined || + shell.latestRunStartedAt === undefined || + shell.latestRunCompletedAt === undefined); + const requestedAt = iso(shell.latestRunRequestedAt); + const startedAt = iso(shell.latestRunStartedAt); + const completedAt = iso(shell.latestRunCompletedAt); + const otherRunInProgress = + (shell.activeRunId !== null && shell.activeRunId !== shell.latestRunId) || + shell.activityRunStatus === "running" || + shell.activityRunStatus === "waiting"; + const undispatched = + shell.latestRunId !== null && + !otherRunInProgress && + requestedAt !== null && + startedAt === null && + (shell.status === "queued" || shell.status === "preparing" || shell.status === "starting"); + const dueIn = undispatched + ? Date.parse(requestedAt) + FLEET_DISPATCH_THRESHOLD_MS - input.now + : null; + if (!missingRunTimes && shell.status === "failed" && shell.latestRunId !== null) { + problems.push({ + kind: "failed-run", + runId: shell.latestRunId, + at: completedAt, + }); + } + if (!missingRunTimes && dueIn !== null && dueIn <= 0) { + problems.push({ kind: "dispatch-overdue", runId: shell.latestRunId!, at: requestedAt! }); + } + const candidates: Array<{ readonly label: string; readonly at: string }> = [ + { label: "Agent created", at: iso(shell.createdAt)! }, + ]; + if (requestedAt !== null) candidates.push({ label: "Turn requested", at: requestedAt }); + if (startedAt !== null) candidates.push({ label: "Turn started", at: startedAt }); + if (completedAt !== null) candidates.push({ label: "Turn ended", at: completedAt }); + if (shell.latestVisibleMessage !== null) + candidates.push({ + label: shell.latestVisibleMessage.role === "assistant" ? "Agent message" : "Message received", + at: iso(shell.latestVisibleMessage.updatedAt)!, + }); + if (shell.pendingRuntimeRequest !== null) + candidates.push({ + label: + shell.pendingRuntimeRequest.kind === "user_input" + ? "Input requested" + : shell.pendingRuntimeRequest.kind === "auth_refresh" + ? "Authentication requested" + : "Approval requested", + at: iso(shell.pendingRuntimeRequest.createdAt)!, + }); + for (const ask of input.ledger?.asks.awaited ?? []) + candidates.push({ label: "Ask opened", at: ask.openedAt }); + for (const problem of input.ledger?.problems ?? []) + if (problem.kind === "delivery-failed") + candidates.push({ label: "Delivery failed", at: problem.at }); + const latest = candidates.reduce((left, right) => + Date.parse(right.at) >= Date.parse(left.at) ? right : left, + ); + const lastActivity: FleetActivityFact = missingRunTimes + ? { state: "unknown", reason: "This environment does not report run timestamps." } + : { state: "known", ...latest }; + const activity = shell.activityRunStatus ?? shell.status; + const status = undispatched + ? "waiting-to-start" + : shell.pendingRuntimeRequest !== null + ? shell.pendingRuntimeRequest.kind === "user_input" + ? "input" + : shell.pendingRuntimeRequest.kind === "auth_refresh" + ? "waiting" + : "approval" + : activity === "running" + ? "working" + : activity === "waiting" + ? "waiting" + : activity === "preparing" || activity === "starting" || shell.status === "queued" + ? "waiting" + : backgroundWorkHoldsCompletion(shell.pendingBackgroundTasks ?? []) + ? "waiting" + : shell.status === "failed" + ? "failed" + : "idle"; + const unknownRuntimeReason = missingRunTimes + ? "This environment does not report run timestamps." + : otherRunInProgress && + shell.activityRunStatus == null && + shell.status !== "running" && + shell.status !== "waiting" + ? "This environment does not report the active run's status." + : status === "idle" && shell.latestRunId !== null && completedAt === null + ? "The latest run has no measured completion time." + : null; + const runtime: FleetRuntimeFact = + unknownRuntimeReason !== null + ? { state: "unknown", reason: unknownRuntimeReason } + : { + state: "known", + status, + since: undispatched + ? requestedAt + : status === "idle" + ? shell.latestRunId === null + ? iso(shell.createdAt) + : completedAt + : iso(shell.activityRunStartedAt), + settled: + status === "idle" && + (shell.settledOverride === "settled" || + (shell.settledOverride !== "active" && shell.settledAt !== null)), + }; + return { + facts: { runtime, asks, lastActivity, problems }, + ...(!missingRunTimes && dueIn !== null && dueIn > 0 ? { nextDeadline: input.now + dueIn } : {}), + }; +}; + +export interface FleetFactRow { + readonly key: string; + readonly shell: OrchestrationV2ThreadShell | undefined; + readonly ledger: FleetAgentFacts | undefined; + readonly live: boolean; +} + +/** Shared by every consumer in one registry. Only a future dispatch boundary schedules work. */ +export const createFleetFactsAtom = (rows: Atom.Atom>) => + Atom.make((get) => { + // @effect-diagnostics-next-line globalDate:off - This Atom runs outside an Effect runtime and shares one presentation deadline. + const now = Date.now(); + const previous = Option.getOrUndefined(get.self>()); + const facts = new Map(); + let nextDeadline: number | undefined; + for (const row of get(rows)) { + if (!row.live) { + const cached = previous?.get(row.key); + const unknown = { + state: "unknown" as const, + reason: "This environment is unavailable; runtime and activity are not current.", + }; + facts.set( + row.key, + cached ?? { + ...deriveFleetFacts({ shell: undefined, ledger: row.ledger, now }).facts, + runtime: unknown, + lastActivity: unknown, + }, + ); + continue; + } + const result = deriveFleetFacts({ shell: row.shell, ledger: row.ledger, now }); + const cached = previous?.get(row.key); + facts.set( + row.key, + cached !== undefined && Equal.equals(cached, result.facts) ? cached : result.facts, + ); + if (result.nextDeadline !== undefined) { + nextDeadline = Math.min(nextDeadline ?? result.nextDeadline, result.nextDeadline); + } + } + if (nextDeadline !== undefined) { + // @effect-diagnostics-next-line globalTimers:off - Atom lifecycle owns this one deadline, outside an Effect runtime. + const timer = setTimeout(() => get.refreshSelf(), nextDeadline - now); + get.addFinalizer(() => clearTimeout(timer)); + } + return facts; + }); diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index feec628718080..e3f7da484aa3b 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -3,10 +3,13 @@ import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; import { Rpc, RpcGroup } from "effect/rpc"; export * from "./j5/actionError.ts"; +export * from "./j5/fleet.ts"; export * from "./j5/peerPoll.ts"; export * from "./j5/playbook.ts"; export * from "./j5/sharing.ts"; +import { FleetAgentFacts } from "./j5/fleet.ts"; + import { ModelSelection } from "./modelSelection.ts"; import { ProviderApprovalDecision, @@ -376,6 +379,8 @@ export const FleetAgent = Schema.Struct({ ), /** Open Exchanges this agent owes a reply on. */ openAsks: Schema.Number, + /** Absent on older environments; clients must show unknown, never healthy. */ + facts: Schema.optionalKey(FleetAgentFacts), }); export type FleetAgent = typeof FleetAgent.Type; /** One project's agents and Crews. `title` is the server's, for a project the client cannot find. */ @@ -389,7 +394,10 @@ export type FleetProject = typeof FleetProject.Type; /** The rail badge reads the live roster only; the Fleet page asks for retired Crews as well. */ export const FleetReadRequest = Schema.Struct({ includeRetired: Schema.optional(Schema.Boolean) }); export type FleetReadRequest = typeof FleetReadRequest.Type; -export const FleetResponse = Schema.Struct({ projects: Schema.Array(FleetProject) }); +export const FleetResponse = Schema.Struct({ + projects: Schema.Array(FleetProject), + asOf: Schema.optionalKey(Schema.String), +}); export type FleetResponse = typeof FleetResponse.Type; /** A person stopping a Crew from the app: every running seat is interrupted, nothing is retired. */ diff --git a/packages/contracts/src/j5/fleet.ts b/packages/contracts/src/j5/fleet.ts new file mode 100644 index 0000000000000..42e5def42907e --- /dev/null +++ b/packages/contracts/src/j5/fleet.ts @@ -0,0 +1,72 @@ +import * as Schema from "effect/Schema"; + +export const FLEET_DISPATCH_THRESHOLD_MS = 5 * 60 * 1000; + +const UnknownFact = Schema.Struct({ state: Schema.Literal("unknown"), reason: Schema.String }); + +export const FleetRuntimeFact = Schema.Union([ + UnknownFact, + Schema.Struct({ + state: Schema.Literal("known"), + status: Schema.Literals([ + "working", + "waiting", + "approval", + "input", + "failed", + "idle", + "waiting-to-start", + ]), + since: Schema.NullOr(Schema.String), + settled: Schema.Boolean, + }), +]); +export type FleetRuntimeFact = typeof FleetRuntimeFact.Type; + +const OpenAsk = Schema.Struct({ + exchangeId: Schema.String, + counterpartyId: Schema.String, + counterpartyName: Schema.NullOr(Schema.String), + intent: Schema.String, + openedAt: Schema.String, +}); + +export const FleetActivityFact = Schema.Union([ + UnknownFact, + Schema.Struct({ + state: Schema.Literal("known"), + label: Schema.String, + at: Schema.String, + }), +]); +export type FleetActivityFact = typeof FleetActivityFact.Type; + +export const FleetProblem = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("failed-run"), + runId: Schema.String, + at: Schema.NullOr(Schema.String), + }), + Schema.Struct({ + kind: Schema.Literal("dispatch-overdue"), + runId: Schema.String, + at: Schema.String, + }), + Schema.Struct({ + kind: Schema.Literal("delivery-failed"), + messageId: Schema.String, + receiverId: Schema.String, + receiverName: Schema.NullOr(Schema.String), + at: Schema.String, + reason: Schema.NullOr(Schema.String), + /** Closing the Exchange changes eligibility, not the delivery fact. */ + exchangeOpen: Schema.Boolean, + }), +]); +export type FleetProblem = typeof FleetProblem.Type; + +export const FleetAgentFacts = Schema.Struct({ + asks: Schema.Struct({ owed: Schema.Array(OpenAsk), awaited: Schema.Array(OpenAsk) }), + problems: Schema.Array(FleetProblem), +}); +export type FleetAgentFacts = typeof FleetAgentFacts.Type; From 65ee34396c84af75d7731b57f524197dd9763d03 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 21 Oct 2026 10:25:36 +0000 Subject: [PATCH 02/11] fix(fleet): measure received messages and bound ask summaries --- apps/server/src/j5/a2a/fleetFacts.test.ts | 27 +++++++++++++++++++ apps/server/src/j5/a2a/fleetFacts.ts | 4 ++- docs/j5/product/features/fleet-page.md | 1 + .../client-runtime/src/j5/fleetFacts.test.ts | 26 ++++++++++++++++++ packages/client-runtime/src/j5/fleetFacts.ts | 2 ++ 5 files changed, 59 insertions(+), 1 deletion(-) diff --git a/apps/server/src/j5/a2a/fleetFacts.test.ts b/apps/server/src/j5/a2a/fleetFacts.test.ts index 8a901827d5a8d..74e66fd3f514c 100644 --- a/apps/server/src/j5/a2a/fleetFacts.test.ts +++ b/apps/server/src/j5/a2a/fleetFacts.test.ts @@ -22,6 +22,33 @@ const sender = "agent:sender"; const receiver = "agent:receiver"; const at = "2026-10-19T10:00:00.000Z"; +it.effect("bounds both Fleet ask summaries without changing the stored intent", () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES ('p', ${at})`; + for (const [intent, summary] of [ + ["Review the diff", "Review the diff"], + ["a".repeat(200), "a".repeat(200)], + ["a".repeat(10_000), `${"a".repeat(199)}…`], + ["🚀".repeat(5_000), `${"🚀".repeat(199)}…`], + ]) { + yield* sql`INSERT INTO j5_a2a_exchange ( + project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at + ) VALUES ('p', 'ask', ${sender}, ${receiver}, 'open', ${intent}, 1, ${at}, ${at}) + ON CONFLICT (project_id, exchange_id) DO UPDATE SET intent = excluded.intent`; + const facts = yield* readFleetLedgerFacts(sql, "p", [sender, receiver], () => null); + assert.equal(facts.awaited.get(sender)?.[0]?.intent, summary); + assert.equal(facts.owed.get(receiver)?.[0]?.intent, summary); + const stored = yield* sql<{ intent: string }>` + SELECT intent FROM j5_a2a_exchange WHERE project_id = 'p' AND exchange_id = 'ask' + `; + assert.equal(stored[0]?.intent, intent); + } + }).pipe(Effect.provide(database)), +); + it.effect( "reads both ask directions across projects and keeps local/remote alarms on their sender", () => diff --git a/apps/server/src/j5/a2a/fleetFacts.ts b/apps/server/src/j5/a2a/fleetFacts.ts index b767182ac6837..cdab57c1f974d 100644 --- a/apps/server/src/j5/a2a/fleetFacts.ts +++ b/apps/server/src/j5/a2a/fleetFacts.ts @@ -39,7 +39,9 @@ export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* for (const batch of batches) { for (const column of ["sender_id", "receiver_id"]) { const rows = yield* sql` - SELECT project_id, exchange_id, sender_id, receiver_id, intent, created_at + SELECT project_id, exchange_id, sender_id, receiver_id, + CASE WHEN length(intent) > 200 THEN substr(intent, 1, 199) || '…' ELSE intent END AS intent, + created_at FROM j5_a2a_exchange WHERE status = 'open' AND ${sql(column)} IN ${sql.in(batch)} AND exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`} diff --git a/docs/j5/product/features/fleet-page.md b/docs/j5/product/features/fleet-page.md index f3a9418404da7..19f6afe3da3f1 100644 --- a/docs/j5/product/features/fleet-page.md +++ b/docs/j5/product/features/fleet-page.md @@ -146,3 +146,4 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p - 2026-09-25 — a retired Crew comes back with its Captain when it retired because the Captain was archived, so AC28 no longer says it can never be reactivated; the roster snapshot shows why each seat joined, since the roster records no approver (Bryant; [#312](https://github.com/Jacksondr5/j5code/issues/312)). - 2026-10-07 — Squadrons retired: the page reads every project and groups roots by upstream's logical project, the sidebar is upstream's project sidebar, and every thread but a provider Subagent is a participant, so AC1 (the Squadron scope) and AC13 (the footer for threads without a home) are retired. Placement and provenance moved here from the retired Squadron definition: its AC10, AC12 and AC13 are AC34 and AC35 (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — an outside agent can be a spawner: the agent it starts is placed at its project's root and its provenance names the outside agent by its label; AC12 and AC34 (Jackson, 2026-10-11; [#498](https://github.com/Jacksondr5/j5code/issues/498)). +- 2026-10-21 — clarified AC15 and AC21: queued follow-ups preserve the active run's status, only completion-holding background work prevents Idle, and dispatch is overdue only when no other run is in progress ([#360](https://github.com/Jacksondr5/j5code/issues/360); [#662](https://github.com/Jacksondr5/j5code/pull/662)). diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index 6338a86b04d78..f72f59f7a96fa 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -191,6 +191,32 @@ describe("Fleet runtime measurements", () => { }); }); + it("measures a steering message without changing the running turn", () => { + const receivedAt = "2026-10-19T10:10:00.000Z"; + const source = shell({ + status: "running", + activityRunStatus: "running", + latestRunStartedAt: date, + latestVisibleMessage: null, + latestUserMessageAt: DateTime.makeUnsafe(receivedAt), + }); + expect(derive(source).facts.lastActivity).toEqual({ + state: "known", + label: "Message received", + at: receivedAt, + }); + expect(derive(source).facts.runtime).toMatchObject({ state: "known", status: "working" }); + const completedAt = "2026-10-19T10:11:00.000Z"; + expect( + derive({ + ...source, + status: "completed", + activityRunStatus: null, + latestRunCompletedAt: DateTime.makeUnsafe(completedAt), + }).facts.lastActivity, + ).toEqual({ state: "known", label: "Turn ended", at: completedAt }); + }); + it("ignores bookkeeping updatedAt and labels the latest measured event", () => { const source = shell({ status: "completed", diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index a905a2ee9b335..54f8ce7fb80c1 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -74,6 +74,8 @@ export const deriveFleetFacts = (input: { if (requestedAt !== null) candidates.push({ label: "Turn requested", at: requestedAt }); if (startedAt !== null) candidates.push({ label: "Turn started", at: startedAt }); if (completedAt !== null) candidates.push({ label: "Turn ended", at: completedAt }); + const receivedAt = iso(shell.latestUserMessageAt); + if (receivedAt !== null) candidates.push({ label: "Message received", at: receivedAt }); if (shell.latestVisibleMessage !== null) candidates.push({ label: shell.latestVisibleMessage.role === "assistant" ? "Agent message" : "Message received", From d98bfe6bd51aee0ff57431499969bc31b532fce0 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 13:56:08 +0000 Subject: [PATCH 03/11] fix(fleet): leave partial ledger activity unknown --- .../client-runtime/src/j5/fleetFacts.test.ts | 32 ++++++++++++++++--- packages/client-runtime/src/j5/fleetFacts.ts | 7 +++- 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index f72f59f7a96fa..234e805de50c7 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -272,10 +272,34 @@ describe("Fleet runtime measurements", () => { }); expect(old.asOf).toBeUndefined(); expect(old.projects[0]!.agents[0]!.facts).toBeUndefined(); - expect( - deriveFleetFacts({ shell: shell(), ledger: old.projects[0]!.agents[0]!.facts, now }).facts - .asks, - ).toBeUndefined(); + const source = shell({ + status: "completed", + activityRunStatus: null, + latestRunStartedAt: date, + latestRunCompletedAt: date, + }); + const partial = deriveFleetFacts({ + shell: source, + ledger: old.projects[0]!.agents[0]!.facts, + now, + }).facts; + expect(partial.asks).toBeUndefined(); + expect(partial.runtime).toMatchObject({ state: "known", status: "idle" }); + expect(partial.lastActivity).toEqual({ + state: "unknown", + reason: "This environment does not report Exchange or delivery activity.", + }); + const later = "2026-10-19T10:01:00.000Z"; + const restored = deriveFleetFacts({ + shell: source, + ledger: { ...ledger, problems: [{ ...alarm, at: later }] }, + now: Date.parse(later), + }).facts; + expect(restored.lastActivity).toEqual({ + state: "known", + label: "Delivery failed", + at: later, + }); }); }); diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index 54f8ce7fb80c1..28800a8e84390 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -101,7 +101,12 @@ export const deriveFleetFacts = (input: { ); const lastActivity: FleetActivityFact = missingRunTimes ? { state: "unknown", reason: "This environment does not report run timestamps." } - : { state: "known", ...latest }; + : input.ledger === undefined + ? { + state: "unknown", + reason: "This environment does not report Exchange or delivery activity.", + } + : { state: "known", ...latest }; const activity = shell.activityRunStatus ?? shell.status; const status = undispatched ? "waiting-to-start" From 520a4650057656c1f59b2bf104122ef280262457 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 14:13:53 +0000 Subject: [PATCH 04/11] fix(fleet): return peer thread-delivery alarms to origin --- apps/server/src/j5/a2a/DeliveryWorker.ts | 51 ++- apps/server/src/j5/a2a/LedgerService.ts | 16 + apps/server/src/j5/a2a/Migrations.test.ts | 4 +- apps/server/src/j5/a2a/Migrations.ts | 3 + apps/server/src/j5/a2a/PeerHttp.test.ts | 4 +- apps/server/src/j5/a2a/PeerInboundService.ts | 104 ++++- .../src/j5/a2a/PeerPollRoundTrip.test.ts | 71 +++- apps/server/src/j5/a2a/PeerRoundTrip.test.ts | 373 +++++++++++++++++- .../src/j5/a2a/PeerStoreService.test.ts | 6 +- apps/server/src/j5/a2a/contracts.ts | 6 +- apps/server/src/j5/a2a/fleetFacts.ts | 7 +- .../a2a/migrations/044_PeerDeliveryAlarms.ts | 15 + apps/server/src/j5/a2a/peerDeliveryBody.ts | 13 + apps/server/src/j5/a2a/peerProtocol.ts | 6 +- .../neutraliseCopiedDatabase.test.ts | 4 + .../persistence/neutraliseCopiedDatabase.ts | 4 + docs/j5/product/a2a/index.md | 3 +- docs/j5/product/cross-device.md | 3 +- packages/contracts/src/j5.ts | 10 + 19 files changed, 679 insertions(+), 24 deletions(-) create mode 100644 apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts diff --git a/apps/server/src/j5/a2a/DeliveryWorker.ts b/apps/server/src/j5/a2a/DeliveryWorker.ts index 9c9398c211fb6..06af51c1a5f1d 100644 --- a/apps/server/src/j5/a2a/DeliveryWorker.ts +++ b/apps/server/src/j5/a2a/DeliveryWorker.ts @@ -38,6 +38,7 @@ import { isMachineParticipantId, isOutsideAgentParticipantId, LedgerMessageId, + LIFECYCLE_PARTICIPANT_ID, MessageReceivedPayload, MessageSentPayload, ParticipantId, @@ -464,6 +465,7 @@ const makeLayer = (daemon: boolean) => // A peer server that refused the message already decided it; a // sender retired since cannot take that back, as with a receipt. if (yield* deliveryUnavailable(row, refusal !== undefined)) return null; + const reported = alarmed ? yield* peerAlarmFact(row, failedAt) : []; const told = refusal !== undefined ? yield* refusalNotices(row, refusal, failedAt) @@ -494,6 +496,7 @@ const makeLayer = (daemon: boolean) => createdAt: failedAt, }, ...told, + ...reported, ], }); }), @@ -556,6 +559,51 @@ const makeLayer = (daemon: boolean) => ]; }); + const peerAlarmFact = Effect.fn("j5.a2a.delivery.peerAlarmFact")(function* ( + row: DeliveryRow, + createdAt: string, + ) { + if ( + row.envelope_channel !== "peer" || + row.origin_environment_id === null || + row.origin_project_id === null + ) + return []; + const supported = yield* sql`SELECT 1 FROM j5_a2a_peer + WHERE environment_id = ${row.origin_environment_id} + AND json_extract(peer_capabilities, '$.deliveryAlarms') = 1`; + if (supported.length === 0) return []; + const received = yield* sql<{ + readonly payload: string; + }>`SELECT payload FROM j5_a2a_comm_event + WHERE project_id = ${row.project_id} AND seq = ${row.sent_seq} AND kind = 'message.received'`; + if (received[0] === undefined) return []; + const payload = yield* decodeReceivedPayload(received[0].payload); + // Legacy authored ids are unbounded; diagnostic limits must not roll back their alarm. + if (payload.originMessageId === undefined || payload.originMessageId.length > 4096) + return []; + return [ + { + kind: "message.sent", + sender: LIFECYCLE_PARTICIPANT_ID, + receiver: ParticipantId.make(row.sender_id), + exchangeId: null, + correlationId: CorrelationId.make(`correlation:peer-delivery-alarm:${row.message_id}`), + payload: { + messageId: LedgerMessageId.make(`message:peer-delivery-alarm:${row.message_id}`), + text: "Peer delivery alarm fact.", + originProjectId: LedgerProjectId.make(row.project_id), + receiverProjectId: LedgerProjectId.make(row.origin_project_id), + receiverEnvironmentId: row.origin_environment_id, + exchangeRole: "none", + envelopeChannel: "lifecycle_notice", + deliveryAlarm: { messageId: payload.originMessageId, code: "attempts-exhausted" }, + }, + createdAt, + }, + ] satisfies ReadonlyArray; + }); + /** * What the sender is told of an alarm: one notice that the message may not * have been delivered, naming the receiver and what the last attempt failed @@ -563,7 +611,8 @@ const makeLayer = (daemon: boolean) => * acknowledged after the wait for it timed out. So an alarmed ask's Exchange * stays open (a2a AC12), and the alarm stays a problem until the sender * withdraws it. A sender on a peer server is not told, as - * with a removed queued message, and nobody is told of a platform notice's alarm. + * with a removed queued message; only the capability-gated Fleet fact crosses back. + * Nobody is told of a platform notice's alarm. */ const alarmNotices = Effect.fn("j5.a2a.delivery.alarmNotices")(function* ( row: DeliveryRow, diff --git a/apps/server/src/j5/a2a/LedgerService.ts b/apps/server/src/j5/a2a/LedgerService.ts index 6fe67a49744f0..196efaf00f8f0 100644 --- a/apps/server/src/j5/a2a/LedgerService.ts +++ b/apps/server/src/j5/a2a/LedgerService.ts @@ -369,6 +369,10 @@ export const layer: Layer.Layer< } if (event.kind === "participant.left" || event.kind === "participant.deleted") { if (event.kind === "participant.deleted") { + yield* sql`DELETE FROM j5_a2a_peer_delivery_alarm + WHERE project_id = ${event.projectId} AND message_id IN ( + SELECT message_id FROM j5_a2a_delivery WHERE project_id = ${event.projectId} + AND sender_id = ${id})`; yield* sql`DELETE FROM j5_a2a_participant_placement WHERE project_id = ${event.projectId} AND participant_id = ${id}`; } yield* sql` @@ -581,6 +585,18 @@ export const layer: Layer.Layer< } case "message.delivery_failed": { const payload = yield* decodeMessageDeliveryFailed(event.payload); + if (payload.peerReported === true) { + yield* sql`INSERT INTO j5_a2a_peer_delivery_alarm + (project_id, message_id, reported_at, reason) + SELECT project_id, message_id, ${event.createdAt}, ${payload.error} + FROM j5_a2a_delivery + WHERE project_id = ${event.projectId} AND message_id = ${payload.messageId} + AND receiver_environment_id = ${payload.peerEnvironmentId ?? null} + AND origin_environment_id IS NULL AND envelope_channel = 'peer' + AND status = 'delivered' + ON CONFLICT(project_id, message_id) DO NOTHING`; + return; + } const rows = yield* sql<{ readonly message_id: string }>` UPDATE j5_a2a_delivery SET diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index ca08eb2c40dc1..bc05c4f789a2f 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -97,6 +97,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 41, name: "SharedConversation" }, { migration_id: 42, name: "EveryoneHereAsks" }, { migration_id: 43, name: "TaskSchedulers" }, + { migration_id: 44, name: "PeerDeliveryAlarms" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -144,6 +145,7 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [41, "SharedConversation"], [42, "EveryoneHereAsks"], [43, "TaskSchedulers"], + [44, "PeerDeliveryAlarms"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1392,7 +1394,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, + 36, 37, 38, 39, 40, 41, 42, 43, 44, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index bd79a2a8609a3..1987c1b387c9a 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -45,6 +45,8 @@ import Migration0041 from "./migrations/041_SharedConversation.ts"; import Migration0042 from "./migrations/042_EveryoneHereAsks.ts"; import Migration0043 from "./migrations/043_TaskSchedulers.ts"; +import Migration0044 from "./migrations/044_PeerDeliveryAlarms.ts"; + export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; // Every entry already in this list is persisted migration history: keep its id, file, and @@ -98,6 +100,7 @@ export const migrationEntries = [ [41, "SharedConversation", Migration0041], [42, "EveryoneHereAsks", Migration0042], [43, "TaskSchedulers", Migration0043], + [44, "PeerDeliveryAlarms", Migration0044], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/PeerHttp.test.ts b/apps/server/src/j5/a2a/PeerHttp.test.ts index 4189796231827..d80ec836063f0 100644 --- a/apps/server/src/j5/a2a/PeerHttp.test.ts +++ b/apps/server/src/j5/a2a/PeerHttp.test.ts @@ -355,7 +355,7 @@ it("answers hello with this environment and the credential's subject, and comple assert.equal(body.peerProtocolVersion, PEER_PROTOCOL_VERSION); assert.deepStrictEqual( body.capabilities, - { poll: true, landing: true }, + { poll: true, landing: true, deliveryAlarms: true }, "this server stores for a poller, and lands a message as its sender asked", ); assert.deepStrictEqual( @@ -716,7 +716,7 @@ it("shows a recorded peer only the agents it could address, and nobody else the assert.equal(response.status, 200); assert.deepStrictEqual(await response.json(), { label: "Work VM", - capabilities: { poll: true, landing: true }, + capabilities: { poll: true, landing: true, deliveryAlarms: true }, agents: [ { participantId: "agent:j5:a2a:thread:local-triage", diff --git a/apps/server/src/j5/a2a/PeerInboundService.ts b/apps/server/src/j5/a2a/PeerInboundService.ts index 8fd8fea1eb58a..54edcc00117a0 100644 --- a/apps/server/src/j5/a2a/PeerInboundService.ts +++ b/apps/server/src/j5/a2a/PeerInboundService.ts @@ -155,6 +155,12 @@ export class A2APeerAskIntentRequiredError extends Schema.TaggedError()( + "A2APeerDeliveryReceiptPendingError", + {}, +) {} + /** * A peer speaks only for its agents. It may not deliver as a person, a machine * participant or the platform, and an agent's message travels on the peer @@ -184,7 +190,7 @@ export class A2APeerSenderNotAllowedError extends Schema.TaggedError Effect.Effect; @@ -251,7 +258,7 @@ const localMessageIdFor = (input: { /** Refuse the sender kinds, channels and roles a peer may not use, before anything is read. */ /** * Who a peer may speak as. Its agents, on the peer channel, never a terminal - * notice. Or the platform itself, as exactly one of two notices, each in the + * notice. Or the platform itself, as a terminal notice, delivery-alarm fact or silence notice in the * shape its producer writes: the lifecycle's terminal notice (the fact that * ends an Exchange) or the silence detector's notice (not part of any * Exchange, naming the one whose answerer went quiet). The receive path then @@ -261,6 +268,19 @@ const assertSenderShape = (input: PeerInboundInput) => { const senderId = ParticipantId.make(input.senderId); const refuse = (reason: A2APeerSenderNotAllowedError["reason"]) => Effect.fail(new A2APeerSenderNotAllowedError({ senderId, reason })); + if (input.deliveryAlarm !== undefined) { + if ( + senderId === LIFECYCLE_PARTICIPANT_ID && + input.envelopeChannel === "lifecycle_notice" && + input.exchangeRole === "none" && + input.exchangeId === null && + input.terminal === undefined && + input.regardingExchangeId === undefined && + input.landing === undefined + ) + return Effect.succeed({ senderId, platform: "delivery-alarm" as const }); + return refuse("platform"); + } if (isHumanParticipantId(senderId)) return refuse("human"); if (isMachineParticipantId(senderId)) return refuse("machine"); if (isOutsideAgentParticipantId(senderId)) return refuse("outside"); @@ -387,15 +407,91 @@ export const layer: Layer.Layer 0) return null; + const rows = yield* sql<{ + readonly project_id: string; + readonly message_id: string; + readonly sender_id: string; + readonly receiver_id: string; + readonly exchange_id: string | null; + readonly correlation_id: string; + readonly status: string; + readonly attempts: number; + }>`SELECT d.project_id, d.message_id, d.sender_id, d.receiver_id, d.exchange_id, + d.correlation_id, d.status, d.attempts + FROM j5_a2a_delivery d JOIN j5_a2a_membership m + ON m.project_id = d.project_id AND m.participant_id = d.sender_id AND m.archived_at IS NULL + WHERE d.message_id = ${report.messageId} AND d.receiver_environment_id = ${input.originEnvironmentId} + AND d.origin_environment_id IS NULL AND d.envelope_channel = 'peer' + LIMIT 2`; + const row = rows.length === 1 ? rows[0] : undefined; + if (row === undefined) return null; + if (row.status === "pending" || row.status === "retry_scheduled") + return yield* new A2APeerDeliveryReceiptPendingError({}); + if (row.status !== "delivered") return null; + const receivedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); + return yield* writer.appendEventsInTransaction({ + commandId, + projectId: LedgerProjectId.make(row.project_id), + acceptedAt: receivedAt, + events: [ + { + kind: "message.delivery_failed", + sender: ParticipantId.make(row.sender_id), + receiver: ParticipantId.make(row.receiver_id), + exchangeId: row.exchange_id === null ? null : ExchangeId.make(row.exchange_id), + correlationId: CorrelationId.make(row.correlation_id), + createdAt: receivedAt, + payload: { + messageId: row.message_id, + attempt: Math.max(1, row.attempts), + error: + "The peer accepted this message, but delivery into its agent's thread failed.", + nextAttemptAt: null, + alarmed: true, + peerReported: true, + peerEnvironmentId: input.originEnvironmentId, + }, + }, + ], + }); + }), + ), + ); + if (outcome?.committed) yield* writer.publishCommitted(outcome.events); + // Unknown, foreign, retired and replayed messages have the same non-oracular receipt. + return { receivedSeq: 1, replay: false } satisfies PeerInboundResult; + }); + const receive: PeerInboundServiceShape["receive"] = (input) => Effect.gen(function* () { + const shape = yield* assertSenderShape(input); + if (shape.platform === "delivery-alarm") return yield* receiveDeliveryAlarm(input); const commandId = peerReceiveCommandId({ originEnvironmentId: input.originEnvironmentId, messageId: input.messageId, }); const replayed = yield* priorReceipt(commandId); if (replayed !== null) return replayed; - const { senderId, platform } = yield* assertSenderShape(input); + const { senderId, platform } = shape; if (platform === null) yield* assertSenderOwnedByOrigin(senderId, input.originEnvironmentId); const receiverId = ParticipantId.make(input.receiverId); diff --git a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts index acc95a73f3a95..7489385ffb00f 100644 --- a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts @@ -72,6 +72,7 @@ import { } from "./PeerStoreService.ts"; import { RosterService } from "./RosterService.ts"; import { A2ASendService, layer as sendLayer } from "./SendService.ts"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; import { A2ASilenceDetector, manualLayer as silenceDetectorLayer } from "./SilenceDetector.ts"; import { CommCommandId, @@ -236,18 +237,28 @@ const makeCore = (input: { const recordingTransport = ( delivered: Ref.Ref>, deliverPeer: A2ADeliveryTransport["Service"]["deliverPeer"], + failLocal = false, ) => Layer.succeed( A2ADeliveryTransport, A2ADeliveryTransport.of({ cancelAgent: () => Effect.succeed("cancelled" as const), - deliverAgent: (input) => Ref.update(delivered, (rows) => [...rows, input]), + deliverAgent: (input) => + failLocal + ? Effect.fail( + new A2ADeliveryTransportError({ + operation: "forced local delivery failure", + cause: "private-local-error", + }), + ) + : Ref.update(delivered, (rows) => [...rows, input]), deliverHuman: () => Effect.void, deliverPeer, }), ); interface VmOptions { + readonly failLocal?: boolean; readonly removing?: Effect.Effect; /** A database file instead of memory, so a test can read it from a second connection. */ readonly filename?: string; @@ -270,8 +281,10 @@ const makeVm = (delivered: Ref.Ref>, options: VmOption const core = makeCore({ database, delivered, - transport: recordingTransport(delivered, () => - Effect.die("the VM never sends to the laptop; it stores for it"), + transport: recordingTransport( + delivered, + () => Effect.die("the VM never sends to the laptop; it stores for it"), + options.failLocal, ), directory, }); @@ -1021,3 +1034,55 @@ const runEnded = (thread: ThreadId, status: "completed" | "failed"): Orchestrati }, } as OrchestrationV2StoredEvent; }; + +it.effect( + "returns a receiver's later delivery alarm through the poll queue to its original sender", + () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pollPair({ failLocal: true }); + const sent = yield* pair.laptopServer.send.send({ + commandId: CommCommandId.make("command:poll-delivery-alarm"), + senderThreadId: laptop.agent.threadId, + to: vm.agent.id, + message: "Inspect the incident", + expectReply: true, + intent: "incident", + acceptedAt: timestamp, + }); + assert.equal((yield* pair.laptopServer.worker.runOnce)?.state, "delivered"); + assert.equal((yield* pair.vmServer.worker.runOnce)?.state, "retry_scheduled"); + yield* TestClock.adjust("250 millis"); + yield* pair.vmServer.worker.runOnce; + yield* TestClock.adjust("500 millis"); + assert.equal((yield* pair.vmServer.worker.runOnce)?.state, "alarmed"); + assert.isNull( + yield* pair.vmServer.worker.runOnce, + "the VM stores its fact for the polling origin", + ); + assert.deepStrictEqual(yield* pair.poll, { kind: "polled", received: 1, more: false }); + const facts = yield* readFleetLedgerFacts( + pair.laptopServer.sql, + laptop.projectId, + [laptop.agent.id], + () => null, + ); + const problem = facts.problems.get(laptop.agent.id)![0]!; + assert.isTrue(problem.kind === "delivery-failed" && problem.exchangeOpen); + assert.equal( + (yield* deliveryStatus(pair.laptopServer.sql, sent.messageId))?.status, + "delivered", + ); + assert.equal( + (yield* Ref.get(pair.laptopDelivered)).length, + 0, + "no authored thread message", + ); + yield* pair.poll; + assert.equal( + (yield* pair.laptopServer.sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, + 1, + ); + }), + ), +); diff --git a/apps/server/src/j5/a2a/PeerRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerRoundTrip.test.ts index b4eeddf403606..97ad189114f29 100644 --- a/apps/server/src/j5/a2a/PeerRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerRoundTrip.test.ts @@ -13,6 +13,12 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import * as Schema from "effect/Schema"; +import { PeerCapabilities, PeerDeliveryRequest, PeerDeliveryResponse } from "@t3tools/contracts/j5"; +import { ownPeerCapabilities } from "./peerProtocol.ts"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; +import { readsChangedByLedgerEvent } from "./ReadChangeFeeds.ts"; import * as SqlClient from "effect/sql/SqlClient"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -52,6 +58,8 @@ import { ParticipantId, LedgerProjectId, type AgentParticipant, + LIFECYCLE_PARTICIPANT_ID, + type StoredCommEvent, } from "./contracts.ts"; /** @@ -63,6 +71,15 @@ import { */ const timestamp = "2026-09-16T12:00:00.000Z"; +const isPeerDelivery = Schema.is(PeerDeliveryRequest); +const isPeerReceipt = Schema.is(PeerDeliveryResponse); +const decodePeerCapabilities = Schema.decodeUnknownSync(PeerCapabilities); +const decodeLegacyCapabilities = Schema.decodeUnknownSync( + Schema.Struct({ + poll: Schema.optionalKey(Schema.Boolean), + landing: Schema.optionalKey(Schema.Boolean), + }), +); interface Server { readonly environmentId: string; @@ -113,6 +130,7 @@ const makeServer = ( peer: Ref.Ref, delivered: Ref.Ref>, crossed: Ref.Ref>, + failLocal = false, ) => { const database = NodeSqliteClient.layer({ filename: ":memory:" }); const ledger = ledgerLayer.pipe(Layer.provide(database)); @@ -146,7 +164,15 @@ const makeServer = ( A2ADeliveryTransport, A2ADeliveryTransport.of({ cancelAgent: () => Effect.succeed("cancelled" as const), - deliverAgent: (input) => Ref.update(delivered, (rows) => [...rows, input]), + deliverAgent: (input) => + failLocal + ? Effect.fail( + new A2ADeliveryTransportError({ + operation: "private-path/token-local-error", + cause: "private-secret", + }), + ) + : Ref.update(delivered, (rows) => [...rows, input]), deliverHuman: () => Effect.void, deliverPeer: (input) => Effect.gen(function* () { @@ -255,8 +281,8 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve yield* runJ5A2AMigrations(); const sql = yield* SqlClient.SqlClient; yield* sql` - INSERT INTO j5_a2a_peer (environment_id, label, link_mode, origin, credential, created_at, updated_at) - VALUES (${peer.environmentId}, ${peer.environmentId}, 'push', 'https://peer.example', 'peer-token', ${timestamp}, ${timestamp}) + INSERT INTO j5_a2a_peer (environment_id, label, link_mode, origin, credential, peer_capabilities, created_at, updated_at) + VALUES (${peer.environmentId}, ${peer.environmentId}, 'push', 'https://peer.example', 'peer-token', '{"deliveryAlarms":true}', ${timestamp}, ${timestamp}) `; const ledger = yield* A2ALedger; yield* ledger.ensureProject({ projectId: self.projectId, createdAt: timestamp }); @@ -280,6 +306,7 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve worker: yield* A2ADeliveryWorker, lifecycle: yield* A2ALifecycleService, silence: yield* A2ASilenceDetector, + ledger, sql: yield* SqlClient.SqlClient, }; }); @@ -287,6 +314,7 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve /** Both servers up and introduced, with Work's agent holding an open ask to Home's agent that has crossed. */ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")(function* ( commandId: string, + failHome = false, ) { const workDoor = yield* Ref.make(null); const homeDoor = yield* Ref.make(null); @@ -297,7 +325,7 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( makeServer(work, home, "Home", homeDoor, workDelivered, crossed), ); const homeContext = yield* Layer.build( - makeServer(home, work, "Work", workDoor, homeDelivered, crossed), + makeServer(home, work, "Work", workDoor, homeDelivered, crossed, failHome), ); const workServer = yield* seed(work, home).pipe(Effect.provide(workContext)); const homeServer = yield* seed(home, work).pipe(Effect.provide(homeContext)); @@ -313,8 +341,15 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( acceptedAt: timestamp, }); assert.equal((yield* workServer.worker.runOnce)?.state, "delivered"); - assert.equal((yield* homeServer.worker.runOnce)?.state, "delivered"); - assert.equal((yield* Ref.get(homeDelivered)).length, 1, "the ask reached Home's agent"); + assert.equal( + (yield* homeServer.worker.runOnce)?.state, + failHome ? "retry_scheduled" : "delivered", + ); + assert.equal( + (yield* Ref.get(homeDelivered)).length, + failHome ? 0 : 1, + "the ask's thread delivery", + ); return { workServer, homeServer, @@ -322,6 +357,7 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( homeDelivered, crossed, exchangeId: ExchangeId.make(asked.exchangeId!), + messageId: asked.messageId, }; }); @@ -693,3 +729,328 @@ it.effect( }), ), ); + +it.effect( + "reports accepted peer messages that later fail in-thread without changing acceptance or closing the ask", + () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pairWithOpenAsk("command:remote-alarm", true); + const original = () => + pair.workServer.sql`SELECT * FROM j5_a2a_delivery WHERE message_id = ${pair.messageId}`; + const before = yield* original(); + yield* TestClock.adjust("250 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "retry_scheduled"); + yield* TestClock.adjust("500 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "alarmed"); + assert.equal( + (yield* pair.homeServer.worker.runOnce)?.state, + "delivered", + "the fact crosses the real peer transport", + ); + assert.deepStrictEqual(yield* original(), before, "the origin acceptance is immutable"); + const facts = yield* readFleetLedgerFacts( + pair.workServer.sql, + work.projectId, + [work.agent.id], + () => null, + ); + const problems = facts.problems.get(work.agent.id)!; + assert.equal(problems.length, 1); + assert.isTrue(problems[0]?.kind === "delivery-failed" && problems[0].exchangeOpen); + assert.notInclude(JSON.stringify(problems), "private-"); + assert.equal( + (yield* exchangeStatus(pair.workServer.sql, pair.exchangeId))[0]?.status, + "open", + ); + assert.equal( + (yield* Ref.get(pair.workDelivered)).length, + 0, + "the fact is never injected into the sender thread", + ); + const event = (yield* pair.workServer.sql<{ + readonly kind: string; + readonly payload: string; + }>` + SELECT kind, payload FROM j5_a2a_comm_event WHERE json_extract(payload, '$.peerReported') = 1`)[0]!; + assert.equal(event.kind, "message.delivery_failed"); + assert.equal( + (yield* pair.workServer + .sql`SELECT 1 FROM j5_a2a_comm_event WHERE kind IN ('message.received','silence.notice')`) + .length, + 0, + ); + assert.equal((yield* pair.workServer.sql`SELECT 1 FROM j5_a2a_human_inbox`).length, 0); + assert.include( + readsChangedByLedgerEvent({ + kind: event.kind, + receiver: home.agent.id, + payload: JSON.parse(event.payload), + } as StoredCommEvent), + "fleet", + ); + yield* pair.workServer.send.clearOwnAsk({ + commandId: CommCommandId.make("command:remote-alarm-clear"), + senderThreadId: work.agent.threadId, + exchangeId: pair.exchangeId, + acceptedAt: timestamp, + }); + const cleared = yield* readFleetLedgerFacts( + pair.workServer.sql, + work.projectId, + [work.agent.id], + () => null, + ); + assert.equal(cleared.problems.get(work.agent.id)?.length, 1, "the historical chip stays"); + const clearedProblem = cleared.problems.get(work.agent.id)![0]!; + assert.isFalse(clearedProblem.kind === "delivery-failed" && clearedProblem.exchangeOpen); + }), + ), +); + +it.effect( + "binds alarm facts only to accepted authored messages for the authenticated peer, idempotently", + () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pairWithOpenAsk("command:report-binding"); + const sql = pair.workServer.sql; + const report = { + messageId: "envelope:report", + senderId: LIFECYCLE_PARTICIPANT_ID, + receiverId: "ignored:receiver", + originProjectId: "ignored:project", + exchangeId: null, + exchangeRole: "none" as const, + envelopeChannel: "lifecycle_notice" as const, + correlationId: "ignored:correlation", + text: "PRIVATE PEER TEXT", + createdAt: "2999-01-01T00:00:00Z", + deliveryAlarm: { messageId: pair.messageId, code: "attempts-exhausted" as const }, + originEnvironmentId: home.environmentId, + }; + const count = () => sql`SELECT * FROM j5_a2a_peer_delivery_alarm`; + const ignored = yield* pair.workServer.inbound.receive({ + ...report, + deliveryAlarm: { ...report.deliveryAlarm, messageId: "not-sent" }, + }); + assert.isTrue(isPeerReceipt({ accepted: true, ...ignored })); + yield* sql`INSERT INTO j5_a2a_peer(environment_id,label,link_mode,origin,credential,created_at,updated_at) + VALUES ('foreign','foreign','push','https://foreign.example','credential',${timestamp},${timestamp})`; + assert.deepStrictEqual( + yield* pair.workServer.inbound.receive({ ...report, originEnvironmentId: "foreign" }), + ignored, + ); + for (const status of ["cancelled", "alarmed"]) { + yield* sql`UPDATE j5_a2a_delivery SET status = ${status} WHERE message_id = ${pair.messageId}`; + assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); + } + yield* sql`UPDATE j5_a2a_delivery SET status='delivered', origin_environment_id='relayed' WHERE message_id=${pair.messageId}`; + assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); + yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id=NULL, status='pending' WHERE message_id=${pair.messageId}`; + const pending = yield* Effect.flip(pair.workServer.inbound.receive(report)); + assert.equal(pending._tag, "A2APeerDeliveryReceiptPendingError"); + assert.equal((yield* count()).length, 0); + yield* sql`UPDATE j5_a2a_delivery SET status='delivered' WHERE message_id=${pair.messageId}`; + yield* sql`UPDATE j5_a2a_membership SET archived_at=${timestamp} WHERE participant_id=${work.agent.id}`; + assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); + yield* sql`UPDATE j5_a2a_membership SET archived_at=NULL WHERE participant_id=${work.agent.id}`; + const membership = yield* sql<{ + readonly payload: string; + readonly project_id: string; + readonly participant_id: string; + readonly participant_kind: string; + readonly thread_id: string; + readonly joined_seq: number; + readonly updated_seq: number; + readonly archived_at: string | null; + }>`SELECT * FROM j5_a2a_membership WHERE participant_id=${work.agent.id}`; + yield* sql`DELETE FROM j5_a2a_membership WHERE participant_id=${work.agent.id}`; + assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); + yield* sql`INSERT INTO j5_a2a_membership ${sql.insert(membership)}`; + const before = yield* sql`SELECT * FROM j5_a2a_delivery WHERE message_id=${pair.messageId}`; + assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); + yield* TestClock.adjust("1 minute"); + assert.deepStrictEqual( + yield* pair.workServer.inbound.receive({ ...report, messageId: "another-envelope" }), + ignored, + ); + const stored = yield* count(); + assert.equal(stored.length, 1); + assert.equal( + stored[0]!.reported_at, + "1970-01-01T00:00:00.000Z", + "only the origin receipt clock is authoritative", + ); + assert.notInclude(JSON.stringify(stored), "PRIVATE"); + assert.deepStrictEqual( + yield* sql`SELECT * FROM j5_a2a_delivery WHERE message_id=${pair.messageId}`, + before, + ); + assert.equal( + (yield* sql`SELECT 1 FROM j5_a2a_comm_event WHERE json_extract(payload,'$.peerReported')=1`) + .length, + 1, + ); + for (const changed of [ + { senderId: home.agent.id, envelopeChannel: "peer" as const }, + { exchangeId: "foreign" }, + { exchangeRole: "terminal_notice" as const }, + { regardingExchangeId: "foreign" }, + { terminal: { kind: "sender-cleared" as const } }, + { + landing: { + mode: "steer" as const, + limit: { runtimeMode: "full-access" as const, interactionMode: "default" as const }, + }, + }, + ]) { + assert.equal( + (yield* Effect.flip(pair.workServer.inbound.receive({ ...report, ...changed })))._tag, + "A2APeerSenderNotAllowedError", + ); + } + assert.isFalse( + isPeerDelivery({ + ...report, + deliveryAlarm: { messageId: "x".repeat(4097), code: "attempts-exhausted" }, + }), + ); + assert.isFalse( + isPeerDelivery({ + ...report, + deliveryAlarm: { messageId: "m", code: "unbounded-peer-code" }, + }), + ); + yield* sql`UPDATE j5_a2a_delivery SET exchange_id=NULL WHERE message_id=${pair.messageId}`; + const plain = (yield* readFleetLedgerFacts( + sql, + work.projectId, + [work.agent.id], + () => null, + )).problems.get(work.agent.id)![0]!; + assert.isTrue( + plain.kind === "delivery-failed" && !plain.exchangeOpen, + "plain message alarms do not become open-Exchange alarms", + ); + yield* sql`DELETE FROM j5_a2a_peer_delivery_alarm`; + yield* sql`UPDATE j5_a2a_delivery SET status='cancelled' WHERE message_id=${pair.messageId}`; + const staleEvent = (yield* sql<{ + readonly payload: string; + }>`SELECT payload FROM j5_a2a_comm_event WHERE json_extract(payload,'$.peerReported')=1`)[0]!; + yield* pair.workServer.ledger.append({ + commandId: CommCommandId.make("command:stale-peer-report"), + projectId: work.projectId, + acceptedAt: timestamp, + event: { + kind: "message.delivery_failed", + sender: work.agent.id, + receiver: home.agent.id, + exchangeId: null, + correlationId: null, + payload: JSON.parse(staleEvent.payload), + createdAt: timestamp, + }, + }); + assert.equal( + (yield* count()).length, + 0, + "a stale projection never fails or resurrects a cancelled delivery", + ); + yield* sql`INSERT INTO j5_a2a_peer_delivery_alarm(project_id,message_id,reported_at,reason) + VALUES (${work.projectId},${pair.messageId},${timestamp},'historical failure')`; + yield* sql`DELETE FROM j5_a2a_delivery WHERE project_id=${work.projectId} AND message_id=${pair.messageId}`; + assert.equal( + (yield* count()).length, + 0, + "deleting the delivery cascades to its diagnostic fact", + ); + }), + ), +); + +it.effect( + "does not send diagnostic facts to an old peer or recurse on an alarmed platform fact", + () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pairWithOpenAsk("command:old-peer-alarm", true); + yield* pair.homeServer.sql`UPDATE j5_a2a_peer SET peer_capabilities='{}'`; + yield* TestClock.adjust("250 millis"); + yield* pair.homeServer.worker.runOnce; + yield* TestClock.adjust("500 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "alarmed"); + assert.equal( + (yield* pair.homeServer + .sql`SELECT 1 FROM j5_a2a_delivery WHERE envelope_channel='lifecycle_notice'`).length, + 0, + ); + yield* pair.homeServer + .sql`UPDATE j5_a2a_peer SET peer_capabilities='{"deliveryAlarms":true}'`; + const report = (yield* Ref.get(pair.crossed))[0]!.body; + const received = yield* pair.homeServer.inbound.receive({ + ...report, + messageId: "other-message", + correlationId: "correlation:other-message", + exchangeId: null, + exchangeRole: "none", + originEnvironmentId: work.environmentId, + }); + assert.isAtLeast(received.receivedSeq, 1); + yield* pair.homeServer.worker.runOnce; + yield* TestClock.adjust("250 millis"); + yield* pair.homeServer.worker.runOnce; + yield* TestClock.adjust("500 millis"); + yield* pair.homeServer.worker.runOnce; + yield* pair.workServer.sql`DELETE FROM j5_a2a_peer`; + yield* pair.homeServer.worker.runOnce; + yield* TestClock.adjust("250 millis"); + yield* pair.homeServer.worker.runOnce; + yield* TestClock.adjust("500 millis"); + yield* pair.homeServer.worker.runOnce; + assert.equal( + (yield* pair.homeServer + .sql`SELECT 1 FROM j5_a2a_delivery WHERE envelope_channel='lifecycle_notice'`).length, + 1, + ); + }), + ), +); + +it.effect("retries an early alarm report until the matching origin acceptance is committed", () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pairWithOpenAsk("command:early-report", true); + yield* pair.workServer + .sql`UPDATE j5_a2a_delivery SET status='pending' WHERE message_id=${pair.messageId}`; + yield* TestClock.adjust("250 millis"); + yield* pair.homeServer.worker.runOnce; + yield* TestClock.adjust("500 millis"); + yield* pair.homeServer.worker.runOnce; + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "retry_scheduled"); + assert.equal( + (yield* pair.workServer.sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, + 0, + ); + yield* pair.workServer + .sql`UPDATE j5_a2a_delivery SET status='delivered' WHERE message_id=${pair.messageId}`; + yield* TestClock.adjust("250 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "delivered"); + assert.equal( + (yield* pair.workServer.sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, + 1, + ); + }), + ), +); + +it("keeps delivery-alarm capabilities additive for old peer decoders", () => { + assert.deepStrictEqual(decodePeerCapabilities({ poll: true, landing: true }), { + poll: true, + landing: true, + }); + assert.deepStrictEqual(decodeLegacyCapabilities(ownPeerCapabilities), { + poll: true, + landing: true, + }); +}); diff --git a/apps/server/src/j5/a2a/PeerStoreService.test.ts b/apps/server/src/j5/a2a/PeerStoreService.test.ts index 2a4e75d6cdc9e..ce86233ce9bb6 100644 --- a/apps/server/src/j5/a2a/PeerStoreService.test.ts +++ b/apps/server/src/j5/a2a/PeerStoreService.test.ts @@ -318,7 +318,11 @@ it.effect( ); assert.isFalse(handed.more); assert.equal(handed.label, "Work VM", "the poller learns the storing server's name"); - assert.deepStrictEqual(handed.capabilities, { poll: true, landing: true }); + assert.deepStrictEqual(handed.capabilities, { + poll: true, + landing: true, + deliveryAlarms: true, + }); // The body is exactly what a direct send would carry, intent included. assert.equal(handed.deliveries[0]!.intent, "first intent"); assert.equal(handed.deliveries[0]!.exchangeRole, "ask"); diff --git a/apps/server/src/j5/a2a/contracts.ts b/apps/server/src/j5/a2a/contracts.ts index 588aecc143bfa..a38881b30a412 100644 --- a/apps/server/src/j5/a2a/contracts.ts +++ b/apps/server/src/j5/a2a/contracts.ts @@ -1,5 +1,5 @@ import { ChatAttachment, ProviderInteractionMode, RuntimeMode, ThreadId } from "@t3tools/contracts"; -import { PeerSenderLabel } from "@t3tools/contracts/j5"; +import { PeerDeliveryAlarm, PeerSenderLabel } from "@t3tools/contracts/j5"; import * as Schema from "effect/Schema"; const Identifier = Schema.String.check(Schema.isNonEmpty()); @@ -303,6 +303,7 @@ export const TerminalFact = Schema.Union([ export type TerminalFact = typeof TerminalFact.Type; export const MessageSentPayload = Schema.Struct({ + deliveryAlarm: Schema.optional(PeerDeliveryAlarm), attachments: Schema.optional(Schema.Array(ChatAttachment)), /** How the sender asked for the message to land; absent means `queue`. */ mode: Schema.optional(SendMode), @@ -328,6 +329,9 @@ export const MessageDeliveredPayload = Schema.Struct({ export type MessageDeliveredPayload = typeof MessageDeliveredPayload.Type; export const MessageDeliveryFailedPayload = Schema.Struct({ + /** Set only after binding an authenticated peer report to this server's outbound delivery. */ + peerReported: Schema.optional(Schema.Literal(true)), + peerEnvironmentId: Schema.optional(Schema.String), messageId: LedgerMessageId, attempt: PositiveInt, error: Schema.String.check(Schema.isNonEmpty()), diff --git a/apps/server/src/j5/a2a/fleetFacts.ts b/apps/server/src/j5/a2a/fleetFacts.ts index cdab57c1f974d..f8be5fb602b8a 100644 --- a/apps/server/src/j5/a2a/fleetFacts.ts +++ b/apps/server/src/j5/a2a/fleetFacts.ts @@ -80,12 +80,15 @@ export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* // their own channels and must never surface as an agent's problem (Fleet AC24). for (const batch of batches) { const alarms = yield* sql` - SELECT d.sender_id, d.receiver_id, d.message_id, d.updated_at, d.last_error, + SELECT d.sender_id, d.receiver_id, d.message_id, COALESCE(a.reported_at, d.updated_at) AS updated_at, + COALESCE(a.reason, d.last_error) AS last_error, EXISTS (SELECT 1 FROM j5_a2a_exchange e WHERE e.project_id = d.project_id AND e.exchange_id = d.exchange_id AND e.status = 'open') AS exchange_open FROM j5_a2a_delivery d + LEFT JOIN j5_a2a_peer_delivery_alarm a ON a.project_id = d.project_id AND a.message_id = d.message_id WHERE d.project_id = ${projectId} AND d.sender_id IN ${sql.in(batch)} - AND d.status = 'alarmed' AND d.envelope_channel = 'peer' + AND (d.status = 'alarmed' OR (d.status = 'delivered' AND a.message_id IS NOT NULL)) + AND d.envelope_channel = 'peer' AND (d.exchange_id IS NULL OR d.exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`}) ORDER BY d.sent_seq, d.message_id `; diff --git a/apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts b/apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts new file mode 100644 index 0000000000000..77e51f1290759 --- /dev/null +++ b/apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts @@ -0,0 +1,15 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE j5_a2a_peer_delivery_alarm ( + project_id TEXT NOT NULL, + message_id TEXT NOT NULL, + reported_at TEXT NOT NULL, + reason TEXT NOT NULL, + PRIMARY KEY (project_id, message_id), + FOREIGN KEY (project_id, message_id) + REFERENCES j5_a2a_delivery(project_id, message_id) ON DELETE CASCADE + )`; +}); diff --git a/apps/server/src/j5/a2a/peerDeliveryBody.ts b/apps/server/src/j5/a2a/peerDeliveryBody.ts index 043f1ad06bf27..f50f369f66346 100644 --- a/apps/server/src/j5/a2a/peerDeliveryBody.ts +++ b/apps/server/src/j5/a2a/peerDeliveryBody.ts @@ -56,6 +56,7 @@ export const buildPeerDeliveryBody = Effect.fn("j5.a2a.peer.deliveryBody")(funct envelopeChannel: row.envelope_channel, text: row.message_text, originProjectId: row.origin_project_id ?? row.project_id, + ...(yield* deliveryAlarm(sql, row)), ...(yield* landing(sql, row)), ...(yield* exchangeFacts(sql, row)), ...(senderLabel.length === 0 ? {} : { senderLabel }), @@ -120,3 +121,15 @@ const exchangeFacts = Effect.fn("j5.a2a.peer.deliveryBody.exchangeFacts")(functi } return {}; }); + +const deliveryAlarm = Effect.fn("j5.a2a.peer.deliveryBody.alarm")(function* ( + sql: SqlClient.SqlClient, + row: PeerBodyRow, +) { + if (row.envelope_channel !== "lifecycle_notice" || row.exchange_role !== "none") return {}; + const sent = yield* sql<{ readonly payload: string }>`SELECT payload FROM j5_a2a_comm_event + WHERE project_id = ${row.project_id} AND seq = ${row.sent_seq} AND kind = 'message.sent'`; + if (sent[0] === undefined) return {}; + const payload = yield* decodeSentPayload(sent[0].payload); + return payload.deliveryAlarm === undefined ? {} : { deliveryAlarm: payload.deliveryAlarm }; +}); diff --git a/apps/server/src/j5/a2a/peerProtocol.ts b/apps/server/src/j5/a2a/peerProtocol.ts index 7eba07d85c35e..c1306c75ee7f0 100644 --- a/apps/server/src/j5/a2a/peerProtocol.ts +++ b/apps/server/src/j5/a2a/peerProtocol.ts @@ -5,7 +5,11 @@ import { } from "@t3tools/contracts/j5"; /** What this server tells every peer it can do, in a hello and in both directions of a poll. */ -export const ownPeerCapabilities = { poll: true, landing: true } satisfies PeerCapabilities; +export const ownPeerCapabilities = { + poll: true, + landing: true, + deliveryAlarms: true, +} satisfies PeerCapabilities; /** * The one compare for both directions of peering. A server states its peer diff --git a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts index 84785f05f0a08..24358ef4da314 100644 --- a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts +++ b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts @@ -77,6 +77,9 @@ const seed = Effect.fn("test.j5.neutralise.seed")(function* () { ${status === "retry_scheduled" ? at : null}, ${at}, ${at}, 'peer', ${handedOutAt})`; } + yield* sql`INSERT INTO j5_a2a_peer_delivery_alarm(project_id,message_id,reported_at,reason) + VALUES ('project','message-delivered',${at},'Peer thread delivery failed')`; + for (const [exchangeId, receiver, status, closedSeq] of [ ["exchange-open", "agent:b", "open", null], ["exchange-human", "human:operator", "open", null], @@ -188,6 +191,7 @@ it.layer(NodeServices.layer)("neutraliseCopiedDatabase", (it) => { playbookStepDeliveries: 1, }); assert.deepEqual(yield* actingRows(), nothingActing); + assert.equal((yield* sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, 0); // Stood down into states the product already reads, not removed. assert.deepEqual( diff --git a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts index 3512adfa03427..07ba6951b4e08 100644 --- a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts +++ b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts @@ -80,6 +80,10 @@ export const neutraliseJ5State = Effect.fn("j5.neutraliseJ5State")(function* () sql`DELETE FROM j5_a2a_peer RETURNING environment_id`, ); + // The copied server has no live peer whose measurements remain current here. + if (tables.has("j5_a2a_peer_delivery_alarm")) + yield* sql`DELETE FROM j5_a2a_peer_delivery_alarm`; + // The same projection an archive's `message.cancelled` writes (LedgerService). const deliveries = yield* count( "j5_a2a_delivery", diff --git a/docs/j5/product/a2a/index.md b/docs/j5/product/a2a/index.md index b3f63ee06f070..8a5c716269ee5 100644 --- a/docs/j5/product/a2a/index.md +++ b/docs/j5/product/a2a/index.md @@ -134,7 +134,7 @@ message, ask, reply, plain message, Exchange, intent, urgency, obligation, envel ### Delivery -12. Every delivery attempt is recorded; a delivery that fails past the retry limit is shown as an alarm attributed to the sender, leaves an ask's Exchange open, and is never marked repaired by time passing or by a different message succeeding. The sender is told once, in a notice that the message may not have been delivered, unless the sender is on a peer server that already holds the receipt. +12. Every delivery attempt is recorded; a delivery that fails past the retry limit is shown as an alarm attributed to the sender, leaves an ask's Exchange open, and is never marked repaired by time passing or by a different message succeeding. The sender is told once, in a notice that the message may not have been delivered, unless the sender is on a peer server that already holds the receipt. The origin's Fleet row still receives the peer's measured failure, without changing that acceptance receipt or delivering a thread notice. 13. A message to an agent whose turn is running is queued and delivered when the turn ends, unless its sender asked for a steer or a restart, or it is a peer message into a running Codex GPT 6 turn, which is delivered into the turn as an ordinary envelope with nothing added. 14. How the person's steer is offered, labeled and sent — in the composer and on a queued row, including whether a send steers or queues by default — follows upstream. An agent's steer or restart is asked for on `j5_send_message` and is defined with that tool ([agent tools](agent-tools.md)). 15. Platform notices are always queued, never steered. @@ -220,3 +220,4 @@ message, ask, reply, plain message, Exchange, intent, urgency, obligation, envel - 2026-10-18 — a delivery alarm is told to its sender in one not-delivered notice, as a refusal is; an alarmed ask's Exchange stays open for the sender to withdraw, and a sender on a peer server is not told of an alarm after its receipt. AC12 rewritten (Jackson, [#260](https://github.com/Jacksondr5/j5code/issues/260)). - 2026-10-19 — a not-delivered notice names its message by the id the send returned, and an ask by its intent too, so a sender with several messages out can tell which one it is about (Jackson, [#670](https://github.com/Jacksondr5/j5code/issues/670)). - 2026-10-20 — native-question answering retains upstream permission checks and unattributed response records; placed agents receive notices without raw thread waiting ([#674](https://github.com/Jacksondr5/j5code/pull/674), [#281](https://github.com/Jacksondr5/j5code/issues/281), [existing access decision](https://github.com/Jacksondr5/j5code/issues/345#issuecomment-6092125478)). +- 2026-10-23 — a receiver's later alarm returns to the origin's Fleet row as a measured diagnostic fact, with no authored notice and no change to the acceptance receipt or open Exchange; AC12 clarified (user-authorized repair; [review record](https://github.com/Jacksondr5/j5code/pull/662#discussion_r4359712499)). diff --git a/docs/j5/product/cross-device.md b/docs/j5/product/cross-device.md index 31f62bccbdf0d..be3222dfa8c90 100644 --- a/docs/j5/product/cross-device.md +++ b/docs/j5/product/cross-device.md @@ -43,7 +43,7 @@ Servers do not find each other; **the client introduces them.** The client is th **A person stays server-local.** A person's participant, their asks, and their inbox belong to each server they use; an ask to a person is delivered on the sender's own server, and the person's view of several servers is the client's merge described above. Peering carries messages between agents, and nothing else. -Delivery across peer servers is the same delivery with one more step: the send is a ledger row on the sender's server, the peer server records its own received row, and that acknowledgement is the sender's delivery receipt. Across servers the receipt means the peer server accepted and recorded the message; delivering it into the agent's thread is then the peer server's own delivery, which retries and alarms there, attributed to the sender as any delivery is. Sent directly, failure to reach the peer server retries and alarms on the sender's server as any failure does. To a polling peer, the message is stored without retrying or alarming until the peer polls for it, and the poller's acknowledgement is the receipt. A message that alarms on the sender's server, one the peer server refuses, or one cancelled before it got there, is reported to its sender; once the peer server has returned the receipt, an alarm there is not reported back. Everything that flows back — a reply, a silence notice, a lifecycle closure — travels the same path in reverse, which is why peering is mutual: one Exchange needs both directions. Peer servers reach each other directly, or one polls the other over connections it opens; a relay or tunnel is never a required part of it. +Delivery across peer servers is the same delivery with one more step: the send is a ledger row on the sender's server, the peer server records its own received row, and that acknowledgement is the sender's delivery receipt. Across servers the receipt means the peer server accepted and recorded the message; delivering it into the agent's thread is then the peer server's own delivery, which retries and alarms there, attributed to the sender as any delivery is. Sent directly, failure to reach the peer server retries and alarms on the sender's server as any failure does. To a polling peer, the message is stored without retrying or alarming until the peer polls for it, and the poller's acknowledgement is the receipt. A message that alarms on the sender's server, one the peer server refuses, or one cancelled before it got there, is reported to its sender; once the peer server has returned the receipt, no authored alarm notice is delivered back into the sender's thread. A receiver's later in-thread delivery alarm returns as a measured Fleet fact on the original sender, without a message in its thread. The original acceptance receipt remains true. The alarm stays visible after the Exchange closes, while the badge counts it only while that Exchange is open. Peers from before this capability continue exchanging without the extra diagnostic fact. Everything that flows back — a reply, a silence notice, a lifecycle closure — travels the same path in reverse, which is why peering is mutual: one Exchange needs both directions. Peer servers reach each other directly, or one polls the other over connections it opens; a relay or tunnel is never a required part of it. Peering is also where another person's server attaches, when that time comes — person boundaries, what may cross, and trust live in the peer record, and nothing else in the architecture needs to anticipate other people. @@ -109,3 +109,4 @@ What this never does: no replicated state, no multi-master, no moving a project' - 2026-10-07 — Squadrons retired: a project, its agents and its ledger live on one server, a participant is resolved straight to its server, and the address book lists a peer server's participants with their project (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — a steer or restart crosses to a peer server: two optional fields on a delivery, a `landing` capability, and a `landing_refused` answer. The protocol version stays 2, since each is an additive change ([#519](https://github.com/Jacksondr5/j5code/issues/519)). - 2026-10-18 — a message sent directly that alarms is reported to its sender, as a refused one is; an alarm on the peer server after its receipt is not reported back (Jackson, [#260](https://github.com/Jacksondr5/j5code/issues/260)). +- 2026-10-23 — an accepted peer message's later in-thread failure appears on the origin sender's Fleet row as a measured fact; the acceptance receipt and open-ask uncertainty remain, and no authored notice is delivered (user-authorized repair; [review record](https://github.com/Jacksondr5/j5code/pull/662#discussion_r4359712499)). diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index c65dfa5816ede..7cc52c374e475 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -748,6 +748,8 @@ export const PEER_PROTOCOL_VERSION = 2; /** Every peer request and response states its sender's version here; a server from before versioning sends none. */ export const PEER_PROTOCOL_HEADER = "x-j5-peer-protocol"; export const PeerCapabilities = Schema.Struct({ + /** Accepts authenticated facts about a previously accepted message's later thread delivery. */ + deliveryAlarms: Schema.optionalKey(Schema.Boolean), /** This server stores messages for a peer that polls for them. */ poll: Schema.optionalKey(Schema.Boolean), /** This server lands a message as its sender asked: a delivery's `landing` is read, not dropped. */ @@ -814,7 +816,15 @@ export const PeerDeliveryLanding = Schema.Struct({ }); export type PeerDeliveryLanding = typeof PeerDeliveryLanding.Type; +/** A diagnostic fact, never an authored message; the origin supplies identities and receipt time. */ +export const PeerDeliveryAlarm = Schema.Struct({ + messageId: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(4096)), + code: Schema.Literal("attempts-exhausted"), +}); +export type PeerDeliveryAlarm = typeof PeerDeliveryAlarm.Type; + export const PeerDeliveryRequest = Schema.Struct({ + deliveryAlarm: Schema.optional(PeerDeliveryAlarm), messageId: Schema.String.check(Schema.isNonEmpty()), /** Absent for a message that waits its turn, which is every message from an older server. */ landing: Schema.optional(PeerDeliveryLanding), From 32ee896ce38e42c8bc87ac9fbc7390d246ec43ad Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 14:19:48 +0000 Subject: [PATCH 05/11] fix(fleet): keep polling past early alarm facts --- apps/server/src/j5/a2a/PeerPoller.test.ts | 55 +++++++++++++++++++---- apps/server/src/j5/a2a/PeerPoller.ts | 16 ++++++- 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/apps/server/src/j5/a2a/PeerPoller.test.ts b/apps/server/src/j5/a2a/PeerPoller.test.ts index 4d141325250a9..d58640114aa27 100644 --- a/apps/server/src/j5/a2a/PeerPoller.test.ts +++ b/apps/server/src/j5/a2a/PeerPoller.test.ts @@ -32,6 +32,7 @@ import { EventSinkV2 } from "../../orchestration-v2/EventSink.ts"; import { A2ADeliveryWorker } from "./DeliveryWorker.ts"; import { A2ALedger } from "./LedgerService.ts"; import { + A2APeerDeliveryReceiptPendingError, A2APeerReceiverNotFoundError, PeerInboundService, type PeerInboundInput, @@ -51,7 +52,7 @@ import { } from "./PeerRegistryService.ts"; import { RosterService } from "./RosterService.ts"; import { peerRosterHash, toPeerRoster } from "./peerRoster.ts"; -import type { StoredCommEvent } from "./contracts.ts"; +import { LIFECYCLE_PARTICIPANT_ID, type StoredCommEvent } from "./contracts.ts"; /** * The polling side alone: one laptop polling one work VM. The VM is a scripted @@ -147,6 +148,7 @@ const rosterEntry = (archived: boolean): A2ARosterEntry => ({ }); interface Harness { + readonly originalAccepted: { value: boolean }; readonly answers: Array; readonly requests: Array; readonly received: Array; @@ -173,6 +175,7 @@ interface Harness { const makeHarness = Effect.gen(function* () { const harness: Harness = { + originalAccepted: { value: false }, answers: [], requests: [], received: [], @@ -321,14 +324,16 @@ const makeTestLayer = ( }), Layer.mock(PeerInboundService)({ receive: (input) => - input.receiverId === "agent:j5:a2a:thread:gone" - ? Effect.fail(new A2APeerReceiverNotFoundError({ participantId: input.receiverId })) - : input.receiverId === "agent:j5:a2a:thread:broken" - ? Effect.die("the ledger is down") - : Effect.sync(() => { - harness.received.push(input); - return { receivedSeq: harness.received.length, replay: false }; - }), + input.deliveryAlarm !== undefined && !harness.originalAccepted.value + ? Effect.fail(new A2APeerDeliveryReceiptPendingError({})) + : input.receiverId === "agent:j5:a2a:thread:gone" + ? Effect.fail(new A2APeerReceiverNotFoundError({ participantId: input.receiverId })) + : input.receiverId === "agent:j5:a2a:thread:broken" + ? Effect.die("the ledger is down") + : Effect.sync(() => { + harness.received.push(input); + return { receivedSeq: harness.received.length, replay: false }; + }), }), Layer.mock(A2ADeliveryWorker)({ notify: Effect.sync(() => { @@ -468,6 +473,38 @@ it.effect( }), ); +it.effect("retries an early alarm fact without holding later polled messages", () => + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* Effect.gen(function* () { + const report: PeerDeliveryRequest = { + ...delivery("early-alarm"), + senderId: LIFECYCLE_PARTICIPANT_ID, + envelopeChannel: "lifecycle_notice", + deliveryAlarm: { messageId: "message:original", code: "attempts-exhausted" }, + }; + harness.answers.push(pollAnswer({ deliveries: [report, delivery("after-alarm")] })); + assert.equal((yield* pollOnce).kind, "failed", "back off while the fact remains unrecorded"); + assert.deepStrictEqual( + harness.received.map((input) => input.messageId), + ["message:after-alarm"], + ); + + harness.originalAccepted.value = true; + harness.answers.push(pollAnswer({ deliveries: [report] })); + assert.deepStrictEqual(yield* pollOnce, { kind: "polled", received: 1, more: false }); + assert.deepStrictEqual(harness.requests[1]!.acks, [ + { messageId: "message:after-alarm", outcome: "received", receivedSeq: 1, replay: false }, + ]); + harness.answers.push(pollAnswer()); + yield* pollOnce; + assert.deepStrictEqual(harness.requests[2]!.acks, [ + { messageId: "message:early-alarm", outcome: "received", receivedSeq: 2, replay: false }, + ]); + }).pipe(Effect.provide(makeTestLayer(harness))); + }), +); + it.effect("stops on a rejected credential, sets a protocol mismatch aside, and says why", () => Effect.gen(function* () { const harness = yield* makeHarness; diff --git a/apps/server/src/j5/a2a/PeerPoller.ts b/apps/server/src/j5/a2a/PeerPoller.ts index e047409980449..9f6516522e920 100644 --- a/apps/server/src/j5/a2a/PeerPoller.ts +++ b/apps/server/src/j5/a2a/PeerPoller.ts @@ -23,7 +23,11 @@ import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/h import { EventSinkV2 } from "../../orchestration-v2/EventSink.ts"; import { A2ADeliveryWorker } from "./DeliveryWorker.ts"; import { A2ALedger } from "./LedgerService.ts"; -import { PeerInboundService, peerDeliveryRefusal } from "./PeerInboundService.ts"; +import { + A2APeerDeliveryReceiptPendingError, + PeerInboundService, + peerDeliveryRefusal, +} from "./PeerInboundService.ts"; import { PeerRegistryService } from "./PeerRegistryService.ts"; import { PEER_POLL_HOLD } from "./PeerStoreService.ts"; import { RosterService } from "./RosterService.ts"; @@ -115,6 +119,7 @@ interface PollState { const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); const decodePollResponse = Schema.decodeUnknownEffect(PeerPollResponse); +const isDeliveryReceiptPending = Schema.is(A2APeerDeliveryReceiptPendingError); const reasonOf = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause)); @@ -172,6 +177,15 @@ const make = (daemon: boolean) => continue; } const failure = Cause.findErrorOption(received.cause); + if ( + delivery.deliveryAlarm !== undefined && + Option.isSome(failure) && + isDeliveryReceiptPending(failure.value) + ) { + // A diagnostic has no message-order constraint; retry it without holding later traffic. + unrecorded = true; + continue; + } const refusal = Option.isSome(failure) ? peerDeliveryRefusal(failure.value) : null; if (refusal === null) { // Not a refusal: leave this and every later one unacknowledged, in From b25b43c624ddd7f3be485da50fc9e717cfabc10c Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 15:09:40 +0000 Subject: [PATCH 06/11] ci(j5): allow cold Chromium setup before server shards --- .github/workflows/j5-ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/j5-ci.yml b/.github/workflows/j5-ci.yml index 8fe06bdcb8f0b..15cbdc126da88 100644 --- a/.github/workflows/j5-ci.yml +++ b/.github/workflows/j5-ci.yml @@ -173,7 +173,8 @@ jobs: test_server: name: Test Server ${{ matrix.shard }} runs-on: ubuntu-24.04 - timeout-minutes: 15 + # Chromium installation shares this budget and can take ten minutes on a cold runner. + timeout-minutes: 25 strategy: fail-fast: false matrix: From 19dde72bf43b149e4bf8c52fa8e5dba1b5f9cb85 Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 23 Oct 2026 15:43:57 +0000 Subject: [PATCH 07/11] docs(a2a): keep delivery criterion in one sentence --- docs/j5/product/a2a/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/j5/product/a2a/index.md b/docs/j5/product/a2a/index.md index 8a5c716269ee5..18035fac2a795 100644 --- a/docs/j5/product/a2a/index.md +++ b/docs/j5/product/a2a/index.md @@ -134,7 +134,7 @@ message, ask, reply, plain message, Exchange, intent, urgency, obligation, envel ### Delivery -12. Every delivery attempt is recorded; a delivery that fails past the retry limit is shown as an alarm attributed to the sender, leaves an ask's Exchange open, and is never marked repaired by time passing or by a different message succeeding. The sender is told once, in a notice that the message may not have been delivered, unless the sender is on a peer server that already holds the receipt. The origin's Fleet row still receives the peer's measured failure, without changing that acceptance receipt or delivering a thread notice. +12. Every delivery attempt is recorded; a delivery that fails past the retry limit remains an alarm attributed to the sender, leaves an ask's Exchange open, and is never marked repaired by time passing or a different message succeeding; its sender receives one notice that it may not have been delivered, except after a peer acceptance receipt, when the origin's Fleet row receives the failure without changing that receipt or delivering a thread notice. 13. A message to an agent whose turn is running is queued and delivered when the turn ends, unless its sender asked for a steer or a restart, or it is a peer message into a running Codex GPT 6 turn, which is delivered into the turn as an ordinary envelope with nothing added. 14. How the person's steer is offered, labeled and sent — in the composer and on a queued row, including whether a send steers or queues by default — follows upstream. An agent's steer or restart is asked for on `j5_send_message` and is defined with that tool ([agent tools](agent-tools.md)). 15. Platform notices are always queued, never steered. From 303d43f54f4b49cc7b7281fe904c8e43facb4905 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 10:31:02 +0000 Subject: [PATCH 08/11] fix(fleet): read remote delivery alarms through client sources --- .github/workflows/j5-ci.yml | 3 +- FORK.md | 2 +- apps/server/src/j5/a2a/DeliveryWorker.ts | 51 +-- apps/server/src/j5/a2a/LedgerService.ts | 16 - apps/server/src/j5/a2a/Migrations.test.ts | 4 +- apps/server/src/j5/a2a/Migrations.ts | 3 - apps/server/src/j5/a2a/PeerHttp.test.ts | 4 +- apps/server/src/j5/a2a/PeerInboundService.ts | 104 +---- .../src/j5/a2a/PeerPollRoundTrip.test.ts | 103 ++--- apps/server/src/j5/a2a/PeerPoller.test.ts | 55 +-- apps/server/src/j5/a2a/PeerPoller.ts | 16 +- apps/server/src/j5/a2a/PeerRoundTrip.test.ts | 376 ++---------------- .../src/j5/a2a/PeerStoreService.test.ts | 6 +- apps/server/src/j5/a2a/contracts.ts | 6 +- apps/server/src/j5/a2a/fleetFacts.test.ts | 34 ++ apps/server/src/j5/a2a/fleetFacts.ts | 69 ++-- apps/server/src/j5/a2a/fleetRead.ts | 12 +- .../a2a/migrations/044_PeerDeliveryAlarms.ts | 15 - apps/server/src/j5/a2a/peerDeliveryBody.ts | 13 - apps/server/src/j5/a2a/peerProtocol.ts | 6 +- .../neutraliseCopiedDatabase.test.ts | 4 - .../persistence/neutraliseCopiedDatabase.ts | 4 - docs/j5/product/a2a/index.md | 3 +- docs/j5/product/cross-device.md | 3 +- docs/j5/product/features/fleet-page.md | 5 +- .../client-runtime/src/j5/fleetFacts.test.ts | 206 +++++++++- packages/client-runtime/src/j5/fleetFacts.ts | 151 ++++++- packages/contracts/src/j5.ts | 22 +- packages/contracts/src/j5/fleet.ts | 26 +- 29 files changed, 563 insertions(+), 759 deletions(-) delete mode 100644 apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts diff --git a/.github/workflows/j5-ci.yml b/.github/workflows/j5-ci.yml index 15cbdc126da88..8fe06bdcb8f0b 100644 --- a/.github/workflows/j5-ci.yml +++ b/.github/workflows/j5-ci.yml @@ -173,8 +173,7 @@ jobs: test_server: name: Test Server ${{ matrix.shard }} runs-on: ubuntu-24.04 - # Chromium installation shares this budget and can take ten minutes on a cold runner. - timeout-minutes: 25 + timeout-minutes: 15 strategy: fail-fast: false matrix: diff --git a/FORK.md b/FORK.md index 8bef954d0b0d6..563ad6f19e0bb 100644 --- a/FORK.md +++ b/FORK.md @@ -164,7 +164,7 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 34. Issue #105's cross-environment reads for the project ledger and the human inbox (read models merge in the client; authority stays on each server, per [`docs/j5/product/cross-device.md`](docs/j5/product/cross-device.md)): `packages/contracts/src/environment.ts` adds three optional capability keys beside upstream's existing optional capabilities: `j5ProjectLedger`, which gates every J5 read, and `j5Squadrons` and `j5HumanInbox`, the two keys a J5 server reported while its ledger was keyed by Squadron. `apps/server/src/environment/ServerEnvironment.ts` (with its test) spreads J5-owned `J5_LEDGER_CAPABILITIES` (`packages/contracts/src/j5.ts`) into its descriptor: `j5ProjectLedger` true and the two older keys false. A server that does not report `j5ProjectLedger` true is shown as unsupported in the Inbox, Fleet, Crew, peer and playbook views, which send it no reads; the sidebar's row reads, the archive preflight and the artifact list still ask it and get "Unknown request tag", as they got a 404 before. An older J5 server, which reports `j5Squadrons` true, is refused at connection (case 56). `packages/contracts/package.json` adds the `./j5` export for J5-owned `packages/contracts/src/j5.ts`; `packages/client-runtime/package.json` appends six `./j5/*` exports for the J5-owned read-source, HTTP, and merge modules under `packages/client-runtime/src/j5/`. Those modules reuse upstream's environment registry and per-environment query atoms. `packages/client-runtime/src/state/environmentHttpAuth.ts` exposes `executeAuthenticatedEnvironmentRawHttpRequest` for the one J5 route a client still calls, the read of an artifact's content (case 64 moved every other read onto the socket); it and upstream's typed-group `executeAuthenticatedEnvironmentHttpRequest` both sit on upstream's `executeEnvironmentRequest`, the one credential/retry implementation, and start their relay DPoP root spans through one helper. That core keeps a `url(httpBaseUrl)` callback, which the raw helper passes as is; the typed wrapper builds it from upstream's contract URL builder, so a typed caller signs the URL the client sends. This keeps cookie, bearer, and relay DPoP with one refresh-and-retry shared without assigning J5 routes to an unrelated upstream API group, and no J5 read falls back to the primary environment. The upstream mount that remains (`CommandPalette.logic.ts`'s thread value, `thread::`) carries the environment beside the id so two environments' rows never collide; no new mount or door is added. Environment labels appear only once a read model spans more than one environment. The draft's Squadron environment lock went with the draft chip (the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): `ChatView.tsx`'s three environment-selection doors are upstream's again. Native mobile screens are deferred. On every rebase, verify the capability keys stay optional, the J5 request helper still goes through the shared authenticated transport, and the scoped identities survive in each recorded mount. - Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read. Keep this subpath on upstream sync. + Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read; receiving-server alarms carry their origin identity for the shared client merge, whose coverage includes each sender's remote receiving environments. Keep this subpath on upstream sync. Cases 10, 11 and 12 are retired, so no launch policy remains to verify here. Client permission guards (Jackson's 2026-10-08 decision 23; [#506](https://github.com/Jacksondr5/j5code/issues/506)). J5's protected actions are registered with upstream's guard and its controls read the guard's answer, as upstream's own do: case 64. A session without the operate scope cannot use Crew approve and decline, Crew runtime answers, Stop and Archive crew, Inbox answers, artifact delete, the playbook and persona library mutations or the skill mutations; peering needs `access:write`. The server remains the authority in every case. diff --git a/apps/server/src/j5/a2a/DeliveryWorker.ts b/apps/server/src/j5/a2a/DeliveryWorker.ts index 06af51c1a5f1d..9c9398c211fb6 100644 --- a/apps/server/src/j5/a2a/DeliveryWorker.ts +++ b/apps/server/src/j5/a2a/DeliveryWorker.ts @@ -38,7 +38,6 @@ import { isMachineParticipantId, isOutsideAgentParticipantId, LedgerMessageId, - LIFECYCLE_PARTICIPANT_ID, MessageReceivedPayload, MessageSentPayload, ParticipantId, @@ -465,7 +464,6 @@ const makeLayer = (daemon: boolean) => // A peer server that refused the message already decided it; a // sender retired since cannot take that back, as with a receipt. if (yield* deliveryUnavailable(row, refusal !== undefined)) return null; - const reported = alarmed ? yield* peerAlarmFact(row, failedAt) : []; const told = refusal !== undefined ? yield* refusalNotices(row, refusal, failedAt) @@ -496,7 +494,6 @@ const makeLayer = (daemon: boolean) => createdAt: failedAt, }, ...told, - ...reported, ], }); }), @@ -559,51 +556,6 @@ const makeLayer = (daemon: boolean) => ]; }); - const peerAlarmFact = Effect.fn("j5.a2a.delivery.peerAlarmFact")(function* ( - row: DeliveryRow, - createdAt: string, - ) { - if ( - row.envelope_channel !== "peer" || - row.origin_environment_id === null || - row.origin_project_id === null - ) - return []; - const supported = yield* sql`SELECT 1 FROM j5_a2a_peer - WHERE environment_id = ${row.origin_environment_id} - AND json_extract(peer_capabilities, '$.deliveryAlarms') = 1`; - if (supported.length === 0) return []; - const received = yield* sql<{ - readonly payload: string; - }>`SELECT payload FROM j5_a2a_comm_event - WHERE project_id = ${row.project_id} AND seq = ${row.sent_seq} AND kind = 'message.received'`; - if (received[0] === undefined) return []; - const payload = yield* decodeReceivedPayload(received[0].payload); - // Legacy authored ids are unbounded; diagnostic limits must not roll back their alarm. - if (payload.originMessageId === undefined || payload.originMessageId.length > 4096) - return []; - return [ - { - kind: "message.sent", - sender: LIFECYCLE_PARTICIPANT_ID, - receiver: ParticipantId.make(row.sender_id), - exchangeId: null, - correlationId: CorrelationId.make(`correlation:peer-delivery-alarm:${row.message_id}`), - payload: { - messageId: LedgerMessageId.make(`message:peer-delivery-alarm:${row.message_id}`), - text: "Peer delivery alarm fact.", - originProjectId: LedgerProjectId.make(row.project_id), - receiverProjectId: LedgerProjectId.make(row.origin_project_id), - receiverEnvironmentId: row.origin_environment_id, - exchangeRole: "none", - envelopeChannel: "lifecycle_notice", - deliveryAlarm: { messageId: payload.originMessageId, code: "attempts-exhausted" }, - }, - createdAt, - }, - ] satisfies ReadonlyArray; - }); - /** * What the sender is told of an alarm: one notice that the message may not * have been delivered, naming the receiver and what the last attempt failed @@ -611,8 +563,7 @@ const makeLayer = (daemon: boolean) => * acknowledged after the wait for it timed out. So an alarmed ask's Exchange * stays open (a2a AC12), and the alarm stays a problem until the sender * withdraws it. A sender on a peer server is not told, as - * with a removed queued message; only the capability-gated Fleet fact crosses back. - * Nobody is told of a platform notice's alarm. + * with a removed queued message, and nobody is told of a platform notice's alarm. */ const alarmNotices = Effect.fn("j5.a2a.delivery.alarmNotices")(function* ( row: DeliveryRow, diff --git a/apps/server/src/j5/a2a/LedgerService.ts b/apps/server/src/j5/a2a/LedgerService.ts index 196efaf00f8f0..6fe67a49744f0 100644 --- a/apps/server/src/j5/a2a/LedgerService.ts +++ b/apps/server/src/j5/a2a/LedgerService.ts @@ -369,10 +369,6 @@ export const layer: Layer.Layer< } if (event.kind === "participant.left" || event.kind === "participant.deleted") { if (event.kind === "participant.deleted") { - yield* sql`DELETE FROM j5_a2a_peer_delivery_alarm - WHERE project_id = ${event.projectId} AND message_id IN ( - SELECT message_id FROM j5_a2a_delivery WHERE project_id = ${event.projectId} - AND sender_id = ${id})`; yield* sql`DELETE FROM j5_a2a_participant_placement WHERE project_id = ${event.projectId} AND participant_id = ${id}`; } yield* sql` @@ -585,18 +581,6 @@ export const layer: Layer.Layer< } case "message.delivery_failed": { const payload = yield* decodeMessageDeliveryFailed(event.payload); - if (payload.peerReported === true) { - yield* sql`INSERT INTO j5_a2a_peer_delivery_alarm - (project_id, message_id, reported_at, reason) - SELECT project_id, message_id, ${event.createdAt}, ${payload.error} - FROM j5_a2a_delivery - WHERE project_id = ${event.projectId} AND message_id = ${payload.messageId} - AND receiver_environment_id = ${payload.peerEnvironmentId ?? null} - AND origin_environment_id IS NULL AND envelope_channel = 'peer' - AND status = 'delivered' - ON CONFLICT(project_id, message_id) DO NOTHING`; - return; - } const rows = yield* sql<{ readonly message_id: string }>` UPDATE j5_a2a_delivery SET diff --git a/apps/server/src/j5/a2a/Migrations.test.ts b/apps/server/src/j5/a2a/Migrations.test.ts index bc05c4f789a2f..ca08eb2c40dc1 100644 --- a/apps/server/src/j5/a2a/Migrations.test.ts +++ b/apps/server/src/j5/a2a/Migrations.test.ts @@ -97,7 +97,6 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () { migration_id: 41, name: "SharedConversation" }, { migration_id: 42, name: "EveryoneHereAsks" }, { migration_id: 43, name: "TaskSchedulers" }, - { migration_id: 44, name: "PeerDeliveryAlarms" }, ]); assert.deepStrictEqual( migrationEntries.map(([id, name]) => [id, name]), @@ -145,7 +144,6 @@ it.effect("tracks J5 A2A migrations independently from upstream migrations", () [41, "SharedConversation"], [42, "EveryoneHereAsks"], [43, "TaskSchedulers"], - [44, "PeerDeliveryAlarms"], ], ); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), @@ -1394,7 +1392,7 @@ it.effect("recreates earlier-shaped crews tables when 14 runs over them", () => applied.map((row) => row.migration_id), [ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, 44, + 36, 37, 38, 39, 40, 41, 42, 43, ], ); const memberColumns = yield* sql<{ readonly name: string }>` diff --git a/apps/server/src/j5/a2a/Migrations.ts b/apps/server/src/j5/a2a/Migrations.ts index 1987c1b387c9a..bd79a2a8609a3 100644 --- a/apps/server/src/j5/a2a/Migrations.ts +++ b/apps/server/src/j5/a2a/Migrations.ts @@ -45,8 +45,6 @@ import Migration0041 from "./migrations/041_SharedConversation.ts"; import Migration0042 from "./migrations/042_EveryoneHereAsks.ts"; import Migration0043 from "./migrations/043_TaskSchedulers.ts"; -import Migration0044 from "./migrations/044_PeerDeliveryAlarms.ts"; - export const J5_A2A_MIGRATIONS_TABLE = "j5_a2a_migrations"; // Every entry already in this list is persisted migration history: keep its id, file, and @@ -100,7 +98,6 @@ export const migrationEntries = [ [41, "SharedConversation", Migration0041], [42, "EveryoneHereAsks", Migration0042], [43, "TaskSchedulers", Migration0043], - [44, "PeerDeliveryAlarms", Migration0044], ] as const; const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/j5/a2a/PeerHttp.test.ts b/apps/server/src/j5/a2a/PeerHttp.test.ts index d80ec836063f0..4189796231827 100644 --- a/apps/server/src/j5/a2a/PeerHttp.test.ts +++ b/apps/server/src/j5/a2a/PeerHttp.test.ts @@ -355,7 +355,7 @@ it("answers hello with this environment and the credential's subject, and comple assert.equal(body.peerProtocolVersion, PEER_PROTOCOL_VERSION); assert.deepStrictEqual( body.capabilities, - { poll: true, landing: true, deliveryAlarms: true }, + { poll: true, landing: true }, "this server stores for a poller, and lands a message as its sender asked", ); assert.deepStrictEqual( @@ -716,7 +716,7 @@ it("shows a recorded peer only the agents it could address, and nobody else the assert.equal(response.status, 200); assert.deepStrictEqual(await response.json(), { label: "Work VM", - capabilities: { poll: true, landing: true, deliveryAlarms: true }, + capabilities: { poll: true, landing: true }, agents: [ { participantId: "agent:j5:a2a:thread:local-triage", diff --git a/apps/server/src/j5/a2a/PeerInboundService.ts b/apps/server/src/j5/a2a/PeerInboundService.ts index 54edcc00117a0..8fd8fea1eb58a 100644 --- a/apps/server/src/j5/a2a/PeerInboundService.ts +++ b/apps/server/src/j5/a2a/PeerInboundService.ts @@ -155,12 +155,6 @@ export class A2APeerAskIntentRequiredError extends Schema.TaggedError()( - "A2APeerDeliveryReceiptPendingError", - {}, -) {} - /** * A peer speaks only for its agents. It may not deliver as a person, a machine * participant or the platform, and an agent's message travels on the peer @@ -190,7 +184,7 @@ export class A2APeerSenderNotAllowedError extends Schema.TaggedError Effect.Effect; @@ -258,7 +251,7 @@ const localMessageIdFor = (input: { /** Refuse the sender kinds, channels and roles a peer may not use, before anything is read. */ /** * Who a peer may speak as. Its agents, on the peer channel, never a terminal - * notice. Or the platform itself, as a terminal notice, delivery-alarm fact or silence notice in the + * notice. Or the platform itself, as exactly one of two notices, each in the * shape its producer writes: the lifecycle's terminal notice (the fact that * ends an Exchange) or the silence detector's notice (not part of any * Exchange, naming the one whose answerer went quiet). The receive path then @@ -268,19 +261,6 @@ const assertSenderShape = (input: PeerInboundInput) => { const senderId = ParticipantId.make(input.senderId); const refuse = (reason: A2APeerSenderNotAllowedError["reason"]) => Effect.fail(new A2APeerSenderNotAllowedError({ senderId, reason })); - if (input.deliveryAlarm !== undefined) { - if ( - senderId === LIFECYCLE_PARTICIPANT_ID && - input.envelopeChannel === "lifecycle_notice" && - input.exchangeRole === "none" && - input.exchangeId === null && - input.terminal === undefined && - input.regardingExchangeId === undefined && - input.landing === undefined - ) - return Effect.succeed({ senderId, platform: "delivery-alarm" as const }); - return refuse("platform"); - } if (isHumanParticipantId(senderId)) return refuse("human"); if (isMachineParticipantId(senderId)) return refuse("machine"); if (isOutsideAgentParticipantId(senderId)) return refuse("outside"); @@ -407,91 +387,15 @@ export const layer: Layer.Layer 0) return null; - const rows = yield* sql<{ - readonly project_id: string; - readonly message_id: string; - readonly sender_id: string; - readonly receiver_id: string; - readonly exchange_id: string | null; - readonly correlation_id: string; - readonly status: string; - readonly attempts: number; - }>`SELECT d.project_id, d.message_id, d.sender_id, d.receiver_id, d.exchange_id, - d.correlation_id, d.status, d.attempts - FROM j5_a2a_delivery d JOIN j5_a2a_membership m - ON m.project_id = d.project_id AND m.participant_id = d.sender_id AND m.archived_at IS NULL - WHERE d.message_id = ${report.messageId} AND d.receiver_environment_id = ${input.originEnvironmentId} - AND d.origin_environment_id IS NULL AND d.envelope_channel = 'peer' - LIMIT 2`; - const row = rows.length === 1 ? rows[0] : undefined; - if (row === undefined) return null; - if (row.status === "pending" || row.status === "retry_scheduled") - return yield* new A2APeerDeliveryReceiptPendingError({}); - if (row.status !== "delivered") return null; - const receivedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso)); - return yield* writer.appendEventsInTransaction({ - commandId, - projectId: LedgerProjectId.make(row.project_id), - acceptedAt: receivedAt, - events: [ - { - kind: "message.delivery_failed", - sender: ParticipantId.make(row.sender_id), - receiver: ParticipantId.make(row.receiver_id), - exchangeId: row.exchange_id === null ? null : ExchangeId.make(row.exchange_id), - correlationId: CorrelationId.make(row.correlation_id), - createdAt: receivedAt, - payload: { - messageId: row.message_id, - attempt: Math.max(1, row.attempts), - error: - "The peer accepted this message, but delivery into its agent's thread failed.", - nextAttemptAt: null, - alarmed: true, - peerReported: true, - peerEnvironmentId: input.originEnvironmentId, - }, - }, - ], - }); - }), - ), - ); - if (outcome?.committed) yield* writer.publishCommitted(outcome.events); - // Unknown, foreign, retired and replayed messages have the same non-oracular receipt. - return { receivedSeq: 1, replay: false } satisfies PeerInboundResult; - }); - const receive: PeerInboundServiceShape["receive"] = (input) => Effect.gen(function* () { - const shape = yield* assertSenderShape(input); - if (shape.platform === "delivery-alarm") return yield* receiveDeliveryAlarm(input); const commandId = peerReceiveCommandId({ originEnvironmentId: input.originEnvironmentId, messageId: input.messageId, }); const replayed = yield* priorReceipt(commandId); if (replayed !== null) return replayed; - const { senderId, platform } = shape; + const { senderId, platform } = yield* assertSenderShape(input); if (platform === null) yield* assertSenderOwnedByOrigin(senderId, input.originEnvironmentId); const receiverId = ParticipantId.make(input.receiverId); diff --git a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts index 7489385ffb00f..b69230be1fc94 100644 --- a/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerPollRoundTrip.test.ts @@ -35,6 +35,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; +import { readFleetLedgerFacts } from "./fleetFacts.ts"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as SqlClient from "effect/sql/SqlClient"; @@ -72,7 +73,6 @@ import { } from "./PeerStoreService.ts"; import { RosterService } from "./RosterService.ts"; import { A2ASendService, layer as sendLayer } from "./SendService.ts"; -import { readFleetLedgerFacts } from "./fleetFacts.ts"; import { A2ASilenceDetector, manualLayer as silenceDetectorLayer } from "./SilenceDetector.ts"; import { CommCommandId, @@ -237,28 +237,18 @@ const makeCore = (input: { const recordingTransport = ( delivered: Ref.Ref>, deliverPeer: A2ADeliveryTransport["Service"]["deliverPeer"], - failLocal = false, ) => Layer.succeed( A2ADeliveryTransport, A2ADeliveryTransport.of({ cancelAgent: () => Effect.succeed("cancelled" as const), - deliverAgent: (input) => - failLocal - ? Effect.fail( - new A2ADeliveryTransportError({ - operation: "forced local delivery failure", - cause: "private-local-error", - }), - ) - : Ref.update(delivered, (rows) => [...rows, input]), + deliverAgent: (input) => Ref.update(delivered, (rows) => [...rows, input]), deliverHuman: () => Effect.void, deliverPeer, }), ); interface VmOptions { - readonly failLocal?: boolean; readonly removing?: Effect.Effect; /** A database file instead of memory, so a test can read it from a second connection. */ readonly filename?: string; @@ -281,10 +271,8 @@ const makeVm = (delivered: Ref.Ref>, options: VmOption const core = makeCore({ database, delivered, - transport: recordingTransport( - delivered, - () => Effect.die("the VM never sends to the laptop; it stores for it"), - options.failLocal, + transport: recordingTransport(delivered, () => + Effect.die("the VM never sends to the laptop; it stores for it"), ), directory, }); @@ -558,6 +546,10 @@ const vmAsksLaptop = Effect.fn("test.j5.a2a.peer.pollRoundTrip.vmAsks")(function // The next poll acknowledges it. yield* pair.poll; assert.equal((yield* deliveryStatus(pair.vmServer.sql, asked.messageId))?.status, "delivered"); + const receivedOrigins = yield* pair.laptopServer.sql<{ origin_environment_id: string }>` + SELECT origin_environment_id FROM j5_a2a_delivery WHERE exchange_id = ${asked.exchangeId} + `; + assert.equal(receivedOrigins[0]?.origin_environment_id, vmDescriptor.environmentId); return ExchangeId.make(asked.exchangeId!); }); @@ -1035,54 +1027,33 @@ const runEnded = (thread: ThreadId, status: "completed" | "failed"): Orchestrati } as OrchestrationV2StoredEvent; }; -it.effect( - "returns a receiver's later delivery alarm through the poll queue to its original sender", - () => - Effect.scoped( - Effect.gen(function* () { - const pair = yield* pollPair({ failLocal: true }); - const sent = yield* pair.laptopServer.send.send({ - commandId: CommCommandId.make("command:poll-delivery-alarm"), - senderThreadId: laptop.agent.threadId, - to: vm.agent.id, - message: "Inspect the incident", - expectReply: true, - intent: "incident", - acceptedAt: timestamp, - }); - assert.equal((yield* pair.laptopServer.worker.runOnce)?.state, "delivered"); - assert.equal((yield* pair.vmServer.worker.runOnce)?.state, "retry_scheduled"); - yield* TestClock.adjust("250 millis"); - yield* pair.vmServer.worker.runOnce; - yield* TestClock.adjust("500 millis"); - assert.equal((yield* pair.vmServer.worker.runOnce)?.state, "alarmed"); - assert.isNull( - yield* pair.vmServer.worker.runOnce, - "the VM stores its fact for the polling origin", - ); - assert.deepStrictEqual(yield* pair.poll, { kind: "polled", received: 1, more: false }); - const facts = yield* readFleetLedgerFacts( - pair.laptopServer.sql, - laptop.projectId, - [laptop.agent.id], - () => null, - ); - const problem = facts.problems.get(laptop.agent.id)![0]!; - assert.isTrue(problem.kind === "delivery-failed" && problem.exchangeOpen); - assert.equal( - (yield* deliveryStatus(pair.laptopServer.sql, sent.messageId))?.status, - "delivered", - ); - assert.equal( - (yield* Ref.get(pair.laptopDelivered)).length, - 0, - "no authored thread message", - ); - yield* pair.poll; - assert.equal( - (yield* pair.laptopServer.sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, - 1, - ); - }), - ), +it.effect("exposes a polled receiver alarm under the origin's client environment identity", () => + Effect.scoped( + Effect.gen(function* () { + const pair = yield* pollPair(); + const exchangeId = yield* vmAsksLaptop(pair, "command:poll-alarm-read"); + const accepted = yield* pair.vmServer + .sql`SELECT * FROM j5_a2a_delivery WHERE exchange_id = ${exchangeId}`; + yield* pair.laptopServer + .sql`UPDATE j5_a2a_delivery SET status = 'alarmed', last_error = 'thread unavailable' + WHERE exchange_id = ${exchangeId}`; + const facts = yield* readFleetLedgerFacts( + pair.laptopServer.sql, + laptop.projectId, + [laptop.agent.id], + () => null, + ); + assert.equal(facts.remoteDeliveryAlarms.length, 1); + assert.equal(facts.remoteDeliveryAlarms[0]?.originEnvironmentId, vmDescriptor.environmentId); + assert.equal(facts.remoteDeliveryAlarms[0]?.senderId, vm.agent.id); + assert.equal(facts.remoteDeliveryAlarms[0]?.problem.exchangeId, exchangeId); + assert.isTrue(facts.remoteDeliveryAlarms[0]?.problem.exchangeOpen); + assert.equal(facts.problems.size, 0); + assert.deepStrictEqual(yield* pair.poll, { kind: "polled", received: 0, more: false }); + assert.deepStrictEqual( + yield* pair.vmServer.sql`SELECT * FROM j5_a2a_delivery WHERE exchange_id = ${exchangeId}`, + accepted, + ); + }), + ), ); diff --git a/apps/server/src/j5/a2a/PeerPoller.test.ts b/apps/server/src/j5/a2a/PeerPoller.test.ts index d58640114aa27..4d141325250a9 100644 --- a/apps/server/src/j5/a2a/PeerPoller.test.ts +++ b/apps/server/src/j5/a2a/PeerPoller.test.ts @@ -32,7 +32,6 @@ import { EventSinkV2 } from "../../orchestration-v2/EventSink.ts"; import { A2ADeliveryWorker } from "./DeliveryWorker.ts"; import { A2ALedger } from "./LedgerService.ts"; import { - A2APeerDeliveryReceiptPendingError, A2APeerReceiverNotFoundError, PeerInboundService, type PeerInboundInput, @@ -52,7 +51,7 @@ import { } from "./PeerRegistryService.ts"; import { RosterService } from "./RosterService.ts"; import { peerRosterHash, toPeerRoster } from "./peerRoster.ts"; -import { LIFECYCLE_PARTICIPANT_ID, type StoredCommEvent } from "./contracts.ts"; +import type { StoredCommEvent } from "./contracts.ts"; /** * The polling side alone: one laptop polling one work VM. The VM is a scripted @@ -148,7 +147,6 @@ const rosterEntry = (archived: boolean): A2ARosterEntry => ({ }); interface Harness { - readonly originalAccepted: { value: boolean }; readonly answers: Array; readonly requests: Array; readonly received: Array; @@ -175,7 +173,6 @@ interface Harness { const makeHarness = Effect.gen(function* () { const harness: Harness = { - originalAccepted: { value: false }, answers: [], requests: [], received: [], @@ -324,16 +321,14 @@ const makeTestLayer = ( }), Layer.mock(PeerInboundService)({ receive: (input) => - input.deliveryAlarm !== undefined && !harness.originalAccepted.value - ? Effect.fail(new A2APeerDeliveryReceiptPendingError({})) - : input.receiverId === "agent:j5:a2a:thread:gone" - ? Effect.fail(new A2APeerReceiverNotFoundError({ participantId: input.receiverId })) - : input.receiverId === "agent:j5:a2a:thread:broken" - ? Effect.die("the ledger is down") - : Effect.sync(() => { - harness.received.push(input); - return { receivedSeq: harness.received.length, replay: false }; - }), + input.receiverId === "agent:j5:a2a:thread:gone" + ? Effect.fail(new A2APeerReceiverNotFoundError({ participantId: input.receiverId })) + : input.receiverId === "agent:j5:a2a:thread:broken" + ? Effect.die("the ledger is down") + : Effect.sync(() => { + harness.received.push(input); + return { receivedSeq: harness.received.length, replay: false }; + }), }), Layer.mock(A2ADeliveryWorker)({ notify: Effect.sync(() => { @@ -473,38 +468,6 @@ it.effect( }), ); -it.effect("retries an early alarm fact without holding later polled messages", () => - Effect.gen(function* () { - const harness = yield* makeHarness; - yield* Effect.gen(function* () { - const report: PeerDeliveryRequest = { - ...delivery("early-alarm"), - senderId: LIFECYCLE_PARTICIPANT_ID, - envelopeChannel: "lifecycle_notice", - deliveryAlarm: { messageId: "message:original", code: "attempts-exhausted" }, - }; - harness.answers.push(pollAnswer({ deliveries: [report, delivery("after-alarm")] })); - assert.equal((yield* pollOnce).kind, "failed", "back off while the fact remains unrecorded"); - assert.deepStrictEqual( - harness.received.map((input) => input.messageId), - ["message:after-alarm"], - ); - - harness.originalAccepted.value = true; - harness.answers.push(pollAnswer({ deliveries: [report] })); - assert.deepStrictEqual(yield* pollOnce, { kind: "polled", received: 1, more: false }); - assert.deepStrictEqual(harness.requests[1]!.acks, [ - { messageId: "message:after-alarm", outcome: "received", receivedSeq: 1, replay: false }, - ]); - harness.answers.push(pollAnswer()); - yield* pollOnce; - assert.deepStrictEqual(harness.requests[2]!.acks, [ - { messageId: "message:early-alarm", outcome: "received", receivedSeq: 2, replay: false }, - ]); - }).pipe(Effect.provide(makeTestLayer(harness))); - }), -); - it.effect("stops on a rejected credential, sets a protocol mismatch aside, and says why", () => Effect.gen(function* () { const harness = yield* makeHarness; diff --git a/apps/server/src/j5/a2a/PeerPoller.ts b/apps/server/src/j5/a2a/PeerPoller.ts index 9f6516522e920..e047409980449 100644 --- a/apps/server/src/j5/a2a/PeerPoller.ts +++ b/apps/server/src/j5/a2a/PeerPoller.ts @@ -23,11 +23,7 @@ import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/h import { EventSinkV2 } from "../../orchestration-v2/EventSink.ts"; import { A2ADeliveryWorker } from "./DeliveryWorker.ts"; import { A2ALedger } from "./LedgerService.ts"; -import { - A2APeerDeliveryReceiptPendingError, - PeerInboundService, - peerDeliveryRefusal, -} from "./PeerInboundService.ts"; +import { PeerInboundService, peerDeliveryRefusal } from "./PeerInboundService.ts"; import { PeerRegistryService } from "./PeerRegistryService.ts"; import { PEER_POLL_HOLD } from "./PeerStoreService.ts"; import { RosterService } from "./RosterService.ts"; @@ -119,7 +115,6 @@ interface PollState { const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); const decodePollResponse = Schema.decodeUnknownEffect(PeerPollResponse); -const isDeliveryReceiptPending = Schema.is(A2APeerDeliveryReceiptPendingError); const reasonOf = (cause: unknown) => (cause instanceof Error ? cause.message : String(cause)); @@ -177,15 +172,6 @@ const make = (daemon: boolean) => continue; } const failure = Cause.findErrorOption(received.cause); - if ( - delivery.deliveryAlarm !== undefined && - Option.isSome(failure) && - isDeliveryReceiptPending(failure.value) - ) { - // A diagnostic has no message-order constraint; retry it without holding later traffic. - unrecorded = true; - continue; - } const refusal = Option.isSome(failure) ? peerDeliveryRefusal(failure.value) : null; if (refusal === null) { // Not a refusal: leave this and every later one unacknowledged, in diff --git a/apps/server/src/j5/a2a/PeerRoundTrip.test.ts b/apps/server/src/j5/a2a/PeerRoundTrip.test.ts index 97ad189114f29..43d19ea232f48 100644 --- a/apps/server/src/j5/a2a/PeerRoundTrip.test.ts +++ b/apps/server/src/j5/a2a/PeerRoundTrip.test.ts @@ -14,11 +14,7 @@ import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import * as Schema from "effect/Schema"; -import { PeerCapabilities, PeerDeliveryRequest, PeerDeliveryResponse } from "@t3tools/contracts/j5"; -import { ownPeerCapabilities } from "./peerProtocol.ts"; import { readFleetLedgerFacts } from "./fleetFacts.ts"; -import { readsChangedByLedgerEvent } from "./ReadChangeFeeds.ts"; import * as SqlClient from "effect/sql/SqlClient"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; @@ -58,8 +54,6 @@ import { ParticipantId, LedgerProjectId, type AgentParticipant, - LIFECYCLE_PARTICIPANT_ID, - type StoredCommEvent, } from "./contracts.ts"; /** @@ -71,15 +65,6 @@ import { */ const timestamp = "2026-09-16T12:00:00.000Z"; -const isPeerDelivery = Schema.is(PeerDeliveryRequest); -const isPeerReceipt = Schema.is(PeerDeliveryResponse); -const decodePeerCapabilities = Schema.decodeUnknownSync(PeerCapabilities); -const decodeLegacyCapabilities = Schema.decodeUnknownSync( - Schema.Struct({ - poll: Schema.optionalKey(Schema.Boolean), - landing: Schema.optionalKey(Schema.Boolean), - }), -); interface Server { readonly environmentId: string; @@ -168,8 +153,8 @@ const makeServer = ( failLocal ? Effect.fail( new A2ADeliveryTransportError({ - operation: "private-path/token-local-error", - cause: "private-secret", + operation: "deliver to agent", + cause: "thread unavailable", }), ) : Ref.update(delivered, (rows) => [...rows, input]), @@ -281,8 +266,8 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve yield* runJ5A2AMigrations(); const sql = yield* SqlClient.SqlClient; yield* sql` - INSERT INTO j5_a2a_peer (environment_id, label, link_mode, origin, credential, peer_capabilities, created_at, updated_at) - VALUES (${peer.environmentId}, ${peer.environmentId}, 'push', 'https://peer.example', 'peer-token', '{"deliveryAlarms":true}', ${timestamp}, ${timestamp}) + INSERT INTO j5_a2a_peer (environment_id, label, link_mode, origin, credential, created_at, updated_at) + VALUES (${peer.environmentId}, ${peer.environmentId}, 'push', 'https://peer.example', 'peer-token', ${timestamp}, ${timestamp}) `; const ledger = yield* A2ALedger; yield* ledger.ensureProject({ projectId: self.projectId, createdAt: timestamp }); @@ -306,7 +291,6 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve worker: yield* A2ADeliveryWorker, lifecycle: yield* A2ALifecycleService, silence: yield* A2ASilenceDetector, - ledger, sql: yield* SqlClient.SqlClient, }; }); @@ -314,7 +298,7 @@ const seed = Effect.fn("test.j5.a2a.peer.roundtrip.seed")(function* (self: Serve /** Both servers up and introduced, with Work's agent holding an open ask to Home's agent that has crossed. */ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")(function* ( commandId: string, - failHome = false, + failReceiver = false, ) { const workDoor = yield* Ref.make(null); const homeDoor = yield* Ref.make(null); @@ -325,7 +309,7 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( makeServer(work, home, "Home", homeDoor, workDelivered, crossed), ); const homeContext = yield* Layer.build( - makeServer(home, work, "Work", workDoor, homeDelivered, crossed, failHome), + makeServer(home, work, "Work", workDoor, homeDelivered, crossed, failReceiver), ); const workServer = yield* seed(work, home).pipe(Effect.provide(workContext)); const homeServer = yield* seed(home, work).pipe(Effect.provide(homeContext)); @@ -343,13 +327,9 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( assert.equal((yield* workServer.worker.runOnce)?.state, "delivered"); assert.equal( (yield* homeServer.worker.runOnce)?.state, - failHome ? "retry_scheduled" : "delivered", - ); - assert.equal( - (yield* Ref.get(homeDelivered)).length, - failHome ? 0 : 1, - "the ask's thread delivery", + failReceiver ? "retry_scheduled" : "delivered", ); + assert.equal((yield* Ref.get(homeDelivered)).length, failReceiver ? 0 : 1); return { workServer, homeServer, @@ -357,7 +337,6 @@ const pairWithOpenAsk = Effect.fn("test.j5.a2a.peer.roundtrip.pairWithOpenAsk")( homeDelivered, crossed, exchangeId: ExchangeId.make(asked.exchangeId!), - messageId: asked.messageId, }; }); @@ -730,327 +709,40 @@ it.effect( ), ); -it.effect( - "reports accepted peer messages that later fail in-thread without changing acceptance or closing the ask", - () => - Effect.scoped( - Effect.gen(function* () { - const pair = yield* pairWithOpenAsk("command:remote-alarm", true); - const original = () => - pair.workServer.sql`SELECT * FROM j5_a2a_delivery WHERE message_id = ${pair.messageId}`; - const before = yield* original(); - yield* TestClock.adjust("250 millis"); - assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "retry_scheduled"); - yield* TestClock.adjust("500 millis"); - assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "alarmed"); - assert.equal( - (yield* pair.homeServer.worker.runOnce)?.state, - "delivered", - "the fact crosses the real peer transport", - ); - assert.deepStrictEqual(yield* original(), before, "the origin acceptance is immutable"); - const facts = yield* readFleetLedgerFacts( - pair.workServer.sql, - work.projectId, - [work.agent.id], - () => null, - ); - const problems = facts.problems.get(work.agent.id)!; - assert.equal(problems.length, 1); - assert.isTrue(problems[0]?.kind === "delivery-failed" && problems[0].exchangeOpen); - assert.notInclude(JSON.stringify(problems), "private-"); - assert.equal( - (yield* exchangeStatus(pair.workServer.sql, pair.exchangeId))[0]?.status, - "open", - ); - assert.equal( - (yield* Ref.get(pair.workDelivered)).length, - 0, - "the fact is never injected into the sender thread", - ); - const event = (yield* pair.workServer.sql<{ - readonly kind: string; - readonly payload: string; - }>` - SELECT kind, payload FROM j5_a2a_comm_event WHERE json_extract(payload, '$.peerReported') = 1`)[0]!; - assert.equal(event.kind, "message.delivery_failed"); - assert.equal( - (yield* pair.workServer - .sql`SELECT 1 FROM j5_a2a_comm_event WHERE kind IN ('message.received','silence.notice')`) - .length, - 0, - ); - assert.equal((yield* pair.workServer.sql`SELECT 1 FROM j5_a2a_human_inbox`).length, 0); - assert.include( - readsChangedByLedgerEvent({ - kind: event.kind, - receiver: home.agent.id, - payload: JSON.parse(event.payload), - } as StoredCommEvent), - "fleet", - ); - yield* pair.workServer.send.clearOwnAsk({ - commandId: CommCommandId.make("command:remote-alarm-clear"), - senderThreadId: work.agent.threadId, - exchangeId: pair.exchangeId, - acceptedAt: timestamp, - }); - const cleared = yield* readFleetLedgerFacts( - pair.workServer.sql, - work.projectId, - [work.agent.id], - () => null, - ); - assert.equal(cleared.problems.get(work.agent.id)?.length, 1, "the historical chip stays"); - const clearedProblem = cleared.problems.get(work.agent.id)![0]!; - assert.isFalse(clearedProblem.kind === "delivery-failed" && clearedProblem.exchangeOpen); - }), - ), -); - -it.effect( - "binds alarm facts only to accepted authored messages for the authenticated peer, idempotently", - () => - Effect.scoped( - Effect.gen(function* () { - const pair = yield* pairWithOpenAsk("command:report-binding"); - const sql = pair.workServer.sql; - const report = { - messageId: "envelope:report", - senderId: LIFECYCLE_PARTICIPANT_ID, - receiverId: "ignored:receiver", - originProjectId: "ignored:project", - exchangeId: null, - exchangeRole: "none" as const, - envelopeChannel: "lifecycle_notice" as const, - correlationId: "ignored:correlation", - text: "PRIVATE PEER TEXT", - createdAt: "2999-01-01T00:00:00Z", - deliveryAlarm: { messageId: pair.messageId, code: "attempts-exhausted" as const }, - originEnvironmentId: home.environmentId, - }; - const count = () => sql`SELECT * FROM j5_a2a_peer_delivery_alarm`; - const ignored = yield* pair.workServer.inbound.receive({ - ...report, - deliveryAlarm: { ...report.deliveryAlarm, messageId: "not-sent" }, - }); - assert.isTrue(isPeerReceipt({ accepted: true, ...ignored })); - yield* sql`INSERT INTO j5_a2a_peer(environment_id,label,link_mode,origin,credential,created_at,updated_at) - VALUES ('foreign','foreign','push','https://foreign.example','credential',${timestamp},${timestamp})`; - assert.deepStrictEqual( - yield* pair.workServer.inbound.receive({ ...report, originEnvironmentId: "foreign" }), - ignored, - ); - for (const status of ["cancelled", "alarmed"]) { - yield* sql`UPDATE j5_a2a_delivery SET status = ${status} WHERE message_id = ${pair.messageId}`; - assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); - } - yield* sql`UPDATE j5_a2a_delivery SET status='delivered', origin_environment_id='relayed' WHERE message_id=${pair.messageId}`; - assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); - yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id=NULL, status='pending' WHERE message_id=${pair.messageId}`; - const pending = yield* Effect.flip(pair.workServer.inbound.receive(report)); - assert.equal(pending._tag, "A2APeerDeliveryReceiptPendingError"); - assert.equal((yield* count()).length, 0); - yield* sql`UPDATE j5_a2a_delivery SET status='delivered' WHERE message_id=${pair.messageId}`; - yield* sql`UPDATE j5_a2a_membership SET archived_at=${timestamp} WHERE participant_id=${work.agent.id}`; - assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); - yield* sql`UPDATE j5_a2a_membership SET archived_at=NULL WHERE participant_id=${work.agent.id}`; - const membership = yield* sql<{ - readonly payload: string; - readonly project_id: string; - readonly participant_id: string; - readonly participant_kind: string; - readonly thread_id: string; - readonly joined_seq: number; - readonly updated_seq: number; - readonly archived_at: string | null; - }>`SELECT * FROM j5_a2a_membership WHERE participant_id=${work.agent.id}`; - yield* sql`DELETE FROM j5_a2a_membership WHERE participant_id=${work.agent.id}`; - assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); - yield* sql`INSERT INTO j5_a2a_membership ${sql.insert(membership)}`; - const before = yield* sql`SELECT * FROM j5_a2a_delivery WHERE message_id=${pair.messageId}`; - assert.deepStrictEqual(yield* pair.workServer.inbound.receive(report), ignored); - yield* TestClock.adjust("1 minute"); - assert.deepStrictEqual( - yield* pair.workServer.inbound.receive({ ...report, messageId: "another-envelope" }), - ignored, - ); - const stored = yield* count(); - assert.equal(stored.length, 1); - assert.equal( - stored[0]!.reported_at, - "1970-01-01T00:00:00.000Z", - "only the origin receipt clock is authoritative", - ); - assert.notInclude(JSON.stringify(stored), "PRIVATE"); - assert.deepStrictEqual( - yield* sql`SELECT * FROM j5_a2a_delivery WHERE message_id=${pair.messageId}`, - before, - ); - assert.equal( - (yield* sql`SELECT 1 FROM j5_a2a_comm_event WHERE json_extract(payload,'$.peerReported')=1`) - .length, - 1, - ); - for (const changed of [ - { senderId: home.agent.id, envelopeChannel: "peer" as const }, - { exchangeId: "foreign" }, - { exchangeRole: "terminal_notice" as const }, - { regardingExchangeId: "foreign" }, - { terminal: { kind: "sender-cleared" as const } }, - { - landing: { - mode: "steer" as const, - limit: { runtimeMode: "full-access" as const, interactionMode: "default" as const }, - }, - }, - ]) { - assert.equal( - (yield* Effect.flip(pair.workServer.inbound.receive({ ...report, ...changed })))._tag, - "A2APeerSenderNotAllowedError", - ); - } - assert.isFalse( - isPeerDelivery({ - ...report, - deliveryAlarm: { messageId: "x".repeat(4097), code: "attempts-exhausted" }, - }), - ); - assert.isFalse( - isPeerDelivery({ - ...report, - deliveryAlarm: { messageId: "m", code: "unbounded-peer-code" }, - }), - ); - yield* sql`UPDATE j5_a2a_delivery SET exchange_id=NULL WHERE message_id=${pair.messageId}`; - const plain = (yield* readFleetLedgerFacts( - sql, - work.projectId, - [work.agent.id], - () => null, - )).problems.get(work.agent.id)![0]!; - assert.isTrue( - plain.kind === "delivery-failed" && !plain.exchangeOpen, - "plain message alarms do not become open-Exchange alarms", - ); - yield* sql`DELETE FROM j5_a2a_peer_delivery_alarm`; - yield* sql`UPDATE j5_a2a_delivery SET status='cancelled' WHERE message_id=${pair.messageId}`; - const staleEvent = (yield* sql<{ - readonly payload: string; - }>`SELECT payload FROM j5_a2a_comm_event WHERE json_extract(payload,'$.peerReported')=1`)[0]!; - yield* pair.workServer.ledger.append({ - commandId: CommCommandId.make("command:stale-peer-report"), - projectId: work.projectId, - acceptedAt: timestamp, - event: { - kind: "message.delivery_failed", - sender: work.agent.id, - receiver: home.agent.id, - exchangeId: null, - correlationId: null, - payload: JSON.parse(staleEvent.payload), - createdAt: timestamp, - }, - }); - assert.equal( - (yield* count()).length, - 0, - "a stale projection never fails or resurrects a cancelled delivery", - ); - yield* sql`INSERT INTO j5_a2a_peer_delivery_alarm(project_id,message_id,reported_at,reason) - VALUES (${work.projectId},${pair.messageId},${timestamp},'historical failure')`; - yield* sql`DELETE FROM j5_a2a_delivery WHERE project_id=${work.projectId} AND message_id=${pair.messageId}`; - assert.equal( - (yield* count()).length, - 0, - "deleting the delivery cascades to its diagnostic fact", - ); - }), - ), -); - -it.effect( - "does not send diagnostic facts to an old peer or recurse on an alarmed platform fact", - () => - Effect.scoped( - Effect.gen(function* () { - const pair = yield* pairWithOpenAsk("command:old-peer-alarm", true); - yield* pair.homeServer.sql`UPDATE j5_a2a_peer SET peer_capabilities='{}'`; - yield* TestClock.adjust("250 millis"); - yield* pair.homeServer.worker.runOnce; - yield* TestClock.adjust("500 millis"); - assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "alarmed"); - assert.equal( - (yield* pair.homeServer - .sql`SELECT 1 FROM j5_a2a_delivery WHERE envelope_channel='lifecycle_notice'`).length, - 0, - ); - yield* pair.homeServer - .sql`UPDATE j5_a2a_peer SET peer_capabilities='{"deliveryAlarms":true}'`; - const report = (yield* Ref.get(pair.crossed))[0]!.body; - const received = yield* pair.homeServer.inbound.receive({ - ...report, - messageId: "other-message", - correlationId: "correlation:other-message", - exchangeId: null, - exchangeRole: "none", - originEnvironmentId: work.environmentId, - }); - assert.isAtLeast(received.receivedSeq, 1); - yield* pair.homeServer.worker.runOnce; - yield* TestClock.adjust("250 millis"); - yield* pair.homeServer.worker.runOnce; - yield* TestClock.adjust("500 millis"); - yield* pair.homeServer.worker.runOnce; - yield* pair.workServer.sql`DELETE FROM j5_a2a_peer`; - yield* pair.homeServer.worker.runOnce; - yield* TestClock.adjust("250 millis"); - yield* pair.homeServer.worker.runOnce; - yield* TestClock.adjust("500 millis"); - yield* pair.homeServer.worker.runOnce; - assert.equal( - (yield* pair.homeServer - .sql`SELECT 1 FROM j5_a2a_delivery WHERE envelope_channel='lifecycle_notice'`).length, - 1, - ); - }), - ), -); - -it.effect("retries an early alarm report until the matching origin acceptance is committed", () => +it.effect("reads a pushed receiver alarm without sending any message back to the origin", () => Effect.scoped( Effect.gen(function* () { - const pair = yield* pairWithOpenAsk("command:early-report", true); - yield* pair.workServer - .sql`UPDATE j5_a2a_delivery SET status='pending' WHERE message_id=${pair.messageId}`; + const pair = yield* pairWithOpenAsk("command:read-remote-alarm", true); + const original = yield* pair.workServer.sql`SELECT * FROM j5_a2a_delivery`; yield* TestClock.adjust("250 millis"); - yield* pair.homeServer.worker.runOnce; - yield* TestClock.adjust("500 millis"); - yield* pair.homeServer.worker.runOnce; assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "retry_scheduled"); + yield* TestClock.adjust("500 millis"); + assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "alarmed"); + assert.isNull(yield* pair.homeServer.worker.runOnce); + const facts = yield* readFleetLedgerFacts( + pair.homeServer.sql, + home.projectId, + [home.agent.id], + () => null, + ); + const remote = facts.remoteDeliveryAlarms[0]!; + assert.equal(remote.originEnvironmentId, work.environmentId); + assert.equal(remote.senderId, work.agent.id); + assert.equal(remote.problem.exchangeId, pair.exchangeId); + assert.isTrue(remote.problem.exchangeOpen); + assert.equal(facts.problems.size, 0); + assert.equal((yield* Ref.get(pair.crossed)).length, 1, "only the authored ask crossed"); + assert.deepStrictEqual(yield* pair.workServer.sql`SELECT * FROM j5_a2a_delivery`, original); + assert.equal((yield* Ref.get(pair.workDelivered)).length, 0); assert.equal( - (yield* pair.workServer.sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, - 0, + (yield* exchangeStatus(pair.workServer.sql, pair.exchangeId))[0]?.status, + "open", ); - yield* pair.workServer - .sql`UPDATE j5_a2a_delivery SET status='delivered' WHERE message_id=${pair.messageId}`; - yield* TestClock.adjust("250 millis"); - assert.equal((yield* pair.homeServer.worker.runOnce)?.state, "delivered"); assert.equal( - (yield* pair.workServer.sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, - 1, + (yield* pair.homeServer + .sql`SELECT 1 FROM j5_a2a_delivery WHERE envelope_channel = 'lifecycle_notice'`).length, + 0, ); }), ), ); - -it("keeps delivery-alarm capabilities additive for old peer decoders", () => { - assert.deepStrictEqual(decodePeerCapabilities({ poll: true, landing: true }), { - poll: true, - landing: true, - }); - assert.deepStrictEqual(decodeLegacyCapabilities(ownPeerCapabilities), { - poll: true, - landing: true, - }); -}); diff --git a/apps/server/src/j5/a2a/PeerStoreService.test.ts b/apps/server/src/j5/a2a/PeerStoreService.test.ts index ce86233ce9bb6..2a4e75d6cdc9e 100644 --- a/apps/server/src/j5/a2a/PeerStoreService.test.ts +++ b/apps/server/src/j5/a2a/PeerStoreService.test.ts @@ -318,11 +318,7 @@ it.effect( ); assert.isFalse(handed.more); assert.equal(handed.label, "Work VM", "the poller learns the storing server's name"); - assert.deepStrictEqual(handed.capabilities, { - poll: true, - landing: true, - deliveryAlarms: true, - }); + assert.deepStrictEqual(handed.capabilities, { poll: true, landing: true }); // The body is exactly what a direct send would carry, intent included. assert.equal(handed.deliveries[0]!.intent, "first intent"); assert.equal(handed.deliveries[0]!.exchangeRole, "ask"); diff --git a/apps/server/src/j5/a2a/contracts.ts b/apps/server/src/j5/a2a/contracts.ts index a38881b30a412..588aecc143bfa 100644 --- a/apps/server/src/j5/a2a/contracts.ts +++ b/apps/server/src/j5/a2a/contracts.ts @@ -1,5 +1,5 @@ import { ChatAttachment, ProviderInteractionMode, RuntimeMode, ThreadId } from "@t3tools/contracts"; -import { PeerDeliveryAlarm, PeerSenderLabel } from "@t3tools/contracts/j5"; +import { PeerSenderLabel } from "@t3tools/contracts/j5"; import * as Schema from "effect/Schema"; const Identifier = Schema.String.check(Schema.isNonEmpty()); @@ -303,7 +303,6 @@ export const TerminalFact = Schema.Union([ export type TerminalFact = typeof TerminalFact.Type; export const MessageSentPayload = Schema.Struct({ - deliveryAlarm: Schema.optional(PeerDeliveryAlarm), attachments: Schema.optional(Schema.Array(ChatAttachment)), /** How the sender asked for the message to land; absent means `queue`. */ mode: Schema.optional(SendMode), @@ -329,9 +328,6 @@ export const MessageDeliveredPayload = Schema.Struct({ export type MessageDeliveredPayload = typeof MessageDeliveredPayload.Type; export const MessageDeliveryFailedPayload = Schema.Struct({ - /** Set only after binding an authenticated peer report to this server's outbound delivery. */ - peerReported: Schema.optional(Schema.Literal(true)), - peerEnvironmentId: Schema.optional(Schema.String), messageId: LedgerMessageId, attempt: PositiveInt, error: Schema.String.check(Schema.isNonEmpty()), diff --git a/apps/server/src/j5/a2a/fleetFacts.test.ts b/apps/server/src/j5/a2a/fleetFacts.test.ts index 0e59e4b495f68..7812e8cb795c3 100644 --- a/apps/server/src/j5/a2a/fleetFacts.test.ts +++ b/apps/server/src/j5/a2a/fleetFacts.test.ts @@ -96,6 +96,13 @@ it.effect( yield* alarm("lifecycle", "lifecycle_notice", null); yield* alarm("retry", "peer", null, null, "retry_scheduled"); yield* alarm("delivered", "peer", null, null, "delivered"); + yield* alarm("accepted-peer", "peer", "outgoing", "receiver-env", "delivered"); + yield* alarm("inbound-peer", "peer", "outgoing"); + yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id = 'origin-env' + WHERE message_id = 'inbound-peer'`; + yield* alarm("inbound-platform", "lifecycle_notice", null); + yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id = 'origin-env' + WHERE message_id = 'inbound-platform'`; const read = () => readFleetLedgerFacts(sql, "p", [sender, receiver], (id) => id === receiver ? "Receiver" : null, @@ -126,6 +133,27 @@ it.effect( ], ); assert.isUndefined(before.problems.get(receiver)); + assert.deepStrictEqual(before.deliveryEnvironmentIds.get(sender), ["receiver-env"]); + assert.deepStrictEqual(before.remoteDeliveryAlarms, [ + { + originEnvironmentId: "origin-env", + senderId: sender, + problem: { + kind: "delivery-failed", + messageId: "inbound-peer", + exchangeId: "outgoing", + receiverId: receiver, + receiverName: "Receiver", + at, + reason: "transport unavailable", + exchangeOpen: true, + }, + }, + ]); + assert.equal( + (yield* readFleetLedgerFacts(sql, "p", [], () => null)).remoteDeliveryAlarms.length, + 1, + ); yield* sql`UPDATE j5_a2a_exchange SET status = 'closed' WHERE exchange_id = 'outgoing'`; const closed = yield* read(); assert.isUndefined(closed.awaited.get(sender)); @@ -183,6 +211,12 @@ it.effect( ), ); const snapshot = yield* fleetRead(false); + assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.originEnvironmentId, "origin-env"); + assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.senderId, sender); + assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.problem.exchangeOpen, false); + assert.deepStrictEqual(snapshot.projects[0]?.agents[0]?.facts?.deliveryEnvironmentIds, [ + "receiver-env", + ]); assert.equal(snapshot.asOf, "1970-01-01T00:00:00.000Z"); assert.equal(snapshot.projects[0]?.agents[0]?.facts?.asks.owed.length, 1); assert.equal( diff --git a/apps/server/src/j5/a2a/fleetFacts.ts b/apps/server/src/j5/a2a/fleetFacts.ts index f8be5fb602b8a..84f327a219756 100644 --- a/apps/server/src/j5/a2a/fleetFacts.ts +++ b/apps/server/src/j5/a2a/fleetFacts.ts @@ -1,4 +1,4 @@ -import type { FleetAgentFacts, FleetProblem } from "@t3tools/contracts/j5"; +import type { FleetAgentFacts, FleetDeliveryProblem, FleetResponse } from "@t3tools/contracts/j5"; import * as Effect from "effect/Effect"; import type * as SqlClient from "effect/sql/SqlClient"; @@ -18,6 +18,8 @@ type AlarmRow = { readonly sender_id: string; readonly receiver_id: string; readonly message_id: string; + readonly exchange_id: string | null; + readonly origin_environment_id: string | null; readonly updated_at: string; readonly last_error: string | null; readonly exchange_open: number; @@ -32,8 +34,8 @@ export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* ) { const owed = new Map>(); const awaited = new Map>(); - const problems = new Map>(); - if (agentIds.length === 0) return { owed, awaited, problems }; + const problems = new Map>(); + const deliveryEnvironmentIds = new Map>(); const batches = clientReadBatches([...new Set(agentIds)]); const exchanges = new Map>(); for (const batch of batches) { @@ -76,35 +78,56 @@ export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* receiverAsks.push(ask(row.sender_id)); owed.set(row.receiver_id, receiverAsks); } - // `peer` is the authored envelope channel, including local delivery. Platform notices have - // their own channels and must never surface as an agent's problem (Fleet AC24). + // Only local authors belong to this project's agent rows; remote authors are exported below. for (const batch of batches) { - const alarms = yield* sql` - SELECT d.sender_id, d.receiver_id, d.message_id, COALESCE(a.reported_at, d.updated_at) AS updated_at, - COALESCE(a.reason, d.last_error) AS last_error, + const destinations = yield* sql<{ sender_id: string; receiver_environment_id: string }>` + SELECT DISTINCT sender_id, receiver_environment_id FROM j5_a2a_delivery + WHERE project_id = ${projectId} AND sender_id IN ${sql.in(batch)} + AND origin_environment_id IS NULL AND receiver_environment_id IS NOT NULL + AND status = 'delivered' AND envelope_channel = 'peer' + AND (exchange_id IS NULL OR exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`}) + ORDER BY receiver_environment_id + `; + for (const row of destinations) { + const environments = deliveryEnvironmentIds.get(row.sender_id) ?? []; + environments.push(row.receiver_environment_id); + deliveryEnvironmentIds.set(row.sender_id, environments); + } + } + const alarms = yield* sql` + SELECT d.sender_id, d.receiver_id, d.message_id, d.exchange_id, d.origin_environment_id, + d.updated_at, d.last_error, EXISTS (SELECT 1 FROM j5_a2a_exchange e WHERE e.project_id = d.project_id AND e.exchange_id = d.exchange_id AND e.status = 'open') AS exchange_open FROM j5_a2a_delivery d - LEFT JOIN j5_a2a_peer_delivery_alarm a ON a.project_id = d.project_id AND a.message_id = d.message_id - WHERE d.project_id = ${projectId} AND d.sender_id IN ${sql.in(batch)} - AND (d.status = 'alarmed' OR (d.status = 'delivered' AND a.message_id IS NOT NULL)) - AND d.envelope_channel = 'peer' + WHERE d.project_id = ${projectId} AND d.status = 'alarmed' AND d.envelope_channel = 'peer' AND (d.exchange_id IS NULL OR d.exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`}) ORDER BY d.sent_seq, d.message_id `; - for (const row of alarms) { - const senderProblems = problems.get(row.sender_id) ?? []; - senderProblems.push({ - kind: "delivery-failed", - messageId: row.message_id, - receiverId: row.receiver_id, - receiverName: nameOf(row.receiver_id), - at: row.updated_at, - reason: row.last_error, - exchangeOpen: row.exchange_open === 1, + const localAgents = new Set(agentIds); + const remoteDeliveryAlarms: NonNullable[number][] = []; + for (const row of alarms) { + const problem: FleetDeliveryProblem = { + kind: "delivery-failed", + messageId: row.message_id, + exchangeId: row.exchange_id, + receiverId: row.receiver_id, + receiverName: nameOf(row.receiver_id), + at: row.updated_at, + reason: row.last_error, + exchangeOpen: row.exchange_open === 1, + }; + if (row.origin_environment_id !== null) { + remoteDeliveryAlarms.push({ + originEnvironmentId: row.origin_environment_id, + senderId: row.sender_id, + problem, }); + } else if (localAgents.has(row.sender_id)) { + const senderProblems = problems.get(row.sender_id) ?? []; + senderProblems.push(problem); problems.set(row.sender_id, senderProblems); } } - return { owed, awaited, problems }; + return { owed, awaited, problems, deliveryEnvironmentIds, remoteDeliveryAlarms }; }); diff --git a/apps/server/src/j5/a2a/fleetRead.ts b/apps/server/src/j5/a2a/fleetRead.ts index ae92d9201ab74..f372f71167a9b 100644 --- a/apps/server/src/j5/a2a/fleetRead.ts +++ b/apps/server/src/j5/a2a/fleetRead.ts @@ -68,7 +68,13 @@ export const projectFleetProject = (input: { openAsks: 0, ...(input.facts === undefined ? {} - : { facts: { asks: { owed: [], awaited: [] }, problems: [] } }), + : { + facts: { + asks: { owed: [], awaited: [] }, + problems: [], + deliveryEnvironmentIds: [], + }, + }), })), ); return { @@ -152,6 +158,7 @@ export const makeFleetRead = Effect.gen(function* () { Effect.gen(function* () { const projects = yield* ledger.listProjectLedgers(); const result: Array = []; + const remoteDeliveryAlarms: NonNullable[number][] = []; const participantsByProject = new Map>(); // Removed people keep their names on historical Exchange and delivery facts. const people = yield* sql<{ readonly person_id: string; readonly display_name: string }>` @@ -214,6 +221,7 @@ export const makeFleetRead = Effect.gen(function* () { agentIds, (id) => names.get(id) ?? outsideAgentNames.get(id) ?? null, ); + remoteDeliveryAlarms.push(...ledgerFacts.remoteDeliveryAlarms); const facts = new Map( agentIds.map((id) => [ id, @@ -223,6 +231,7 @@ export const makeFleetRead = Effect.gen(function* () { awaited: ledgerFacts.awaited.get(id) ?? [], }, problems: ledgerFacts.problems.get(id) ?? [], + deliveryEnvironmentIds: ledgerFacts.deliveryEnvironmentIds.get(id) ?? [], }, ]), ); @@ -249,6 +258,7 @@ export const makeFleetRead = Effect.gen(function* () { } return { projects: result, + remoteDeliveryAlarms, asOf: DateTime.formatIso(yield* DateTime.now), } satisfies FleetResponse; }); diff --git a/apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts b/apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts deleted file mode 100644 index 77e51f1290759..0000000000000 --- a/apps/server/src/j5/a2a/migrations/044_PeerDeliveryAlarms.ts +++ /dev/null @@ -1,15 +0,0 @@ -import * as Effect from "effect/Effect"; -import * as SqlClient from "effect/sql/SqlClient"; - -export default Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* sql`CREATE TABLE j5_a2a_peer_delivery_alarm ( - project_id TEXT NOT NULL, - message_id TEXT NOT NULL, - reported_at TEXT NOT NULL, - reason TEXT NOT NULL, - PRIMARY KEY (project_id, message_id), - FOREIGN KEY (project_id, message_id) - REFERENCES j5_a2a_delivery(project_id, message_id) ON DELETE CASCADE - )`; -}); diff --git a/apps/server/src/j5/a2a/peerDeliveryBody.ts b/apps/server/src/j5/a2a/peerDeliveryBody.ts index f50f369f66346..043f1ad06bf27 100644 --- a/apps/server/src/j5/a2a/peerDeliveryBody.ts +++ b/apps/server/src/j5/a2a/peerDeliveryBody.ts @@ -56,7 +56,6 @@ export const buildPeerDeliveryBody = Effect.fn("j5.a2a.peer.deliveryBody")(funct envelopeChannel: row.envelope_channel, text: row.message_text, originProjectId: row.origin_project_id ?? row.project_id, - ...(yield* deliveryAlarm(sql, row)), ...(yield* landing(sql, row)), ...(yield* exchangeFacts(sql, row)), ...(senderLabel.length === 0 ? {} : { senderLabel }), @@ -121,15 +120,3 @@ const exchangeFacts = Effect.fn("j5.a2a.peer.deliveryBody.exchangeFacts")(functi } return {}; }); - -const deliveryAlarm = Effect.fn("j5.a2a.peer.deliveryBody.alarm")(function* ( - sql: SqlClient.SqlClient, - row: PeerBodyRow, -) { - if (row.envelope_channel !== "lifecycle_notice" || row.exchange_role !== "none") return {}; - const sent = yield* sql<{ readonly payload: string }>`SELECT payload FROM j5_a2a_comm_event - WHERE project_id = ${row.project_id} AND seq = ${row.sent_seq} AND kind = 'message.sent'`; - if (sent[0] === undefined) return {}; - const payload = yield* decodeSentPayload(sent[0].payload); - return payload.deliveryAlarm === undefined ? {} : { deliveryAlarm: payload.deliveryAlarm }; -}); diff --git a/apps/server/src/j5/a2a/peerProtocol.ts b/apps/server/src/j5/a2a/peerProtocol.ts index c1306c75ee7f0..7eba07d85c35e 100644 --- a/apps/server/src/j5/a2a/peerProtocol.ts +++ b/apps/server/src/j5/a2a/peerProtocol.ts @@ -5,11 +5,7 @@ import { } from "@t3tools/contracts/j5"; /** What this server tells every peer it can do, in a hello and in both directions of a poll. */ -export const ownPeerCapabilities = { - poll: true, - landing: true, - deliveryAlarms: true, -} satisfies PeerCapabilities; +export const ownPeerCapabilities = { poll: true, landing: true } satisfies PeerCapabilities; /** * The one compare for both directions of peering. A server states its peer diff --git a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts index 24358ef4da314..84785f05f0a08 100644 --- a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts +++ b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.test.ts @@ -77,9 +77,6 @@ const seed = Effect.fn("test.j5.neutralise.seed")(function* () { ${status === "retry_scheduled" ? at : null}, ${at}, ${at}, 'peer', ${handedOutAt})`; } - yield* sql`INSERT INTO j5_a2a_peer_delivery_alarm(project_id,message_id,reported_at,reason) - VALUES ('project','message-delivered',${at},'Peer thread delivery failed')`; - for (const [exchangeId, receiver, status, closedSeq] of [ ["exchange-open", "agent:b", "open", null], ["exchange-human", "human:operator", "open", null], @@ -191,7 +188,6 @@ it.layer(NodeServices.layer)("neutraliseCopiedDatabase", (it) => { playbookStepDeliveries: 1, }); assert.deepEqual(yield* actingRows(), nothingActing); - assert.equal((yield* sql`SELECT 1 FROM j5_a2a_peer_delivery_alarm`).length, 0); // Stood down into states the product already reads, not removed. assert.deepEqual( diff --git a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts index 07ba6951b4e08..3512adfa03427 100644 --- a/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts +++ b/apps/server/src/j5/persistence/neutraliseCopiedDatabase.ts @@ -80,10 +80,6 @@ export const neutraliseJ5State = Effect.fn("j5.neutraliseJ5State")(function* () sql`DELETE FROM j5_a2a_peer RETURNING environment_id`, ); - // The copied server has no live peer whose measurements remain current here. - if (tables.has("j5_a2a_peer_delivery_alarm")) - yield* sql`DELETE FROM j5_a2a_peer_delivery_alarm`; - // The same projection an archive's `message.cancelled` writes (LedgerService). const deliveries = yield* count( "j5_a2a_delivery", diff --git a/docs/j5/product/a2a/index.md b/docs/j5/product/a2a/index.md index 18035fac2a795..b3f63ee06f070 100644 --- a/docs/j5/product/a2a/index.md +++ b/docs/j5/product/a2a/index.md @@ -134,7 +134,7 @@ message, ask, reply, plain message, Exchange, intent, urgency, obligation, envel ### Delivery -12. Every delivery attempt is recorded; a delivery that fails past the retry limit remains an alarm attributed to the sender, leaves an ask's Exchange open, and is never marked repaired by time passing or a different message succeeding; its sender receives one notice that it may not have been delivered, except after a peer acceptance receipt, when the origin's Fleet row receives the failure without changing that receipt or delivering a thread notice. +12. Every delivery attempt is recorded; a delivery that fails past the retry limit is shown as an alarm attributed to the sender, leaves an ask's Exchange open, and is never marked repaired by time passing or by a different message succeeding. The sender is told once, in a notice that the message may not have been delivered, unless the sender is on a peer server that already holds the receipt. 13. A message to an agent whose turn is running is queued and delivered when the turn ends, unless its sender asked for a steer or a restart, or it is a peer message into a running Codex GPT 6 turn, which is delivered into the turn as an ordinary envelope with nothing added. 14. How the person's steer is offered, labeled and sent — in the composer and on a queued row, including whether a send steers or queues by default — follows upstream. An agent's steer or restart is asked for on `j5_send_message` and is defined with that tool ([agent tools](agent-tools.md)). 15. Platform notices are always queued, never steered. @@ -220,4 +220,3 @@ message, ask, reply, plain message, Exchange, intent, urgency, obligation, envel - 2026-10-18 — a delivery alarm is told to its sender in one not-delivered notice, as a refusal is; an alarmed ask's Exchange stays open for the sender to withdraw, and a sender on a peer server is not told of an alarm after its receipt. AC12 rewritten (Jackson, [#260](https://github.com/Jacksondr5/j5code/issues/260)). - 2026-10-19 — a not-delivered notice names its message by the id the send returned, and an ask by its intent too, so a sender with several messages out can tell which one it is about (Jackson, [#670](https://github.com/Jacksondr5/j5code/issues/670)). - 2026-10-20 — native-question answering retains upstream permission checks and unattributed response records; placed agents receive notices without raw thread waiting ([#674](https://github.com/Jacksondr5/j5code/pull/674), [#281](https://github.com/Jacksondr5/j5code/issues/281), [existing access decision](https://github.com/Jacksondr5/j5code/issues/345#issuecomment-6092125478)). -- 2026-10-23 — a receiver's later alarm returns to the origin's Fleet row as a measured diagnostic fact, with no authored notice and no change to the acceptance receipt or open Exchange; AC12 clarified (user-authorized repair; [review record](https://github.com/Jacksondr5/j5code/pull/662#discussion_r4359712499)). diff --git a/docs/j5/product/cross-device.md b/docs/j5/product/cross-device.md index be3222dfa8c90..31f62bccbdf0d 100644 --- a/docs/j5/product/cross-device.md +++ b/docs/j5/product/cross-device.md @@ -43,7 +43,7 @@ Servers do not find each other; **the client introduces them.** The client is th **A person stays server-local.** A person's participant, their asks, and their inbox belong to each server they use; an ask to a person is delivered on the sender's own server, and the person's view of several servers is the client's merge described above. Peering carries messages between agents, and nothing else. -Delivery across peer servers is the same delivery with one more step: the send is a ledger row on the sender's server, the peer server records its own received row, and that acknowledgement is the sender's delivery receipt. Across servers the receipt means the peer server accepted and recorded the message; delivering it into the agent's thread is then the peer server's own delivery, which retries and alarms there, attributed to the sender as any delivery is. Sent directly, failure to reach the peer server retries and alarms on the sender's server as any failure does. To a polling peer, the message is stored without retrying or alarming until the peer polls for it, and the poller's acknowledgement is the receipt. A message that alarms on the sender's server, one the peer server refuses, or one cancelled before it got there, is reported to its sender; once the peer server has returned the receipt, no authored alarm notice is delivered back into the sender's thread. A receiver's later in-thread delivery alarm returns as a measured Fleet fact on the original sender, without a message in its thread. The original acceptance receipt remains true. The alarm stays visible after the Exchange closes, while the badge counts it only while that Exchange is open. Peers from before this capability continue exchanging without the extra diagnostic fact. Everything that flows back — a reply, a silence notice, a lifecycle closure — travels the same path in reverse, which is why peering is mutual: one Exchange needs both directions. Peer servers reach each other directly, or one polls the other over connections it opens; a relay or tunnel is never a required part of it. +Delivery across peer servers is the same delivery with one more step: the send is a ledger row on the sender's server, the peer server records its own received row, and that acknowledgement is the sender's delivery receipt. Across servers the receipt means the peer server accepted and recorded the message; delivering it into the agent's thread is then the peer server's own delivery, which retries and alarms there, attributed to the sender as any delivery is. Sent directly, failure to reach the peer server retries and alarms on the sender's server as any failure does. To a polling peer, the message is stored without retrying or alarming until the peer polls for it, and the poller's acknowledgement is the receipt. A message that alarms on the sender's server, one the peer server refuses, or one cancelled before it got there, is reported to its sender; once the peer server has returned the receipt, an alarm there is not reported back. Everything that flows back — a reply, a silence notice, a lifecycle closure — travels the same path in reverse, which is why peering is mutual: one Exchange needs both directions. Peer servers reach each other directly, or one polls the other over connections it opens; a relay or tunnel is never a required part of it. Peering is also where another person's server attaches, when that time comes — person boundaries, what may cross, and trust live in the peer record, and nothing else in the architecture needs to anticipate other people. @@ -109,4 +109,3 @@ What this never does: no replicated state, no multi-master, no moving a project' - 2026-10-07 — Squadrons retired: a project, its agents and its ledger live on one server, a participant is resolved straight to its server, and the address book lists a peer server's participants with their project (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — a steer or restart crosses to a peer server: two optional fields on a delivery, a `landing` capability, and a `landing_refused` answer. The protocol version stays 2, since each is an additive change ([#519](https://github.com/Jacksondr5/j5code/issues/519)). - 2026-10-18 — a message sent directly that alarms is reported to its sender, as a refused one is; an alarm on the peer server after its receipt is not reported back (Jackson, [#260](https://github.com/Jacksondr5/j5code/issues/260)). -- 2026-10-23 — an accepted peer message's later in-thread failure appears on the origin sender's Fleet row as a measured fact; the acceptance receipt and open-ask uncertainty remain, and no authored notice is delivered (user-authorized repair; [review record](https://github.com/Jacksondr5/j5code/pull/662#discussion_r4359712499)). diff --git a/docs/j5/product/features/fleet-page.md b/docs/j5/product/features/fleet-page.md index 19f6afe3da3f1..93f78ae12a0b5 100644 --- a/docs/j5/product/features/fleet-page.md +++ b/docs/j5/product/features/fleet-page.md @@ -75,7 +75,7 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### The four facts -15. Status shows the runtime's own fact: Working, Waiting, Approval, Input or Failed; "Waiting to start · Nm" takes precedence while a run has been requested and not dispatched and no other run is in progress; a follow-up queued behind an active run keeps that active run's status. "Idle since ⟨time⟩" appears only when nothing is active and no background work holds completion; a non-holding command such as a dev server does not prevent Idle. +15. Status shows the runtime's own fact: Working, Waiting, Approval, Input or Failed; "Waiting to start · Nm" takes precedence while a run has been requested and not dispatched and no other run is in progress; a follow-up queued behind an active run keeps that active run's status; "Idle since ⟨time⟩" appears only when nothing is active and no background work holds completion; a non-holding command such as a dev server does not prevent Idle. 16. Read and snooze bookkeeping (upstream's Woke and Done) is not a status and does not appear. 17. Silence notices are not shown on the page; the age of an open ask is the visible fact. 18. Open asks show two counts, "Owes N" for open asks the agent must answer and "Awaiting N" for open asks it is waiting on, with a hover list of counterparty, intent and age; a follow-up joined to an open Exchange counts once. @@ -85,7 +85,7 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### Problems and the badge 21. A row's measured problems are a failed latest run, a delivery alarm, and a requested run that has waited past the dispatch threshold with no other run in progress; the row lists every one it has. -22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). +22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true, including a receiving server's alarm on a remote sender when both environments are connected; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). 23. The badge counts agents that have at least one measured problem across every project the page reads; an agent counts once however many problems it has, unknowns never count, and the badge never counts open asks to the person or silence notices. 24. A delivery alarm counts toward the badge only while the Exchange it belongs to is open; an alarm on a plain message is shown on the row and never counted; a failed delivery of a platform-authored notice is neither shown nor counted. @@ -147,3 +147,4 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p - 2026-10-07 — Squadrons retired: the page reads every project and groups roots by upstream's logical project, the sidebar is upstream's project sidebar, and every thread but a provider Subagent is a participant, so AC1 (the Squadron scope) and AC13 (the footer for threads without a home) are retired. Placement and provenance moved here from the retired Squadron definition: its AC10, AC12 and AC13 are AC34 and AC35 (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — an outside agent can be a spawner: the agent it starts is placed at its project's root and its provenance names the outside agent by its label; AC12 and AC34 (Jackson, 2026-10-11; [#498](https://github.com/Jacksondr5/j5code/issues/498)). - 2026-10-21 — clarified AC15 and AC21: queued follow-ups preserve the active run's status, only completion-holding background work prevents Idle, and dispatch is overdue only when no other run is in progress ([#360](https://github.com/Jacksondr5/j5code/issues/360); [#662](https://github.com/Jacksondr5/j5code/pull/662)). +- 2026-10-24 — receiving servers expose later peer delivery alarms through their own Fleet read, and the client attaches them to the remote sender only while both environments are readable; unavailable receiver facts leave coverage incomplete, with no alarm returned over A2A (Jackson, 2026-10-24; [#662](https://github.com/Jacksondr5/j5code/pull/662)). diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index 234e805de50c7..1c7ed7c9cfab5 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -1,16 +1,29 @@ import { describe, expect, it, vi, afterEach } from "vite-plus/test"; -import { RunId, RuntimeRequestId, type OrchestrationV2ThreadShell } from "@t3tools/contracts"; +import { + EnvironmentId, + RunId, + RuntimeRequestId, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; import { FleetResponse, FLEET_DISPATCH_THRESHOLD_MS, type FleetAgentFacts, + type FleetDeliveryProblem, } from "@t3tools/contracts/j5"; import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; import { Atom, AtomRegistry } from "effect/reactivity"; import { v2ThreadShell } from "../state/orchestrationV2TestFixtures.ts"; -import { createFleetFactsAtom, deriveFleetFacts, type FleetFactRow } from "./fleetFacts.ts"; +import type { J5ReadSource } from "./readSources.ts"; +import { + createFleetFactsAtom, + deriveFleetFacts, + fleetAgentKey, + mergeFleetDeliveryFacts, + type FleetFactRow, +} from "./fleetFacts.ts"; const decodeFleet = Schema.decodeUnknownSync(FleetResponse); @@ -396,3 +409,192 @@ it("does not advance offline dispatch facts when unrelated live rows change", () stop(); registry.dispose(); }); + +describe("receiving-environment delivery alarm merge", () => { + const senderId = "agent:shared"; + const ask = (exchangeId: string) => ({ + exchangeId, + counterpartyId: "agent:receiver", + counterpartyName: "Receiver", + intent: "Review", + openedAt: at, + }); + const openLedger: FleetAgentFacts = { + ...ledger, + asks: { owed: [], awaited: [ask("exchange")] }, + deliveryEnvironmentIds: ["receiver"], + }; + const problem = { + kind: "delivery-failed" as const, + messageId: "received-message", + exchangeId: "exchange", + receiverId: "agent:receiver", + receiverName: "Receiver", + at, + reason: "thread unavailable", + exchangeOpen: true, + }; + const project = (facts: FleetAgentFacts | undefined, id = "project") => ({ + id, + title: id, + crews: [], + agents: [ + { + participantId: senderId, + threadId: "thread", + displayName: "Sender", + origin: "human" as const, + placementParentId: null, + crew: null, + openAsks: 0, + ...(facts === undefined ? {} : { facts }), + }, + ], + }); + const source = (id: string, data: FleetResponse): J5ReadSource => ({ + environmentId: EnvironmentId.make(id), + environmentLabel: id, + connected: true, + status: "ready", + data, + error: null, + refreshing: false, + }); + const origin = (facts: FleetAgentFacts | undefined = openLedger, id = "origin") => + source(id, { projects: [project(facts)], remoteDeliveryAlarms: [] }); + const receiver = (changes: Partial = {}) => + source("receiver", { + projects: [], + remoteDeliveryAlarms: [ + { originEnvironmentId: "origin", senderId, problem: { ...problem, ...changes } }, + ], + }); + const merge = (...sources: J5ReadSource[]) => + mergeFleetDeliveryFacts({ isReady: true, sources }); + const key = fleetAgentKey("origin", senderId); + + it("attaches remote facts to the origin environment and participant without phantom rows", () => { + const receiving = source("receiver", { + projects: [], + remoteDeliveryAlarms: [ + ...receiver().data!.remoteDeliveryAlarms!, + { + originEnvironmentId: "other", + senderId, + problem: { ...problem, messageId: "other-message" }, + }, + { originEnvironmentId: "origin", senderId: "agent:elsewhere", problem }, + ], + }); + const facts = merge(origin(), origin(openLedger, "other"), receiving); + expect(facts.get(key)?.ledger?.problems).toEqual([problem]); + expect(facts.get(fleetAgentKey("other", senderId))?.ledger?.problems).toEqual([ + { ...problem, messageId: "other-message" }, + ]); + expect(facts.get(key)?.problemsIncomplete).toBe(false); + expect(merge(receiving).size).toBe(0); + expect(facts.size).toBe(2); + }); + + it("counts a remote alarm only while both Exchange reads say open, preserving closed and plain facts", () => { + expect(merge(origin(), receiver()).get(key)?.ledger?.problems).toEqual([problem]); + const closedOrigin = { ...openLedger, asks: ledger.asks }; + expect(merge(origin(closedOrigin), receiver()).get(key)?.ledger?.problems).toEqual([ + { ...problem, exchangeOpen: false }, + ]); + expect(merge(origin(), receiver({ exchangeOpen: false })).get(key)?.ledger?.problems).toEqual([ + { ...problem, exchangeOpen: false }, + ]); + expect(merge(origin(), receiver({ exchangeId: null })).get(key)?.ledger?.problems).toEqual([ + { ...problem, exchangeId: null, exchangeOpen: false }, + ]); + }); + + it("reports missing, old, disconnected and unreadable relevant receivers as incomplete", () => { + const unavailable: J5ReadSource[] = [ + { ...receiver(), connected: false, status: "offline" }, + { ...receiver(), status: "error", error: "read failed" }, + { ...receiver(), status: "loading" }, + { ...receiver(), status: "unsupported" }, + source("receiver", { projects: [] }), + ]; + for (const receiving of unavailable) { + expect(merge(origin(), receiving).get(key)).toMatchObject({ + ledger: { problems: [] }, + problemsIncomplete: true, + }); + } + expect(merge(origin()).get(key)?.problemsIncomplete).toBe(true); + expect( + merge(origin({ ...ledger, deliveryEnvironmentIds: [] }), ...unavailable).get(key) + ?.problemsIncomplete, + ).toBe(false); + expect(merge(origin(ledger), receiver()).get(key)?.problemsIncomplete).toBe(true); + const staleOrigin = { ...origin(), connected: false, status: "offline" as const }; + expect(merge(staleOrigin, receiver()).get(key)).toMatchObject({ + ledger: { problems: [] }, + problemsIncomplete: true, + }); + expect( + mergeFleetDeliveryFacts( + { isReady: true, sources: [origin(), receiver()] }, + new Map([ + ["origin", true], + ["receiver", false], + ]), + ).get(key), + ).toMatchObject({ ledger: { problems: [] }, problemsIncomplete: true }); + }); + + it("aggregates repeated placements across projects before merging receiver alarms", () => { + const first = { ...openLedger, problems: [{ ...problem, messageId: "local-first" }] }; + const second = { + ...openLedger, + asks: { owed: [], awaited: [ask("second")] }, + deliveryEnvironmentIds: ["second-receiver"], + }; + const sending = source("origin", { + projects: [project(first, "one"), project(second, "two"), project(first, "three")], + remoteDeliveryAlarms: [], + }); + const receiving = source("second-receiver", { + projects: [], + remoteDeliveryAlarms: [ + { + originEnvironmentId: "origin", + senderId, + problem: { ...problem, messageId: "second-message", exchangeId: "second" }, + }, + ], + }); + const result = merge(sending, receiver(), receiving).get(key)!; + expect(result.problemsIncomplete).toBe(false); + expect(result.ledger?.deliveryEnvironmentIds).toEqual(["receiver", "second-receiver"]); + expect(result.ledger?.asks.awaited.map((entry) => entry.exchangeId)).toEqual([ + "exchange", + "second", + ]); + expect( + result.ledger?.problems.map((entry) => entry.kind === "delivery-failed" && entry.messageId), + ).toEqual(["local-first", "received-message", "second-message"]); + }); + + it("removes a cached receiver alarm from a live origin when receiver coverage is lost", () => { + const rows = Atom.make>([]); + const facts = createFleetFactsAtom(rows); + const registry = AtomRegistry.make(); + const stop = registry.subscribe(facts, () => {}, { immediate: true }); + const update = (receiving: J5ReadSource) => { + const merged = merge(origin(), receiving).get(key)!; + registry.set(rows, [ + { key, shell: shell({ latestRunId: null, status: "completed" }), live: true, ...merged }, + ]); + }; + update(receiver()); + expect(registry.get(facts).get(key)?.problems).toEqual([problem]); + update({ ...receiver(), connected: false, status: "offline" }); + expect(registry.get(facts).get(key)).toMatchObject({ problems: [], problemsIncomplete: true }); + stop(); + registry.dispose(); + }); +}); diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index 28800a8e84390..307b7e38d44a1 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -5,37 +5,164 @@ import { type FleetRuntimeFact, type FleetActivityFact, type FleetProblem, + type FleetResponse, } from "@t3tools/contracts/j5"; import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as Equal from "effect/Equal"; import * as Option from "effect/Option"; import { Atom } from "effect/reactivity"; import * as DateTime from "effect/DateTime"; +import type { J5ReadSources } from "./readSources.ts"; const iso = (value: DateTime.Utc | null | undefined) => value == null ? null : DateTime.formatIso(value); +export const fleetAgentKey = (environmentId: string, participantId: string) => + `${environmentId.length}:${environmentId}${participantId}`; + +/** Remote alarms are current only when both independently read environments are readable. */ +export const mergeFleetDeliveryFacts = ( + sources: J5ReadSources, + live?: ReadonlyMap, +) => { + const readable = (source: J5ReadSources["sources"][number]) => + source.connected && + source.status === "ready" && + source.data !== null && + (live === undefined || live.get(source.environmentId) === true); + const receivers = new Map< + string, + Map[number][]> + >(); + for (const source of sources.sources) { + if (!readable(source) || source.data?.remoteDeliveryAlarms === undefined) continue; + const senders = new Map[number][]>(); + for (const alarm of source.data.remoteDeliveryAlarms) { + const key = fleetAgentKey(alarm.originEnvironmentId, alarm.senderId); + const alarms = senders.get(key) ?? []; + alarms.push(alarm); + senders.set(key, alarms); + } + receivers.set(source.environmentId, senders); + } + const unique = (values: ReadonlyArray, key: (value: A) => string) => [ + ...new Map(values.map((value) => [key(value), value])).values(), + ]; + const origins = new Map< + string, + { + readable: boolean; + ledger: FleetAgentFacts | undefined; + incomplete: boolean; + } + >(); + for (const source of sources.sources) { + for (const project of source.data?.projects ?? []) { + for (const agent of project.agents) { + const key = fleetAgentKey(source.environmentId, agent.participantId); + const previous = origins.get(key); + const left = previous?.ledger; + const right = agent.facts; + const ledger = + left === undefined + ? right + : right === undefined + ? left + : { + asks: { + owed: unique([...left.asks.owed, ...right.asks.owed], (ask) => ask.exchangeId), + awaited: unique( + [...left.asks.awaited, ...right.asks.awaited], + (ask) => ask.exchangeId, + ), + }, + problems: unique([...left.problems, ...right.problems], (problem) => + JSON.stringify([ + problem.kind, + problem.kind === "delivery-failed" ? problem.messageId : problem.runId, + ]), + ), + deliveryEnvironmentIds: [ + ...new Set([ + ...(left.deliveryEnvironmentIds ?? []), + ...(right.deliveryEnvironmentIds ?? []), + ]), + ], + }; + origins.set(key, { + readable: readable(source), + ledger, + incomplete: previous?.incomplete === true || right?.deliveryEnvironmentIds === undefined, + }); + } + } + } + const result = new Map< + string, + { readonly ledger: FleetAgentFacts | undefined; readonly problemsIncomplete: boolean } + >(); + for (const [key, origin] of origins) { + const { ledger } = origin; + const destinations = ledger?.deliveryEnvironmentIds ?? []; + const openExchanges = new Set( + [...(ledger?.asks.owed ?? []), ...(ledger?.asks.awaited ?? [])].map((ask) => ask.exchangeId), + ); + const remoteProblems = origin.readable + ? destinations.flatMap((environmentId) => + (receivers.get(environmentId)?.get(key) ?? []).map((alarm) => ({ + ...alarm.problem, + // The origin owns the Exchange; its closure can precede the receiver's mirror. + exchangeOpen: + alarm.problem.exchangeOpen && + alarm.problem.exchangeId != null && + openExchanges.has(alarm.problem.exchangeId), + })), + ) + : []; + result.set(key, { + ledger: + ledger === undefined || remoteProblems.length === 0 + ? ledger + : { + ...ledger, + problems: [...ledger.problems, ...remoteProblems], + }, + problemsIncomplete: + !origin.readable || + origin.incomplete || + destinations.some((environmentId) => !receivers.has(environmentId)), + }); + } + return result; +}; + export interface FleetDerivedFacts { readonly runtime: FleetRuntimeFact; readonly asks: FleetAgentFacts["asks"] | undefined; readonly lastActivity: FleetActivityFact; readonly problems: ReadonlyArray; + readonly problemsIncomplete: boolean; } export const deriveFleetFacts = (input: { readonly shell: OrchestrationV2ThreadShell | undefined; readonly ledger: FleetAgentFacts | undefined; readonly now: number; + readonly problemsIncomplete?: boolean | undefined; }): { readonly facts: FleetDerivedFacts; readonly nextDeadline?: number } => { const { shell } = input; const problems = [...(input.ledger?.problems ?? [])]; const asks = input.ledger?.asks; + const problemsIncomplete = + input.problemsIncomplete ?? input.ledger?.deliveryEnvironmentIds === undefined; if (shell === undefined) { const unknown = { state: "unknown" as const, reason: "This environment has no readable thread shell.", }; - return { facts: { runtime: unknown, lastActivity: unknown, asks, problems } }; + return { + facts: { runtime: unknown, lastActivity: unknown, asks, problems, problemsIncomplete }, + }; } const missingRunTimes = shell.latestRunId !== null && @@ -76,11 +203,6 @@ export const deriveFleetFacts = (input: { if (completedAt !== null) candidates.push({ label: "Turn ended", at: completedAt }); const receivedAt = iso(shell.latestUserMessageAt); if (receivedAt !== null) candidates.push({ label: "Message received", at: receivedAt }); - if (shell.latestVisibleMessage !== null) - candidates.push({ - label: shell.latestVisibleMessage.role === "assistant" ? "Agent message" : "Message received", - at: iso(shell.latestVisibleMessage.updatedAt)!, - }); if (shell.pendingRuntimeRequest !== null) candidates.push({ label: @@ -156,7 +278,7 @@ export const deriveFleetFacts = (input: { (shell.settledOverride !== "active" && shell.settledAt !== null)), }; return { - facts: { runtime, asks, lastActivity, problems }, + facts: { runtime, asks, lastActivity, problems, problemsIncomplete }, ...(!missingRunTimes && dueIn !== null && dueIn > 0 ? { nextDeadline: input.now + dueIn } : {}), }; }; @@ -166,6 +288,7 @@ export interface FleetFactRow { readonly shell: OrchestrationV2ThreadShell | undefined; readonly ledger: FleetAgentFacts | undefined; readonly live: boolean; + readonly problemsIncomplete?: boolean | undefined; } /** Shared by every consumer in one registry. Only a future dispatch boundary schedules work. */ @@ -186,14 +309,24 @@ export const createFleetFactsAtom = (rows: Atom.Atom facts.set( row.key, cached ?? { - ...deriveFleetFacts({ shell: undefined, ledger: row.ledger, now }).facts, + ...deriveFleetFacts({ + shell: undefined, + ledger: row.ledger, + problemsIncomplete: true, + now, + }).facts, runtime: unknown, lastActivity: unknown, }, ); continue; } - const result = deriveFleetFacts({ shell: row.shell, ledger: row.ledger, now }); + const result = deriveFleetFacts({ + shell: row.shell, + ledger: row.ledger, + problemsIncomplete: row.problemsIncomplete, + now, + }); const cached = previous?.get(row.key); facts.set( row.key, diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 7cc52c374e475..9a7fb6ca0e4da 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -12,7 +12,7 @@ export * from "./j5/people.ts"; export * from "./j5/sharedConversation.ts"; export * from "./j5/sharing.ts"; -import { FleetAgentFacts } from "./j5/fleet.ts"; +import { FleetAgentFacts, FleetDeliveryProblem } from "./j5/fleet.ts"; import { ModelSelection } from "./modelSelection.ts"; import { @@ -403,6 +403,16 @@ export type FleetProject = typeof FleetProject.Type; export const FleetReadRequest = Schema.Struct({ includeRetired: Schema.optional(Schema.Boolean) }); export type FleetReadRequest = typeof FleetReadRequest.Type; export const FleetResponse = Schema.Struct({ + /** Receiving-server facts, attributed by the sender's stable environment and participant. */ + remoteDeliveryAlarms: Schema.optionalKey( + Schema.Array( + Schema.Struct({ + originEnvironmentId: Schema.String, + senderId: Schema.String, + problem: FleetDeliveryProblem, + }), + ), + ), projects: Schema.Array(FleetProject), asOf: Schema.optionalKey(Schema.String), }); @@ -748,8 +758,6 @@ export const PEER_PROTOCOL_VERSION = 2; /** Every peer request and response states its sender's version here; a server from before versioning sends none. */ export const PEER_PROTOCOL_HEADER = "x-j5-peer-protocol"; export const PeerCapabilities = Schema.Struct({ - /** Accepts authenticated facts about a previously accepted message's later thread delivery. */ - deliveryAlarms: Schema.optionalKey(Schema.Boolean), /** This server stores messages for a peer that polls for them. */ poll: Schema.optionalKey(Schema.Boolean), /** This server lands a message as its sender asked: a delivery's `landing` is read, not dropped. */ @@ -816,15 +824,7 @@ export const PeerDeliveryLanding = Schema.Struct({ }); export type PeerDeliveryLanding = typeof PeerDeliveryLanding.Type; -/** A diagnostic fact, never an authored message; the origin supplies identities and receipt time. */ -export const PeerDeliveryAlarm = Schema.Struct({ - messageId: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(4096)), - code: Schema.Literal("attempts-exhausted"), -}); -export type PeerDeliveryAlarm = typeof PeerDeliveryAlarm.Type; - export const PeerDeliveryRequest = Schema.Struct({ - deliveryAlarm: Schema.optional(PeerDeliveryAlarm), messageId: Schema.String.check(Schema.isNonEmpty()), /** Absent for a message that waits its turn, which is every message from an older server. */ landing: Schema.optional(PeerDeliveryLanding), diff --git a/packages/contracts/src/j5/fleet.ts b/packages/contracts/src/j5/fleet.ts index 42e5def42907e..c6a8f5e3cf161 100644 --- a/packages/contracts/src/j5/fleet.ts +++ b/packages/contracts/src/j5/fleet.ts @@ -41,6 +41,19 @@ export const FleetActivityFact = Schema.Union([ ]); export type FleetActivityFact = typeof FleetActivityFact.Type; +export const FleetDeliveryProblem = Schema.Struct({ + kind: Schema.Literal("delivery-failed"), + messageId: Schema.String, + exchangeId: Schema.optionalKey(Schema.NullOr(Schema.String)), + receiverId: Schema.String, + receiverName: Schema.NullOr(Schema.String), + at: Schema.String, + reason: Schema.NullOr(Schema.String), + /** Closing the Exchange changes eligibility, not the delivery fact. */ + exchangeOpen: Schema.Boolean, +}); +export type FleetDeliveryProblem = typeof FleetDeliveryProblem.Type; + export const FleetProblem = Schema.Union([ Schema.Struct({ kind: Schema.Literal("failed-run"), @@ -52,21 +65,14 @@ export const FleetProblem = Schema.Union([ runId: Schema.String, at: Schema.String, }), - Schema.Struct({ - kind: Schema.Literal("delivery-failed"), - messageId: Schema.String, - receiverId: Schema.String, - receiverName: Schema.NullOr(Schema.String), - at: Schema.String, - reason: Schema.NullOr(Schema.String), - /** Closing the Exchange changes eligibility, not the delivery fact. */ - exchangeOpen: Schema.Boolean, - }), + FleetDeliveryProblem, ]); export type FleetProblem = typeof FleetProblem.Type; export const FleetAgentFacts = Schema.Struct({ asks: Schema.Struct({ owed: Schema.Array(OpenAsk), awaited: Schema.Array(OpenAsk) }), problems: Schema.Array(FleetProblem), + /** Receivers whose Fleet reads complete this sender's delivery-alarm coverage. */ + deliveryEnvironmentIds: Schema.optionalKey(Schema.Array(Schema.String)), }); export type FleetAgentFacts = typeof FleetAgentFacts.Type; From 60ce9cfc409399112da4c7c9c31a926ad221706a Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 10:39:55 +0000 Subject: [PATCH 09/11] fix(fleet): track remote coverage from open Exchanges --- FORK.md | 2 +- apps/server/src/j5/a2a/fleetFacts.test.ts | 65 ++++++++++++++++++- apps/server/src/j5/a2a/fleetFacts.ts | 18 +++-- docs/j5/product/features/fleet-page.md | 4 +- .../client-runtime/src/j5/fleetFacts.test.ts | 35 +++++++++- packages/client-runtime/src/j5/fleetFacts.ts | 36 +++++----- packages/contracts/src/j5/fleet.ts | 2 +- 7 files changed, 128 insertions(+), 34 deletions(-) diff --git a/FORK.md b/FORK.md index 9849a6daf6212..bf5d67e67405f 100644 --- a/FORK.md +++ b/FORK.md @@ -164,7 +164,7 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 34. Issue #105's cross-environment reads for the project ledger and the human inbox (read models merge in the client; authority stays on each server, per [`docs/j5/product/cross-device.md`](docs/j5/product/cross-device.md)): `packages/contracts/src/environment.ts` adds three optional capability keys beside upstream's existing optional capabilities: `j5ProjectLedger`, which gates every J5 read, and `j5Squadrons` and `j5HumanInbox`, the two keys a J5 server reported while its ledger was keyed by Squadron. `apps/server/src/environment/ServerEnvironment.ts` (with its test) spreads J5-owned `J5_LEDGER_CAPABILITIES` (`packages/contracts/src/j5.ts`) into its descriptor: `j5ProjectLedger` true and the two older keys false. A server that does not report `j5ProjectLedger` true is shown as unsupported in the Inbox, Fleet, Crew, peer and playbook views, which send it no reads; the sidebar's row reads, the archive preflight and the artifact list still ask it and get "Unknown request tag", as they got a 404 before. An older J5 server, which reports `j5Squadrons` true, is refused at connection (case 56). `packages/contracts/package.json` adds the `./j5` export for J5-owned `packages/contracts/src/j5.ts`; `packages/client-runtime/package.json` appends six `./j5/*` exports for the J5-owned read-source, HTTP, and merge modules under `packages/client-runtime/src/j5/`. Those modules reuse upstream's environment registry and per-environment query atoms. `packages/client-runtime/src/state/environmentHttpAuth.ts` exposes `executeAuthenticatedEnvironmentRawHttpRequest` for the one J5 route a client still calls, the read of an artifact's content (case 64 moved every other read onto the socket); it and upstream's typed-group `executeAuthenticatedEnvironmentHttpRequest` both sit on upstream's `executeEnvironmentRequest`, the one credential/retry implementation, and start their relay DPoP root spans through one helper. That core keeps a `url(httpBaseUrl)` callback, which the raw helper passes as is; the typed wrapper builds it from upstream's contract URL builder, so a typed caller signs the URL the client sends. This keeps cookie, bearer, and relay DPoP with one refresh-and-retry shared without assigning J5 routes to an unrelated upstream API group, and no J5 read falls back to the primary environment. The upstream mount that remains (`CommandPalette.logic.ts`'s thread value, `thread::`) carries the environment beside the id so two environments' rows never collide; no new mount or door is added. Environment labels appear only once a read model spans more than one environment. The draft's Squadron environment lock went with the draft chip (the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): `ChatView.tsx`'s three environment-selection doors are upstream's again. Native mobile screens are deferred. On every rebase, verify the capability keys stay optional, the J5 request helper still goes through the shared authenticated transport, and the scoped identities survive in each recorded mount. - Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read; receiving-server alarms carry their origin identity for the shared client merge, whose coverage includes each sender's remote receiving environments. Keep this subpath on upstream sync. + Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read; receiving-server alarms carry their origin identity for the shared client merge, whose badge coverage follows each sender's open-Exchange receiving environments. Keep this subpath on upstream sync. Cases 10, 11 and 12 are retired, so no launch policy remains to verify here. Client permission guards (Jackson's 2026-10-08 decision 23; [#506](https://github.com/Jacksondr5/j5code/issues/506)). J5's protected actions are registered with upstream's guard and its controls read the guard's answer, as upstream's own do: case 64. A session without the operate scope cannot use Crew approve and decline, Crew runtime answers, Stop and Archive crew, Inbox answers, artifact delete, the playbook and persona library mutations or the skill mutations; peering needs `access:write`. The server remains the authority in every case. diff --git a/apps/server/src/j5/a2a/fleetFacts.test.ts b/apps/server/src/j5/a2a/fleetFacts.test.ts index 7812e8cb795c3..492d4cf406b39 100644 --- a/apps/server/src/j5/a2a/fleetFacts.test.ts +++ b/apps/server/src/j5/a2a/fleetFacts.test.ts @@ -97,6 +97,7 @@ it.effect( yield* alarm("retry", "peer", null, null, "retry_scheduled"); yield* alarm("delivered", "peer", null, null, "delivered"); yield* alarm("accepted-peer", "peer", "outgoing", "receiver-env", "delivered"); + yield* sql`UPDATE j5_a2a_delivery SET exchange_role = 'ask' WHERE message_id = 'accepted-peer'`; yield* alarm("inbound-peer", "peer", "outgoing"); yield* sql`UPDATE j5_a2a_delivery SET origin_environment_id = 'origin-env' WHERE message_id = 'inbound-peer'`; @@ -157,6 +158,7 @@ it.effect( yield* sql`UPDATE j5_a2a_exchange SET status = 'closed' WHERE exchange_id = 'outgoing'`; const closed = yield* read(); assert.isUndefined(closed.awaited.get(sender)); + assert.isUndefined(closed.deliveryEnvironmentIds.get(sender)); assert.equal(closed.problems.get(sender)?.length, 3); assert.isTrue( closed.problems @@ -214,9 +216,7 @@ it.effect( assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.originEnvironmentId, "origin-env"); assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.senderId, sender); assert.equal(snapshot.remoteDeliveryAlarms?.[0]?.problem.exchangeOpen, false); - assert.deepStrictEqual(snapshot.projects[0]?.agents[0]?.facts?.deliveryEnvironmentIds, [ - "receiver-env", - ]); + assert.deepStrictEqual(snapshot.projects[0]?.agents[0]?.facts?.deliveryEnvironmentIds, []); assert.equal(snapshot.asOf, "1970-01-01T00:00:00.000Z"); assert.equal(snapshot.projects[0]?.agents[0]?.facts?.asks.owed.length, 1); assert.equal( @@ -278,3 +278,62 @@ it.effect( assert.isNull(facts.awaited.get(agents[0]!)?.[0]?.counterpartyName); }).pipe(Effect.provide(database)), ); + +it.effect("tracks only open origin-owned ask destinations across projects before acceptance", () => + Effect.gen(function* () { + yield* runMigrations(); + yield* runJ5A2AMigrations(); + const sql = yield* SqlClient.SqlClient; + for (const project of ["p", "other"]) + yield* sql`INSERT INTO j5_a2a_project_ledger (project_id, created_at) VALUES (${project}, ${at})`; + yield* sql`INSERT INTO j5_a2a_peer (environment_id, label, link_mode, origin, credential, created_at, updated_at) + VALUES ('removed-peer', 'Removed', 'push', 'https://removed.example', 'test-token', ${at}, ${at})`; + const add = Effect.fnUntraced(function* ( + id: string, + status: "open" | "closed", + role: "ask" | "followup" | "none", + destination: string, + originEnvironment: string | null = null, + channel = "peer", + from = sender, + ) { + const to = `agent:receiver:${id}`; + const exchangeId = role === "none" ? null : id; + if (exchangeId !== null) + yield* sql`INSERT INTO j5_a2a_exchange + (project_id, exchange_id, sender_id, receiver_id, status, intent, opened_seq, created_at, updated_at) + VALUES ('other', ${id}, ${from}, ${to}, ${status}, ${id}, 1, ${at}, ${at})`; + yield* sql`INSERT INTO j5_a2a_delivery + (project_id, message_id, command_id, sent_seq, sender_id, receiver_id, receiver_project_id, + exchange_id, exchange_role, correlation_id, message_text, status, attempts, + created_at, updated_at, envelope_channel, receiver_environment_id, origin_environment_id) + VALUES ('other', ${id}, ${id}, 1, ${from}, ${to}, 'remote-project', ${exchangeId}, ${role}, + ${id}, 'hello', 'pending', 0, ${at}, ${at}, ${channel}, ${destination}, ${originEnvironment})`; + }); + yield* add("open-ask", "open", "ask", "active-peer"); + yield* add("old-ask", "closed", "ask", "removed-peer"); + yield* add("plain", "closed", "none", "plain-peer"); + yield* add("followup", "open", "followup", "followup-peer"); + yield* add("received-ask", "open", "ask", "inbound-peer", "foreign-origin"); + yield* add(`${CREW_ALERT_EXCHANGE_PREFIX}notice`, "open", "ask", "platform-peer"); + yield* add("lifecycle", "open", "ask", "notice-peer", null, "lifecycle_notice"); + yield* add("other-sender", "open", "ask", "other-peer", null, "peer", "agent:other"); + const read = () => readFleetLedgerFacts(sql, "p", [sender], () => null); + const pending = yield* read(); + assert.deepStrictEqual(pending.deliveryEnvironmentIds.get(sender), ["active-peer"]); + assert.isTrue(pending.awaited.get(sender)?.some((ask) => ask.exchangeId === "open-ask")); + for (const status of ["retry_scheduled", "delivered"]) { + yield* sql`UPDATE j5_a2a_delivery SET status = ${status} WHERE message_id = 'open-ask'`; + assert.deepStrictEqual((yield* read()).deliveryEnvironmentIds.get(sender), ["active-peer"]); + } + yield* sql`UPDATE j5_a2a_delivery SET status = 'delivered' WHERE message_id = 'old-ask'`; + yield* sql`DELETE FROM j5_a2a_peer WHERE environment_id = 'removed-peer'`; + yield* sql`UPDATE j5_a2a_exchange SET status = 'closed' WHERE exchange_id = 'open-ask'`; + assert.isUndefined((yield* read()).deliveryEnvironmentIds.get(sender)); + assert.equal( + (yield* sql`SELECT 1 FROM j5_a2a_delivery WHERE message_id = 'old-ask' AND status = 'delivered'`) + .length, + 1, + ); + }).pipe(Effect.provide(database)), +); diff --git a/apps/server/src/j5/a2a/fleetFacts.ts b/apps/server/src/j5/a2a/fleetFacts.ts index 84f327a219756..696317cf7c8dd 100644 --- a/apps/server/src/j5/a2a/fleetFacts.ts +++ b/apps/server/src/j5/a2a/fleetFacts.ts @@ -78,15 +78,19 @@ export const readFleetLedgerFacts = Effect.fn("readFleetLedgerFacts")(function* receiverAsks.push(ask(row.sender_id)); owed.set(row.receiver_id, receiverAsks); } - // Only local authors belong to this project's agent rows; remote authors are exported below. + // Coverage follows the open debt, so acceptance needs no extra Fleet invalidation. + // CROSS JOIN keeps the small open-Exchange set ahead of indexed receiver-route lookups. for (const batch of batches) { const destinations = yield* sql<{ sender_id: string; receiver_environment_id: string }>` - SELECT DISTINCT sender_id, receiver_environment_id FROM j5_a2a_delivery - WHERE project_id = ${projectId} AND sender_id IN ${sql.in(batch)} - AND origin_environment_id IS NULL AND receiver_environment_id IS NOT NULL - AND status = 'delivered' AND envelope_channel = 'peer' - AND (exchange_id IS NULL OR exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`}) - ORDER BY receiver_environment_id + SELECT DISTINCT d.sender_id, d.receiver_environment_id + FROM j5_a2a_exchange e CROSS JOIN j5_a2a_delivery d + ON d.project_id = e.project_id AND d.exchange_id = e.exchange_id + AND d.sender_id = e.sender_id AND d.receiver_id = e.receiver_id + WHERE e.status = 'open' AND e.sender_id IN ${sql.in(batch)} + AND e.exchange_id NOT LIKE ${`${CREW_ALERT_EXCHANGE_PREFIX}%`} + AND d.origin_environment_id IS NULL AND d.receiver_environment_id IS NOT NULL + AND d.exchange_role = 'ask' AND d.envelope_channel = 'peer' + ORDER BY d.receiver_environment_id `; for (const row of destinations) { const environments = deliveryEnvironmentIds.get(row.sender_id) ?? []; diff --git a/docs/j5/product/features/fleet-page.md b/docs/j5/product/features/fleet-page.md index 93f78ae12a0b5..970df0a0eb961 100644 --- a/docs/j5/product/features/fleet-page.md +++ b/docs/j5/product/features/fleet-page.md @@ -85,7 +85,7 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p ### Problems and the badge 21. A row's measured problems are a failed latest run, a delivery alarm, and a requested run that has waited past the dispatch threshold with no other run in progress; the row lists every one it has. -22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true, including a receiving server's alarm on a remote sender when both environments are connected; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). +22. A delivery alarm is shown on the sender's row as "Delivery failed · to ⟨receiver⟩ · ⟨time⟩ · ⟨reason⟩" and stays while the fact is true, including a receiving server's alarm on a remote sender when both environments are connected to this client; it is never inferred repaired ([agent-to-agent communication](../a2a/index.md)). 23. The badge counts agents that have at least one measured problem across every project the page reads; an agent counts once however many problems it has, unknowns never count, and the badge never counts open asks to the person or silence notices. 24. A delivery alarm counts toward the badge only while the Exchange it belongs to is open; an alarm on a plain message is shown on the row and never counted; a failed delivery of a platform-authored notice is neither shown nor counted. @@ -147,4 +147,4 @@ The Fleet page is **not** the inbox: it never demands a reply. It is **not** a p - 2026-10-07 — Squadrons retired: the page reads every project and groups roots by upstream's logical project, the sidebar is upstream's project sidebar, and every thread but a provider Subagent is a participant, so AC1 (the Squadron scope) and AC13 (the footer for threads without a home) are retired. Placement and provenance moved here from the retired Squadron definition: its AC10, AC12 and AC13 are AC34 and AC35 (Jackson, 2026-10-05; [#412](https://github.com/Jacksondr5/j5code/issues/412)). - 2026-10-12 — an outside agent can be a spawner: the agent it starts is placed at its project's root and its provenance names the outside agent by its label; AC12 and AC34 (Jackson, 2026-10-11; [#498](https://github.com/Jacksondr5/j5code/issues/498)). - 2026-10-21 — clarified AC15 and AC21: queued follow-ups preserve the active run's status, only completion-holding background work prevents Idle, and dispatch is overdue only when no other run is in progress ([#360](https://github.com/Jacksondr5/j5code/issues/360); [#662](https://github.com/Jacksondr5/j5code/pull/662)). -- 2026-10-24 — receiving servers expose later peer delivery alarms through their own Fleet read, and the client attaches them to the remote sender only while both environments are readable; unavailable receiver facts leave coverage incomplete, with no alarm returned over A2A (Jackson, 2026-10-24; [#662](https://github.com/Jacksondr5/j5code/pull/662)). +- 2026-10-24 — receiving servers expose later peer delivery alarms through their own Fleet read, and the client attaches them to the remote sender only while both environments are readable; unavailable receivers of open asks leave badge coverage incomplete, with no alarm returned over A2A (Jackson, 2026-10-24; [#662](https://github.com/Jacksondr5/j5code/pull/662)). diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index 1c7ed7c9cfab5..8a2008fe1710d 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -470,7 +470,10 @@ describe("receiving-environment delivery alarm merge", () => { ], }); const merge = (...sources: J5ReadSource[]) => - mergeFleetDeliveryFacts({ isReady: true, sources }); + mergeFleetDeliveryFacts( + { isReady: true, sources }, + new Map(sources.map((entry) => [entry.environmentId, true])), + ); const key = fleetAgentKey("origin", senderId); it("attaches remote facts to the origin environment and participant without phantom rows", () => { @@ -510,6 +513,36 @@ describe("receiving-environment delivery alarm merge", () => { ]); }); + it("attaches a later receiver alarm using the unchanged pending-origin snapshot", () => { + const pendingOrigin = origin(); + const before = merge( + pendingOrigin, + source("receiver", { projects: [], remoteDeliveryAlarms: [] }), + ); + expect(before.get(key)).toMatchObject({ ledger: { problems: [] }, problemsIncomplete: false }); + const after = merge(pendingOrigin, receiver()); + expect(after.get(key)).toMatchObject({ + ledger: { problems: [problem] }, + problemsIncomplete: false, + }); + expect(pendingOrigin.data?.projects[0]?.agents[0]?.facts?.problems).toEqual([]); + }); + + it("shows connected plain and closed-Exchange alarms independently of badge coverage dependencies", () => { + const noOpenDebt = origin({ ...ledger, deliveryEnvironmentIds: [] }); + expect(merge(noOpenDebt, receiver({ exchangeId: null })).get(key)).toMatchObject({ + ledger: { problems: [{ ...problem, exchangeId: null, exchangeOpen: false }] }, + problemsIncomplete: false, + }); + expect(merge(noOpenDebt, receiver()).get(key)).toMatchObject({ + ledger: { problems: [{ ...problem, exchangeOpen: false }] }, + problemsIncomplete: false, + }); + expect( + merge(noOpenDebt, { ...receiver(), connected: false, status: "offline" }).get(key), + ).toMatchObject({ ledger: { problems: [] }, problemsIncomplete: false }); + }); + it("reports missing, old, disconnected and unreadable relevant receivers as incomplete", () => { const unavailable: J5ReadSource[] = [ { ...receiver(), connected: false, status: "offline" }, diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index 307b7e38d44a1..4796d3d89d745 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -23,27 +23,27 @@ export const fleetAgentKey = (environmentId: string, participantId: string) => /** Remote alarms are current only when both independently read environments are readable. */ export const mergeFleetDeliveryFacts = ( sources: J5ReadSources, - live?: ReadonlyMap, + live: ReadonlyMap, ) => { const readable = (source: J5ReadSources["sources"][number]) => source.connected && source.status === "ready" && source.data !== null && - (live === undefined || live.get(source.environmentId) === true); - const receivers = new Map< + live.get(source.environmentId) === true; + const readableReceivers = new Set(); + const remoteAlarms = new Map< string, - Map[number][]> + NonNullable[number][] >(); for (const source of sources.sources) { if (!readable(source) || source.data?.remoteDeliveryAlarms === undefined) continue; - const senders = new Map[number][]>(); + readableReceivers.add(source.environmentId); for (const alarm of source.data.remoteDeliveryAlarms) { const key = fleetAgentKey(alarm.originEnvironmentId, alarm.senderId); - const alarms = senders.get(key) ?? []; + const alarms = remoteAlarms.get(key) ?? []; alarms.push(alarm); - senders.set(key, alarms); + remoteAlarms.set(key, alarms); } - receivers.set(source.environmentId, senders); } const unique = (values: ReadonlyArray, key: (value: A) => string) => [ ...new Map(values.map((value) => [key(value), value])).values(), @@ -108,16 +108,14 @@ export const mergeFleetDeliveryFacts = ( [...(ledger?.asks.owed ?? []), ...(ledger?.asks.awaited ?? [])].map((ask) => ask.exchangeId), ); const remoteProblems = origin.readable - ? destinations.flatMap((environmentId) => - (receivers.get(environmentId)?.get(key) ?? []).map((alarm) => ({ - ...alarm.problem, - // The origin owns the Exchange; its closure can precede the receiver's mirror. - exchangeOpen: - alarm.problem.exchangeOpen && - alarm.problem.exchangeId != null && - openExchanges.has(alarm.problem.exchangeId), - })), - ) + ? (remoteAlarms.get(key) ?? []).map((alarm) => ({ + ...alarm.problem, + // The origin owns the Exchange; its closure can precede the receiver's mirror. + exchangeOpen: + alarm.problem.exchangeOpen && + alarm.problem.exchangeId != null && + openExchanges.has(alarm.problem.exchangeId), + })) : []; result.set(key, { ledger: @@ -130,7 +128,7 @@ export const mergeFleetDeliveryFacts = ( problemsIncomplete: !origin.readable || origin.incomplete || - destinations.some((environmentId) => !receivers.has(environmentId)), + destinations.some((environmentId) => !readableReceivers.has(environmentId)), }); } return result; diff --git a/packages/contracts/src/j5/fleet.ts b/packages/contracts/src/j5/fleet.ts index c6a8f5e3cf161..10bc2cccab826 100644 --- a/packages/contracts/src/j5/fleet.ts +++ b/packages/contracts/src/j5/fleet.ts @@ -72,7 +72,7 @@ export type FleetProblem = typeof FleetProblem.Type; export const FleetAgentFacts = Schema.Struct({ asks: Schema.Struct({ owed: Schema.Array(OpenAsk), awaited: Schema.Array(OpenAsk) }), problems: Schema.Array(FleetProblem), - /** Receivers whose Fleet reads complete this sender's delivery-alarm coverage. */ + /** Remote receivers of this sender's open asks whose reads complete badge coverage. */ deliveryEnvironmentIds: Schema.optionalKey(Schema.Array(Schema.String)), }); export type FleetAgentFacts = typeof FleetAgentFacts.Type; From 87ed2dd73f8412a1a3f2abaaa89beecc84845cfc Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 26 Oct 2026 11:01:59 +0000 Subject: [PATCH 10/11] fix(fleet): qualify frozen rows as incomplete --- .../client-runtime/src/j5/fleetFacts.test.ts | 21 ++++++++++++++++++- packages/client-runtime/src/j5/fleetFacts.ts | 6 +++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/j5/fleetFacts.test.ts b/packages/client-runtime/src/j5/fleetFacts.test.ts index 8a2008fe1710d..42ac92a51903f 100644 --- a/packages/client-runtime/src/j5/fleetFacts.test.ts +++ b/packages/client-runtime/src/j5/fleetFacts.test.ts @@ -376,16 +376,29 @@ it("does not advance offline dispatch facts when unrelated live rows change", () exchangeOpen: true, }; const rows = Atom.make>([ - { key: "offline:a", shell: shell(), ledger: { ...ledger, problems: [alarm] }, live: true }, + { + key: "offline:a", + shell: shell(), + ledger: { ...ledger, problems: [alarm], deliveryEnvironmentIds: [] }, + live: true, + }, { key: "cached:a", shell: shell(), ledger, live: false }, ]); const facts = createFleetFactsAtom(rows); const registry = AtomRegistry.make({ defaultIdleTTL: 0 }); const stop = registry.subscribe(facts, () => {}, { immediate: true }); + const measured = registry.get(facts).get("offline:a")!; + expect(measured.problemsIncomplete).toBe(false); registry.set( rows, registry.get(rows).map((row) => ({ ...row, live: false })), ); + const frozen = registry.get(facts).get("offline:a")!; + expect(frozen.problemsIncomplete).toBe(true); + expect(frozen.runtime).toBe(measured.runtime); + expect(frozen.lastActivity).toBe(measured.lastActivity); + expect(frozen.asks).toBe(measured.asks); + expect(frozen.problems).toBe(measured.problems); vi.advanceTimersByTime(FLEET_DISPATCH_THRESHOLD_MS * 2); registry.set(rows, [ ...registry.get(rows), @@ -402,10 +415,16 @@ it("does not advance offline dispatch facts when unrelated live rows change", () }, ]); const stale = registry.get(facts).get("offline:a")!; + expect(stale).toBe(frozen); expect(stale.runtime).toMatchObject({ state: "known", status: "waiting-to-start" }); expect(stale.lastActivity.state).toBe("known"); expect(stale.problems).toEqual([alarm]); expect(registry.get(facts).get("cached:a")?.runtime.state).toBe("unknown"); + registry.set( + rows, + registry.get(rows).map((row) => (row.key === "offline:a" ? { ...row, live: true } : row)), + ); + expect(registry.get(facts).get("offline:a")?.problemsIncomplete).toBe(false); stop(); registry.dispose(); }); diff --git a/packages/client-runtime/src/j5/fleetFacts.ts b/packages/client-runtime/src/j5/fleetFacts.ts index 4796d3d89d745..21cc8e5d98aec 100644 --- a/packages/client-runtime/src/j5/fleetFacts.ts +++ b/packages/client-runtime/src/j5/fleetFacts.ts @@ -300,13 +300,17 @@ export const createFleetFactsAtom = (rows: Atom.Atom for (const row of get(rows)) { if (!row.live) { const cached = previous?.get(row.key); + const frozen = + cached === undefined || cached.problemsIncomplete + ? cached + : { ...cached, problemsIncomplete: true }; const unknown = { state: "unknown" as const, reason: "This environment is unavailable; runtime and activity are not current.", }; facts.set( row.key, - cached ?? { + frozen ?? { ...deriveFleetFacts({ shell: undefined, ledger: row.ledger, From 7026b3241904ddb37d86ca8e6618223cacab7f33 Mon Sep 17 00:00:00 2001 From: Bastian Huppertz Date: Thu, 29 Oct 2026 12:53:10 +0100 Subject: [PATCH 11/11] fix(fleet): show measured status, asks and problems (#663) * fix(fleet): show measured status, asks and problems Use the existing live shell and ledger facts for Fleet rows, with explicit unknown reasons, per-environment read times and frozen stale measurements. Add the Fleet command-palette delegate and keep section and Crew summaries aligned with those measurements. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex * fix(fleet): keep dates explicit in measured timestamps Use the existing absolute timestamp formatter for every Fleet time, including the date and year, so stale measurements never depend on midnight clocks. Omit the empty problems line while preserving unknowns and actual problems. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex * fix(fleet): make row fact details keyboard accessible * docs(fleet): record keyboard test dependency seam * fix(fleet): refresh relative timestamps while live * fix(fleet): keep exact times accessible and relative labels clear * fix(fleet): merge receiver facts and qualify incomplete coverage * test(fleet): respect local timezone in keyboard assertions * fix(fleet): badge counts agents with measured problems (#664) * fix(fleet): badge counts agents with measured problems Count live agents with failed runs, overdue dispatch or open-Exchange delivery failures once per environment and participant. Keep source gaps and unmeasured agents explicit, and preserve facts across duplicate project placements. Co-authored-by: GPT-6.1 Sol AI-Model: gpt-6.1-sol AI-Harness: Codex * fix(fleet): omit counts when every source is unavailable * test(fleet): verify cross-environment badge coverage and recovery --------- Co-authored-by: GPT-6.1 Sol Co-authored-by: Codex --------- Co-authored-by: GPT-6.1 Sol Co-authored-by: Codex --- FORK.md | 7 +- apps/web/package.json | 1 + apps/web/src/components/CommandPalette.tsx | 4 +- .../src/j5/fleet/FleetFacts.keyboard.test.tsx | 411 +++++++++++++++ apps/web/src/j5/fleet/FleetFacts.tsx | 491 ++++++++++++++++++ apps/web/src/j5/fleet/FleetPage.tsx | 140 +++-- apps/web/src/j5/fleet/FleetRailEntry.tsx | 25 +- apps/web/src/j5/fleet/fleet.logic.test.ts | 46 +- apps/web/src/j5/fleet/fleet.logic.ts | 29 +- apps/web/src/j5/fleet/fleetClient.ts | 7 +- apps/web/src/j5/fleet/fleetPalette.tsx | 23 + .../src/j5/fleet/fleetPresentation.test.ts | 227 ++++++++ apps/web/src/j5/fleet/fleetPresentation.ts | 134 +++++ apps/web/src/j5/fleet/fleetState.test.ts | 193 +++++++ apps/web/src/j5/fleet/fleetState.ts | 128 +++++ .../client-runtime/src/j5/fleetFacts.test.ts | 224 +++++++- packages/client-runtime/src/j5/fleetFacts.ts | 146 ++++-- pnpm-lock.yaml | 3 + 18 files changed, 2086 insertions(+), 153 deletions(-) create mode 100644 apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx create mode 100644 apps/web/src/j5/fleet/FleetFacts.tsx create mode 100644 apps/web/src/j5/fleet/fleetPalette.tsx create mode 100644 apps/web/src/j5/fleet/fleetPresentation.test.ts create mode 100644 apps/web/src/j5/fleet/fleetPresentation.ts create mode 100644 apps/web/src/j5/fleet/fleetState.test.ts create mode 100644 apps/web/src/j5/fleet/fleetState.ts diff --git a/FORK.md b/FORK.md index bf5d67e67405f..e8a1ace58706b 100644 --- a/FORK.md +++ b/FORK.md @@ -165,6 +165,8 @@ Landing-order collision: two cases landed as `15.`; resolved by the `b` suffix o 34. Issue #105's cross-environment reads for the project ledger and the human inbox (read models merge in the client; authority stays on each server, per [`docs/j5/product/cross-device.md`](docs/j5/product/cross-device.md)): `packages/contracts/src/environment.ts` adds three optional capability keys beside upstream's existing optional capabilities: `j5ProjectLedger`, which gates every J5 read, and `j5Squadrons` and `j5HumanInbox`, the two keys a J5 server reported while its ledger was keyed by Squadron. `apps/server/src/environment/ServerEnvironment.ts` (with its test) spreads J5-owned `J5_LEDGER_CAPABILITIES` (`packages/contracts/src/j5.ts`) into its descriptor: `j5ProjectLedger` true and the two older keys false. A server that does not report `j5ProjectLedger` true is shown as unsupported in the Inbox, Fleet, Crew, peer and playbook views, which send it no reads; the sidebar's row reads, the archive preflight and the artifact list still ask it and get "Unknown request tag", as they got a 404 before. An older J5 server, which reports `j5Squadrons` true, is refused at connection (case 56). `packages/contracts/package.json` adds the `./j5` export for J5-owned `packages/contracts/src/j5.ts`; `packages/client-runtime/package.json` appends six `./j5/*` exports for the J5-owned read-source, HTTP, and merge modules under `packages/client-runtime/src/j5/`. Those modules reuse upstream's environment registry and per-environment query atoms. `packages/client-runtime/src/state/environmentHttpAuth.ts` exposes `executeAuthenticatedEnvironmentRawHttpRequest` for the one J5 route a client still calls, the read of an artifact's content (case 64 moved every other read onto the socket); it and upstream's typed-group `executeAuthenticatedEnvironmentHttpRequest` both sit on upstream's `executeEnvironmentRequest`, the one credential/retry implementation, and start their relay DPoP root spans through one helper. That core keeps a `url(httpBaseUrl)` callback, which the raw helper passes as is; the typed wrapper builds it from upstream's contract URL builder, so a typed caller signs the URL the client sends. This keeps cookie, bearer, and relay DPoP with one refresh-and-retry shared without assigning J5 routes to an unrelated upstream API group, and no J5 read falls back to the primary environment. The upstream mount that remains (`CommandPalette.logic.ts`'s thread value, `thread::`) carries the environment beside the id so two environments' rows never collide; no new mount or door is added. Environment labels appear only once a read model spans more than one environment. The draft's Squadron environment lock went with the draft chip (the Squadron fold, [#412](https://github.com/Jacksondr5/j5code/issues/412)): `ChatView.tsx`'s three environment-selection doors are upstream's again. Native mobile screens are deferred. On every rebase, verify the capability keys stay optional, the J5 request helper still goes through the shared authenticated transport, and the scoped identities survive in each recorded mount. Fleet measurements (#360) add the `./j5/fleetFacts` export to `packages/client-runtime/package.json`. The J5-owned module derives runtime, dispatch deadlines and labeled activity from the existing raw live shell; its shared Atom owns one future local deadline and performs no RPC reads. Ledger Exchanges, sender delivery alarms and the read time remain in the J5 Fleet read; receiving-server alarms carry their origin identity for the shared client merge, whose badge coverage follows each sender's open-Exchange receiving environments. Keep this subpath on upstream sync. + + The Fleet command-palette entry is J5-owned `apps/web/src/j5/fleet/fleetPalette.tsx`; `apps/web/src/components/CommandPalette.tsx` adds one import, one hook call and appends those items beside the other J5 delegates. Preserve that mount when upstream moves palette actions. Web and desktop use the same Fleet page; native mobile has no Fleet entry or badge. `apps/web/package.json` adds the test-only `@testing-library/user-event` dependency for the Fleet row’s keyboard disclosure regression; `pnpm-lock.yaml` records its web importer. Keep it while that interaction test uses it. Cases 10, 11 and 12 are retired, so no launch policy remains to verify here. Client permission guards (Jackson's 2026-10-08 decision 23; [#506](https://github.com/Jacksondr5/j5code/issues/506)). J5's protected actions are registered with upstream's guard and its controls read the guard's answer, as upstream's own do: case 64. A session without the operate scope cannot use Crew approve and decline, Crew runtime answers, Stop and Archive crew, Inbox answers, artifact delete, the playbook and persona library mutations or the skill mutations; peering needs `access:write`. The server remains the authority in every case. @@ -806,7 +808,7 @@ explicitly marked. | `apps/web/src/environments/primary/auth.ts` | N | 70 | | `apps/web/src/components/CommandPalette.logic.test.ts` | R | 34 | | `apps/web/src/components/CommandPalette.logic.ts` | R | 34 | -| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75, 85 | +| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75, 85, 34 | | `apps/web/src/components/ConfirmDialogHost.tsx` | R | 22 | | `apps/web/src/components/LegacySidebar.tsx` | A | 21, 22, 85 | | `apps/web/src/components/Sidebar.logic.test.ts` | R | 21 | @@ -849,6 +851,7 @@ explicitly marked. | `apps/web/src/routes/_chat.tsx` | R | B | | `apps/web/src/routeTree.gen.ts` | R | generated route registrations for 6/9 | | `apps/web/src/components/onboarding/WelcomeWizard.tsx` | R | 39, B | +| `apps/web/package.json` | N | 34 | | `apps/web/tsconfig.json` | R | B | | `packages/client-runtime/package.json` | R | 23, 34, 45, 69, 70, 75 | | `packages/client-runtime/src/connection/compatibility.ts` | A | 56 | @@ -866,7 +869,7 @@ explicitly marked. | `packages/shared/src/model.test.ts` | A | 32 | | `packages/ssh/src/tunnel.test.ts` | R | H, 50 | | `packages/ssh/src/tunnel.ts` | R | H, 50 | -| `pnpm-lock.yaml` | N | 45, patched-package pins | +| `pnpm-lock.yaml` | N | 34, 45, patched-package pins | | `pnpm-workspace.yaml` | N | patched-package pins | | `scripts/build-cli-archive.ts` | N | 50 | | `scripts/build-desktop-artifact.test.ts` | A | B, S, 50 | diff --git a/apps/web/package.json b/apps/web/package.json index e048338dfa236..049fc7ba7b0a6 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -78,6 +78,7 @@ "@effect/vitest": "catalog:", "@tailwindcss/vite": "^4.0.0", "@tanstack/router-plugin": "^1.161.0", + "@testing-library/user-event": "14.6.7", "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/mdast": "^4.0.4", diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 5f2a2535773f0..ef8c5d556b47d 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1,5 +1,6 @@ "use client"; +import { useFleetPaletteItems } from "../j5/fleet/fleetPalette"; import { useHighlightsPaletteItems } from "../j5/highlights/highlightsPalette"; import { useSharingPaletteItems } from "../j5/sharing/sharingPalette"; import { useCanAddProject, useCanStartIn } from "../j5/sharing/access"; @@ -1684,6 +1685,7 @@ function OpenCommandPaletteDialog(props: { projectRef: contextualProjectRef, }); const highlightsPaletteItems = useHighlightsPaletteItems(); + const fleetPaletteItems = useFleetPaletteItems(); const actionItems: Array = []; if (projects.length > 0 && projectThreadItems.length > 0) { const activeProjectTitle = @@ -2161,7 +2163,7 @@ function OpenCommandPaletteDialog(props: { }, }); - actionItems.push(...sharingPaletteItems, ...highlightsPaletteItems); + actionItems.push(...sharingPaletteItems, ...highlightsPaletteItems, ...fleetPaletteItems); const contextualProjectGroup = (contextualProjectRef diff --git a/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx new file mode 100644 index 0000000000000..60a396e6290ee --- /dev/null +++ b/apps/web/src/j5/fleet/FleetFacts.keyboard.test.tsx @@ -0,0 +1,411 @@ +// @vitest-environment jsdom + +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import { EnvironmentId } from "@t3tools/contracts"; +import type { FleetAgent } from "@t3tools/contracts/j5"; +import userEvent from "@testing-library/user-event"; +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; + +import { formatChatTimestampTooltip } from "../../timestampFormat"; + +const state = vi.hoisted(() => ({ + facts: undefined as FleetDerivedFacts | undefined, + live: true, + version: 0, + listeners: new Set<() => void>(), + timestampFormat: "24-hour" as "12-hour" | "24-hour", + asOf: "2026-10-23T12:05:00Z", +})); +vi.mock("@effect/atom-react", async () => { + const { useSyncExternalStore } = await import("react"); + return { + useAtomValue: (atom: { read: () => unknown }) => { + useSyncExternalStore( + (listener) => { + state.listeners.add(listener); + return () => state.listeners.delete(listener); + }, + () => state.version, + ); + return atom.read(); + }, + }; +}); +vi.mock("../../hooks/useSettings", async () => { + const { useSyncExternalStore } = await import("react"); + return { + useClientSettings: ( + select: (settings: { timestampFormat: typeof state.timestampFormat }) => unknown, + ) => { + useSyncExternalStore( + (listener) => { + state.listeners.add(listener); + return () => state.listeners.delete(listener); + }, + () => state.version, + ); + return select({ timestampFormat: state.timestampFormat }); + }, + }; +}); +vi.mock("./fleetState", () => ({ + fleetAgentFactsAtom: () => ({ read: () => state.facts }), + fleetLiveAgentAtom: () => ({ read: () => state.live }), + fleetReadTimeAtom: () => ({ read: () => state.asOf }), + fleetEnvironmentLivenessAtom: { read: () => new Map([["fleet-test", state.live]]) }, +})); + +vi.mock("../state", () => ({ + fleetSourcesAtom: { + read: () => ({ + sources: [ + { environmentId: "fleet-test", environmentLabel: "Test", data: { asOf: state.asOf } }, + ], + }), + }, +})); +vi.mock("./fleetClient", () => ({})); +vi.mock("../logicalProjects", () => ({})); +vi.mock("../../state/entities", () => ({})); +vi.mock("../crew/crewArchiveClient", () => ({})); +vi.mock("../crew/crewStopClient", () => ({})); +vi.mock("../playbooks/PlaybookRunsSection", () => ({})); +vi.mock("../../confirmDialog", () => ({})); +vi.mock("../../components/ProjectFavicon", () => ({ ProjectFavicon: () => null })); +vi.mock("../../components/WorkspaceBreadcrumb", () => ({})); +vi.mock("../../components/WorkspacePageHeader", () => ({})); +vi.mock("../../components/ui/sidebar", () => ({})); +vi.mock("../../components/ui/scroll-area", () => ({})); +vi.mock("../../components/ui/toast", () => ({})); +vi.mock("../a2a/ArchiveWarningContent", () => ({})); +vi.mock("../../threadRoutes", () => ({})); +vi.mock("../../env", () => ({ isElectron: false })); + +import { FleetRowItem } from "./FleetPage"; +import { FleetSourceReadout } from "./FleetFacts"; + +const absoluteTime = (iso: string) => formatChatTimestampTooltip(iso, state.timestampFormat); + +const environmentId = EnvironmentId.make("fleet-test"); +const agent: FleetAgent = { + participantId: "agent:test", + threadId: "thread:test", + displayName: "Builder", + origin: "unknown", + placementParentId: null, + crew: null, + openAsks: 1, +}; +const measured: FleetDerivedFacts = { + runtime: { state: "unknown", reason: "This environment has no readable thread shell." }, + lastActivity: { state: "unknown", reason: "Ledger activity is unavailable." }, + asks: { + owed: [ + { + exchangeId: "owed", + counterpartyId: "captain", + counterpartyName: "Captain", + intent: "Review the patch", + openedAt: "2026-10-23T12:00:00Z", + }, + ], + awaited: [ + { + exchangeId: "awaited", + counterpartyId: "peer", + counterpartyName: "Reviewer", + intent: "Send the result", + openedAt: "2026-10-23T12:02:00Z", + }, + ], + }, + problems: [], + problemsIncomplete: false, +}; +let root: Root; +let container: HTMLDivElement; +const navigate = vi.fn(); +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + state.facts = measured; + state.live = true; + state.timestampFormat = "24-hour"; + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-10-23T12:10:00Z")); + navigate.mockClear(); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); +afterEach(async () => { + await act(() => root.unmount()); + container.remove(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); +async function render(rowAgent = agent) { + await act(() => + root.render( + <> + +
    + undefined} + onOpenThread={navigate} + /> +
+ , + ), + ); +} +async function refreshState() { + await act(() => { + state.version++; + for (const listener of state.listeners) listener(); + }); +} +const summary = () => container.querySelector("button[aria-expanded]")!; +const disclosure = () => document.getElementById(summary().getAttribute("aria-controls")!)!; +const navigation = () => container.querySelector("button:not([aria-expanded])")!; + +async function key(user: ReturnType, value: string) { + await act(() => user.keyboard(value)); +} + +it("reveals the complete facts with Tab and Enter, closes with Space, and preserves row navigation", async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + await render(); + expect(disclosure().hidden).toBe(true); + await act(() => user.tab()); + expect(document.activeElement).toBe(navigation()); + await act(() => user.tab()); + expect(document.activeElement).toBe(summary()); + expect(summary().getAttribute("aria-label")).toBe("Facts for Builder"); + await key(user, "{Enter}"); + expect(disclosure().hidden).toBe(false); + expect(disclosure().textContent).toContain("Captain · Review the patch · opened 10m ago"); + expect(disclosure().textContent).toContain("Reviewer · Send the result · opened 8m ago"); + expect(disclosure().textContent).toContain("This environment has no readable thread shell."); + expect(disclosure().textContent).toContain("Ledger activity is unavailable."); + expect(disclosure().textContent).toContain( + "This environment has no recorded provenance for this agent.", + ); + expect(navigate).not.toHaveBeenCalled(); + expect(navigation().querySelector("summary, button, details")).toBeNull(); + await key(user, " "); + expect(disclosure().hidden).toBe(true); + expect(disclosure().querySelector("div")).toBeNull(); + await act(() => user.tab({ shift: true })); + expect(document.activeElement).toBe(navigation()); + await act(() => user.keyboard("{Enter}")); + expect(navigate).toHaveBeenCalledExactlyOnceWith(environmentId, "thread:test"); +}); + +it("keeps unknown reasons reachable when the agent has no thread and navigation is disabled", async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + state.facts = undefined; + await render({ ...agent, threadId: null }); + expect(navigation().disabled).toBe(true); + await act(() => user.tab()); + expect(document.activeElement).toBe(summary()); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("The live Fleet read has not provided this fact."); + expect(disclosure().textContent).toContain( + "This environment does not provide owed and awaited Exchange details.", + ); + expect(disclosure().textContent).toContain( + "This environment does not provide delivery problems.", + ); + expect(navigate).not.toHaveBeenCalled(); +}); + +it("keeps stale ask ages frozen and names outside spawners in the disclosure", async () => { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + state.live = false; + await render({ + ...agent, + outsideSpawner: { participantId: "outside", name: "External captain" }, + }); + summary().focus(); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("this environment is unavailable"); + expect(disclosure().textContent).toContain("Captain · Review the patch · 5m at last read"); + expect(disclosure().textContent).toContain("Provenance: Spawned by External captain"); +}); + +const timedFacts: FleetDerivedFacts = { + ...measured, + runtime: { state: "known", status: "idle", settled: false, since: "2026-10-23T12:00:00Z" }, + lastActivity: { state: "known", at: "2026-10-23T12:03:00Z", label: "Last turn ended" }, + problems: [ + { + kind: "delivery-failed", + messageId: "failed", + receiverId: "peer", + receiverName: "Reviewer", + at: "2026-10-23T12:08:00Z", + reason: "offline", + exchangeOpen: true, + }, + ], +}; + +it("refreshes live row, expanded facts, asks and environment times on the shared minute tick", async () => { + state.facts = timedFacts; + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + await render(); + summary().focus(); + await key(user, "{Enter}"); + expect(navigation().textContent).toContain("Idle 10m"); + expect(navigation().textContent).toContain("Last turn ended 7m ago"); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 2m ago · offline"); + expect(disclosure().textContent).toContain("opened 10m ago"); + expect(container.querySelector("p")?.textContent).toContain("ledger read 5m ago"); + + await act(() => vi.advanceTimersByTime(60_000)); + + expect(navigation().textContent).toContain("Idle 11m"); + expect(navigation().textContent).toContain("Last turn ended 8m ago"); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 3m ago · offline"); + expect(disclosure().textContent).toContain("Status: Idle 11m"); + expect(disclosure().textContent).toContain("Last activity: Last turn ended 8m ago"); + expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 3m ago · offline"); + expect(disclosure().textContent).toContain("opened 11m ago"); + expect(container.querySelector("p")?.textContent).toContain("ledger read 6m ago"); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:00:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:03:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:08:00Z")); + expect(disclosure().textContent).toContain( + `Environment read: 6m ago (${absoluteTime(state.asOf)})`, + ); + expect(container.querySelector("p")?.textContent).toContain( + `6m ago (${absoluteTime(state.asOf)})`, + ); + + state.timestampFormat = "12-hour"; + await refreshState(); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:00:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:03:00Z")); + expect(disclosure().textContent).toContain(absoluteTime("2026-10-23T12:08:00Z")); +}); + +it("stops aging every measurement when a live row freezes, then resumes from the current clock", async () => { + state.facts = timedFacts; + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + await render(); + summary().focus(); + await key(user, "{Enter}"); + expect(navigation().textContent).toContain("Idle 10m"); + + state.live = false; + await refreshState(); + const frozen = container.textContent; + expect(vi.getTimerCount()).toBe(0); + expect(frozen).toContain(absoluteTime("2026-10-23T12:00:00Z")); + expect(disclosure().textContent).toContain("5m at last read · opened"); + expect(navigation().textContent).not.toContain("Idle 10m"); + expect(navigation().textContent).not.toContain("Last turn ended 7m ago"); + expect(navigation().textContent).not.toContain("Reviewer · 2m"); + expect(container.querySelector("p")?.textContent).toContain("stale"); + + await act(() => vi.advanceTimersByTime(3 * 86_400_000)); + expect(container.textContent).toBe(frozen); + + state.live = true; + await refreshState(); + expect(navigation().textContent).toContain("Idle 3d"); + expect(navigation().textContent).toContain("Last turn ended 3d ago"); + expect(disclosure().textContent).toContain("opened 3d ago"); + expect(container.querySelector("p")?.textContent).toContain("ledger read 3d ago"); +}); + +it("advances waiting-to-start ages and freezes their absolute request time", async () => { + state.facts = { + ...measured, + runtime: { + state: "known", + status: "waiting-to-start", + settled: false, + since: "2026-10-23T12:00:00Z", + }, + problems: [{ kind: "dispatch-overdue", runId: "requested", at: "2026-10-23T12:00:00Z" }], + }; + await render(); + expect(navigation().textContent).toContain("Waiting to start · 10m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 10m ago"); + await act(() => vi.advanceTimersByTime(60_000)); + expect(navigation().textContent).toContain("Waiting to start · 11m"); + expect(navigation().textContent).toContain("Run not dispatched · requested 11m ago"); + + state.live = false; + await refreshState(); + expect(navigation().textContent).toContain( + `Waiting to start · since ${absoluteTime("2026-10-23T12:00:00Z")}`, + ); + expect(navigation().textContent).toContain( + `Run not dispatched · requested ${absoluteTime("2026-10-23T12:00:00Z")}`, + ); + const frozen = navigation().textContent; + await act(() => vi.advanceTimersByTime(60_000)); + expect(navigation().textContent).toBe(frozen); +}); + +it("shows ask ages in one tooltip without nested triggers and refreshes the open popup", async () => { + await render(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const asks = [ + ...navigation().querySelectorAll('[data-slot="tooltip-trigger"]'), + ].find((element) => element.textContent === "Owes 1 · Awaiting 1")!; + await act(() => user.hover(asks)); + await act(() => vi.advanceTimersByTime(1_000)); + const popup = document.querySelector('[data-slot="tooltip-popup"]')!; + expect(popup).not.toBeNull(); + expect(popup.textContent).toContain("Captain · Review the patch · opened 10m ago"); + expect(popup.querySelector('[data-slot="tooltip-trigger"]')).toBeNull(); + await act(() => vi.advanceTimersByTime(60_000)); + expect(popup.textContent).toContain("Captain · Review the patch · opened 11m ago"); +}); + +it("keeps incomplete delivery coverage visible and keyboard-readable until a complete read", async () => { + state.facts = { ...timedFacts, problems: [], problemsIncomplete: true }; + await render(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + expect(navigation().textContent).toContain("Delivery problems ?"); + summary().focus(); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("Delivery problems may be missing"); + expect(disclosure().textContent).not.toContain("No measured problems."); + + state.facts = { ...state.facts, problemsIncomplete: false }; + await refreshState(); + expect(navigation().textContent).not.toContain("Delivery problems ?"); + expect(disclosure().textContent).not.toContain("Delivery problems may be missing"); + expect(disclosure().textContent).toContain("No measured problems."); +}); + +it("preserves measured delivery failures while warning about incomplete coverage", async () => { + state.facts = { ...timedFacts, problemsIncomplete: true }; + await render(); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + expect(navigation().textContent).toContain("Delivery failed · to Reviewer · 2m ago · offline"); + expect(navigation().textContent).toContain("Delivery problems ?"); + summary().focus(); + await key(user, "{Enter}"); + expect(disclosure().textContent).toContain("Delivery failed · to Reviewer · 2m ago · offline"); + expect(disclosure().textContent).toContain("Delivery problems may be missing"); + expect(disclosure().textContent).not.toContain("No measured problems."); +}); diff --git a/apps/web/src/j5/fleet/FleetFacts.tsx b/apps/web/src/j5/fleet/FleetFacts.tsx new file mode 100644 index 0000000000000..5c75b27686e5b --- /dev/null +++ b/apps/web/src/j5/fleet/FleetFacts.tsx @@ -0,0 +1,491 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FleetDerivedFacts } from "@t3tools/client-runtime/j5/fleetFacts"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; +import type { FleetAgent, FleetAgentFacts, FleetRuntimeFact } from "@t3tools/contracts/j5"; +import { useId, useState, type ReactNode } from "react"; + +import { Button } from "../../components/ui/button"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../../components/ui/tooltip"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { useClientSettings } from "../../hooks/useSettings"; +import { fleetSourcesAtom } from "../state"; +import { + fleetFactsAtom, + fleetLiveRowsAtom, + fleetAgentFactsAtom, + fleetLiveAgentAtom, + fleetEnvironmentLivenessAtom, + fleetReadTimeAtom, +} from "./fleetState"; +import { + fleetCrewSummary, + fleetAgentKey, + fleetStatusLabel, + fleetMinutes, + fleetTime, + fleetAgo, + fleetProblemLabel, +} from "./fleetPresentation"; + +const incompleteDeliveryReason = + "Delivery problems may be missing because an environment is unavailable or does not provide complete delivery facts."; + +export function FleetFactHint({ + reason, + children, + className, +}: { + readonly reason: string | undefined; + readonly children: ReactNode; + readonly className?: string; +}) { + if (reason === undefined) return {children}; + return ( + + }>{children} + {reason} + + ); +} + +type TimedLabelProps = { + readonly at: string | null | undefined; + readonly label?: (now: number | undefined, timestampFormat: TimestampFormat) => string; + readonly showAbsolute?: boolean | undefined; +}; + +function FleetTimeLabel({ + at, + label, + showAbsolute, + now, +}: TimedLabelProps & { readonly now?: number }) { + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); + const absolute = fleetTime(at, undefined, timestampFormat); + return ( + + + {showAbsolute && now !== undefined && at != null ? ` (${absolute})` : null} + + ); +} + +function FleetLiveTimeLabel(props: TimedLabelProps) { + const minute = useNowMinute(); + return ; +} + +function FleetTimestamp({ live, ...props }: TimedLabelProps & { readonly live: boolean }) { + return live ? : ; +} + +function FleetRuntimeLabel({ + runtime, + live, + showAbsolute, +}: { + readonly runtime: FleetRuntimeFact; + readonly live: boolean; + readonly showAbsolute?: boolean | undefined; +}) { + if ( + runtime.state !== "known" || + runtime.settled || + (runtime.status !== "idle" && runtime.status !== "waiting-to-start") + ) { + return <>{fleetStatusLabel(runtime)}; + } + return ( + + runtime.status === "waiting-to-start" && runtime.since !== null + ? `Waiting to start · ${now === undefined ? `since ${fleetTime(runtime.since, undefined, timestampFormat)}` : `${fleetMinutes(runtime.since, now)}m`}` + : fleetStatusLabel(runtime, now, timestampFormat) + } + /> + ); +} + +export function FleetSourceReadout() { + const sources = useAtomValue(fleetSourcesAtom); + const live = useAtomValue(fleetEnvironmentLivenessAtom); + return ( +
+ {sources.sources.map((source) => ( +

+ {source.environmentLabel} · ledger read{" "} + {source.data?.asOf === undefined ? ( + + ? + + ) : ( + + )} + {live.get(source.environmentId) === true + ? " · runtime live" + : " · stale — current facts unavailable"} +

+ ))} +
+ ); +} + +function AskDetails({ + asks, + live, + asOf, + showAbsolute, + plain = false, + now, +}: { + readonly asks: FleetAgentFacts["asks"]; + readonly live: boolean; + readonly asOf: string | undefined; + readonly showAbsolute?: boolean | undefined; + readonly plain?: boolean; + readonly now?: number | undefined; +}) { + const timestampFormat = useClientSettings((settings) => settings.timestampFormat); + return ( +
+ {( + [ + ["Owes", asks.owed], + ["Awaiting", asks.awaited], + ] as const + ).map(([label, entries]) => ( +
+

+ {label} {entries.length} +

+ {entries.map((ask) => ( +

+ + {ask.counterpartyName ?? ask.counterpartyId} + {ask.counterpartyName === null ? " (name unavailable)" : ""} + + {` · ${ask.intent} · `} + {!live + ? `${asOf === undefined ? "age ?" : `${fleetMinutes(ask.openedAt, Date.parse(asOf))}m at last read`} · ` + : null} + opened{" "} + {plain ? ( + fleetAgo(ask.openedAt, now, timestampFormat) + ) : ( + + )} + {!live ? " (stale)" : null} +

+ ))} +
+ ))} +
+ ); +} + +type AskTooltipProps = { + readonly asks: FleetAgentFacts["asks"]; + readonly live: boolean; + readonly asOf: string | undefined; +}; + +function FleetAskTooltipContent({ now, ...props }: AskTooltipProps & { readonly now?: number }) { + return ( + + }> + Owes {props.asks.owed.length} · Awaiting {props.asks.awaited.length} + + + + + + ); +} + +function FleetLiveAskTooltip(props: AskTooltipProps) { + const minute = useNowMinute(); + return ; +} + +function FleetAskTooltip(props: AskTooltipProps) { + return props.live ? : ; +} + +export function FleetFactDetails({ + environmentId, + agent, + title, +}: { + readonly environmentId: EnvironmentId; + readonly agent: FleetAgent; + readonly title: string; +}) { + const [open, setOpen] = useState(false); + const contentId = useId(); + return ( +
+ + +
+ ); +} + +function FleetFactDetailContent({ + environmentId, + agent, +}: { + readonly environmentId: EnvironmentId; + readonly agent: FleetAgent; +}) { + const key = fleetAgentKey(environmentId, agent.participantId); + const facts = useAtomValue(fleetAgentFactsAtom(key)); + const live = useAtomValue(fleetLiveAgentAtom(key)); + const asOf = useAtomValue(fleetReadTimeAtom(environmentId)); + const runtime = facts?.runtime; + const activity = facts?.lastActivity; + return ( +
+ {!live ?

Showing the last measured facts; this environment is unavailable.

: null} +

+ Status:{" "} + {runtime === undefined ? ( + "The live Fleet read has not provided this fact." + ) : runtime.state === "unknown" ? ( + runtime.reason + ) : ( + + )} +

+

+ Environment read:{" "} + {asOf === undefined ? ( + "This environment does not report its Fleet read time." + ) : ( + + )} +

+

+ Provenance:{" "} + {agent.outsideSpawner !== undefined + ? `Spawned by ${agent.outsideSpawner.name ?? agent.outsideSpawner.participantId}` + : agent.origin === "unknown" + ? "This environment has no recorded provenance for this agent." + : agent.origin === "agent" + ? "Spawned by an agent." + : "Unrecorded."} +

+ {facts?.asks === undefined ? ( +

This environment does not provide owed and awaited Exchange details.

+ ) : ( + + )} +

+ Last activity:{" "} + {activity === undefined ? ( + "The live Fleet read has not provided this fact." + ) : activity.state === "unknown" ? ( + activity.reason + ) : ( + + `${activity.label} ${fleetAgo(activity.at, now, timestampFormat)}` + } + /> + )} +

+
+

Problems

+ {facts?.problems.map((problem) => ( +

+ fleetProblemLabel(problem, now, timestampFormat)} + /> +

+ ))} + {facts?.asks === undefined ? ( +

This environment does not provide delivery problems.

+ ) : facts.problemsIncomplete ? ( +

{incompleteDeliveryReason}

+ ) : null} + {runtime?.state !== "known" ? ( +

{runtime?.reason ?? "Runtime facts are unavailable."}

+ ) : null} + {runtime?.state === "known" && + facts?.asks !== undefined && + !facts.problemsIncomplete && + facts.problems.length === 0 ? ( +

No measured problems.

+ ) : null} +
+
+ ); +} + +export function FleetFactCells({ + environmentId, + agent, +}: { + readonly environmentId: EnvironmentId; + readonly agent: FleetAgent; +}) { + const key = fleetAgentKey(environmentId, agent.participantId); + const facts = useAtomValue(fleetAgentFactsAtom(key)); + const live = useAtomValue(fleetLiveAgentAtom(key)); + const asOf = useAtomValue(fleetReadTimeAtom(environmentId)); + const runtime = facts?.runtime; + const activity = facts?.lastActivity; + const unknownReason = "The live Fleet read has not provided this fact."; + return ( + <> + + {runtime === undefined ? "?" : } + {!live ? (stale) : null} + + {facts?.asks === undefined ? ( + + ? + + ) : ( + + )} + + {activity?.state === "known" ? ( + + `${activity.label} ${fleetAgo(activity.at, now, timestampFormat)}` + } + /> + ) : ( + "?" + )} + + + + ); +} + +function FleetProblems({ + facts, + ledgerKnown, + live, +}: { + readonly facts: FleetDerivedFacts | undefined; + readonly ledgerKnown: boolean; + readonly live: boolean; +}) { + const runtimeKnown = facts?.runtime.state === "known"; + if (facts?.problems.length === 0 && !facts.problemsIncomplete && runtimeKnown && ledgerKnown) + return null; + return ( + + {facts?.problems.map((problem) => ( + + fleetProblemLabel(problem, now, timestampFormat)} + /> + + ))} + {ledgerKnown && facts?.problemsIncomplete ? ( + + Delivery problems ? + + ) : null} + {!ledgerKnown || !runtimeKnown ? ( + + Problems ? + + ) : null} + + ); +} + +export function FleetCrewSummary({ + environmentId, + agents, +}: { + readonly environmentId: EnvironmentId; + readonly agents: ReadonlyArray; +}) { + const facts = useAtomValue(fleetFactsAtom); + const live = useAtomValue(fleetLiveRowsAtom); + const summary = fleetCrewSummary( + agents.map((agent) => fleetAgentKey(environmentId, agent.participantId)), + facts, + live, + ); + return summary === "" ? null : <> · {summary}; +} diff --git a/apps/web/src/j5/fleet/FleetPage.tsx b/apps/web/src/j5/fleet/FleetPage.tsx index 2d49d41b0b8fb..224c51689b9c6 100644 --- a/apps/web/src/j5/fleet/FleetPage.tsx +++ b/apps/web/src/j5/fleet/FleetPage.tsx @@ -12,7 +12,6 @@ import { ChevronRightIcon, RefreshCwIcon } from "lucide-react"; import { useCallback, useMemo, useState, type ReactNode } from "react"; import { ProjectFavicon } from "../../components/ProjectFavicon"; -import { resolveThreadStatusPill } from "../../components/Sidebar.logic"; import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem } from "../../components/WorkspaceBreadcrumb"; import { WorkspacePageHeader } from "../../components/WorkspacePageHeader"; import { Badge } from "../../components/ui/badge"; @@ -34,12 +33,7 @@ import { useLogicalProjects } from "../logicalProjects"; import { requestConfirmDialog } from "../../confirmDialog"; import { ArchiveWarningCrewSeats, type ArchiveWarningCrew } from "../a2a/ArchiveWarningContent"; import { archiveCrew } from "../crew/crewArchiveClient"; -import { - classifyCrewSeat, - crewHasRunningSeat, - formatCrewStateSummary, - summarizeCrewState, -} from "../crew/crewState"; +import { crewHasRunningSeat, summarizeCrewState } from "../crew/crewState"; import { stopCrew } from "../crew/crewStopClient"; import { countFleetProjects, @@ -63,8 +57,19 @@ import { type ScopedFleetLedgerProject, } from "./fleetClient"; +import { fleetSeatStatesAtom, fleetProblemSummaryAtom } from "./fleetState"; +import { fleetAgentKey, fleetProblemNotices } from "./fleetPresentation"; +import { + FleetFactCells, + FleetFactDetails, + FleetSourceReadout, + FleetFactHint, + FleetCrewSummary, +} from "./FleetFacts"; + /** Header and rows share one template so the Project, Status, asks, and activity columns line up. */ -const FLEET_GRID_CLASS = "grid grid-cols-[minmax(0,1fr)_11rem_8rem_5rem_7rem] items-center gap-3"; +const FLEET_GRID_CLASS = + "grid grid-cols-[minmax(12rem,1fr)_10rem_11rem_9rem_12rem] items-center gap-3"; type ThreadLookup = ReadonlyMap; @@ -105,18 +110,21 @@ export function FleetPage() { const navigate = useNavigate(); const threads = useThreadShells(); const sources = useAtomValue(fleetDetailSourcesAtom); + const seatStates = useAtomValue(fleetSeatStatesAtom); + const problemSummary = useAtomValue(fleetProblemSummaryAtom); useFleetDetailRefresh(); const [refreshing, setRefreshing] = useState(false); const projects = useMemo(() => mergeFleetSources(sources), [sources]); const showEnvironment = spansMultipleEnvironments(projects); const loading = !sources.isReady || sources.sources.some((source) => source.status === "loading"); const notices = [ - ...new Set( - sources.sources.flatMap((source) => { + ...new Set([ + ...fleetProblemNotices(problemSummary), + ...sources.sources.flatMap((source) => { const notice = j5SourceNotice(source); return notice === null ? [] : [notice]; }), - ), + ]), ]; const refresh = useCallback(async () => { @@ -146,15 +154,17 @@ export function FleetPage() { [logicalProjectOf], ); const sections = useMemo(() => { - const partitioned = partitionFleet(projects, (environmentId, threadId) => - threadsByKey.get(scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(threadId)))), + const partitioned = partitionFleet( + projects, + (environmentId, agent) => + seatStates.get(fleetAgentKey(environmentId, agent.participantId)) ?? "unknown", ); return { ...partitioned, active: orderFleetRowsByProject(partitioned.active, projectOf), settled: orderFleetRowsByProject(partitioned.settled, projectOf), }; - }, [projectOf, projects, threadsByKey]); + }, [projectOf, projects, seatStates]); const projectCount = useMemo( () => countFleetProjects([...sections.active, ...sections.settled], projectOf), [projectOf, sections], @@ -208,7 +218,7 @@ export function FleetPage() { -
+

Fleet

@@ -229,6 +239,7 @@ export function FleetPage() { Refresh
+ {notices.length > 0 ? (