The watch tables and the 0002 migration stay here, so the committed drizzle
snapshot keeps describing them. The four contract types the schema annotates
are widened here and re-narrowed where the watch code lands.
Review of #4418: the cloud path builds the ability from the user's role, so a read-only delegated token could exchange it for a write JWT; and the finalisable set was the whole replayed transcript rather than what the turn produced.
A turn stores its messages before the model finishes, so the completed bodies arrived against ids that already existed and were skipped. Reopening a chat then replayed a tool call that never ends.
The agent ships Chat and Investigate here; Watch — telling the user later —
follows in its own PR. The whole user-facing feature leaves: the watch card,
chips, wake banner and toast, the unread-wake badge and its poll, the watch
routes, checks, batches and sweeps, the watch alert email and its channel type,
and the watchMaintenance cron.
The agent no longer promises it either: schedule_watch and the alert tools are
gone from the tool set, and the Watches section is out of the system prompt.
Leaving that text in would have had the agent refuse to poll for something it
could no longer offer.
The datastore's watch tables stay. The migrations ship in this PR, so the drizzle
schema that describes them has to ship too — a schema that no longer matched the
migrated tables would make the next generate emit a drop.
The malformed-message error carried 200 characters of the payload, which can be user text or tool output. It now names the shape only. A finalisation also verifies that the body's id is the row it targets, so the stored key and the payload cannot name different messages. The legacy-column guard missed a schema-qualified update, and now self-tests both spellings.
`storeChatMessages` ended in `onConflictDoUpdate`, so `persistMessages` and
`persistTurn` — which are handed a whole snapshot — treated any differing body
under an existing message id as a deliberate finalisation. A stale snapshot
carrying `wake:watch_1:fired`, the watch consent record, the deterministic
confirmation or an investigation settlement card with a different body would
overwrite the durable row that was already recorded. The proxy caps body size
and metadata but does not rewrite message ids, so this was not an
internal-bug-only exposure. The same clause updated only the `message` JSONB and
never the `role` column, so `chat_messages.role` could end up disagreeing with
`message.role` — and the UI reads one while the quota query reads the other.
Ordinary transcript writes are now insert-only. Changing a stored message is its
own operation, `finalizeChatMessage`, guarded on chat id, message id and role.
`role` is verified rather than updated, and verified on both sides: the stored
column must match `expectedRole` and so must the incoming body's own `role`, so
the two cannot drift. A finalisation that matches nothing returns false; one
whose body contradicts `expectedRole` throws.
No production caller depended on the implicit finalisation. Every existing
finalisation-shaped path already writes through an insert-only append:
`settleInvestigationAndCloseCard`, `settleInvestigationStateAndCloseCard` and
the watch request/confirmation/refusal records all use
`appendChatMessageOnce(ByChatId)`.
Also: re-sending a snapshot no longer reserves positions for messages that are
already stored. The chat row is held, the missing ids are read under that lock,
and only those get slots. A 40-message chat grown one turn at a time used to
burn 1+2+…+40 = 820 slots for its 40 rows; it now burns 40. Deltas would be the
proper fix, but that reaches into the agent's turn hooks and is a larger change
than this pass.
Two smaller repairs in the same file: `messageIdOf`/`messageRoleOf` now fail
fast and name the chat and the offending message instead of casting unchecked
and surfacing a `NOT NULL` violation from the driver; and a batch carrying the
same message id twice throws instead of silently keeping the first, since that
is an impossible state and a silent pick is how the upstream bug would stay
invisible.
The comment on `reserveMessagePositions` claiming the row lock is "released with
the statement" was wrong — Postgres holds it to commit — and now says what is
true.
The concurrency test only exercised the single-message append, which
allocates its position inside one statement. Replacing the batch
allocator's atomic `next_message_position` bump with a read-then-write
left every test passing — so the invariant that concurrent writers get
disjoint ranges was not actually covered on the path a turn takes.
Four concurrent three-message batches now assert twelve distinct
positions and that each batch's own messages stayed contiguous and in
order. Against the read-then-write version this fails on
`chat_messages_chat_position_key`, which is the constraint doing the
work rather than the application code.
The feature is unreleased and this branch is local, so there is no rolling
deploy in which an old instance still selects `chats.messages` — the usual
reason to keep a replaced column for one more release does not apply, and
after release the drop would cost two deploys. So it goes now.
With no data to preserve there is no backfill, and with no backfill there
is no such thing as a stored message without an id: `message_id` is
`NOT NULL` and the writers read `message.id` with no fallback, so a
malformed message fails the insert instead of being given an invented
identity by untested code.
Removing the column from the drizzle schema is also the enforcement that
nothing writes it — a surviving TypeScript reference stops compiling. The
scan for raw SQL naming the column found nothing to guard, so there is no
test for it.
The four idempotency invariants each get their own test against a real
table: a repeated message id creates no row and keeps its position; eight
genuinely concurrent appends take eight distinct positions, with a raw
insert past the query layer proving it is `UNIQUE (chat_id, position)`
doing the work; a controlled update changes one body and leaves identity,
position and every other row alone; and a mid-turn append survives the
turn's write, landing where it happened rather than at the end.
`dashboardAgentTranscriptMerge.test.ts` becomes
`dashboardAgentTranscriptStore.test.ts`: it no longer tests a merge, and
the ordering it asserted has deliberately changed.