Skip to content

feat(bots): persist drafts and attach images in bot chats - #449

Merged
nixuuu merged 1 commit into
devfrom
feat/bot-composer-1
Nov 9, 2026
Merged

nixuuu merged 1 commit into
devfrom
feat/bot-composer-1

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Bot composer text was held by the mounted component, so leaving Bots could discard the message. Bot drafts now live in the owner's gateway database and restore on web, desktop and mobile. Bot chats also accept images and deliver them to the official worker harness.

  • Persist text, structured mentions, quotes/comments and uploaded image metadata with revision checks. Keep pending uploads through navigation, preserve failed sends and their request IDs, and clear only the acknowledged draft revision.
  • Reuse attachment uploads, configured file/count/message limits, thumbnails and viewers. Web/desktop support paste, drop and Attach images; mobile uses the existing paste/photos/files intake. This scope supports PNG, JPEG, GIF and WebP only; other file types can follow.
  • Deliver verified, normalized images as native Claude SDK, Codex app-server and Grok ACP image parts. Bots gain no filesystem tools. Resumed sessions receive current images; rebuilt sessions also receive bounded historical images, with a note for omissions. Preserve fix(bots): route platform tool approvals through the gateway #429's Canopy MCP approval override on Codex start/resume, Grok MCP allow rule, actionable failures and shared approval labels; gateway authorization remains authoritative.
  • Add bot_images_v1 and remote_bot_composer_v1 capability gates. Linked draft/upload/send operations remain owner-scoped. Moving a bot preserves its draft, images and thumbnails; an older destination is refused before cut-over.
  • Add migration 0102_bot_composer (latest dev migration was 0101 when opening this PR), additive RPC/fields and generated contracts. Polish docs cover persistence, native delivery, schema and mobile behavior.

Validation: bun install --frozen-lockfile, bun run typecheck, bun run lint, bun run format:check, bun run gen:check and bun run --filter @canopy/web build passed.

