Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

23.1 KB
Raw Blame

Poll cost: Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Cut backend CPU spent on polls: count what polls return, patch the last four whole-reloaded cache entries, and make the daemon and Desktop stop reads that tell nothing new.

Architecture:

  • Backend: adds counters, extends the delta cache (#2519) to feed, light, host:state:{m}, host:inputs and startsOf, makes the receipt read cheap, and pushes delivery cancels/answers and terminal requests.
  • CLI daemon: retries held deliveries locally, backs off receipt checks, and slows its other polls behind push leases.
  • Desktop: reads the open conversation's messages only when its own counters move.

Tech Stack: TypeScript (backend Node/Fastify/Prisma-on-Mongo/ioredis; CLI Node), Dart/Flutter (Desktop), vitest, flutter test.

Spec: docs/superpowers/specs/2026-11-02-poll-cost-design.md (read it first; it carries the why and the measured numbers).

Global Constraints

  • No commits or pushes until Ken asks. Branch perf/poll-cost from main. Leave work in the tree.

  • Repository conventions: docs and comments in English, saying why; no dead code; each file keeps its style.

  • Release order:

    1. backend: Tasks 1–9;
    2. CLI: Tasks 10–14;
    3. Desktop: Task 15.

    Each client task falls back to today's cadence without the backend's push lease.

  • Spec values:

    Value Where
    Held delivery re-claim at most every 2 min; held agent list every 30 s plus on push Part 3
    Receipt check back-off 5 s doubling to 5 min; retire on final refusal or after 25 h; HOST_UNAVAILABLE from billing is not final Part 3
    Telemetry settings at start, on local change and hourly; reports every 5 min Part 4
    Terminal: __terminal_waiting push; 8 s fallback poll with the push lease, 3 s without; backend deadline stays 10 s Part 4
    Fleet machine list 45 s TTL, refresh every 5 min plus on machines_changed; window path joins in-flight reads only Part 4
    Experiment settings re-read only on desk_changed with revision 0 Part 4
    Pro cards follow the swarm_changed push lease with a 2 min safety net Part 4
    Desktop own-receipt refresh by ?messageId= every 30 s, bounded 10 min (60 min held), for queued, claimed, uncertain Part 2
  • Tests:

    • backend: NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=, integration with --config vitest.super-tabs.config.ts, real Redis with REDIS_TEST_URL=redis://127.0.0.1:6379/15;
    • CLI: npx vitest run <files>; npm run test:core when touching src/core or src/services;
    • Desktop: flutter test <files> from desktop/.

Review Focus

  1. A push lost while a delivery is held. The held message must still be written within 30 s of the pane freeing, and a cancel must still stop it. Test: Task 10, "a cancel missed by push stops the retry at the next 30 s read".
  2. Desktop with two Swarm tabs, one off screen. The off-screen tab's open conversation must not read messages on the other tab's changes. Test: Task 15, "a change in another Swarm reads nothing here".
  3. A machine that leaves a Swarm while its host:state is held. Its rows must not keep showing that Swarm's agents. Test: Task 5, "a machine whose agents all left derives an empty state".
  4. A daemon restarted with held deliveries and failing receipt entries on disk. Back-off state must survive or restart safely, with no burst of retries. Test: Task 11, "back-off resumes from the journal after a restart".
  5. An older daemon against the new backend. __terminal_waiting and the extra delivery pushes must not break it. Test: Task 9, "a frame an older daemon sees is a __ control frame or a delivery push it already reads".

Task 1: counters (backend, Part 0)

Files:

  • Modify: backend/src/lib/routeLatency.ts.
  • Modify the route handlers: GET changes, GET messages (after), GET deliveries, hosts/:m/terminal in backend/src/routes/superTabs*.ts.
  • Create: backend/src/lib/deliveryCalls.ts.
  • Modify: backend/src/superTabs/store.ts (delivery, deliveryReceipt).
  • Modify: backend/src/server.ts.
  • Test: routeLatency.test.ts, deliveryCalls.test.ts.

Interfaces:

  • Produces:

    export function markNothingNew(request: FastifyRequest): void            // routeLatency.ts
    // route window gains: empty: number; bytes: number (from Content-Length or payload length in onSend)
    export function recordDeliveryCall(event: 'reclaim' | 'receipt403' | 'receipt404' | 'hold', reason?: string): void
    export function startDeliveryCalls(opts?: { everyMs?: number; log?: Log }): () => void   // logs 'delivery calls'
    
  • Step 1: Write the tests:

    • 'a reply marked nothing-new counts as empty, and bytes are summed per route';
    • 'delivery calls counts re-claims within 10 s, receipt 403/404 and holds by reason, and logs nothing when empty'.
  • Step 2: Run them: npx vitest run src/lib/routeLatency.test.ts src/lib/deliveryCalls.test.ts. Expected: FAIL.

  • Step 3: Implement.

    • Each handler calls markNothingNew when its reply carries nothing new:
      • changes with no changed parts;
      • messages after with no rows;
      • deliveries with none open;
      • terminal with no request.
    • store.delivery records reclaim when the same host claims the same delivery within 10 s, and hold with its reason.
    • deliveryReceipt records its 403/404.
    • server.ts starts and stops the delivery calls log beside startRetryStats.
  • Step 4: Run the tests and npx tsc --noEmit. Expected: PASS.

Task 2: delta carries host columns (backend)

Files:

  • Modify: backend/src/superTabs/parts/load.ts (CHANGED_FIELDS, changedPart) and parts/types.ts (Part).
  • Test: integration/superTabCache.test.ts (describe('loadDelta')).

Interfaces:

  • Produces: Part.host?: { digest?: string; changedAt?: number }, set by changedPart from hostDigest (groups) and hostChangedAt (machines). Load paths never set it.

  • Step 1: Write the test 'loadDelta carries a group's hostDigest and a machine's hostChangedAt'.

  • Step 2: Run: npx vitest run --config vitest.super-tabs.config.ts integration/superTabCache.test.ts -t loadDelta. Expected: FAIL.

  • Step 3: Implement.

    • Add hostDigest: 1, hostChangedAt: 1 to CHANGED_FIELDS, and map them in changedPart.
    • Every patch rule's asLoaded drops host, as it drops readAt.
  • Step 4: Run the cache unit and integration tests. Expected: PASS.

Task 3: feed patched (backend, Part 1.1)

Files:

  • Modify: backend/src/superTabs/cachePatch.ts, cachedReads.ts (readChanged).
  • Test: cachePatch.test.ts, cachedReads.test.ts.

Interfaces:

  • Produces: export const feedRule: PatchRule<{ from: number; parts: Part[] }>.

    • Kinds: all seven.
    • Merge by kind and key, newer version wins.
    • Keeps tombstones, dormant groups and readAt; drops host.
    • from unchanged.
  • Step 1: Write the tests:

    • 'feedRule keeps tombstones, dormant groups and readAt, and the newer version';
    • 'readChanged passes feedRule'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement. readChanged passes feedRule as the fifth argument of view.get.

  • Step 4: Run npx vitest run src/superTabs. Expected: PASS.

Task 4: one light selection and projection (backend, Part 1.2, shared core)

Files:

  • Create: backend/src/superTabs/parts/lightSelect.ts.
  • Modify: backend/src/superTabs/parts/light.ts (loadLight and lightGroup use it).
  • Test: parts/lightSelect.test.ts, parts/light.test.ts.

Interfaces:

  • Produces:

    export function projectLightGroup(group: Part<GroupData>): Part<GroupData>   // GROUP_FIELDS always/whenRunning, as lightGroup
    export interface LightCandidates { head: Part<HeadData>; members: Part[]; agents: Part<Agent>[]; starts: Part<AgentStart>[];
      groups: Part<GroupData>[] }                                                  // groups: any superset of what is selected
    export function lightSelect(c: LightCandidates, opts: { groups?: 'active' | 'working'; groupIds?: string[]; agentIds?: string[];
      projectIds?: string[]; includeRecentStarts?: boolean }): Omit<SwarmParts, 'machines'>
    
  • Rule:

    • loadLight keeps its index reads as the candidate fetch, then returns lightSelect(candidates, opts).
    • The selection is written once: Lead conversations, running work, start- and invitation-named, undecided work, legacy agents' awake groups, plus groupIds/agentIds/projectIds as loadLight reads them.
  • Step 1: Write the tests:

    • 'projectLightGroup equals lightGroup of the projected row', for running and finished work and every GROUP_FIELDS entry;
    • 'lightSelect over all parts equals loadLight', on generated Swarms for working, active, and with agent, project and group names.
  • Step 2: Run: npx vitest run src/superTabs/parts. Expected: FAIL.

  • Step 3: Implement, and move loadLight's in-code selection into lightSelect.

  • Step 4: Run npx vitest run src/superTabs and integration/superTabCache.test.ts. Expected: PASS, with light.test.ts unchanged.

Task 5: light and host:state:{m} derived from patched entries (backend, Part 1.2)

Files:

  • Modify: backend/src/superTabs/cachedReads.ts (readLight) and read/host.ts (tabState, hostParts).
  • Test: cachedReads.test.ts, read/host.test.ts.

Interfaces:

  • Consumes: lightSelect, projectLightGroup (Task 4); readParts entries (parts, machines, dormant:agent:{id}, light-group:{id}).

  • Produces: readLight and tabState keep their signatures. On a cache miss their loader derives from the held entries, not from Mongo. Without a view (DIRECT) they call loadLight as today.

  • Step 1: Write the tests:

    • 'readLight derives from the held base and reads no Swarm collection' (spied db, no calls);
    • 'host:state derives the machine's agents' dormant conversations from dormant:agent entries';
    • 'a machine whose agents all left derives an empty state'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement. The candidates are:

    • the base;
    • each named agent's dormant:agent:{id} (for host:state);
    • light-group:{id} for named ids the base lacks.

    Project the selected groups with projectLightGroup. The machines come from readMachines.

  • Step 4: Run npx vitest run src/superTabs and the integration superTabs.test.ts (host rows). Expected: PASS.

Task 6: host:inputs held as a patched map (backend, Part 1.3)

Files:

  • Modify: backend/src/superTabs/read/host.ts (inputs), cachePatch.ts.
  • Test: cachePatch.test.ts, read/host.test.ts.

Interfaces:

  • Produces:

    export interface HostInputs { head: number; members: Record<string, number>; agents: Record<string, number>;
      starts: Record<string, number>; machines: Record<string, number>; groups: Record<string, string> }  // digest + '0'|'1'; '' if missing
    export const hostInputsRule: PatchRule<HostInputs | null>   // kinds: head, member, agent, start, machine, group
    export function hostInputsHash(inputs: HostInputs | null): string | null   // today's sha256, same key order and slice
    
  • Step 1: Write the tests:

    • 'hostInputsHash equals today's hash for the same rows' (golden from the current inputs);
    • 'hostInputsRule moves only the changed keys, and a missing digest gives null'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement.

    • The loader reads the map with today's five queries.
    • host.ts compares hostInputsHash(map).
    • The entry is held at scope main with hostInputsRule.
  • Step 4: Run them. Expected: PASS.

Task 7: startsOf patched (backend, Part 1.4)

Files:

  • Modify: backend/src/superTabs/cachePatch.ts, read/service.ts (pollStarts).
  • Test: cachePatch.test.ts.

Interfaces:

  • Produces: export function startsOfRule(agents: readonly string[]): PatchRule<Part<AgentStart>[]>. A live start whose stableId(request.machineId, harnessId) is in agents is added or replaced; otherwise it is dropped.

  • Step 1: Write the test 'startsOfRule follows starts in and out of the agent list'.

  • Step 2: Run it. Expected: FAIL.

  • Step 3: Implement. pollStarts passes the rule.

  • Step 4: Run it. Expected: PASS.

Task 8: equivalence extended (backend)

Files:

  • Modify: backend/integration/superTabCacheDelta.test.ts.

  • Step 1: Extend the existing test. After each of the 60 seeded writes, compare each entry with its direct load:

    Entry Equals
    readChanged(view, since) loadChanged(since)
    readLight(view, LIGHT) loadLight({groups:'working'})
    tabState for each machine hostParts + loadMachines
    the host:inputs hash today's hash
    startsOf loadStartsOfAgents

    Compare by cacheDigest, and include machine readings and a machine leaving.

  • Step 2: Run: npx vitest run --config vitest.super-tabs.config.ts integration/superTabCacheDelta.test.ts. Expected: PASS. A failure is a bug in Tasks 2–7: fix it there.

  • Step 3: Mutation-check.

    • Drop the version guard in feedRule: expect FAIL.
    • Drop running work from lightSelect: expect FAIL.
    • Restore both.

Task 9: cheap receipt read and new pushes (backend, Parts 3.2, 3.4, 4.2)

Files:

  • Modify: backend/src/superTabs/store.ts:
    • deliveryReceipt;
    • the cancel and answer writes at ~1518, 1525, 1693, 1701, 1714, 2281 and 3436 call this.announce for held deliveries;
    • the terminal request write calls a new terminalWaiting hook.
  • Modify: backend/src/lib/swarmDeliveryPushes.ts (a __terminal_waiting frame on the same machine channel) and the route/worker wiring of the hooks.
  • Test: store unit or integration superTabs.test.ts, swarmDeliveryPushes.test.ts.

Interfaces:

  • Produces:

    // store hooks
    terminalWaiting?: (waiting: { machineId: string; tabId: string; agentId: string }) => void
    // frame on the machine's down channel
    { type: '__terminal_waiting', payload: { tabId, agentId } }
    
  • deliveryReceipt:

    • reads the delivery row and the machine row;
    • checks owner, host and billing as today, and that the Swarm row is readable;
    • loads the Swarm through the read cache only when the row lacks machineOwnerId.
  • Step 1: Write the tests:

    • 'a receipt with machineOwnerId loads no Swarm parts' (profiled reads);
    • 'cancelling or answering a held delivery tells its machine';
    • 'a terminal request tells its machine with __terminal_waiting';
    • 'a frame an older daemon sees is a __ control frame or a delivery push it already reads'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement. TERMINAL_PICKUP_MS stays 10 s.

  • Step 4: Run npx vitest run src/lib src/superTabs, the integration superTabs.test.ts, and npx tsc --noEmit. Expected: PASS.

Task 10: held deliveries retried locally (CLI, Part 3.1–3.3, 3.5)

Files:

  • Modify: cli/src/superTabs/host.ts:
    • accept ~1719;
    • heard ~2099;
    • the list read ~1011–1082;
    • pushed ~658;
    • the write lease ~1716 and ~1777.
  • Test: cli/src/superTabs/host.spec.ts (or the host's existing spec).

Interfaces:

  • Produces:

    • const HELD_RECLAIM_MS = 120_000, const HELD_LIST_MS = 30_000.
    • A refused write (team_waiting_*, dialog, draft, unavailable screen) keeps the claimed message in a per-delivery map. It is retried on each tick and re-claimed at most every HELD_RECLAIM_MS; hold is sent once, as today.
    • A held agent's list is read every HELD_LIST_MS and on push.
    • busy is computed from the list after the pass's acks.
    • The write lease is taken per agent right before its write.
  • Step 1: Write the tests, with a fake core that refuses then accepts, and a fake backend:

    • 'a held delivery makes no claim for 2 minutes and is written once the pane frees';
    • 'a cancel pushed while held stops the retry';
    • 'a cancel missed by push stops the retry at the next 30 s read';
    • 'an acked message costs no extra list read';
    • 'a slow pass does not refuse writes for an expired lease'.
  • Step 2: Run: npx vitest run src/superTabs/host. Expected: FAIL.

  • Step 3: Implement. Re-link signed files on retry (relink).

  • Step 4: Run the host specs and npm run typecheck. Expected: PASS.

Task 11: receipt checks back off and retire (CLI, Part 3.4)

Files:

  • Modify: cli/src/superTabs/host.ts (checkReceipts ~849 and the journal entry type).
  • Test: the host spec.

Interfaces:

  • Produces:

    • Journal entry fields nextCheckAt: number and checkFails: number, persisted.
    • Back-off: 5 s doubling to 5 min.
    • Retire on 404, on codes ackRefused treats as final, or when older than 25 h. Never retire on HOST_UNAVAILABLE.
    • An entry the last list showed is skipped.
  • Step 1: Write the tests:

    • 'a failing entry backs off to 5 minutes';
    • '404 and final codes retire, HOST_UNAVAILABLE does not';
    • 'an entry older than 25 h retires';
    • 'back-off resumes from the journal after a restart';
    • 'an entry the list shows is not asked about'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement.

  • Step 4: Run them. Expected: PASS.

Task 12: terminal pickup by push (CLI, Part 4.2)

Files:

  • Modify: cli/src/superTabs/terminal.ts (SERVE_EVERY_MS ~22) and the gateway's backendControl (gateway.ts), which hands __terminal_waiting to the core's notices.
  • Test: terminal.spec.ts, gateway.spec.ts.

Interfaces:

  • Produces:

    • export const SERVE_EVERY_MS = 3_000 and export const SERVE_PUSHED_EVERY_MS = 8_000.
    • The 8 s interval applies while the delivery push lease is held.
    • A __terminal_waiting notice triggers an immediate pickup.
  • Step 1: Write the tests:

    • 'with the push lease, polls every 8 s and picks up at once on __terminal_waiting';
    • 'without it, polls every 3 s'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement.

  • Step 4: Run npx vitest run src/superTabs src/gateway. Expected: PASS.

Task 13: telemetry cadence (CLI, Part 4.1)

Files:

  • Modify: cli/src/gateway/productUsage.ts (TICK_MS ~27, syncOnce ~296).
  • Test: productUsage.spec.ts.

Interfaces:

  • Produces:

    • Settings GET at start, after a local choice(), and when SETTINGS_EVERY_MS = 3_600_000 has passed.
    • Report POST every REPORT_EVERY_MS = 300_000, from the on-disk queue.
    • CHOICE_CHANGED still re-reads settings at once.
  • Step 1: Write the tests:

    • 'settings are read at start, on a local choice, hourly, and on CHOICE_CHANGED only';
    • 'reports go every 5 minutes'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement.

  • Step 4: Run them. Expected: PASS.

Task 14: cards, fleet machine list, experiments (CLI, Part 4.3–4.5)

Files:

  • Modify:
    • cli/src/superTabs/cards.ts (intervalMs ~269, the tick ~300);
    • cli/src/device/machineList.ts (MachineListCache.refresh);
    • cli/src/services/fleet.ts;
    • cli/src/core/experiments.ts (~135).
  • Test: cards.spec.ts, machineList.spec.ts, fleet.spec.ts, experiments.spec.ts (core: run npm run test:core).

Interfaces:

  • Produces:

    • Cards: read list only when told by swarm_changed (main parts) or after a CARDS_SAFETY_MS = 120_000 gap, while the push lease holds; 5 s without it.
    • MachineListCache.refresh({ maxAgeMs }): joins a read in flight, and returns the held list when it is younger than maxAgeMs. The fleet passes 45_000, refreshes every 5 min, and on machines_changed with maxAgeMs: 0. The window path passes 0.
    • Experiments: desk_changed triggers a read only when its revision === 0.
  • Step 1: Write the tests:

    • 'cards read on push and every 2 minutes, every 5 s without the lease';
    • 'the fleet's machine list is served for 45 s and refreshed on machines_changed, a window always reads';
    • 'a desk operation's desk_changed reads no experiments, a revision-0 one does'.
  • Step 2: Run them. Expected: FAIL.

  • Step 3: Implement.

  • Step 4: Run the specs and npm run test:core. Expected: PASS at 100% for the core and services files touched.

Task 15: Desktop reads messages by the open conversation's counters (Desktop, Part 2)

Files:

  • Modify:
    • desktop/lib/super_tabs/controller.dart: _pollDue ~523, _receiptOpen ~531, _read/refresh early read ~3148, the messages gate ~3158–3292, _loadMessages ~3785;
    • desktop/lib/super_tabs/model.dart: parse reactionSeq and messageSeq.
  • Test:
    • desktop/test/super_tab_reading_test.dart;
    • update super_tab_reactions_test.dart, super_tab_message_paging_test.dart and super_tab_saved_view_test.dart.

Interfaces:

  • Produces:

    • Per open conversation, the controller remembers readMessageSeq and readReactionSeq.
    • A messages read happens only when the conversation's lastMessageSequence > readMessageSeq (after) or reactionSeq != readReactionSeq (page re-read), plus first reads, saved views and _latestWanted.
    • No early read in parallel with the state read.
    • _receiptOpen counts queued, claimed and uncertain only, within 10 min (60 min held). The own message refreshes with ?messageId= every 30 s.
  • Step 1: Write the tests:

    • 'no messages read while the open conversation's counters are unchanged, whatever else in the Swarm or its machines changed';
    • 'a change in another Swarm reads nothing here';
    • 'one after read when lastMessageSequence moves';
    • 'a page re-read only when reactionSeq moves';
    • 'the own receipt refreshes by messageId every 30 s and stops after its bound'.
    • Update "each poll reads the state, then the messages" to the new rule.
  • Step 2: Run: cd desktop && flutter test test/super_tab_reading_test.dart. Expected: FAIL.

  • Step 3: Implement.

  • Step 4: Run flutter test test/super_tab_* and flutter analyze. Expected: PASS.

Task 16: validation, review and measurement

  • Step 1: Typecheck backend and CLI; run flutter analyze for Desktop.

  • Step 2: Run the full suites:

    • backend unit with REDIS_TEST_URL;
    • backend integration;
    • CLI npm test, compared with main's known failures;
    • CLI npm run test:core;
    • Desktop flutter test.
  • Step 3: Run the CLI e2e for delivery and terminal: npm run test:e2e -- delivery terminal (the closest e2e specs).

  • Step 4: One independent reviewer (Opus) on the whole diff, with the spec, this plan and its Review Focus. Fix Critical and Important findings test-first.

  • Step 5: After each release, compare against the spec's numbers:

    • route latency empty counts and per-route requests;
    • delivery calls;
    • swarm cache full loads per entry;
    • cpu by kind and the profile.

    Report to Ken. Do not commit until he asks.