Skip to content

docs(design): threading surface ruling — the citable text for the walking skeleton - #1107

Merged
lilyshen0722 merged 3 commits into
mainfrom
threading-surface-ruling
Aug 22, 2026
Merged

lilyshen0722 merged 3 commits into
mainfrom
threading-surface-ruling

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Lands the threading shape ruling in the repo so the walking skeleton (TASK-029, command post 56756) is built and reviewed against a text, not a recollection.

  • Verbatim 55852 (inline expand, not a side panel; headline card; indented rail; collapse state persisted; the three reasons)
  • The four collapsed-render constraints the skeleton builds to, ambient-only scoping (Inline threading — scope the ambient class, leave addressed untouched #1045), follow-by-participation, per-surface run cap, and the explicit not-in-skeleton list
  • Provenance per line, naming the two lines that are new on 2026-08-22 (one re-targeted composer; the exclusion list) rather than part of the original ruling

Why a repo doc and not the issue comment alone: sprint-review could page back to 55852 and pod-architect could not — citability is a function of the reader's window, not the store (56794). Mirrors #1045 comment 5380419117.

Gate split for threading PRs: sprint-review gates code, ux-lead gates shape against this doc.

🤖 Generated with Claude Code

lilyshen0722 and others added 2 commits August 22, 2026 05:33
…king skeleton

The inline-expand ruling (55852) and the ambient-only scoping (#1045)
lived in a pod message and an issue comment; the seat building the
skeleton could not page back to the ruling and was building to a
paraphrase. Records the verbatim ruling, the four collapsed-render
constraints, scoping/follow rules, and the provenance of every line —
including which two lines are new on 2026-08-22 rather than part of the
original ruling.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gated at head 9c2b44a2. Good doc — a reader needs neither a paging window nor GitHub, which was the point. Two corrections, and the second takes credit away from me.

1. The verbatim block carries an evidence claim that was checked and did not attach

Line 8 quotes 55852 in full, including its first justification:

our threads are agent-length (tonight's 24-message debate is the median shape, not the tail)

I checked that at the time — pod message 55857, same night — and it does not hold: every message in that debate came back replyTo: null. It was flat pod chat with zero threading, mine included. So it is a sample of what people do when threads are absent, which is the condition the design changes. It may well still be the median shape; that just is not the measurement which shows it.

Quoting verbatim is right — the ruling should not be silently edited, and the #1045 comment's approach of paraphrasing the three reasons drops the problem rather than recording it. But the doc is now the citable text, so the caveat has to sit next to the quote or the next reader takes the debate as measured. Constraint 3 already promotes the 390px argument to load-bearing ("Mobile at 390px is the reason this option lost"), which is the right instinct; this just makes the same move explicit for leg 1.

Suggested, directly under the quote:

Leg 1's evidence was checked and does not attach (55857): every message in that debate carried replyTo: null, so it measures behaviour with threading absent. The ruling stands on legs 2 and 3.

2. Line 27 credits me for something @ux-lead found

## One state record, two booleans (consequence costed 2026-08-22, sprint-review 56796)

That attribution is wrong and I am the reason it is in the doc. @ux-lead costed it at 56793, at 12:32:28Z:

that's one more column or key in the skeleton's follow/collapse state — small, but it's in the ruling, so it's in the text now rather than a later surprise

I posted 56796 at 12:34:01Z, ninety-three seconds later, having just fetched their updated #1045 comment, read the consequence in it, and written it back as a finding — with the words "one cross-PR consequence nobody's costed." They had costed it.

Please change the heading to (ux-lead 56793). The one part that was mine is narrower and worth keeping only if it is useful: falling back to localStorage would make "a reload does not re-expand what you closed" true per device, which is not what the constraint says.

This is the failure mode where re-deriving a peer's finished finding is indistinguishable, from the inside, from verifying it. The defence is reading the log before working rather than after publishing, and I did the fetch and skipped the log.

Everything else checks out

The verbatim quote matches 55852 exactly against what I pulled at 56790. Constraint 3's parenthetical correctly identifies 390px as the surviving reason. The provenance line at 41 marking constraint 4 and the not-in-skeleton list as ux-lead's-today, rather than folding them into the 2026-08-19 ruling, is what makes the rest of the document trustworthy — it says which lines a reader can attribute to the ruling and which to the person recording it.

Not verified

mergeStateStatus is BLOCKED; for a docs-only PR I did not chase whether that is a pending check or a missing gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@lilyshen0722
lilyshen0722 merged commit 2ac7996 into main Aug 22, 2026
3 checks passed
@lilyshen0722
lilyshen0722 deleted the threading-surface-ruling branch August 22, 2026 12:42
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
… follow

Reshapes 2/4's table per ux-lead's ruling in #1107 (56799) and
sprint-review's cost note (56796/56797): persisted collapse (surface
constraint 2) shares the key (userId, podId, threadRootId) with follow
state, so it is ONE record with two columns, not a second table on an
identical key and not a localStorage fallback — localStorage would make
'a reload does not re-expand what you closed' true per device, which is
not what the constraint says.

thread_follows -> thread_user_state, because row PRESENCE no longer
means following: a collapse write creates rows for non-followers, so
'following' has to be a column.

'following' is TRI-STATE, and that is the load-bearing part. NULL means
'defer to the participation default'; TRUE explicit follow; FALSE an
explicit mute that must outrank participation. A NOT NULL DEFAULT false
would be a live bug rather than a simplification — a collapse-only row
would silently unfollow a participant who never touched the toggle.
Unfollow writes FALSE rather than deleting for the same reason, and
because deleting would discard the row's collapse state.

Each writer touches exactly one column (upsertOne takes the column), and
follow/collapse are separate endpoints: following never implies expanded,
so one PATCH taking both booleans invites a client to clobber the half
the user did not touch.

followerIds -> explicitFollowerIds: it omits participation-default
followers, whose resolution needs the participant set and belongs to 3/4.
The old name made under-notification read as correct.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
#1112)

Two rulings pushed to #1107's branch after its 12:42:42Z squash-merge and
therefore never reached main:

- readers of follow state filter following = true, never EXISTS (row),
  because collapse writes create rows for non-followers (#1109 rename
  thread_follows -> thread_user_state); third test
- following is tri-state: NULL defers to participation (derived at read;
  participation never writes), TRUE explicit follow, FALSE explicit mute
  that outranks; unfollow writes FALSE; effective = COALESCE(following,
  participated); fourth test

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
…ling

@ux-lead 56809 / 4170760 on #1107 is literal — each writer touches only
its own column — and my upsert also wrote pod_id = EXCLUDED.pod_id. Both
directions of the non-clobber behaviour were already correct and tested,
so this is not a behaviour fix; it is the implementation actually
matching what was ruled.

Worth doing rather than claiming compliance. The write was inconsistent
with followByParticipation, which never rewrote pod_id, and a thread
root's pod cannot change — the root implies it. So it could only ever be
a no-op or a bug quietly papered over. If a row's pod_id disagrees with
the caller's, that is a fact worth surfacing.

Test asserts the SET clause names the target column and updated_at and
nothing else, so the next addition to it has to be argued for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
@ux-lead 56820 (doc 5e7060f on #1107): once rows exist for
non-followers, every reader of follow state must filter on following,
never on EXISTS(row). I had the two neighbours — muted with collapsed at
its default, and collapse-only with following NULL — but not the
combination they named.

(following=false, collapsed=false) is the discriminating one precisely
because it is the row most likely to be mistaken for engagement: it
exists, and the user actively opened the thread. Neither fact is consent
to be woken. Also covered with that user as the ONLY participant, so the
empty set cannot be masked by someone else being in it.

Two controls, because every assertion above is that a wake did not
happen: the same row with following=true DOES wake, and with
following=NULL falls back to participation. All three tri-state values
are now exercised here rather than two.

Plus a structural backstop asserting the query says `following IS TRUE`
and contains no EXISTS over thread_user_state, so a rewrite that
reintroduces row-presence is flagged even if it passes the cases.

This suite also still hand-wrote its tables, which is the correction
@sprint-review made on 2/4's suites (56811) and I had not carried across.
Now built from schema.sql, which brought the real FK to messages with it
— roots referenced by state have to be real rows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
@ux-lead 56822 (392b86e on #1107): "a participant at (NULL,
collapsed=false) is woken; the SAME participant at FALSE is not."

Both halves existed but as separate cases with different users on
different roots, so a difference in outcome could in principle have come
from something other than `following`. These flip exactly one field on
one row and assert the wake set changes by exactly that user, stated as
a set difference so a change in the wrong direction or affecting someone
else fails rather than passing on length.

Three cases: NULL -> FALSE removes them, FALSE -> NULL restores them
(a one-way test passes against code that simply stops waking people),
and flipping `collapsed` with `following` held at NULL changes nothing —
the field that must not matter, asserted as not mattering.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
@ux-lead 56830 corrected themselves: #1107 squash-merged at 12:42:42Z and
the later rules landed in #1112. Checking that against my own comments,
I had cited three shas — 4170760, 5e7060f, 392b86e — and all three
are on NEITHER main. Both PRs were squash-merged, which rewrites them.
They resolve in this clone only because it still has the branches; a
fresh clone gets nothing.

So every one of my citations was a dangling pointer, in exactly the way
ux-lead's own first check misled them.

Replaced with the doc path and section heading, which survive a squash.
The one place shas still appear is a comment explaining why they must
not be used.

Verified the rules themselves ARE on main by content, not by sha:
tri-state, row-presence, and the writer-scoping rule are all present in
docs/design/threading-surface-ruling.md at origin/main. So what 2/4 and
3/4 were built against is live; only my pointers to it were wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
Same correction as the 2/4 commit, for this branch's own suite.
@ux-lead 56830: #1107 and #1112 were both squash-merged, so 5e7060f and
392b86e — which I cited here — are on neither main. They resolve in a
clone that still has the branches and nowhere else.

The rules themselves ARE on main; verified by content in
docs/design/threading-surface-ruling.md, not by sha.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…d (TASK-029 2/4) (#1109)

* feat(threading): thread_root_id — schema, derivation on write, backfill (TASK-029)

First of four PRs for the W-T walking skeleton. Schema and write path only;
follow state, wake-scoping and render follow separately so each can be
reviewed against one question.

thread_root_id is a SEPARATE column from reply_to_message_id, deliberately.
The reply edge is an ADDRESSING edge — it feeds isRouted
(agentMentionService:1025) and the implicit-reply chat.mention (:1356) — so if
thread membership rode it, joining a thread would ping the parent's author,
which is the opposite of what ambient scoping is for under fable's #1045
ruling. The root carries no addressing.

Derived on write as COALESCE(parent.thread_root_id, parent.id): one level
covers any depth, because a reply to a reply inherits the root its parent
already stored. Stored rather than walked because reply_to_message_id has no
index, so resolving a root per read is a seq-scan per level.

Backfill is a separate one-shot script, dry-run by default, idempotent, and
touches only rows with a reply edge and a NULL root. Measured population:
227 reply edges across 153 threads, mean 2.48, max depth 7. Orphaned chains
stay NULL by design — an unreachable root is not a thread.

8 tests. They assert the emitted SQL rather than a function, because the
derivation is a subquery inside the INSERT and there is nothing to call.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): thread follow state — table, model, dualAuth routes (TASK-029 2/4)

Follow state keyed (thread_root_id, user_id), as a new `thread_follows`
table rather than a widened `User.followedThreads`. That field is typed
`postId: ObjectId ref 'Post', required` and cannot hold a Postgres
messages.id; widening it silently drops chat rows from every consumer
doing Post.find({_id: {$in: postIds}}) — postController 457/513/548,
activityService 614/712, ActivityFeedPage 584.

Following is a SUBSCRIPTION, not an addressing edge. Nothing here writes
reply_to_message_id and nothing here enqueues a mention; 3/4 consumes
this state ambient-only per the #1045 ruling.

Routes are dualAuth, matching the reactions precedent — an agent
following a thread is first-class, and gating on req.userId alone
silently excludes every agent. Any message in a thread may be followed;
the root is resolved server-side via COALESCE(thread_root_id, id), the
same derivation the write path uses.

The membership gate reactionController had inlined is extracted to
services/podWriteAccessService and shared rather than copied — both
comments it carries record divergence bugs, and a second copy is how a
third one happens. The 15 existing reaction tests pass through it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): one state record, two booleans — collapse ships with follow

Reshapes 2/4's table per ux-lead's ruling in #1107 (56799) and
sprint-review's cost note (56796/56797): persisted collapse (surface
constraint 2) shares the key (userId, podId, threadRootId) with follow
state, so it is ONE record with two columns, not a second table on an
identical key and not a localStorage fallback — localStorage would make
'a reload does not re-expand what you closed' true per device, which is
not what the constraint says.

thread_follows -> thread_user_state, because row PRESENCE no longer
means following: a collapse write creates rows for non-followers, so
'following' has to be a column.

'following' is TRI-STATE, and that is the load-bearing part. NULL means
'defer to the participation default'; TRUE explicit follow; FALSE an
explicit mute that must outrank participation. A NOT NULL DEFAULT false
would be a live bug rather than a simplification — a collapse-only row
would silently unfollow a participant who never touched the toggle.
Unfollow writes FALSE rather than deleting for the same reason, and
because deleting would discard the row's collapse state.

Each writer touches exactly one column (upsertOne takes the column), and
follow/collapse are separate endpoints: following never implies expanded,
so one PATCH taking both booleans invites a client to clobber the half
the user did not touch.

followerIds -> explicitFollowerIds: it omits participation-default
followers, whose resolution needs the participant set and belongs to 3/4.
The old name made under-notification read as correct.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): state in 1/4 what 3/4 does to the rows it backfills

@sprint-review (56773): the four-PR split has a composition seam that is
in neither diff. Review 1 alone and it is a harmless column; review 3
alone and it is correct scoping of new traffic. The interaction — the
backfill retroactively deciding the wake set of every pre-existing
conversation — is invisible in both.

Measured on the live instance today rather than argued: 245 reply edges,
172 threads, 0 orphans, 6 pods; participants per thread min 1 / median 2
/ max 3. In the busiest affected pod (135 threads, 9 distinct authors) a
reply into a backfilled thread would reach a median of 2 of 9 where it
previously reached all 9.

The sharp edge is 20 single-participant self-reply chains across 2 pods
(19 threads / 59 messages, and 1 / 2): their wake set after scoping is
the author alone, so an un-addressed reply into one reaches nobody.

Not overstated: ambient-only scoping does not suppress explicit
@mentions, so an addressed reply still wakes its target throughout. The
exposure is un-addressed replies into backfilled threads.

Also records that the orphan branch has a live population of zero — an
untested safety branch, not a measured behaviour, and it should not be
cited as verified. And that the population counts drift day to day (227
edges yesterday, 245 today), so a reviewer should re-measure rather than
trust either figure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the separation is a test, not a comment (TASK-029 1/4)

@sprint-review 56777: a comment saying 'these can't be one column' is
exactly what a later refactor deletes. The discriminating assertion is
that setting a thread root alone enqueues no chat.mention.

Eight cases through enqueueMentions, the module boundary. Every
'nothing enqueued' case is paired with a control that DOES enqueue —
an assertion that nothing happened is worthless from an instrument
that cannot make anything happen.

Also covers the mirror failure: threading must not make a message
unaddressable, and must not make it look routed (which would stop
ADR-018 D8 wake-on-message delivery for every threaded message).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): make the separation test able to fail

The first version passed a mutation that routed thread roots straight
through resolveImplicitReplyTarget — the exact refactor it was written to
stop. It passed because models/pg/Message was unmocked, so the lookup
died in the harness rather than the code declining to make it. The
controls hid it: they pass a populated replyTo inline and never touch
that path, so control and negative case ran different code.

Mocks the PG lookup with a real bot-authored row 101, and asserts the
resolver was never CALLED, not merely that it found nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): give the cutoff somewhere to live, and record it

#1115 rules that pre-cutoff thread roots render expanded, with the cutoff
'read from the migration record'. @sprint-review (56859) found there is
no such record — no migrations table anywhere under backend/, schema.sql
is idempotent boot DDL, and this backfill wrote nothing. The ruling
referenced a thing that did not exist.

Adds migration_records (name PK, applied_at, details JSONB), general
rather than threading-shaped: a one-off threading_migration table is the
thing that has to be generalised the second time someone needs this, and
the second time is when it gets done wrong. It is a LEDGER, not a runner
— boot DDL still decides what applies, and a reader must never infer
'migration X has not run' from a missing row.

The backfill now captures the cutoff it was discarding (@sprint-review
56860). Defined as MAX(created_at) over rows with a reply edge and no
root — that predicate IS 'written before derivation-on-write shipped',
so the boundary is exact rather than a deploy timestamp guessed after the
fact, and correct on a self-hosted instance migrating on any day.

Read BEFORE the UPDATE, because the UPDATE eliminates the predicate and
the boundary is unrecoverable afterwards. Written ON CONFLICT DO NOTHING
rather than DO UPDATE: by a second run the population the first measured
no longer exists, so re-deriving would overwrite a true boundary the
surface is already rendering against. The dry run reports the cutoff it
would record, so it can be checked before it is written.

NULL means 'no pre-cutoff roots exist' — a fresh instance has no
pre-threading history. Documented explicitly because the dangerous
misreading is 'unknown, assume everything is pre-cutoff', which would
expand every thread on a new instance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): thread-state read carries the pre-cutoff expanded default

@sprint-review (56862): #1115 makes the collapsed default FALSE for
pre-cutoff roots, and stateForPod's shipped contract — 'caller applies
collapsed true' — could not express that. 4/4 would have discovered it
while wiring the component.

GET /threads/state now returns
defaults.expandedForRootsCreatedBefore, read from the migration ledger
by the backfill's own exported MIGRATION_NAME rather than a second
definition of it or a hardcoded date.

ONE timestamp, not a per-thread resolution. Resolving server-side would
enumerate every root in the pod and join messages.created_at —
duplicating data the client already holds, since it is rendering those
messages. This is O(1) and the client-side step is a date compare.

Best-effort: a missing ledger row (backfill not run, or an instance
predating the table) degrades to null rather than failing the read. A
cosmetic default must never take the render path down. null means 'no
pre-cutoff roots exist', documented at the wire because the dangerous
misreading — 'unknown, assume pre-cutoff' — would expand every thread on
a fresh instance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): execute the derivation against a real Postgres (TASK-029 1/4)

@sprint-review blocked #1106 correctly: all nine unit tests are regexes
over Message.ts and schema.sql as strings, and nothing runs the SQL. A
regex proves the query was WRITTEN; it cannot prove it is correct.

Eight cases through the SHIPPED PGMessage.create — not a re-typed copy of
its SQL, which would test the test. Covers the load-bearing claim a regex
cannot reach: one parent lookup collapses a 7-deep chain to the single
true root, because the parent already stored its own.

Tier 1 only, and honestly skipped otherwise. pg-mem cannot run this —
probed today: it rejects WITH RECURSIVE outright and mistypes the
parameterised INSERT. CI already provides postgres:16 with
INTEGRATION_TEST=true.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): run the derivation at the unit tier, on pg-mem (TASK-029 1/4)

@sprint-review 56787 was right twice. The depth claim was asserted by
grepping for the COALESCE substring that implements it — assertion and
thing asserted are the same text, so it could not discriminate. And
pg-mem does handle this.

My earlier 'pg-mem cannot run this' was too broad: I probed it, hit
WITH RECURSIVE unsupported, and generalised from the backfill CTE to the
whole feature. Only the CTE is out of reach. The write-path derivation
runs once the scalar subquery is cast — pg-mem otherwise types it
integer[].

So the production query now carries ::int casts. Inert in Postgres,
which infers the same types either way, and they are what let the REAL
query string be exercised in plain npm test rather than only against a
tier-1 server. The test mocks config/db-pg with a pg-mem pool and calls
the shipped PGMessage.create, so it is the production path and not a
re-typed copy.

Five cases including their exact scenario (A, B->A, C->B; C's root is A,
not B) and depth 7, the deepest chain on live data.

The tier-1 suite stays for what genuinely needs a server: the recursive
CTE, the foreign keys, ON DELETE SET NULL.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): participation follows a thread, but never un-mutes it

55854 (relayed @sprint-review 56791): follow is implicit by
participation — posting follows, being mentioned follows — with one
explicit override on the thread header. A mention in an unfollowed
thread auto-follows the target.

Composed with the tri-state (ux-lead 56822, FALSE is a mute that
outranks participation), that ruling has an edge it does not name.
Read literally, 'auto-follow the target' flips an explicit FALSE to TRUE
and silently revokes a mute. Muting a thread and then being mentioned in
it is the ordinary case, not an exotic one.

followByParticipation writes TRUE only WHERE following IS NULL. The
mention still WAKES the muted user — a mute scopes ambient activity,
never addressing — but it does not resurrect the subscription. The
header toggle still overrides in both directions.

Returns state by re-reading rather than trusting rowCount: a conditional
DO UPDATE matching nothing is not reliably distinguishable from one that
wrote (pg-mem reports 1 either way).

Nine cases executed on pg-mem, not grepped — the claim is entirely about
what the conditional upsert does. Includes the mirror control (an
explicit follow after a mute must still take) and the collapse-only row
that has expressed nothing and belongs in neither read.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): thread_root_id must be retrofitted, not only declared

Production-breaking bug in this PR, found by @sprint-review's caveat that
CREATE TABLE IF NOT EXISTS cannot retrofit a constraint. The same
sentence applies to COLUMNS, and I had verified the FK half without
noticing the column half rode on it.

thread_root_id was declared only inside CREATE TABLE IF NOT EXISTS
messages, which is a no-op where the table already exists. Verified on
the live dev instance: 7,001 rows, oldest 2026-07-07, thread_root_id
ABSENT while payload — which has an ALTER retrofit — is present.

Merging as-is would not have degraded, it would have stopped chat: the
index throws at boot, and every PGMessage.create INSERT names a column
that does not exist.

Nothing I ran could catch it. The unit tests read the DDL as text and saw
a column declaration. The tier-1 suite provisions a FRESH postgres:16 per
CI run, so it exercises the CREATE path and never the ALTER path. Both
green, and the defect between them.

So the new suite starts from the OLD table shape and applies the
retrofits on top — the only arrangement in which this is visible — with
a control proving the old shape genuinely lacks the column, an
idempotency case (boot DDL runs every start), and an ordering case
(CREATE INDEX before the ALTER throws at boot).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs: the two-declaration rule, where someone adding a column will read it

I stated this rule in pod chat, which is the same as not writing it.

schema.sql now opens with it, because that is the file someone adding a
column has open. TESTING.md carries the half that belongs to the test
tiers: neither exercises an EXISTING database, so a retrofit needs a
third arrangement — start from the old table shape, apply the ALTERs,
assert the column appears.

Both name the live incident rather than stating the rule abstractly: on
2026-08-22 thread_root_id shipped declared only inside its CREATE TABLE,
both tiers green, and it would have stopped chat on every existing
instance.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): requiring the backfill script ran the migration

threadStateController imported MIGRATION_NAME from
scripts/backfill-thread-root-id, which calls main() at module scope. So
pulling one string out of it EXECUTED the migration, on the boot path:
server.ts -> routes/messages.ts -> threadStateController -> the script.

In CI that surfaced as process.exit(2) ('PG_HOST is required') failing
server.test.js. In production, where PG_HOST is set, it would not have
exited — it would have opened a pool and run the script's queries on
every server start.

Two fixes, because either alone leaves the trap. The name moves to
constants/migrations.ts, a module with no imports and no side effects;
and main() is now guarded by require.main === module, so no future
importer can re-arm it.

Found by CI and by nothing I ran. My local jest invocations were targeted
at the threading suites and never loaded server.ts, and server.test.js
fails 9/9 on origin/main on this machine for an unrelated Node 26
jsonwebtoken reason — so locally the signal is indistinguishable from
the background. It needed a Node 20 CI run to be visible at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the ledger-name assertion pinned the defect it described

This test required threadStateController to import MIGRATION_NAME from
the backfill SCRIPT. That import was the boot bug — the script calls
main() at module scope, so reading one string out of it ran the
migration. The assertion was pinning the thing that had to be removed.

Now asserts the opposite: the name comes from constants/migrations, and
the controller imports nothing from scripts/ at all.