Focused tests rerun on dev ecb20e4 (#429): 52 passed across bot-composer, bots-harness-context, bots-harness-approvals, worker isolation/Grok transcript and DB schema (282 assertions). The official Codex MCP approval regression also passed (4 assertions). The bot computer-move case was previously verified during implementation (20 assertions). Coverage includes restart durability, structured draft CAS and lost acknowledgements, send idempotency, owner scoping, MIME/size/count limits, active-turn blob authorization, all three native image adapters, resume/rebuild and historical image limits. The move case also exercises draft/upload/send through a linked computer.

Manual browser check used an isolated gateway with the fake Codex harness: Threads/Bots navigation, full reload, picker, clipboard/drop events, dropping on an existing chip, uploaded draft restoration, send/clear, message thumbnails and viewer. The harness recorded five native image parts across two sends. Checked light/dark at desktop and phone widths, including long filenames; no console errors. No UI tests were added. Native device UI and live provider accounts were not exercised.

Mobile changes are JS/TS only. Both bunx [email protected] fingerprint:generate --platform <ios|android> --build-profile production --json --non-interactive results match current dev (ecb20e4, including #427/#428/#429):

  • iOS: 6ddec9ef559ee0095ac33e94ff9418a942053b17
  • Android: 5f6eae3ab278f1cd543e9ed763f923a319b65ec9

Full check:tmp was intentionally left to CI as requested for the shared machine. An upload still in progress when the application closes must be added again; completed uploads are durable.

Copy audit (§8): “Attachments are coming soon” → “Attach images” for the implemented action; new “Drop images to attach” describes the supported intake; “Load saved draft” names the recovery result. Conflict copy tells the user to copy edits before loading the saved version; upload/send errors explain recovery. Labels use English sentence case and action verbs, existing attachment terms and limits are reused, and controls have text/accessibility labels independent of icons or colour. No new empty states or decorative sentences. Short, typical and long filenames were checked at desktop and phone widths.

Related: #398, #421

@nixuuu
nixuuu force-pushed the feat/bot-composer-1 branch from 4d309ca to 232a7c0 Compare November 9, 2026 18:52
@nixuuu
nixuuu merged commit 618cbd1 into dev Nov 9, 2026
10 checks passed
@nixuuu
nixuuu deleted the feat/bot-composer-1 branch November 9, 2026 19:00
nixuuu added a commit that referenced this pull request Nov 9, 2026
Import progress previously rescanned each run's items separately for
multiple aggregates. It now computes counts and exact bigint byte totals
together after selecting at most 50 owner-scoped runs. The runner checks
only run state before admitting the next item, and calculates full
totals when finishing.

## Measurement

Two warmups, 20 serial samples. Fixture: 50 completed imports with 2,000
items each.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| Import progress | 1 → 1 | 399.88 → 53.70 | 50 → 50 | 26,601 → 26,601 |

The initial mixed-load run reduced progress p95 from 2,982.12 to 335.72
ms and elapsed workload from 18.09 to 3.83 s; this was an exploratory
run, before the streaming correctness assertion was added. It is not a
verified streaming comparison. Later concurrent harness runs verify the
running turn's complete contents and are documented on the overview
layer.

## SQL audit

| Statements / path | Verdict |
|---|---|
| imports/store.ts: runs + progress aggregates | Replaced repeated
correlated scans with one lateral aggregate per selected run; owner and
run selection precede the expensive scan; exact decimal sums preserved.
|
| imports/store.ts: item UI projection | Source snapshots, append base
and resume cursors excluded from UI rows; internal operations retain the
complete record. |
| imports/runs.ts: runState | Indexed owner + run-id point read replaces
progress aggregation in admission loop. |
| imports/runner.ts: next item / completion | Cancellation is rechecked
before admitting another item; totals remain exact at completion. |
| scripts/bench/concurrent.ts | Independent polling, ingest and mirror
workload; no production instrumentation. |
| scripts/bench/seed.ts | Optional agentTail defaults to zero,
preserving all callers after #418 throughout the stack. |

Import batching/restart tests cover order, owner isolation, large bigint
totals and rollback.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## Shared CI test corrections

This bottom layer also carries two existing linked-computer integration
test synchronization corrections, so every PR in the stack receives
them. The slow-read test waits for actual GetComputerUpdates admission
before timing the stale-state transition. The repeated-blackhole test
waits for both transport readiness and persisted overview presence while
continuing to assert committed-row retention and local-list latency. No
production timeout, polling, mirror or retention behavior is relaxed.

Detailed original-head/dev comparison and diagnostic evidence are
recorded in #439 and #443. The timeout trace showed approximately 10
seconds waiting for an RPC slot plus the 10-second RPC timeout on both
the original layer-10 head and dev at diagnosis. A temporary 100 ms
presence-write delay reproduced #443's exact assertion on both dev and
the original layer-14 head; the corrected wait passed under that same
delay. Diagnostic instrumentation is not committed. These are
pre-existing test races, so they do not receive promotion-holding
Fixes/Refs links.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Pending-command reads previously decoded the entire active outbox.
Delivery now uses ordered keyset pages of at most 2,048 commands and
approximately 512 KiB, allowing one oversized command to make progress.
The consumer preserves per-command TTL checks and ordering. Restartable,
opt-in concurrent index tasks are added separately from transactional
schema migrations.

## Measurement and approved TTL change

Three rounds, two warmups and 20 samples per round, alternating
legacy/current reads. Fixture: 4,096 pending commands with real protobuf
IDs plus 16,384 completed commands.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded JSON bytes before → after |
|---|---:|---:|---:|---:|
| First command page, final TTL variant | 1 → 1 | 11.31 → 6.03 | 4,096 →
2,048 | 3,350,566 → 1,472,592 |
| Complete read, final TTL variant | 1 → 3 | 9.25 → 9.47 | 4,096 → 4,096
| 3,350,566 → 2,945,065 |

**Approved by the user:** filtering TTL in SQL is required so expired
commands are never prefetched. The 9.25 → 9.47 ms full-read difference
is within noise and remains below the original 10.32 ms baseline. No
further tuning is requested for this path. The epoch-float variant
(full-read p95 10.88 ms versus 8.88 ms in its paired legacy run) was
rejected and is absent.

Earlier 64-command paging required 65 queries and 37.45 ms for a
complete read; that implementation was rejected in favor of the final
larger bounded pages. The table is the final runtime/legacy comparison,
not an isolated claim for every intervening index revision.

## SQL audit

| Statements / path | Verdict |
|---|---|
| store/outbox.ts: enqueue / commandDone | Single-row durable writes
retained; IDs and completion markers survive retries. |
| store/outbox.ts: pendingCommands | SQL TTL predicate, narrow columns,
stable (created_at,id) cursor, row and payload budgets; no full-queue JS
decoding. |
| core/core-commands.ts | Iterates pages, checks TTL again before
delivery, advances cursor even when a command expires after prefetch. |
| 0103_queue_read_indexes.sql | Performance-only index task; subsequent
lifecycle layer replaces its temporary redelivery index after the
replacement is valid. |
| migrations/index-tasks.ts | Reserved session, nonblocking
advisory-lock acquisition, definition and indisvalid checks, restart of
invalid index; concurrent DDL never enters transaction. |
| migrations/index.ts / gateway migration entrypoints | Schema migration
commits before tasks; opt in with CANOPY_DATABASE_INDEX_MODE=concurrent.
Existing legacy transactional migrations are not converted. |

Migration tests cover repeated/concurrent migrators, writes during a
concurrent build, failed/invalid tasks, changed definitions and
transaction rejection. Command tests cover restart, same-time ordering,
byte budget and expiry after prefetch. Default desktop builds remain
blocking. Large legacy migrations still need their documented
maintenance window.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Schedule workspace preparation no longer holds the schedule row lock or
a database connection while awaiting worker I/O. The final transaction
rechecks the lease, version, occurrence and placement before inserting
the thread, command and scheduled turn. The scheduler claims one
occurrence immediately before handling it instead of leasing 50 ahead of
a potentially slow operation.

## Measurement

Two warmups, 20 samples; edit starts after workspace preparation begins,
with 50 ms synthetic external I/O. Edit latency includes row-lock wait.

| Operation | Queries / rows / bytes | p95 ms before → after |
Lock-related result |
|---|---|---:|---|
| Concurrent schedule edit | Not counted by this contention harness; no
query reduction claimed | 72.89 → 8.35 | Queued despite the concurrent
edit: 20 → 0 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| bus-schedules.ts: claimDueSchedules | FOR UPDATE SKIP LOCKED remains
atomic; stable next_run_at,id order; normal loop claims one row. |
| schedule-workspace.ts: preparation reads | Read-only lookup and
external preparation happen outside the firing transaction. |
| bus-schedules.ts: fireSchedule fence | Locks the claimed schedule only
after preparation; rejects replacement lease/version/occurrence. |
| schedule-workspace.ts: placementAvailable | Revalidates worker,
project and workspace before committing the prepared placement. |
| bus-schedules.ts: turn, schedule_run, command and schedule writes |
Existing atomic enqueue/occurrence durability preserved. |
| schedule-workspace.ts: preparation failure retry | Shortens only the
same lease through a fenced update; never shortens a replacement lease.
|

Restart, idempotent occurrence, offline reconnect, pause during
preparation and archived placement tests cover the changed boundaries.
The lease is 180 s; preparation failures retain the occurrence and retry
promptly.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Obsolete mirror data and reconstructible payloads are pruned by an
owner-scoped durable maintenance job instead of an unbounded foreground
delete during checkpoint installation. The job uses bounded batches, a
durable due time, SKIP LOCKED, a 100 ms lock timeout and a 1 s statement
timeout.

## Measurement

Two warmups, 20 samples; 4,096 obsolete mirror snapshots with 4 KiB
logical content.

| Operation | Queries | p95 ms before → after | Rows / bytes |
|---|---:|---:|---|
| Foreground checkpoint cleanup → first complete maintenance batch | 16
for new full maintenance transaction; old count not recorded | 13.48 →
8.63 | Foreground deleted rows 4,096 → 0; batch limit 256; 258 returned
rows / 13,742 decoded bytes |
| Complete bounded backlog drain | Multiple committed batches | new
164.61 | All 4,096 snapshots removed |

Drain measurement advances the durable due time between batches;
production yields between scheduled attempts. This trades total drain
time for bounded foreground cost and never claims physical disk shrink.

## SQL audit and retention policy

| Statements / path | Verdict |
|---|---|
| maintenance/prune.ts: claim and reschedule | Durable per-owner row
coordinates instances; progress and eligibility commit with each batch.
|
| worker_commands compaction | Completed/failed thread commands older
than 7 days lose payload only; IDs/status/results stay; harness commands
excluded. |
| bot_harness_events deletion | Terminal turn older than 7 days, same
ingestion lock, only at/below durable worker/journal/bot ACK. Projection
and dedup cursor remain. |
| computer_thread_changes | Keep latest 10,000 revisions; old resume
cursor falls back to full snapshot. |
| mirror generations | Delete only non-current, abandoned/expired
registered generations, with subscription/state fence; never active
staging/current generation. |
| config_history / OAuth states / source previews | Existing 90-day
history policy; expired OAuth states after 7 days; expired source
previews. Bounded, owner-scoped. |
| 0104–0105 migrations | Durable maintenance/generation metadata and
performance indexes; expected migration list updated. |

No age-only deletion of user timelines, transcript events/items, import
history, audit logs, command dedup keys or move redirects. See
docs/database-retention.md for exact policy and unbounded tables
intentionally retained. Integration tests cover restart, ACK fences,
owner isolation, active generations and bounded drain.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Polling reads now have explicit pages, and repeated reference resolution
uses grouped queries. Notification previews are projected in SQL before
content reaches JavaScript.

## Measurement

Two warmups, 20 samples. Fixture: 32 targets, 256 notifications, 24
secrets, 10,013 workers.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Bus facts, 32 targets | 36 → 5 | 5.82 → 1.50 | 34 → 34 | 40,282 →
10,268 |
| Notification first page | 513 → 1 | 94.31 → 0.65 | 768 → 50 | 535,041
→ 26,901 |
| Complete 256-notification read | 513 → 7 | 94.31 → 2.27 | 768 → 256 |
535,041 → 137,736 |
| Worker config, 24 secrets | 25 → 2 | 3.93 → 0.99 | 25 → 25 | 10,909 →
11,954 |
| Worker credential miss | 1 → 1 | 0.89 → 0.14 | 0 → 0 | 2 → 2 |

Secret resolution returns a few more metadata bytes to eliminate 24
round trips; latency improves.

## SQL audit

| Statements / path | Verdict |
|---|---|
| store/bus-calls.ts: facts | One grouped header lookup for requested
targets; existing domain authorization enforces owner/tree before
execution. No target-by-target SELECT. |
| UUID lookup aliases | Grouped results retain the exact requested UUID
keys, including uppercase spelling. Integration coverage verifies that
the owner authorization still rejects a foreign thread. |
| bus-deliveries.ts / core-agent-bus-deliveries.ts | Notification pages
50, fallbacks 64, durable status and keyset cursor; one latest answer
per target turn. |
| bots/store-wakeups.ts / store-queue.ts | Bounded 32-row watch/wakeup
polls; grouped answer text, no tool payload decoding. |
| worker-config-store.ts | Grouped encrypted secret references;
ciphertext stays server-side. |
| workers-store.ts / desktop-updates/store.ts | Credential-hash index
and UUID comparison without casting indexed UUID column to text. |
| worktrees.ts: branch context | First and three latest prompts via
ordered index, excluding middle history. |
| 0106_polling_indexes.sql | Partial polling and credential indexes use
online-capable tasks. |

Owner, restart, same-time cursor, queue fairness and large-history tests
protect the changed reads.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
The concurrent benchmark now writes into a genuinely running streaming
turn and verifies its complete text/status after the workload. It can
exercise several independent SQL pools while reserving administrative
capacity below PostgreSQL's 40-connection desktop limit.

**No production overview optimization ships in this layer.** The
proposed read-only scratch-placement fast path was reverted at the
user's request after repeated measurements showed worse latency on
streaming ingest and other paths. Production project reads and their
tests are identical to the preceding layer.

## Measurement and SQL audit

| Statements / path | Before → after / verdict |
|---|---|
| projects-store.ts | No production changes; existing 8-statement steady
reconciliation, owner lock and placement/path checks retained. No new
latency improvement claimed. |
| concurrent.ts: polling | Projects, paged history, import progress and
pending commands run through actual stores, with eight polling clients
and 40 iterations. |
| concurrent.ts: streaming | Eight-event batches into a separate running
turn; complete text, item status and turn status verified after every
workload. |
| pg_stat_activity / pg_blocking_pids | Separate monitoring connection
samples about every 10 ms; counters are sampled waits/blockers, not
exact lock-wait duration. |
| pool probe / statement timeout | Scoped checkout includes connection
setup; explicit timeout cancellation rolls back its transaction and SET
LOCAL does not leak. |

Pool-capacity exploration on the 40-connection server: capacities
4,10,30 and three independent pools of 10 gave acquisition p95
71.61,10.87,0.25,7.42 ms; peak connections 4,10,11,13. Three pools had
page/ingest p95 638.72/580.30 ms and event-loop p95 54.76 ms. These are
capacity observations, not permission to raise production defaults. The
harness runs SQL pools rather than several real gateway processes.

## Remaining

Profile scratch-project reconciliation further before proposing the fast
path again. Three new before/experimental-after rounds used identical
fixture and harness code, changing only the production project-read
implementation, in order before/after, after/before, before/after. Each
workload had eight clients, pool 10, max_connections=40, 40 client
iterations, streaming ingest and mirror writes. There were zero
operation failures; streaming contents and timeout rollback passed in
all six workloads.

Values below are per-round nearest-rank p95 in milliseconds. The last
column is the median of those three p95 values, **not a pooled p95**.

| Operation | Before rounds | Rejected fast-path rounds | Median before
→ rejected |
|---|---|---|---:|
| Overview | 327.07 / 99.50 / 82.07 | 80.35 / 69.96 / 69.34 | 99.50 →
69.96 |
| History page | 307.16 / 191.10 / 185.11 | 224.76 / 188.81 / 303.22 |
191.10 → 224.76 |
| Streaming ingest | 408.60 / 199.93 / 105.08 | 287.82 / 104.04 / 416.63
| 199.93 → 287.82 |
| Import progress | 386.48 / 372.93 / 386.24 | 410.29 / 383.81 / 401.24
| 386.24 → 401.24 |
| Commands | 129.29 / 83.74 / 82.61 | 87.00 / 82.55 / 84.92 | 83.74 →
84.92 |
| Mirror write | 152.80 / 89.02 / 83.01 | 98.34 / 83.18 / 80.68 | 89.02
→ 83.18 |
| Pool acquisition | 17.18 / 60.47 / 5.14 | 20.23 / 10.37 / 12.49 |
17.18 → 12.49 |
| Event-loop delay | 25.35 / 2.60 / 1.10 | 4.80 / 0.71 / 12.98 | 2.60 →
4.80 |

Sampled waits/blockers were 160/188,40/46,33/32 before and 0/0 in all
experimental-after rounds. Peak connections/active connections were
10/10 throughout. The shared machine shows substantial variance; the
measurements do not establish the cause of the regression. In
particular, faster overview and fewer locks do not justify
streaming-ingest p95 increasing from 199.93 to 287.82 ms. The user
explicitly rejected that trade-off. No regression exception is claimed;
the fast path and its behavior-specific test were removed before final
validation.

An earlier single comparison gave overview 92.99 → 78.34, page 190.58 →
196.57 and mirror 86.05 → 91.46 ms. Those observations are retained as
context and superseded for acceptance by the repeated rejection above.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40). Latency runs without tracing; pool and lock
observations are separate probes. Store measurements exclude transport
and external CLI work. Raw results, hosts and datasets are not
committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining SQL-audit gaps are recorded in the top
PR. CI remains the full gate. Polish documentation is updated; no UI
text changes, so the copy audit does not apply.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Large snapshot protobuf conversion now yields to the I/O phase between
~4 ms slices, after materializing and closing the consistent read
transaction. The complete timeline and original ordering remain intact.

## Measurement

Same 32,768 synthetic protobuf item rows, three rounds, two warmups and
20 samples per mode/round; alternating mode order. Decode only, no SQL
or transport.

| Operation | Queries / rows / bytes | p95 ms before → after | Timer-gap
p95 before → after |
|---|---|---:|---:|
| Snapshot decode, final chunk-mapping implementation | 0 / 32,768 /
identical input (bytes not separately counted) | 52.93 → 46.52 | 53.67 →
9.05 ms |

Earlier per-row cooperative decoding regressed 38.11 → 51.13 ms, and a
preallocated-array experiment gave 36.66 → 36.82 ms. Those
implementations were rejected. The committed implementation maps small
chunks and reduces timer starvation without the measured p95 regression.

## SQL / request-path audit

| Statements / path | Verdict |
|---|---|
| thread-snapshot.ts: turn/item/notice/interactions reads | SQL range
and payload are unchanged. Full legacy/restored windows remain complete.
|
| repeatable-read cursor snapshot | All rows materialized before leaving
transaction; cooperative decode does not extend the owned read
transaction. |
| snapshot-decode.ts | Real I/O-phase yield, not a microtask; mapping
preserves item/notice sequence. |
| single huge item / driver JSON / transport serialization | Still
synchronous; not claimed solved by slicing between rows. Requires a
separate codec/fragmentation contract. |

Existing fork/history/mirror/restart read-cost suites verify unchanged
contents. No new trivial helper test is added.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Diagnostic plan capture now includes writes and locked SELECTs without
changing their original effects: EXPLAIN runs on the same owned
connection, inside a rollback/savepoint, before the original statement.
The maintenance selector skips terminal harness turns whose remaining
events have no acknowledged pruneable rows, avoiding starvation behind
an unacknowledged oldest turn.

## Measurement

| Path | Queries / p95 / rows / bytes | Verdict |
|---|---|---|
| Production without diagnostic opt-in | No tracing added; no
instrumentation latency claim | Same ordinary SQL path |
| Diagnostic EXPLAIN mode | Deliberately adds execution + rollback;
excluded from latency samples | Reports sanitized
nodes/buffers/fingerprints, errors and skipped effects |
| Unacknowledged prune candidate | Latency not benchmarked separately |
Correctness/fairness fence; integration test proves eligible later turn
can progress |

## SQL audit

| Statements / path | Verdict |
|---|---|
| plan-capture.ts: SELECT/INSERT/UPDATE/DELETE/WITH | EXPLAIN ANALYZE
BUFFERS before original execution with preserved FK/lock context. |
| transaction/savepoint handling | Failed diagnostic plan rolls back its
savepoint and leaves original transaction usable; nested writes execute
exactly once. |
| session and sequence effects | Advisory locks, notifications, sequence
mutation, cancellation and session setters skipped explicitly. |
| SQL inventory/evidence matching | Candidate templates, not
executed-call-site proof; dynamic fragments and cold paths can remain
unmatched. |
| maintenance/prune.ts: terminal harness candidate | Requires no
remaining events or at least one durable acknowledged event before
claiming the oldest turn. |

A historical inventory run found 2,171 statement/fragment locations, 380
with template evidence from 386 unique fingerprints, 83 unmatched plans
and zero plan errors. **This is not complete SQL audit coverage**, and
source line numbers can shift after edits/rebase. New final-revision
coverage must be distinguished from this diagnostic snapshot. DDL and
transaction control have no EXPLAIN plan. Test fixtures do not establish
large-dataset performance.

The pre-rebase diagnostic repeat on head `3381f50b` used the standard
240-thread / 2,048-long-turn / 4,096-byte fixture plus the queue/import
fixture: 22 operations, 80 plans, 58 unique fingerprints, zero plan
errors and zero skipped plans. Template matching found 64 candidate
locations in that revision's inventory of 2,177 locations; 16 plans had
no source match. The 2,113 locations without evidence from this repeat
are not declared reviewed. One diagnostic iteration and two warmups were
used to refresh plans, **not to establish before/after p95**. Database
storage was approximately 201 MiB. The post-rebase static inventory
still contains 2,177 locations across 311 files; plan matches were not
reassigned across revisions. Historical and current source-location
counts are not combined.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Connector lists now fetch metadata and resolve worker/bot grants in two
grouped reads. Instance lists filter ownership in SQL before decoding
configuration, and instance assignment inserts workers with unnest
instead of one INSERT each. Import admission checks read run state
without recomputing totals.

## Measurement

Two warmups, 20 samples; 32 connector catalogs and 32 foreign instance
configurations, each 64 KiB; 13 assigned workers; one 2,000-item import.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Connectors list | 65 → 3 | 20.64 → 1.94 | 96 → 96 | 2,116,943 → 19,217
|
| Owner instance list | 4 → 4 | 7.71 → 1.43 | 49 → 17 | 2,115,729 →
3,130 |
| Assign instance to workers | 15 → 3 | 41.25 → 36.30 | 13 → 13 | 1,847
→ 1,823 |
| Import runner admission | 1 → 1 | 1.23 → 0.31 | 1 → 1 | 533 → 101 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| connectors/accounts.ts list + grants | Metadata projection, owner
scope and grouped grants; execution still fetches actual tool catalog
after authorization. |
| store/instance-queries.ts instance/proxy/config/count reads | Owner or
explicitly shared instance applied in SQL, not after blob decode. |
| store/instance-queries.ts assignWorkers | One unnest insert with
existing transaction/validation. |
| store/worker-config-store.ts secret reference insert | Grouped
insertion retains transactional configuration revision. |
| connectors/store-oauth-state.ts | Owner-scoped lookup retained in
token-state transitions. |
| imports/runs.ts / runner.ts | Keyed run-state check; terminal counters
computed at completion. |

Internal cross-owner configuration reconciliation is deliberately
separate from owner-visible list reads. Focused connector/config/import
and owner tests cover behavior.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Worktree activity checks use partial indexes for active turns and
background items instead of walking long completed histories. Secret UI
reads exclude ciphertext. The redelivery index supports both active and
expired-prefix command reads without duplicating the composer-choices
index.

## Measurement

Two warmups, 20 samples; long worktree history, 16,384 expired commands
before 64 active ones, 64 secrets with 8 KiB ciphertext.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Worktree inventory | 1 → 1 | 14.37 → 6.21 | 1 → 1 | 759 → 759 |
| Commands past expired prefix | 1 → 1 | 10.24 → 1.36 | 64 → 64 | 32,513
→ 32,513 |
| Secret metadata | 1 → 1 | 6.70 → 0.54 | 64 → 64 | 5,725,057 → 14,529 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| worktree-lifecycle.ts / worktrees.ts: active-turn EXISTS | Partial
active-turn index; completed history excluded. |
| worktree activity: background items | Existing status/type semantics
retained; matching partial index. |
| thread-secrets.ts: threadSecrets / secretResult | Narrow metadata
projection; secret values never enter UI/history. |
| outbox.ts: pending command page | Narrow columns and SQL TTL;
supported by replacement index. |
| 0107_lifecycle_read_indexes.sql | Online-capable performance indexes;
old outbox indexes retired only after valid replacement. |

The final outbox TTL-in-SQL p95 9.25 → 9.47 ms is the user's explicitly
approved correctness/noise exception; details and rejected epoch-float
experiment are on the queue/index layer. Worktree lifecycle and
command-expiry tests cover guards and replay.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## CI timeout investigation

On the original layer-10 head `e7e27bb7`, the isolated slow-read case
passed 10/10 times. Repeating the complete file 10 times passed 70/70
tests in 765.48 seconds, with clean temp-directory checks. The isolated
case also passed 10/10 times on dev `119b373a`.

A temporary diagnostic on the layer-10 head established the deadline
race after the preceding reconnect case: the stalled GetComputerUpdates
RPC reached the peer at 10,023 ms, while its cache became stale at
20,006 ms from the beginning of the test's wait. The test's 20-second
budget included admission behind other bounded background reads and the
RPC's own 10-second timeout. The CI assertion failed at 20,012 ms. The
permanent test correction waits for the actual new RPC before starting
the stale-state deadline; cooldown, local-read latency, reachability and
recovery assertions remain active. It is applied at the bottom of the
stack so every layer receives it.

PeerReads, connection tracking, handshake handling and linked update
reads are unchanged between this layer and dev. The linked fixture does
not start the maintenance job. This investigation found a test deadline
race, not evidence of a lifecycle/retention production regression. No
production timeout or polling limit is relaxed.

The same temporary diagnostic on dev at diagnosis `618cbd15` observed
RPC admission at 10,017 ms and stale state at 20,015 ms; the complete
file passed 7/7 tests in 78.33 seconds. Both instrumented runs exhibit
the same pre-existing scheduling boundary. Diagnostic logging is not
part of the committed tests.

After the fix and rebase, the complete timeout file passed **21/21 tests
across three full-file rounds in 230.24 seconds**, with a clean temp
directory. The 20-second stale-state bound starts after actual RPC
admission; the outer test timeout covers the separate bounded admission,
timeout, cooldown and recovery phases.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Skill assignment now reuses current immutable artifacts already loaded
in the owner's library snapshot. Historical pinned versions are fetched
as plain rows in a grouped query. Worker settings read version/hash
metadata once for all skills.

## Profile and measurement

The first reported run regressed snapshot p95 **175.8 → 229.9 ms**
despite 426 → 11 queries and ~10 MB → 1.08 MB. That result was rejected.
Profiling then separated normal latency, process CPU, driver wall time
and PostgreSQL EXPLAIN; other own benchmarks/tests/builds were stopped
for paired final runs.

Final three-round comparison: 32 skills, two 16 KiB versions, 13
workers, 16 historical pins. Two warmups and 20 samples per round.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Skills snapshot | 426 → 11 | 136.62 → 20.16 | 463 → 63 | 9,970,938 →
1,078,459 |
| Worker environment settings | 480 → 18 | 124.84 → 27.99 | 543 → 127 |
9,978,614 → 1,087,944 |

Snapshot round p95 before: 120.21 / 109.63 / 144.77 ms; after: 20.88 /
13.26 / 12.48 ms. Worker settings: 130.72 / 101.26 / 121.97 → 50.60 /
14.12 / 16.85 ms. Snapshot CPU including warmups across rounds: 4,412.08
→ 552.39 ms.

Findings: reuse eliminates repeated artifact reads and protobuf decode
for every skill/worker combination. Historical reads return plain rows;
no new large server-side JSON aggregate is introduced. Representative
PostgreSQL execution: current-library read 0.639 ms, historical batch
0.129 ms, version metadata 0.088 ms. Final snapshot driver wall: current
32-skill read 2.51 ms, historical batch 1.04 ms. A cold diagnostic
connection consumed 7.94 ms on its first operation; diagnostic totals
include instrumentation and must not be subtracted from uninstrumented
p95 to infer JS time. The initial regression does not establish a single
slow SQL/JS cause; it remains recorded as an adverse shared-host
observation, superseded for acceptance by the isolated paired
measurements.

## SQL audit

| Statements / path | Verdict |
|---|---|
| skill-database.ts: skillVersions | Owner-scoped grouped historical
pins, exact bigint version strings; current snapshot artifacts reused. |
| skill-assignment.ts: desiredSkills | No SELECT per current
skill/worker; mapping preserves destination collision/size validation. |
| worker-settings.ts: version metadata / overrides | One metadata read
for selected skill IDs, no artifact transfer for hash-only display. |
| source-database.ts: preview cleanup | Existing scoped preview behavior
retained. |
| library snapshot SQL | Full files remain available for preview and
environment reconciliation; no clipping or owner-crossing cache. |

Restart, historical pin and assignment integration coverage is retained.
No regression approval is needed for the final measured implementation.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Secret delivery now claims at most 64 items and durably advances a
fairness cursor. Reconnect replay resets at most 256 rows per
transaction and survives restart. Expiry also uses bounded 256-row SKIP
LOCKED batches.

## Measurement

Three rounds, two warmups and 20 samples each; baseline/current
alternate each sample on one private database with 1,024 saved synthetic
secrets. State is restored outside timing; stable mode VACUUMs
reset/expiry fixtures outside timing.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Poll | 3 → 1 | 8.03 → 3.44 | 1,024 → 64 | 959,493 → 61,441 |
| First reconnect reset batch | 4 → 7 | 30.66 → 13.10 | 1,024 → 321 |
959,495 → 73,244 |
| First expiry batch | 1 → 1 | 83.35 → 34.46 | 1,024 → 256 | 460,801 →
115,201 |

This compares a bounded first batch with the old full operation; it is
not a claim of faster complete replay/expiry drain. Earlier separate
runs had adverse reset p95 (37.35 → 119.80 ms) and were retained during
profiling; atomic claim/cursor work plus interleaved measurements
produced the final comparison above. Churn mode without VACUUM is
available to expose update/index bloat.

## SQL audit

| Statements / path | Verdict |
|---|---|
| secret-deliveries.ts: claim CTE | Cursor and row claim commit in one
statement, SKIP LOCKED, wrap-around fairness; acknowledged state remains
authoritative. |
| resetBatch + worker_secret_replays | Durable cursor, 256-row sweep,
transaction only when replay needs several statements. |
| thread-secrets.ts: secretResult | Replay cursor prevents old receipt
from appearing applied while reconnect reset has not reached it. |
| secretReceipt | Worker/thread/request/revision fence retained. |
| expireSecrets | Owner-scoped 256-row batch; wipes ciphertext before
delivery of removal. |
| 0108–0109 migrations | Durable replay/delivery cursors and performance
indexes; expected list updated. |

Durability/owner tests cover more than one batch, late ACKs, replay
continuation after reopening, fair polling and expiry.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Routine dispatch no longer locks up to 100 bots before slowly enqueueing
each one's routines. It locks one bot per transaction, checks all of its
routines' busy state in one read, and atomically enqueues/advances that
bot before moving on.

## Measurement

Two warmups, 20 samples; 16 bots × 4 routines. Separate contention pass
adds 5 ms enqueue delay and edits the last bot after dispatch starts.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Routine dispatch | 675 → 531 | 395.34 → 324.96 | 272 → 272 | 123,048 →
51,330 |
| Concurrent last-bot edit | Included above; not separately counted |
685.43 → 18.12 | Unchanged mutation | Not separately counted |

## SQL audit

| Statements / path | Verdict |
|---|---|
| bots/routines.ts: due bot claim | One bot lock per transaction, SKIP
LOCKED, bounded dispatch loop. |
| routine busy lookup | One grouped check per bot; no repeated busy
SELECT per routine. |
| bot header reads | Instructions/payload excluded when only dispatch
metadata is needed. |
| enqueue + routine next occurrence | Same transaction and idempotent
occurrence semantics retained. |
| bot lease / routine updates | No lock held on later bots during
earlier enqueue work. |

Routine gRPC and restart tests cover concurrency and occurrence
durability.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

The rebase includes #449's image/draft enqueue behavior. This layer
reuses a narrow `BotTurnKey` type for its three ID-only projections,
keeping botEnqueue within the lint size limit after the combined
changes. This is a type-only adjustment; SQL and runtime behavior are
unchanged.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Move previews used a complete exported bot conversation just to list
reconnectable account names. The preview now fetches only the required
metadata. Move dependency inspection resolves bot/thread headers in two
owner-scoped grouped reads.

## Measurement

Two warmups, 20 samples. One bot has 2,048 additional 4 KiB messages; 32
connectors; inspection covers 16 bots and 8 threads.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Bot move preview | 6 → 6 | 272.35 → 4.25 | 4 → 35 | 10,255,669 → 2,345
|
| Inspect 24 dependencies | 24 → 2 | 6.35 → 1.93 | 24 → 24 | 1,624 →
1,602 |

## SQL audit

| Statements / path | Verdict |
|---|---|
| moves-preview.ts: bot preview | Connection-name metadata only; no
conversation export/decode. |
| moves-preview.ts: inspect | Batched bot/thread/project headers; owner
predicate includes side threads. |
| move source/target durability | Export and transfer behavior
unchanged; not measured as a preview optimization. |
| computers/redirects.ts | Separate audit/optimization on the final
redirect layer; not claimed covered by preview changes. |

Real service without transport; inspection response is synthetic. Full
move gRPC tests cover transfer/restart/owner behavior; transport
serialization is not measured.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## CI mirror-list investigation

The original layer-14 head `200edb16` passed the unchanged
repeated-blackhole case 10/10 times (108.06 seconds, clean temp
directory). Dev `618cbd15` at diagnosis passed its ordinary run too. In
CI, every committed worker/project/thread retention assertion passed
before the failing assertion: `awayReason(peer)` was still undefined.

Connection tracking removes the ready transport before awaiting the SQL
presence update. The test waited only for transport disappearance and
then assumed the overview's persisted presence had already changed. A
temporary 100 ms delay before persisting `unreachable` reproduced the
exact assertion on **both dev and layer 14** (4,897 ms and 4,875 ms
respectively). Waiting for both transport readiness and the overview's
actual presence made that same delayed experiment pass (11.53 seconds).
The temporary injected delay is not committed.

The permanent test correction, placed on the bottom layer so every PR
receives it, polls the real overview presence on both disconnect and
recovery. Every poll still checks committed workers, projects, threads
and the 500 ms local-list bound. The linked fixture does not run the
pruning job; active mirror generations remain excluded from pruning. No
production mirror, lease, presence or retention behavior is changed by
this correction. The existing retention/mirror integration tests remain
part of the focused revalidation.

The corrected repeated-blackhole case passed **10/10 rounds in 110.24
seconds**, with a clean temp directory. Focused retention (5), durable
mirrors (20), mirror listing (3), migration/index (28) and bot
composer/routine (17) tests also passed. These focused runs used top
head `1c4f213f`, before the subsequent dev refreshes; the final
top-branch full run is recorded in #447.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Configuration blob retry checks now find missing hashes in SQL before
decoding all configuration fields. Repeated hash references are
deduplicated before validation. Reapplication selects only live waiting
records or records naming newly received content.

## Measurement

Three rounds, two warmups and 20 samples each; 129 configuration records
sharing 64 missing versions, including one waiting record.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Missing-blob lookup | 2 → 1 | 15.15 → 9.46 | 129 → 64 | 1,855,729 →
4,865 |
| Recheck waiting library | 71 → 8 | 144.21 → 12.97 | 130 → 2 |
1,855,994 → 14,568 |

Earlier per-reference validation variants were profiled/rejected;
deduplicating before hash validation avoids repeated work. Transfer is
outside measurement.

## SQL audit

| Statements / path | Verdict |
|---|---|
| environment-blobs.ts | Owner scope, deduplicated/validated hashes,
existence checks across all three library tables; no full config blob
result. |
| environment-sync.ts | Filters waiting or matching-content records in
SQL; marketplace precedes plugin; partial tombstones with fields remain
live. |
| environment-support.ts | Batch hash-presence check avoids
missing-artifact reads per version. |
| content materialization | Existing owner-local content is still hash
verified before use. |

Integration tests cover another owner's hash, malformed/missing content,
shared content across library kinds, tombstones and waiting
dependencies.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Bot MCP listings now read narrow metadata and group grants. Bot model
catalogs filter owner/provider/instance in SQL before decoding profiles,
and configuration validation reads only owned/shared instance model
metadata.

## Measurement

Three rounds, two warmups and 20 samples each; 32 MCP catalogs × 64 KiB;
13 owned and 32 foreign worker catalogs with two irrelevant 64 KiB
profiles and one small matching profile.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Bot MCP servers | 65 → 3 | 16.50 → 1.23 | 64 → 64 | 2,113,679 → 16,082
|
| Bot model lookup | 2 → 2 | 17.80 → 0.98 | 46 → 14 | 5,911,811 → 1,258
|

## SQL audit

| Statements / path | Verdict |
|---|---|
| bots/store-access.ts: MCP server list + grants | Metadata projection
and two grouped grants; execution retains authorized full catalog. |
| bots/store-config.ts: catalogs | Worker owner/shared scope and
provider/instance filter precede protobuf decoding; array order
retained. |
| botValidate instance lookup | Requires owner or shared instance and
projects custom_models only. |
| bots/store-bots.ts | Threads the acting owner through catalog lookup.
|

Owner integration coverage includes foreign worker models and foreign
instances; explicitly shared workers remain supported. The independent
ModelStore.catalogs security fix already merged as #426; this layer does
not replace it.

Related: #426

Related: a76a0c1

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Local ConfigSync recording now writes changed rows in batches instead of
allocating a revision and upserting each record separately.
Project/environment and worker lookup maps replace repeated JS array
scans. The same owner clock lock and transaction still cover domain
rows, secrets, tombstones and configuration versions.

## Measurement

Three rounds, two warmups and 20 samples each. ConfigSync.start with 128
instruction documents × 4 KiB, 24 projects and 13 workers. Cold
bootstrap clears only the owner's sync state outside timing; steady
restart retains it.

| Operation | Queries before → after | p95 ms before → after | Rows
before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Cold bootstrap | 400 → 69 | 74.64 → 23.71 | 418 → 248 | 615,045 →
579,364 |
| Steady restart | 60 → 60 | 21.55 → 14.09 | 419 → 419 | 1,304,645 →
1,304,724 |

Small clock-string byte differences are expected; bytes count returned
JSON, not writes. Final round p95: bootstrap 25.17 / 21.71 / 21.85 ms;
restart 15.06 / 12.71 / 14.06 ms.

## SQL audit

| Statements / path | Verdict |
|---|---|
| record-batches.ts: clock UPDATE + config_items UPSERT | One CTE per
≤128 rows / ~512 KiB; exact bigint revision range allocated in SQL and
input order retained. |
| project-writer.ts | Defers changed rows until finish inside existing
transaction; uses local-id map. |
| provider-records.ts / connector-records.ts | Batches only row
persistence; encryption, secret pruning and tombstone/history behavior
retained. |
| worker-records.ts | Bounded persistence and global-id map; caller
retains clock lock. |
| json-batches.ts / import callers | Reuses existing bounded helper
through shared path; import behavior unchanged. |

A focused run exposed JSON.stringify on a database-returned bigint
revision. The final batch explicitly serializes only required values;
SQL owns revisions. The loaded-row regression, revisions above 2^53,
owner isolation, reopening, late-batch rollback, tombstones and
immutable home are tested. **53 focused ConfigSync tests passed** across
seven files.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.
nixuuu added a commit that referenced this pull request Nov 9, 2026
Move redirect handshake learning performed one local-object lookup, one
durable write and one reference update per notice. It now groups
local-object reads, persists at most 128 distinct IDs per statement and
updates distinct target references together. Identical replay uses the
restored map and does no SQL.

## Measurement

Three rounds, two warmups and 20 samples each; 256 notices, half bots
and half threads, no live local targets. Reset and map loading are
outside timing. Real Redirects service, no transport.

| Operation | Queries before → after | p95 ms before → after | Returned
rows before → after | Decoded bytes before → after |
|---|---:|---:|---:|---:|
| Learn 256 new redirects | 768 → 5 | 2,095.52 → 9.66 | 256 → 256 |
89,984 → 88,712 |
| Repeat handshake | 256 → 0 | 22.54 → 0.22 | 0 → 0 | 512 → 0 |

The first lookup-only experiment still had new-redirect p95 2,133.23 ms
and 514 queries, so it was rejected. EXPLAIN showed tiny individual
lookups/writes (roughly 0.01–0.42 ms); 256 separately committed inserts
dominated the service path. The accepted version groups durable writes
as well. No claim is made for large populated reference tables; the
performance fixture's reference table is empty.

## SQL audit

| Statements / path | Verdict |
|---|---|
| redirects.ts: load | Owner primary-key prefix; full durable redirect
map retained because old IDs still need routing. No age-based deletion.
|
| redirects.ts: local bot/thread lookup | At most two grouped,
owner-scoped UUID lookups; invalid IDs rejected before SQL; uppercase
UUIDs cannot bypass local protection. |
| redirect-records.ts: batch UPSERT | Atomic statement, ≤128 distinct
IDs, timestamp fence retained; returned order follows input. Duplicate
IDs split batches and recheck committed state. |
| redirects.ts: single record | Original one-statement write retained
for isolated notifications. |
| redirect-records.ts: reference UPDATE |
Owner/target/former-home/direction fence; distinct IDs grouped.
Duplicate IDs and a failed bulk reference update preserve ordered
best-effort per-item recovery. |
| redirects.ts: map/rewrite/list | In-memory routing unchanged; no
history/durability pruning. |

Move suite passed seven tests; additional owner/durability tests verify
two owners, local bots/threads, spoofed senders, stale/equal-time
notices, restart and reference isolation. A final regression check also
verifies that uppercase UUIDs retain single-notice deduplication and
routing after reload. No sync transport/client-stream/computer-link
changes overlap the other delegate.

## Method and stack validation

Synthetic data only, private PostgreSQL 18 (2 CPU, 1.5 GiB,
max_connections=40; ordinary measurement pool 8 unless stated). Latency
runs without tracing; a separate diagnostic pass counts SQL including
transaction controls, returned rows and decoded JSON representation
bytes, and captures EXPLAIN (ANALYZE, BUFFERS). These bytes are not wire
traffic, scanned bytes or disk I/O. Shared-host observations are not
production SLOs. Raw results, hosts and datasets are not committed.

All layers remain **ready for review**, as requested by the maintainer.
The bottom targets dev; descendants target the preceding branch. The
stack is rebased on **dev 6e5a371**, including the client and sync
performance stacks, #418, #426, #429, #449, #450, #451, #452 and #453.
New migrations are **0103–0109**, following **0102_bot_composer**, the
schema expectation is updated, and no new index duplicates
turns_composer_choices or overlaps bot_composer tables/indexes. Full
top-branch gates and remaining audit gaps are recorded in the top PR. CI
remains the full gate. Polish documentation is updated; no UI text
changes, so the copy audit does not apply.

The SQL audit table describes the statements reviewed for this layer. It
does not claim that the repository's entire static SQL inventory has
received a large-dataset EXPLAIN.

## Remaining across the stack

This is a **ready stack with an incomplete statement-level SQL audit**.
At the previous publication, the static inventory contained **2,177
statement/fragment locations across 311 files**. It includes DDL,
transaction controls, triggers and overlapping/dynamic fragments, so it
is not a count of distinct executable application queries. The
historical diagnostic snapshot on the plan-capture layer matched 380 of
2,171 locations to plan templates; those numbers are not
current-revision or complete large-dataset coverage.

A pre-rebase diagnostic pass on head `3381f50b` ran 22 standard
benchmark operations with `--explain-writes --iterations 1`: 80 plans,
58 unique fingerprints, zero plan errors, zero skipped plans, 64
candidate source locations matched and 16 plans unmatched. There are
2,113 locations without evidence from that revision's pass, including
DDL/controls/dynamic fragments. The fixture used 240 threads, a
2,048-turn long thread, 4 KiB content, large import/command queues and
approximately 201 MiB of database storage. That publication's
post-rebase static inventory had 2,177 locations across 311 files; it
was not refreshed for the latest dev base, and plan matches were not
reassigned across revisions. This refresh does not replace paired
latency evidence or prove execution of every matching call site;
historical and current line matches are not combined.

| Area | Coverage and limitation |
|---|---|
| Imports and polling stores | Progress/admission, notifications, bus
reference reads, worker configuration, worktree activity and secret
metadata have focused fixtures, plans and before/after tables on their
layers. Cold/admin branches and dynamic query variants still need
exhaustive statement-level review and large-dataset evidence. |
| Outbox and secret queues | Bounded reads/claims, TTL, cursor fairness,
replay/reset, timeout, expiry, restart and owner behavior checked. The
outbox's 9.25 → 9.47 ms correctness exception is explicitly
user-approved. |
| Schedules and routines | External preparation moved outside schedule
lock; claims/fencing, concurrent edits, occurrence durability and
grouped routine busy checks measured and tested. |
| Retention | Bounded durable pruning covers eligible mirror
journals/generations, acknowledged terminal harness events, obsolete
command payloads, config history, previews and OAuth state. History,
deduplication keys, user transcripts, import/audit history and necessary
cursors remain intentionally unbounded; further deletion needs an
archival contract. |
| Online indexes | New performance indexes support opt-in concurrent
builds with definition/validity/restart checks. Older transactional
index migrations retain the documented maintenance-window requirement. |
| Concurrent load | Verified running-turn deltas, mirror commits, pool
saturation, sampled locks and statement-timeout rollback. Several SQL
pools are not an end-to-end test of several real gateway processes. |
| Event-loop safety | Cooperative complete-snapshot decoding and reduced
blob reads measured. A single huge item, driver JSON decoding and
transport serialization can still block synchronously. |
| Skills, configuration and moves | Skill pin/version batching,
retry-hash filtering, bot metadata/catalogs, local ConfigSync batches
and move previews/redirects have focused measurements and SQL verdict
tables. Populated large move-reference tables still need a separate
workload. |

The overview scratch-lock fast path was **removed before publication**
because the user's repeated-load criterion rejected its streaming-ingest
regression. The concurrency/overview layer retains the benchmark and all
three before/experimental-after rounds in its Remaining section. No
approval is inferred for that rejected change.

## CI repair and revalidation

Rebased top head: `de19ad424da6601523792908dc1fdef2030c608c`, source
tree `15f769e5b291fdec6665c40170b505e969197fda`, based on dev
`6e5a37188f41381d3d94153d34fa328359d29fe4` (including #429, #449, #450,
#451, #452 and #453). All 18 layers remain **ready**, as requested by
the maintainer. The seven DB2 migrations are now **0103–0109**, in the
layers that introduce them. SQL file contents are byte-identical
renames; schema expectations and Polish docs are updated. The base's
`0102_bot_composer` is preserved, no DB2 index overlaps its
tables/indexes or `turns_composer_choices`, and the retention policy
explicitly preserves bot composer drafts and attachments.

Both CI failures were test synchronization races that also occur on dev,
not demonstrated production regressions in the performance layers. The
slow-read test included roughly 10 seconds of RPC admission wait in its
20-second timeout assertion; the repeated-blackhole test read overview
presence before the asynchronous presence write committed. The corrected
waits live on the bottom layer so every PR receives them. Full
original-head/dev diagnostics, including a controlled 100 ms
presence-write delay that reproduces the exact #443 assertion on both,
are documented in #439 and #443. No diagnostic instrumentation is
committed and no production timeout, mirror, lease or retention behavior
is relaxed. The #442 enqueue type alias keeps the combined #449/routine
changes within the function size limit without changing SQL/runtime
behavior.

Focused validation on prior top `1c4f213f`: **104 pass, 0 fail**,
including three complete timeout-file rounds (21 tests), ten
repeated-blackhole rounds, migration/index tests (28), retention (5),
durable mirrors (20), mirror listing (3) and bot composer/routines (17).
Every temp-directory check passed. Subsequent dev refreshes include
gateway/configuration, protocol, mobile and web changes; this focused
result is historical, and the final top-head full run is recorded
separately below.

On prior head `3baeb92f`, all local gates passed, including a complete
foreground `bun run check:tmp`: **2,022 tests, 163 skips, 0 failures,
24,835 assertions across 367 files in 1,018.18 seconds**, with nothing
left in the checked temp directory.

On final head `de19ad424da6601523792908dc1fdef2030c608c`, `bun install`,
`bun run gen:check`, full `bun run typecheck` (including scripts/tools),
`bun run lint`, `bun run format:check` and the web build all passed. The
complete foreground `bun run check:tmp` passed **2,035 tests, 163 skips,
0 failures, 25,556 assertions across 370 files in 995.54 seconds**. The
temp-directory check passed. Both previously failing scenarios passed in
this run: repeated blackholes in 9,964.81 ms and slow live reads in
32,017.39 ms. The working tree is clean.

Paired latency measurements in the individual layers were not rerun
during this CI repair. Their original methods and limitations remain
documented. Local validation does not replace the full CI gate on
**every** current stack head. CI status after the lease-protected
restack push is recorded separately below, especially for #434, #435,
#442 and #445.

## Current-head CI publication snapshot

After the atomic push with explicit per-branch force-with-lease checks,
all 18 current heads have a CI workflow run (queued or in progress).
None is missing CI, including #434, #435, #442 and #445. The aggregate
`Typecheck, tests, builds` must still pass on every layer before merge;
this snapshot does not claim green CI. All PRs remain ready
(`isDraft=false`), with no approving review recorded. Snapshot:
2026-11-09, approximately 20:05 UTC.

| PR | Head branch | Head SHA | CI workflow |
|---|---|---|---|
| [#430](#430) |
`perf/db2-1-imports` | `6dc7ed8b0f0c795e3d1bb4daaa87805fb68541ec` |
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689394107)
|
| [#431](#431) |
`perf/db2-2-online-indexes` | `36841847211f8470492b65efc0599453eddea607`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689380806)
|
| [#432](#432) |
`perf/db2-3-schedules` | `f9ba88510c460e5d17dfca76acd96720bf9193f2` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689472854) |
| [#433](#433) |
`perf/db2-4-retention` | `e1c0676cdbfffd6c6bba003a0b3c5b42ef9842e1` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689479073) |
| [#434](#434) |
`perf/db2-5-bounded-reads` | `9ad42f78c85d99f8d3a09fda11ce7fd8de00dbad`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689351696)
|
| [#435](#435) |
`perf/db2-6-overview` | `73cb9fa3bc1a52c1c2c2682562550af51e7b6cf7` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689419982) |
| [#436](#436) |
`perf/db2-7-snapshot-decoding` |
`94185a553b84bdb16cc248bc6e76f74d7f0e1a21` |
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689406661)
|
| [#437](#437) |
`perf/db2-8-audit-plans` | `dceeb2dcf860aecc4cd988f2036a655d2839d15b` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689403516) |
| [#438](#438) |
`perf/db2-9-config-stores` | `4b8583f43937dea79e4f0a08ac27bd52c3b6970c`
| [queued](https://github.com/itsoltech/canopy/actions/runs/42689486310)
|
| [#439](#439) |
`perf/db2-10-lifecycle` | `b8ce40857b2d878961a014b16b90ad723eb80d4b` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689475177) |
| [#440](#440) |
`perf/db2-11-skill-reads` | `105f47aa7e18ae81850a4ccf1d8b9c0e1a3a790e` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689467700) |
| [#441](#441) |
`perf/db2-12-secret-queues` | `935f16adfa0c8f1d4cf56508851a665cea218ba9`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689394660)
|
| [#442](#442) |
`perf/db2-13-routines` | `4896642250c8962e593d451f0ff5780ef61aee4f` |
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689403870)
|
| [#443](#443) |
`perf/db2-14-move-previews` | `3e086ff0a89af5a5ead37c02386fddde294ab551`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689374643)
|
| [#444](#444) |
`perf/db2-15-config-blobs` | `59f015d96c6a3cbcc26ba2cf77a7dd350bdd3449`
|
[in_progress](https://github.com/itsoltech/canopy/actions/runs/42689369835)
|
| [#445](#445) |
`perf/db2-16-bot-config` | `f612a949d3a833fb320f72805a92d63f3398c96f` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689434187) |
| [#446](#446) |
`perf/db2-17-config-records` |
`2ba4ff15d9d516dba1161d9e25bda66d48be366c` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689485086) |
| [#447](#447) |
`perf/db2-18-redirects` | `de19ad424da6601523792908dc1fdef2030c608c` |
[queued](https://github.com/itsoltech/canopy/actions/runs/42689419268) |
nixuuu added a commit that referenced this pull request Nov 10, 2026
Bot conversations now accept the same files as threads. A bot can read
text and PDFs without filesystem tools, then pass selected conversation
attachment references to `start_thread` or `send_message`. The gateway
copies references to the existing blobs and uses the normal thread
delivery pipeline.

Forwarding validates the owner, current bot conversation, duplicates and
current limits before approval and again during execution. It shares the
action's existing approval; the card lists filenames, types and sizes.
File copies, thread input, bot attribution, durable confirmation and
tool result commit together. The read-only `list_attachments` tool
exposes only sent files in that conversation.

| File type | Claude | Codex | Grok |
|---|---|---|---|
| Images | Native image parts | Native image parts | Native image parts;
CLI image capability required |
| UTF-8 text, Markdown, code, JSON, CSV | Bounded turn text | Bounded
turn text | Bounded turn text |
| PDF | Native document blocks | Extracted text | Extracted text |
| Archives and other binary files | Metadata and forwardable references
| Metadata and forwardable references | Metadata and forwardable
references |

Text is capped at 64,000 characters per file and 128,000 per turn, with
truncation notes. PDF extraction reads at most 50 pages, without OCR;
unreadable or image-only PDFs retain their original forwardable
references. Nonimage bot input requires worker capability
`bot_files_v1`; images retain `bot_images_v1`. No wire fields or
migrations were added.

Web/desktop retain the common picker, paste, drop, chips and previews.
Mobile changes are TypeScript only, including ordinary attachment
previews under bot-attributed thread input. The bot conversation records
“Sent report.md to ‘Thread’”. Forwarding to another linked computer is
explicitly refused before approval; users can choose a thread on the
bot's computer.

Validation:

1. `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run
lint`, `bun run format:check` and the web build pass.
2. Focused tests pass: `bot-files.test.ts` (9), `bot-composer.test.ts`
(7), `bots-remote.test.ts` (7), and the four affected harness
adapter/stop files (10). Coverage includes real gateway/worker transport
with fake provider CLIs, native versus extracted input, shared blobs and
worker paths, ownership/conversation refusal, approval denial and
execution-time revalidation, old-worker refusal and linked-target
refusal. Multi-gateway files ran separately.
3. Real-browser check on isolated fixture services: attach MD/PDF/PNG,
inspect Markdown/image previews and PDF file controls, fake-harness
forwarding, durable bot confirmation, normal thread attachment preview
and bot attribution. Checked light/dark at desktop and phone widths,
including a long filename. No UI test suite was added.
4. Requested EAS CLI 27.4.1 production fingerprints equal current `dev`:
iOS `6ddec9ef559ee0095ac33e94ff9418a942053b17`; Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`.

Copy audit (§8): “Attach images” → “Attach files” and “Drop images to
attach” → “Drop files to attach”, matching the accepted input. New
forwarding confirmation names the file and destination; refusal and
limit errors state the problem and next action. Existing file
vocabulary, verb-led controls and accessible labels are reused; no new
empty state or decorative copy. Short, typical and long filenames were
checked on desktop and phone. Long file chips and previews truncate or
wrap within the viewport.

Remaining gate: CI runs the full suite, including `check:tmp`; it was
intentionally not run locally. Live provider inference and native mobile
device interaction were not exercised.

Related: #449, #398, #421, #429
nixuuu added a commit that referenced this pull request Nov 10, 2026
Hovering an attachment in the bot composer could briefly flash a preview
and close it while the pointer stayed on the chip. Keep the selected
attachment and anchor stable when pointerover reaches the same chip
again.

Bot and thread composers already use the same `EditorAttachmentPreview`
and `AttachmentPreview`. When loaded content increases the card's
height, the card can briefly cross the pointer before repositioning.
Returning to the chip recreated `selected`, reran the anchor effect and
closed the preview during cleanup. Pointer movement between the chip's
icon and text had the same failure path. The shared component now
updates selection only for a different chip or attachment key. Existing
300 ms open / 180 ms close delays, keyboard focus, Escape, viewers and
motion tokens are preserved.

Validation:

1. `bun install --frozen-lockfile`, `bun run typecheck`, `bun run lint`,
`bun run format`, `bun run format:check`, and `bun run --filter
@canopy/web build` passed. No UI tests were added or run.
2. Real Chromium browser with an isolated gateway, database and scripted
model: Markdown, PDF metadata and PNG previews in the bot composer, sent
messages and actual bot-forwarded thread messages, light/dark at desktop
width. Verified pointer transfer to the card, keyboard focus and Escape.
Phone-width clicks open the Markdown viewer, PDF metadata actions and
image lightbox in both themes. Long filenames remain within the
viewport. The thread composer also retains its preview while moving
repeatedly between the chip's icon and text; leaving closes it at the
existing delay.
3. Hover evidence includes eight sampled screenshot frames per theme and
100 ms visibility samples showing the card remaining open for at least
two seconds. Evidence is outside the repository under
`/var/tmp/canopy-bot-attachment-hover/`.
4. Requested EAS CLI 27.4.1 production fingerprints are byte-identical
before/after: iOS `6ddec9ef559ee0095ac33e94ff9418a942053b17`; Android
`5f6eae3ab278f1cd543e9ed763f923a319b65ec9`. Native mobile already shares
`AttachmentChips` between bots and threads. No native or mobile source
changes.

Native device interaction remains unverified: device support twice
returned “Could not communicate with device support. Try refreshing
devices.” Phone-width browser interaction was checked. Full
integration/temporary-directory checks and generated-contract checks
were left to CI; this change only touches the shared web editor preview.
Copy audit: no UI copy changed.

The faulty selection assignment was introduced by the attachment-preview
implementation in #398; verified in its original diff. Bot attachment
PRs reused that component.

Fixes: #398
Related: #449, #469
nixuuu added a commit that referenced this pull request Nov 12, 2026
## Change

A file sent once could be presented to the bot again when its hidden
harness session was rebuilt. The gateway collected historical
attachments into `historyAttachments`, and the worker flattened them
into the newest native user input. The generic “Canopy attached files”
note did not distinguish the original message. This originated in #449;
#469 extended the same path to other file types.

Send file bytes only with their original message, for both resumed and
rebuilt Claude, Codex and Grok sessions. Historical messages retain
dated, forwardable references and explicitly say they are earlier
attachments. The current message is supplied once, separately from
history. Workers ignore the legacy historical binary field, and the
session context key changes once to discard previously mixed attachment
context.

The server already clears the sent draft revision atomically with
message acceptance and attachment binding. A separate race in the shared
web/desktop/mobile synchronizer allowed a draft read started before
acknowledgement to restore the old client draft afterward. Ignore stale
reads and reload the current revision after clearing. Newer device
edits, failed-send drafts and idempotency remain preserved.

Connector accounts expose MCP tools; there is no automatic inbound
Slack/thread-file ingestion path in this flow. Owner/conversation checks
and attachment forwarding authorization remain in the gateway.

## Verification

- Added gateway → real WorkerHost → fake CLI regressions for all three
providers: two images, three text-only follow-ups across resume/rebuild,
then one fresh image. Assert both durable command attachment IDs and
native harness parts.
- Added delayed-read regression using the shared client synchronizer
against real draft/send RPCs; retained restart durability, failed-send,
idempotency, revision-conflict and owner-scoping coverage.
- Extended PDF/text/image coverage to ensure rebuilt sessions receive
references without old binary or extracted content. Added worker
compatibility coverage for legacy historical attachments and
session-cache invalidation.
- `bun install --frozen-lockfile`, targeted spacing autofix and
formatting, full `bun run lint`, `git diff --check`, and the Angular
commit-message hook passed.
- Focused `check:tmp` run passed: 44 tests, 371 assertions across bot
composer, bot files, harness context, harness durability/restarts and
worker attachment compatibility. No files remained in the temporary
directory.
- **Not run locally:** browser, typecheck, generation checks, web build
or fingerprint generation. CI covers the remaining
static/build/full-suite checks. No RED/GREEN reproduction is claimed. No
real provider or connector APIs were called.

Mobile is affected only through shared TypeScript. No native
configuration, dependencies, assets, lockfiles or fingerprint inputs
were changed; fingerprints were not recalculated locally. No UI markup
or UI text changed; copy audit §8 is not applicable to the model-facing
provenance notes. Polish bot docs describe the resulting behavior.

Fixes: #449
Related: #469
nixuuu added a commit that referenced this pull request Nov 15, 2026
## Change

Navigating away while a draft, history request, or queue gesture was
pending could resume callbacks against another conversation or destroyed
Svelte derived values.

- Capture the bot, draft, and pending-message baseline before draft
synchronization. Sending from bot A still delivers and acknowledges A's
draft after navigation to B; completion cannot alter B's pending
messages or sending indicator.
- Dispose queue pointer listeners when the panel unmounts or its queue
changes. Pointer cancellation restores the preview without saving, and
deferred positioning cannot revive a finished gesture.
- Bind quote navigation to the original thread lifetime and check it
after history and render waits. Navigation cancels the jump silently
instead of expanding/scrolling the next thread or showing a stale
missing-source toast.

Document the lifecycle rules for retained callbacks and asynchronous
work. These fixes address confirmed navigation races; they do not
establish the cause of every reported `derived_inert` warning.

Fixes: #449
Fixes: #302

## Verification

- Web typecheck: `bun run --cwd apps/web typecheck` — zero errors and
warnings.
- Scoped oxlint, oxfmt, and `git diff --check` passed.
- Temporary reproductions using the production code and Svelte runtime
confirmed the failures before the fixes and zero `derived_inert`
warnings afterward. Covered bot delivery/retry across navigation, queue
disposal/cancellation, and quote cancellation during history loading and
feed reveal, including genuine missing-source results.
- Chromium with mocked backend responses: queue drop, cancellation,
unmount, and replacement passed at desktop and phone widths in light and
dark themes. Normal drop writes once; the cancellation cases write
nothing. Timeline scrolling and fold expansion also produced no
`derived_inert` warnings in the exercised fixture.
- No UI copy changes. Reproduction scripts, screenshots, and logs remain
outside the repository. Full repository checks and builds are left to
CI; packaged desktop and a live gateway were not exercised for these
fixes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant