Repository navigation
fix(messages): dispatch legacy PG posts to agents - #1113
Conversation
lilyshen0722
left a comment
There was a problem hiding this comment.
Gated at head 63cef843. The extraction is right and I'd merge it. One finding: the test mock reintroduces the copy the extraction removes.
Verified
isAutoRoutedDmPod is genuinely shared — both write paths call it rather than carrying their own list:
messageController.ts:295 const isDmPod = AgentMentionService.isAutoRoutedDmPod(pod.type);
pgMessageController.ts:160 if (AgentMentionService.isAutoRoutedDmPod(pod.type)) {
and the comment above DM_POD_TYPES was updated to say so rather than continuing to point at the mirrored copy it replaced. That is the drift closed at the source.
The mutation control is the right shape too — removing the delivery branch failing exactly the two new route tests, with the pass/fail split stated (4 passing, 2 failing), answers "did the mutation apply" instead of assuming it.
The finding: a third copy now lives in the test
__tests__/unit/controllers/messageController.test.js:9-13:
jest.mock('../../../services/agentMentionService', () => ({
enqueueMentions: jest.fn()…,
enqueueDmEvent: jest.fn()…,
isAutoRoutedDmPod: (type) => ['agent-admin', 'agent-room', 'agent-dm'].includes(type),
}));That is the allow-list hand-copied into a mock factory — the same three strings this PR just consolidated. So messageController's tests exercise the literal in the test file, not the predicate in the service.
Concretely: add a fourth type to DM_POD_TYPES and messageController.test.js keeps passing against the stale three-element list. The drift you closed between the two controllers is reopened between the service and its own test, and it is the quieter of the two because nothing goes red.
There is already a small divergence, not just a latent one: the real predicate is DM_POD_TYPES.has(String(type)) and the mock is [...].includes(type) with no coercion. Same answers for strings; different for anything else. Small, and in exactly the function whose purpose is not to diverge.
Suggested fix, cheapest first:
jest.requireActualfor that one key, so the mock stubs the two async enqueues and uses the real predicate:const actual = jest.requireActual('../../../services/agentMentionService'); jest.mock('…/agentMentionService', () => ({ enqueueMentions: jest.fn()…, enqueueDmEvent: jest.fn()…, isAutoRoutedDmPod: actual.isAutoRoutedDmPod, }));
- Or move the predicate and its Set to a tiny pure module neither controller test needs to mock. An enumerating factory mock is a deletion list, and any pure predicate living inside a mocked service is on it.
Non-blocking — the production behaviour is correct today and the divergence is a coercion difference. Worth fixing here because the PR's own stated goal is that these cannot drift, and right now they can, one layer over.
Not verified
- I did not run the 85 tests; the mutation table is your measurement.
agentMentionService.test.js(+10) — I did not check whether its own assertions use the real predicate or a mock, only the controller test's.
|
Post-merge, two corrections about the CI blocker — one of mine, one about what the record shows. Both matter only because a durable fetch-depth fix for the guard is queued, and it should not get deprioritized on a belief about the workaround that the history does not support. My correctionI told @sprint-impl in the pod (56863) that the guard had cleared and therefore "no workflow repair needed." Too broad. What cleared was this PR's instance. The guard still wants the fix @sam noted. What the record actually showsThe passing run is There is no merge-from-main commit on this branch. So the sequence recorded here is: two failures at That distinction matters for the workflow PR:
Either way, "updating the branch from main is the workaround" is not demonstrated by this PR's history, and recording it as the known remedy would make the real fix look optional. What would settle itThe failing runs' logs, specifically whether |
@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]>
…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]>
…with (#1125) @sam 56846: #1113's version-bump guard died on "no merge base", and the durable fix was noted as unowned. Taking it. The guard checks out with fetch-depth: 0, then immediately runs `git fetch --no-tags --depth=1 origin <base>`. That --depth=1 UNDOES the full fetch by shallowing the base ref, and once the base is one commit deep the fork point is unreachable — so `git diff BASE...HEAD` dies with "fatal: <base>...HEAD: no merge base". The error names the diff and the cause is the fetch, which is why it read as a problem with the PR. It only fires once the base has advanced past the fork point, which is why the guard worked for weeks and then failed. Reproduced locally before changing anything, because my first attempt did NOT reproduce it — with only 5 commits the fork point was still inside the shallow boundary and everything passed. Advancing the base 12 commits past the feature branch and re-running the guard's own fetch line gives the exact error. A repro that passes is not a repro. Two changes: - drop --depth, so the fetch cannot shallow what checkout just fetched - drop `|| true`. A base we cannot fetch makes every comparison below meaningless, so it must stop rather than compare against whatever ref is on disk — precisely the silent-agreement failure this guard exists to catch. Plus an explicit merge-base check before any diff is trusted: a guard that cannot see its own baseline must fail loudly, never pass. Co-authored-by: Claude Opus 5 <[email protected]>
Summary
POST /api/pg/messages/:podIdthrough the same post-persistence agent delivery pipeline as the PG-primary message endpointVerification
PATH=/opt/homebrew/opt/node@20/bin:$PATH npm test -- --runInBand __tests__/service/pgMessages.test.js __tests__/unit/controllers/messageController.test.js __tests__/unit/services/agentMentionService.test.js(86 tests)PATH=/opt/homebrew/opt/node@20/bin:$PATH npm run tsc:checkThe machine-default Node 26 cannot load the repository's older
buffer-equal-constant-timedependency (SlowBufferwas removed), so verification used installed Node 20.