Missed because I ran only the new inert-script suite after the fix, not
the existing suite that pinned the old wiring. CI caught it — the same
CI that a stacked PR does not get.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): a collapse toggle must not rewrite follow state

@sprint-review 56807 named the mirror of the risk ux-lead closed: ruling
out two writes for one gesture invites one write for two meanings.
following is durable, collapsed flips constantly, so a collapse that
upserts the whole record erodes the durable value under the volatile one.

upsertOne already takes the column as an argument and the SET list never
names the other semantic column, so the design was right — but the suite
only had the collapse-then-follow direction. It did not have the one they
named, which is the dangerous one precisely because collapse is the
high-frequency writer.

Five cases: collapse preserves an explicit follow; collapse preserves a
MUTE (the worse half — a clobbered mute reads as consent to be woken);
follow survives eight collapse toggles; collapse survives four
follow/unfollow cycles; and a control proving each writer does change its
own column, without which the other four pass from a model that writes
nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): pin what the read says about a thread with no row

@sprint-review 56808: 'collapsed defaults true for everyone' means an
absent row must READ as collapsed, and that needs asserting rather than
inferred from the column default. The default only governs rows that get
created; it says nothing about threads nobody has touched, which is most
of them.

stateForPod had no executing test at all before this — only a check that
the function exists. The absence contract lived in a comment and a JSON
key.

Nine cases through the real controller handler, since the row-to-payload
mapping is where the contract is actually expressed. The pair worth
naming: absence and an explicit collapsed:true differ in PAYLOAD but not
in MEANING, and are the two a client is most likely to treat differently
by accident; absence and collapsed:false differ in both, which is what
makes the row worth storing.

Also pins that following round-trips as three states. Boolean(null) is
false and false is a MUTE, so a careless mapping turns every
collapse-only row into a muted thread.

Their first ask — toggle collapsed twice, assert following unchanged —
shipped in the previous commit with eight toggles and both directions.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): the UPDATE set writes only its own column, per the ruling

@ux-lead 56809 / 4170760 on #1107 is literal — each writer touches only
its own column — and my upsert also wrote pod_id = EXCLUDED.pod_id. Both
directions of the non-clobber behaviour were already correct and tested,
so this is not a behaviour fix; it is the implementation actually
matching what was ruled.

Worth doing rather than claiming compliance. The write was inconsistent
with followByParticipation, which never rewrote pod_id, and a thread
root's pod cannot change — the root implies it. So it could only ever be
a no-op or a bug quietly papered over. If a row's pod_id disagrees with
the caller's, that is a fact worth surfacing.

Test asserts the SET clause names the target column and updated_at and
nothing else, so the next addition to it has to be argued for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): build the pg-mem tables from schema.sql, not by hand

@sprint-review 56811: a UNIQUE constraint present in schema.sql and one
the database enforces are different claims, and only the second is worth
a test. That landed on my own suites — they hand-wrote their tables, so
every constraint they exercised was one I typed into the fixture. ON
CONFLICT firing proved my fixture had a unique index; it proved nothing
about the DDL that ships.

Now extracted from schema.sql via __tests__/utils/schemaTable.js, which
throws rather than silently skipping if the table is gone.

Doing it surfaced two things the hand-written version hid:
  - messages has an FK to pods, so the real dependency chain is
    pods -> messages -> thread_user_state
  - my fixture declared thread_root_id INTEGER NOT NULL with NO
    REFERENCES, dropping the FK entirely. Every test in that file was
    keying state to message ids that do not exist, and nothing objected.
    Roots are now real message rows.

Five enforcement tests against the shipped DDL: the unique rejects a
duplicate; two users on one thread are fine (the control that separates
a subscription from a claim); the FK rejects a phantom root; deleting the
root CASCADEs the state away; collapsed defaults TRUE.

Also: PgPod/PgMessage/PgPodModel.extra all import newDb and never call
it — they mock pool.query. pg-mem had no live user in this directory
before these suites.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(test): ignore the whole helper dir, not a file-by-file list

Adding __tests__/utils/schemaTable.js broke CI — jest collected it as a
test suite and failed with "your test suite must contain at least one
test". Every other helper in that directory was individually enumerated
in testPathIgnorePatterns, so the list goes stale the moment anyone adds
one.

Fixed the class rather than my instance: the directory is ignored.
collectCoverageFrom already treated it that way (!**/__tests__/utils/**),
so the two configs now agree instead of one being a stale enumeration.

Why my local runs missed it: I ran targeted paths, and a helper that is
never collected cannot fail collection. Only a full sweep sees it.
Verified with jest --listTests piped to grep -c __tests__/utils, which
now returns 0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): cite the ruling by section, not by squashed sha (2/4)

@ux-lead 56830 corrected themselves: #1107 squash-merged at 12:42:42Z and
the later rules landed in #1112. Checking that against my own comments,
I had cited three shas — 4170760, 5e7060f, 392b86e — and all three
are on NEITHER main. Both PRs were squash-merged, which rewrites them.
They resolve in this clone only because it still has the branches; a
fresh clone gets nothing.

So every one of my citations was a dangling pointer, in exactly the way
ux-lead's own first check misled them.

Replaced with the doc path and section heading, which survive a squash.
The one place shas still appear is a comment explaining why they must
not be used.

Verified the rules themselves ARE on main by content, not by sha:
tri-state, row-presence, and the writer-scoping rule are all present in
docs/design/threading-surface-ruling.md at origin/main. So what 2/4 and
3/4 were built against is live; only my pointers to it were wrong.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): the backfill hardcoded SSL and could not run without it

`ssl: { rejectUnauthorized: false }` was unconditional, so the script
fails with "The server does not support SSL connections" before reading
a row against any Postgres that has no SSL — `./dev.sh up`, a plain
docker postgres, and any self-hosted instance. Self-hosting is in scope
for the very cutoff this script records.

Now decided the way config/db-pg decides it: PG_SSL_CA_PATH present and
readable => ssl with rejectUnauthorized TRUE; otherwise false. The old
`false` also silently accepted any certificate on the one path where it
did work, a weaker posture than the app's own connection.

Found by rehearsing the migration rather than reasoning about it: #1106
is on main and undeployed, and every test I had run was against a FRESH
database. So I reconstructed the live pre-threading shape from the
running instance (7,001 rows, pod_id nullable, no thread_root_id, no
index on reply_to_message_id) on a throwaway postgres:16 and replayed
the real sequence.

Result, which is the point of doing it: schema.sql applies exit 0 with
only "already exists" notices, the column and index land, both new
tables are created, the backfill dry-runs and applies 233/233, the
ledger records the cutoff, a second --apply is a no-op that does NOT
move the cutoff, and a second boot of schema.sql is clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): the population is re-measured at run time, never quoted

@ux-lead's #1115 ruling, fourth point: the number goes in a PR body as
"re-measured at merge time", not as 227 or 245. That was the one part of
the ruling I had not done — the script header led with two frozen
figures and mentioned re-measuring once, at the bottom.

The two figures are the argument for the rule. 227 edges / 153 threads
on 2026-08-21 and 245 / 172 on 2026-08-22, same instance, one day apart.
Both are now marked as dated observations kept for SHAPE — a few-hundred
-row UPDATE rather than a table rewrite — with the digits explicitly not
current. A rule stated without its counter-example reads as pedantry and
gets dropped, so both numbers stay, visibly disagreeing.

The mechanism that makes quoting unnecessary already existed and is now
named at the top: the dry run prints the live count AND the cutoff it
would record before anything is written. That output is the
authoritative number for a PR body or a deploy note.

Four tests pin it, including that the phrasing the ruling rejects — a
bare count asserted as the population — cannot come back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): requireActual the identity chain instead of retyping it

@sprint-review's #1113 finding and @sprint-impl's fix at ad274e3 apply
to my own suite. My mock hand-wrote `getCallerId: (req) => req.userId`.

Mine was worse than a copied list. The real chain is
`req.user?._id || req.userId || req.agentUser?._id`, so the mock skipped
the first branch and — the part that matters — the AGENT branch, which
is the entire reason these routes are dualAuth. Every read test in the
file passed without ever resolving an agent caller.

Now spreads requireActual and stubs only `callerHasPodWriteAccess`, the
one function that queries Mongo. Adds the two cases the old mock made
unreachable: a cm_agent_* caller (req.agentUser, with req.userId absent,
which is what agentRuntimeAuth actually produces) sees its own rows, and
req.user._id wins over req.userId in the documented order.

Probe: replacing the chain with `String(req.userId || '')` — the mock's
own logic, promoted into the source — turns exactly those two red. Under
the old mock that same change turned nothing red, which is the point.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): a missing cutoff is two states, and they render oppositely

@sprint-review 56862 asked whether the pre-cutoff comparison resolves
server-side. It does, via one timestamp — but following that through
against the live instance exposed an ambiguity in my own answer.

A missing ledger row reported `cutoff: null`, and my own comment
documented it as "no pre-cutoff roots exist (fresh instance, or the
backfill has not run)". Those two are lumped together and need OPPOSITE
renders:

  fresh instance, no history -> nothing is pre-cutoff; collapse all.
  backfill pending, history  -> cutoff UNKNOWN; collapsing everything
                                buries existing conversation under
                                headline cards, which is exactly the
                                failure #1115's carve-out prevents.

Not hypothetical: the live instance is the second case right now — 245
reply edges with no root, ledger empty. Had 4/4 shipped before the
backfill ran, the carve-out would have silently not applied.

Distinguished by the one fact that separates them: un-rooted reply edges
only exist if there is pre-threading history nobody has processed. The
extra query runs only when the ledger row is missing, and the catch fails
toward "pending" — a render that expands too much costs a click, one
that hides history is not obviously recoverable because the user cannot
tell anything is missing.

Four cases, including that the cutoff wins once written even if orphans
remain, since orphans legitimately stay NULL forever and must not make a
completed run look unstarted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): unknown cutoff expands; the ledger row is always written

both of which were wrong in the same direction, toward collapsing.

Three deltas against what I had:

1. A MISSING LEDGER ROW MEANS UNKNOWN, AND UNKNOWN EXPANDS. I returned
   pending:false when no un-rooted edges existed, which told the client
   to collapse everything. On an already-backfilled instance whose row
   was lost, that hides all history — and the user cannot tell anything
   is missing, which is why an ambiguous state has to resolve to the
   noisy side rather than the destructive one.

2. THE UN-ROOTED PROBE IS RETIRED, not fixed. It cannot work: after a
   backfill the old threads are rooted and indistinguishable from new
   ones, so zero un-rooted means "no history" OR "already backfilled",
   and the row that would tell them apart is the missing one. It also
   counted ORPHANS — a reply whose parent is gone stays un-rooted by
   design, so one dead row would have pinned the instance to expand
   forever.

3. THE BACKFILL NOW WRITES THE ROW EVEN WHEN IT ROOTS ZERO EDGES. "Ran
   and rooted nothing" is knowledge; absence of a row is not. Without
   this, a fresh instance finishes the script with no row and sits
   permanently expanded while being perfectly migrated — and the safety
   of "missing means unknown" depends on a migrated instance being
   unable to present a missing row.

The four superseded tests are skipped rather than deleted for one
release. They encode the shape the ruling rejected, and a reader who
finds only the new ones cannot tell the old shape was considered.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): the backfill must run AFTER derivation deploys

@sprint-review 56911 verified the DO NOTHING and the read-before-UPDATE.
Following that through surfaced a precondition neither the script nor
the deploy shows on its own.

The zero-edges branch writes the ledger row with a NULL cutoff, meaning
"ran, and there was no pre-threading history". That is only TRUE once
derivation-on-write is live, because from then on every new reply
carries a root and the un-rooted population is closed.

Run it BEFORE the deploy and zero edges means "not yet" rather than
"none". The null cutoff is then wrong, ON CONFLICT DO NOTHING makes it
permanent, and the surface collapses pre-existing threads on an instance
that does have history — the exact harm #1115's carve-out prevents.

On this instance derivation deployed 16:01:52Z and the backfill had not
run, so the ordering held by luck rather than by anything written down.

Three tests: the precondition is stated, the CONSEQUENCE is stated (a
bare "run after X" gets read as advice), and both ledger writes are
still DO NOTHING — if either became DO UPDATE the precondition relaxes
and the comment goes stale.

Also re-verified sprint-review's line citations against the current
head: their conclusions hold, their line numbers do not. I added a
second INSERT after they read it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): check the ordering precondition instead of warning about it

@sprint-review 56912: "there's no check that derivation is live" — the
header warned about the ordering and nothing enforced it. A warning is
the part people skip, and DO NOTHING freezes a wrong boundary as firmly
as a right one.

Zero eligible edges is ambiguous and the two readings write opposite
records. Derivation live => genuinely no pre-threading history, null
cutoff correct. Derivation NOT live => the population is still growing,
null cutoff wrong and permanent.

Now resolved by POSITIVE evidence where it exists: a row with both a
reply edge and a root can only have been written by derivation, since
the backfill has not run. Presence is proof.

Absence is not proof of the opposite — a live instance with no replies
looks identical to a backend that predates the feature. So the script
does not assume: it REFUSES, exits 3, and names both readings and what
to do about each. --derivation-live is the operator's explicit
assertion for the genuinely-empty case, and the ledger records which
path was taken (observed vs asserted-by-flag) so a later reader can tell
evidence from a claim.

Verified against a real postgres:16 in all three states: no evidence
refuses and writes nothing; the flag records as asserted; observable
derivation records as observed with no flag needed.

The first run of that third case appeared to refuse — I had hidden the
seed's errors with >/dev/null and the rows were never inserted. A probe
whose setup fails silently reports the same thing as a real finding.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
@ux-lead 56820 (doc 5e7060f on #1107): once rows exist for
non-followers, every reader of follow state must filter on following,
never on EXISTS(row). I had the two neighbours — muted with collapsed at
its default, and collapse-only with following NULL — but not the
combination they named.

(following=false, collapsed=false) is the discriminating one precisely
because it is the row most likely to be mistaken for engagement: it
exists, and the user actively opened the thread. Neither fact is consent
to be woken. Also covered with that user as the ONLY participant, so the
empty set cannot be masked by someone else being in it.

Two controls, because every assertion above is that a wake did not
happen: the same row with following=true DOES wake, and with
following=NULL falls back to participation. All three tri-state values
are now exercised here rather than two.

Plus a structural backstop asserting the query says `following IS TRUE`
and contains no EXISTS over thread_user_state, so a rewrite that
reintroduces row-presence is flagged even if it passes the cases.

This suite also still hand-wrote its tables, which is the correction
@sprint-review made on 2/4's suites (56811) and I had not carried across.
Now built from schema.sql, which brought the real FK to messages with it
— roots referenced by state have to be real rows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
@ux-lead 56822 (392b86e on #1107): "a participant at (NULL,
collapsed=false) is woken; the SAME participant at FALSE is not."

Both halves existed but as separate cases with different users on
different roots, so a difference in outcome could in principle have come
from something other than `following`. These flip exactly one field on
one row and assert the wake set changes by exactly that user, stated as
a set difference so a change in the wrong direction or affecting someone
else fails rather than passing on length.

Three cases: NULL -> FALSE removes them, FALSE -> NULL restores them
(a one-way test passes against code that simply stops waking people),
and flipping `collapsed` with `following` held at NULL changes nothing —
the field that must not matter, asserted as not mattering.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
Same correction as the 2/4 commit, for this branch's own suite.
@ux-lead 56830: #1107 and #1112 were both squash-merged, so 5e7060f and
392b86e — which I cited here — are on neither main. They resolve in a
clone that still has the branches and nowhere else.

The rules themselves ARE on main; verified by content in
docs/design/threading-surface-ruling.md, not by sha.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…et (TASK-029 3/4) (#1120)

* feat(threading): ambient-only wake scoping — the effective follower set (TASK-029 3/4)

effective = (participants union explicitFollowers) minus muted, per
fable's #1045 ambient-only ruling, ux-lead 56822 and sprint-review 56823.

participants are derived at read from messages and never stored: it is a
fact about the conversation, and materialising it would create a second
writer that can disagree with the first. That is the tri-state's
following IS NULL case. Mentions become explicit rows at the moment they
happen (followByParticipation) rather than being re-derived from history
forever. muted is subtracted LAST, because an explicit mute outranks
participation.

One query, not three — the terms are correlated and this path runs for
every threaded reply.

narrowToThread only ever NARROWS. Threading is additive and must not
start delivering to seats that never opted in to anything. Two
deliberate degradations, both toward today's behaviour rather than
toward silence: a target whose user id cannot be resolved is KEPT, and a
scoping query failure returns the unscoped list. A wake that vanishes
because scoping could not classify it is the failure nobody reports.

Not the addressing path — an explicit @mention wakes its target whether
or not they follow or muted the thread. isRouted short-circuits before
the ambient branch, so that path never reaches this service.

15 cases executed on pg-mem. Includes the root author (whose own
thread_root_id is NULL, so the obvious query omits the person who
started the thread) and a collapse-only row conferring nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): hook ambient scoping into the wake fan-out (TASK-029 3/4)

enqueueWakeOnMessage narrows its opt-in list through narrowToThread when
the message carries a thread root, keyed on installedBy — the bot User id
thread_user_state holds.

Writing the test corrected a belief I had stated twice in the pod: that
isRouted short-circuits before any ambient fan-out, so a routed message
never reaches scoping. It does reach it. There are TWO wake call sites —
:1157 for unrouted messages and :1470 for routed ones, the latter waking
opt-ins who were not mention targets.

The code was right and the assumption was wrong, and the truth is the
better invariant: an addressed message delivers its chat.mention
unconditionally, while the AMBIENT fan-out accompanying it is scoped like
any other ambient traffic. Addressing is untouchable; its ambient
companion is not, and should not be — an opt-in who neither follows the
thread nor was addressed has no claim on it.

Ten cases, three of them controls, because every core assertion here is
that something did NOT happen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): name the second wake call site at both call sites

I asserted twice in the pod that isRouted short-circuits before any
ambient fan-out, so a routed message never reaches wake-on-message. It
is false: enqueueWakeOnMessage has a second call site ~310 lines later,
for routed messages, waking the opt-ins the mention path did not reach.

An early return bounds the statements below it, never a helper a later
call site re-enters. Both sites now name the other, and the correction is
stated at the site that produced it — fixing the belief and not the
surface is how a peer reproduces it next week.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the third state — muted AND expanded gets no wake

@ux-lead 56820 (doc 5e7060f on #1107): once rows exist for
non-followers, every reader of follow state must filter on following,
never on EXISTS(row). I had the two neighbours — muted with collapsed at
its default, and collapse-only with following NULL — but not the
combination they named.

(following=false, collapsed=false) is the discriminating one precisely
because it is the row most likely to be mistaken for engagement: it
exists, and the user actively opened the thread. Neither fact is consent
to be woken. Also covered with that user as the ONLY participant, so the
empty set cannot be masked by someone else being in it.

Two controls, because every assertion above is that a wake did not
happen: the same row with following=true DOES wake, and with
following=NULL falls back to participation. All three tri-state values
are now exercised here rather than two.

Plus a structural backstop asserting the query says `following IS TRUE`
and contains no EXISTS over thread_user_state, so a rewrite that
reintroduces row-presence is flagged even if it passes the cases.

This suite also still hand-wrote its tables, which is the correction
@sprint-review made on 2/4's suites (56811) and I had not carried across.
Now built from schema.sql, which brought the real FK to messages with it
— roots referenced by state have to be real rows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the fourth test as a paired flip on one row

@ux-lead 56822 (392b86e on #1107): "a participant at (NULL,
collapsed=false) is woken; the SAME participant at FALSE is not."

Both halves existed but as separate cases with different users on
different roots, so a difference in outcome could in principle have come
from something other than `following`. These flip exactly one field on
one row and assert the wake set changes by exactly that user, stated as
a set difference so a change in the wrong direction or affecting someone
else fails rather than passing on length.

Three cases: NULL -> FALSE removes them, FALSE -> NULL restores them
(a one-way test passes against code that simply stops waking people),
and flipping `collapsed` with `following` held at NULL changes nothing —
the field that must not matter, asserted as not mattering.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): cite the ruling by section, not by squashed sha (3/4)

Same correction as the 2/4 commit, for this branch's own suite.
@ux-lead 56830: #1107 and #1112 were both squash-merged, so 5e7060f and
392b86e — which I cited here — are on neither main. They resolve in a
clone that still has the branches and nowhere else.

The rules themselves ARE on main; verified by content in
docs/design/threading-surface-ruling.md, not by sha.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): findById dropped thread_root_id, so scoping never fired

@sprint-review's blocker on this PR (57291): `m.thread_root_id` count 0.
They were right, and it is 3/4's bug rather than 4/4's — this is the PR
whose feature is inert without it, so the fix belongs here.

The hook reads `message.thread_root_id`. The controller does
`message = (populated || created)` and hands THAT to enqueueMentions, so
the object the hook receives is findById's row, not create()'s RETURNING *.
findById projects an explicit column list that did not name the column.
Ambient scoping therefore read undefined for every message and silently
never scoped — the feature has never fired on a real message.

Every 3/4 test passed throughout, because they construct the message object
directly with thread_root_id set and never travel create -> findById. A test
that builds the shape the code under test never receives cannot find a
projection bug; only a round trip can.

Four round-trip tests, and the mutation probe is paired rather than
wholesale: dropping BOTH projections kills 4 of 4, dropping only
findByPodId's kills exactly 1. That second run is the one worth having —
the column list is written twice, and fixing the copy a failing test names
while leaving the other wrong is a mistake already made once here.

The fixture builds pods, users and messages from schema.sql via applyTable
rather than by hand. The first attempt typed VARCHAR(255) keys against
schema.sql's VARCHAR(24) and died on a foreign-key type mismatch — a
fixture drifting from the DDL is the same class of defect as the projection
this file exists to catch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): installedBy is not the bot — key scoping on the bot's User row

@sprint-review's second blocker on this PR (57291). They were right, and the
comment I had written above the call asserted the opposite: "Keyed on
`installedBy` — the bot's User row id".

`installedBy` holds two different identities depending on who installed the
agent. The bot's own User row at agentAutoJoinService:80,
podWriteAccessService:48 and three sites in agentsRuntime; the HUMAN caller
at podController:119, personaHireService:93, podCurationService:147,
authController:201 and agentProfile:259. AgentRun.ts:65 calls it "the hiring
user" outright. The schema declares a bare ObjectId with no ref, so nothing
at the type level separates the two, and the name reads like the second
meaning while the comment claimed the first.

thread_user_state.user_id is the BOT's User row id — the follow/mute routes
are dualAuth, so an agent writing its own thread state writes under
`req.agentUser._id`. Keying on installedBy would therefore have read a
human-installed agent's thread state off its INSTALLER's row: the human's
mute silences the agent, and the agent's own mute is ignored. Wrong in both
directions, and invisible on any fixture where the two ids coincide — which
is why the test I had written passed.

Resolves the bot User row by (botMetadata.agentName, botMetadata.instanceId)
instead. One query for the whole target list, not one per target. A failure
returns an EMPTY map rather than throwing, so every identify() returns null,
narrowToThread keeps every target, and scoping degrades to today's unscoped
delivery — losing the narrowing is a noisier pod, losing the wake is a
message nobody sees.

The fixture now gives installedBy a DIFFERENT value from the bot user id, so
the assertion can discriminate; with them equal it could not. Four tests:
the correct key, the unresolvable install keying to null so it is kept, the
lookup failing closed to unscoped delivery, and one query rather than N.
Mutation probe: restoring the installedBy callback kills 3 of the 4.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): the header claimed a wire-up that does not exist

@sprint-review's third blocker on 3/4 (57306). The service header asserted
"the mention writes the row at the moment it happens, via
ThreadUserState.followByParticipation". Nothing calls it. The method shipped
with passing tests and the only thing claiming it was wired was prose — which
is why nobody noticed: a false comment reads exactly like a true one.

Consequence, stated plainly rather than implied: a user @-mentioned in a
thread who never posts is not an effective follower, so they stop receiving
its ambient activity. A spec gap, not a regression — the mention itself still
wakes them, because addressing never passes through this service.

Not closing the gap here. A synchronous Postgres write on the mention hot
path is a decision about where and how often, not a line to slot in wherever
it compiles, and 3/4 is not the place to make it quietly.

The guard is executable in BOTH directions, because a comment nobody can
run is what produced this. It fails if a production caller appears while the
header still says there is none, and fails if the header stops saying so
while there is still no caller. Control run: dropping a fake caller into
services/ turns it red, so the test can actually fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the wired branch was unreachable, so the guard ran one way

@sprint-review (57311), both notes, and both were right about the thing I
had just described as running in two directions.

1. Test 1 asserted `claimsUnwired === true`, which meant test 2's else could
   never execute. The second direction was carried entirely by test 1, and
   the branch I pointed at as the mechanism was decoration. Now test 1 asserts
   EXACTLY ONE of two markers is present, so swapping the marker makes the
   other branch live. Softening to unstructured prose matches neither and
   fails, so vagueness is still not a pass.

2. The marker ended a line, one reflow away from splitting across a newline
   and turning a true claim false. Collapsing whitespace was my first fix and
   it was insufficient: inside a block comment a reflow leaves the ` * ` gutter
   mid-phrase, so `NOTHING\n * CALLS IT` flattens to `NOTHING * CALLS IT` and
   still misses. Strip the gutter, then collapse.

   I only know that because the probe ran the scenario the fix existed for and
   it was the one scenario still red. A normalisation asserted rather than
   exercised would have shipped looking correct.

Six probes, each restoring the file afterwards: reflow with gutter (pass),
reflow without (pass), softened prose (fail), wired-claim-no-caller (fail —
the branch that used to be dead), wired-claim-with-caller (pass),
unwired-claim-with-stray-caller (fail). Both directions of test 2 now
demonstrably fire.

The service header tells whoever closes TASK-045 to swap the marker, and
deliberately does NOT quote the other one — writing both out is how this
commit first went red, which is the guard working on its own author.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…back (#1128)

* feat(threading): ambient-only wake scoping — the effective follower set (TASK-029 3/4)

effective = (participants union explicitFollowers) minus muted, per
fable's #1045 ambient-only ruling, ux-lead 56822 and sprint-review 56823.

participants are derived at read from messages and never stored: it is a
fact about the conversation, and materialising it would create a second
writer that can disagree with the first. That is the tri-state's
following IS NULL case. Mentions become explicit rows at the moment they
happen (followByParticipation) rather than being re-derived from history
forever. muted is subtracted LAST, because an explicit mute outranks
participation.

One query, not three — the terms are correlated and this path runs for
every threaded reply.

narrowToThread only ever NARROWS. Threading is additive and must not
start delivering to seats that never opted in to anything. Two
deliberate degradations, both toward today's behaviour rather than
toward silence: a target whose user id cannot be resolved is KEPT, and a
scoping query failure returns the unscoped list. A wake that vanishes
because scoping could not classify it is the failure nobody reports.

Not the addressing path — an explicit @mention wakes its target whether
or not they follow or muted the thread. isRouted short-circuits before
the ambient branch, so that path never reaches this service.

15 cases executed on pg-mem. Includes the root author (whose own
thread_root_id is NULL, so the obvious query omits the person who
started the thread) and a collapse-only row conferring nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): hook ambient scoping into the wake fan-out (TASK-029 3/4)

enqueueWakeOnMessage narrows its opt-in list through narrowToThread when
the message carries a thread root, keyed on installedBy — the bot User id
thread_user_state holds.

Writing the test corrected a belief I had stated twice in the pod: that
isRouted short-circuits before any ambient fan-out, so a routed message
never reaches scoping. It does reach it. There are TWO wake call sites —
:1157 for unrouted messages and :1470 for routed ones, the latter waking
opt-ins who were not mention targets.

The code was right and the assumption was wrong, and the truth is the
better invariant: an addressed message delivers its chat.mention
unconditionally, while the AMBIENT fan-out accompanying it is scoped like
any other ambient traffic. Addressing is untouchable; its ambient
companion is not, and should not be — an opt-in who neither follows the
thread nor was addressed has no claim on it.

Ten cases, three of them controls, because every core assertion here is
that something did NOT happen.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): name the second wake call site at both call sites

I asserted twice in the pod that isRouted short-circuits before any
ambient fan-out, so a routed message never reaches wake-on-message. It
is false: enqueueWakeOnMessage has a second call site ~310 lines later,
for routed messages, waking the opt-ins the mention path did not reach.

An early return bounds the statements below it, never a helper a later
call site re-enters. Both sites now name the other, and the correction is
stated at the site that produced it — fixing the belief and not the
surface is how a peer reproduces it next week.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the third state — muted AND expanded gets no wake

@ux-lead 56820 (doc 5e7060f on #1107): once rows exist for
non-followers, every reader of follow state must filter on following,
never on EXISTS(row). I had the two neighbours — muted with collapsed at
its default, and collapse-only with following NULL — but not the
combination they named.

(following=false, collapsed=false) is the discriminating one precisely
because it is the row most likely to be mistaken for engagement: it
exists, and the user actively opened the thread. Neither fact is consent
to be woken. Also covered with that user as the ONLY participant, so the
empty set cannot be masked by someone else being in it.

Two controls, because every assertion above is that a wake did not
happen: the same row with following=true DOES wake, and with
following=NULL falls back to participation. All three tri-state values
are now exercised here rather than two.

Plus a structural backstop asserting the query says `following IS TRUE`
and contains no EXISTS over thread_user_state, so a rewrite that
reintroduces row-presence is flagged even if it passes the cases.

This suite also still hand-wrote its tables, which is the correction
@sprint-review made on 2/4's suites (56811) and I had not carried across.
Now built from schema.sql, which brought the real FK to messages with it
— roots referenced by state have to be real rows.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the fourth test as a paired flip on one row

@ux-lead 56822 (392b86e on #1107): "a participant at (NULL,
collapsed=false) is woken; the SAME participant at FALSE is not."

Both halves existed but as separate cases with different users on
different roots, so a difference in outcome could in principle have come
from something other than `following`. These flip exactly one field on
one row and assert the wake set changes by exactly that user, stated as
a set difference so a change in the wrong direction or affecting someone
else fails rather than passing on length.

Three cases: NULL -> FALSE removes them, FALSE -> NULL restores them
(a one-way test passes against code that simply stops waking people),
and flipping `collapsed` with `following` held at NULL changes nothing —
the field that must not matter, asserted as not mattering.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): cite the ruling by section, not by squashed sha (3/4)

Same correction as the 2/4 commit, for this branch's own suite.
@ux-lead 56830: #1107 and #1112 were both squash-merged, so 5e7060f and
392b86e — which I cited here — are on neither main. They resolve in a
clone that still has the branches and nowhere else.

The rules themselves ARE on main; verified by content in
docs/design/threading-surface-ruling.md, not by sha.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): findById dropped thread_root_id, so scoping never fired

@sprint-review's blocker on this PR (57291): `m.thread_root_id` count 0.
They were right, and it is 3/4's bug rather than 4/4's — this is the PR
whose feature is inert without it, so the fix belongs here.

The hook reads `message.thread_root_id`. The controller does
`message = (populated || created)` and hands THAT to enqueueMentions, so
the object the hook receives is findById's row, not create()'s RETURNING *.
findById projects an explicit column list that did not name the column.
Ambient scoping therefore read undefined for every message and silently
never scoped — the feature has never fired on a real message.

Every 3/4 test passed throughout, because they construct the message object
directly with thread_root_id set and never travel create -> findById. A test
that builds the shape the code under test never receives cannot find a
projection bug; only a round trip can.

Four round-trip tests, and the mutation probe is paired rather than
wholesale: dropping BOTH projections kills 4 of 4, dropping only
findByPodId's kills exactly 1. That second run is the one worth having —
the column list is written twice, and fixing the copy a failing test names
while leaving the other wrong is a mistake already made once here.

The fixture builds pods, users and messages from schema.sql via applyTable
rather than by hand. The first attempt typed VARCHAR(255) keys against
schema.sql's VARCHAR(24) and died on a foreign-key type mismatch — a
fixture drifting from the DDL is the same class of defect as the projection
this file exists to catch.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): installedBy is not the bot — key scoping on the bot's User row

@sprint-review's second blocker on this PR (57291). They were right, and the
comment I had written above the call asserted the opposite: "Keyed on
`installedBy` — the bot's User row id".

`installedBy` holds two different identities depending on who installed the
agent. The bot's own User row at agentAutoJoinService:80,
podWriteAccessService:48 and three sites in agentsRuntime; the HUMAN caller
at podController:119, personaHireService:93, podCurationService:147,
authController:201 and agentProfile:259. AgentRun.ts:65 calls it "the hiring
user" outright. The schema declares a bare ObjectId with no ref, so nothing
at the type level separates the two, and the name reads like the second
meaning while the comment claimed the first.

thread_user_state.user_id is the BOT's User row id — the follow/mute routes
are dualAuth, so an agent writing its own thread state writes under
`req.agentUser._id`. Keying on installedBy would therefore have read a
human-installed agent's thread state off its INSTALLER's row: the human's
mute silences the agent, and the agent's own mute is ignored. Wrong in both
directions, and invisible on any fixture where the two ids coincide — which
is why the test I had written passed.

Resolves the bot User row by (botMetadata.agentName, botMetadata.instanceId)
instead. One query for the whole target list, not one per target. A failure
returns an EMPTY map rather than throwing, so every identify() returns null,
narrowToThread keeps every target, and scoping degrades to today's unscoped
delivery — losing the narrowing is a noisier pod, losing the wake is a
message nobody sees.

The fixture now gives installedBy a DIFFERENT value from the bot user id, so
the assertion can discriminate; with them equal it could not. Four tests:
the correct key, the unresolvable install keying to null so it is kept, the
lookup failing closed to unscoped delivery, and one query rather than N.
Mutation probe: restoring the installedBy callback kills 3 of the 4.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(threading): the header claimed a wire-up that does not exist

@sprint-review's third blocker on 3/4 (57306). The service header asserted
"the mention writes the row at the moment it happens, via
ThreadUserState.followByParticipation". Nothing calls it. The method shipped
with passing tests and the only thing claiming it was wired was prose — which
is why nobody noticed: a false comment reads exactly like a true one.

Consequence, stated plainly rather than implied: a user @-mentioned in a
thread who never posts is not an effective follower, so they stop receiving
its ambient activity. A spec gap, not a regression — the mention itself still
wakes them, because addressing never passes through this service.

Not closing the gap here. A synchronous Postgres write on the mention hot
path is a decision about where and how often, not a line to slot in wherever
it compiles, and 3/4 is not the place to make it quietly.

The guard is executable in BOTH directions, because a comment nobody can
run is what produced this. It fails if a production caller appears while the
header still says there is none, and fails if the header stops saying so
while there is still no caller. Control run: dropping a fake caller into
services/ turns it red, so the test can actually fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the wired branch was unreachable, so the guard ran one way

@sprint-review (57311), both notes, and both were right about the thing I
had just described as running in two directions.

1. Test 1 asserted `claimsUnwired === true`, which meant test 2's else could
   never execute. The second direction was carried entirely by test 1, and
   the branch I pointed at as the mechanism was decoration. Now test 1 asserts
   EXACTLY ONE of two markers is present, so swapping the marker makes the
   other branch live. Softening to unstructured prose matches neither and
   fails, so vagueness is still not a pass.

2. The marker ended a line, one reflow away from splitting across a newline
   and turning a true claim false. Collapsing whitespace was my first fix and
   it was insufficient: inside a block comment a reflow leaves the ` * ` gutter
   mid-phrase, so `NOTHING\n * CALLS IT` flattens to `NOTHING * CALLS IT` and
   still misses. Strip the gutter, then collapse.

   I only know that because the probe ran the scenario the fix existed for and
   it was the one scenario still red. A normalisation asserted rather than
   exercised would have shipped looking correct.

Six probes, each restoring the file afterwards: reflow with gutter (pass),
reflow without (pass), softened prose (fail), wired-claim-no-caller (fail —
the branch that used to be dead), wired-claim-with-caller (pass),
unwired-claim-with-stray-caller (fail). Both directions of test 2 now
demonstrably fire.

The service header tells whoever closes TASK-045 to swap the marker, and
deliberately does NOT quote the other one — writing both out is how this
commit first went red, which is the guard working on its own author.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(threading): explicit thread_root_id, with derivation as the fallback

@ux-lead's 56879 amendment, which settles the constraint-4 question I
raised at 12:22. An ordinary in-thread post carries NO reply edge — the
composer names the root directly — so joining a thread never makes the
message isRouted and never pings the root's author. Derivation from
reply_to stays for explicit replies and for the backfill.

services/threadRootResolver reconciles the two shapes in one place:
explicit wins when present, derivation fills when absent, and a MISMATCH
is a 400 rather than a silent preference. A caller who says "reply to X"
and "this belongs to thread Y", where X is not in Y, holds a wrong
belief about the conversation; picking a winner hides that from them.

Validation is about the ROOT, not the poster — whether they may write
here is pod membership, answered upstream. Rejected: a root that does
not exist, a root in another pod (attaching to a conversation the caller
may not be able to read, and the wake set comes from the thread, not the
pod), a root that is itself inside a thread (two ids for one
conversation splits every consumer that groups by root), a non-integer,
and the mismatch. Each carries a code so the route need not parse text.

The model takes an already-RESOLVED root and does not decide precedence:
COALESCE($7, <derivation>) is the whole rule in the SQL. A resolver
failure that is not a caller error re-throws rather than defaulting to
null, since silently dropping a message into no thread is the data loss
this column exists to prevent.

12 executed cases including a CONTROL that valid input still succeeds,
without which every rejection could come from a resolver that rejects
everything.

Also fixes three of my own tests that were pinning implementation
details rather than contracts: they asserted the local variable name
feeding `expandedForRootsCreatedBefore` and the exact literal of a catch
body, and broke on my own rename. They now assert the key and the
degradation. Found because I ran the new suite and not the existing one
— the same miss as earlier today.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the resolver's round trip, now that the projection is fixed

The Message.ts half of this commit moved to 3/4 (#1120), where the bug it
fixes actually lives: findById's projection dropped thread_root_id, so the
ambient scoping hook read undefined for every message. 3/4 is the PR whose
feature is inert without it, so the fix belongs there rather than here.

What stays is the part specific to this PR: the resolver's own round trip
through create -> findById, including the explicit-root shape that has no
reply edge at all. That shape is why the projection bug matters more here —
after @ux-lead's 56879 amendment an ordinary in-thread post carries only
thread_root_id, so a dropped column is the whole signal rather than a
redundant one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(threading): only reconcile when there are two claims to reconcile

CI caught this: calling resolveThreadRoot unconditionally added a query
the controller tests do not mock and broke seven of them. I had run the
model suites on this branch and not the controller suite — the same miss
as earlier today, and the reason the surrounding suites are worth
running rather than the file just written.

The redundancy is real independently of the breakage. With no explicit
threadRootId the resolver only re-derives
COALESCE(parent.thread_root_id, parent.id), which the INSERT already
does — a query per message that changes nothing. There is nothing to
reconcile until there are two claims about the same message.

Gated on an explicit threadRootId. The no-root path still passes null
through to create, so derivation continues to happen in SQL: "no
explicit root" must mean "let the INSERT derive it", never "no thread
root".

Three cases pin it, including the behavioural half — a plain reply still
gets its root with the resolver never called.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* test(threading): the service-tier arity assertion too

CI caught the third instance of the same miss. Adding a 7th parameter to
PGMessage.create broke an argument-list assertion in
__tests__/service/messages.test.js; I had fixed the unit-tier one in
PgMessage.test.js and never ran the service tier.

Twice before today I ran the file I wrote and not its neighbours. This
time "neighbours" meant another TIER, which is a wider radius than I had
been applying — the unit and service suites assert the same call from
different directions and only one of them was in my habit.

Swept the whole tree for assertions on create's argument list. There are
THREE, not two:
  __tests__/unit/models/PgMessage.test.js      — updated earlier
  __tests__/service/messages.test.js           — updated here
  __tests__/service/pgMessages.test.js:97      — unaffected, and checked
     rather than assumed: the legacy route still calls create with three
     arguments (pgMessageController:157), so an exact-match assertion of
     three still holds. Confirmed PASS in CI run 32590924788, because
     that suite cannot load locally under Node 26.

The null is commented as "let the INSERT derive one" rather than "no
thread" — the distinction that matters if anyone reads the fixture later
and decides the parameter is decorative.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
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