Declare each wire shape and each row vocabulary once #180
No reviewers
Labels
No labels
bug
duplicate
enhancement
help wanted
invalid
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
lz/agent-nexus!180
Loading…
Reference in a new issue
No description provided.
Delete branch "refactor/collapse-declarations"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes #176. Closes #181.
A simplification audit of the two MCP specs found the same wire shapes declared twice — once in the browser-safe
lib/api/types.tsand again under$lib/server. This collapses them, plus three smaller duplications, before the fleet status layer (#177) adds a fifth declaration of each and a new SSE wire shape.Rebased onto
mainafter #174 merged, and extended to absorb #181 rather than leave a second pass over the same files.What changed
b9dcbad1790abefeb3ef8dbecd31readJsonBodyrather than re-declaring it92e20aadeb70818019648kindd4a773e5e0ad81c23eabec83cd97The second commit is net-positive and that is the honest result. The new module and its test are 68 lines against ~53 removed. It is here for correctness, not size: it collapses eight call sites that derived a session's base path three different ways.
The #181 half
The duplication was worse than #181 reported — partly because #174 added a copy after the issue was written, partly because the issue undercounted, and partly because this branch's own first census undercounted too. Final figures, re-derived with
git grep -Fat the branch base:SessionKindschema.ts, the DTO inline,mcp/projection.ts'sz.enum, and two test fixtures that restated the unionProviderKindschema.ts,providers/types.ts, the DTO inline, the connections route'sz.enumPreviewSchemeschema.ts,api/types.ts,client.ts's signature, two routez.enums,Previews.svelte's$state, and the<option>values in that same component's markupPreviewStatus/PreviewSourceschema.ts,api/types.tsEach is now one
as constarray in$lib/api/types, type derived from it. The request schemas and the scheme picker read the array, so a hand-written pair is no longer expressible where one used to be. The two test fixtures matter more than they look: under the old form a rename turned production red while they stayed green, still minting a kind the schema no longer knew — both are now among the files a rename takes down.Why the browser-safe module, honestly. An earlier revision of this description (and of
d4a773e's message) said a const array in$lib/server"could never back the client's$state<PreviewScheme>or the DTO". That is false — both are type positions, erased before the bundle. At that point no client module read any of the five arrays at runtime; they sat with their siblings because that is where this app's vocabulary is declared, not because a rule forced it. Making the picker iteratePREVIEW_SCHEMEShas since given them one genuine client-side reader. The array that always had to live there isATTENTION_STATES, which$lib/attentionspreads intoSESSION_MARKSin the browser.The rule two docblocks stated is false in both directions (#181 item 3): server code imports
$lib/api/typesthroughout, and nine browser-shipped modulesimport typefrom$lib/server/artifacts/types, which is legal because a type import is erased before SvelteKit's own illegal-import plugin sees it (@sveltejs/kit/src/exports/vite/index.js, whose error text says as much). Both copies are corrected in one commit, because fixing one leaves the survivor looking authoritative.mcp-dto-parity.test.tsstays — its duplication is live and its assertion still fails on real drift; only the stated reason was wrong.#181 item 4 was already wrong when it was filed, and this branch repeated it before catching it.
attention.test.ts:115has had adescribe('attention CSS parity')since 2026-09-05 that readsapp.css, loops the sameSESSION_MARKS, and requires a rule that actually paints — strictly stronger than the selector grep this branch briefly added in a new file. Only the reverse direction was ever missing: a stale.status-dot.<mark>for a mark that no longer exists. That single assertion now lives in the existing block, stripping CSS comments first, and the new file is gone.Why deleting two parity tests is legitimate
worker-dto-parity.test.tswas itself type-level only, so the gate did not weaken — the file was removed from under the same gate.vitest.config.tssets notest.typecheck, so vitest never executed those two assignability assertions;pnpm typecheckwas already their sole enforcement. That is a stronger argument than "typecheck replaces the test", and it is measured rather than reasoned.The duplication it guarded is gone: there is one
WorkerDTO, andworkerRowToDTOconstructs it as an object literal with a declared return type, so missing-field and excess-property checking now enforce both drift directions at compile time. The same protection extends toSessionDTO,PreviewDTOand both health DTOs, none of which ever had a parity test.pnpm builddoes not type-check, and this was measured, not inferred: injectingbogus_field_that_does_not_exist: 42into theworkerRowToDTOliteral and runningvite buildemitted both bundles with no error, and the field is present in the output chunk.vite.config.tscarries onlysveltekit();scripts/build-server.mjsis a bare esbuild bundle. eslint is not a second gate either —eslint.config.jsusestseslint.configs.recommendedwith noproject/projectService, so it is not type-aware. CI runs all four gates as separate steps, sopnpm typecheckdoes gate merges.For
session-attention-parity.test.ts, only its first assertion becomes impossible. A rename is still forced throughhooks-parity.test.ts(which pins the set againstworker/plugins/nexus/hooks/hooks.jsonin both directions),attention.test.ts(which asserts the four literals through the re-export, and now both CSS directions), and four typecheck-red literal sites inlib/attention.ts.The name→kind switch is a behaviour change on old databases, and it corrects them
On main the base path was derived three ways: five sites keyed on
worktree_name === 'workspace'; two keyed onkind === 'workspace_shell'(checkSessionHealthand the artifact submit route); andscope.tstested neither, always returning the worktree path.A row with
kind='session'andworktree_name='workspace'is constructible on a database predating2caa986. Before that commitcreateSessionhad no name reservation and the workspace shell was not asessionsrow at all, soworkspacewas an ordinary legal session name;worktree_namehas existed since migration 0002; and0006_workspace_shell_session.tsaddskindasnotNull().defaultTo('session')with no backfill pass, so such a row becomeskind='session'.For that row the truth is "a regular session with a worktree at
/workspace/.nexus/worktrees/workspace". The old name test resolved its artifacts against/workspace; the kind test resolves them against the worktree. So on real legacy data the five switched sites go from wrong to right. The reverse direction is unconstructible —openWorkspaceSessionis the only writer ofworkspace_shelland sets both fields toworkspace.Nobody would have noticed, because on such a worker
openWorkspaceSessionhas always been unable to insert its own row anyway:uq_sessions_worker_nameon(worker_id, name)from migration 0002 already holds the name. The shell is broken there independently.Separately, the client's
sessionScopepreviously computed the shell's path wrongly, but no caller could reach it — all four call sites plus the indirectRailHoverCardpath filter tokind === 'session'first. That fixes nothing observable; what changes is thatsessionScope's correctness no longer depends on those filters.Verification
Each gate its own command, output redirected,
$?read before the log — never piped totail.The rebase replayed seven commits with no conflict and all four gates were green before any new work — so nothing in #174 (which added
mcp/projection.tsandmcp-dto-parity.test.ts, both consumers of the shapes collapsed here) conflicted semantically with this branch.Two timeouts on later runs, neither this branch's, and worth recording as a suite property.
oauth/provider-cross-bundle.test.ts(builds two oidc-provider instances) andsession-path.test.tseach exceeded vitest's 10s default on a loaded host — different tests on different runs. Both pass in isolation (the second at 4.8s, i.e. half the budget when the host is quiet), and the first reproduces on plainorigin/mainin a separate worktree. Several tests sit close enough to the default that a busy machine flips them; a per-testtestTimeouton the slow ones would remove the ambiguity.Negative controls. Every mutation was diffed against a
cpbackup before its result was believed, and restored from that backup rather thangit checkout:WorkerDTOworkerRowToDTO— the direction the deleted test guardedcreateSession's name reservation disabledsession-pathreservation test redhooks-parity.test.tsredWORKTREES_ROOT→/wrong/rootsession-path.test.tsred (it was not, beforedeb7081)sessionBasePathloses its shell armsession-path.test.tsand the new agent-artifacts shell case redsession-path.test.ts:10dies — the single guard for the switchSESSION_KINDSmember renamed.status-dotrule for a mark that does not existrulesFordemands a real{…}blockended→ended_v2.status-dot.workingdeleted,@mediaoverride keptReview
Four agents reviewed the first seven commits; three more reviewed the #181 commits. Ten findings changed the code.
From the first round: a false comment justifying
session-path.ts's location, which had also displaced a true one; a test whose expectation was built from the constant under test and so could not fail; a wrong call-site census; and a fixture that under-specified what the route reads.From the second round, every one of these was a claim of mine that turned out to be false:
app.csswas never unguarded — the new test file is deleted and only its reverse assertion kept.$lib/servercould never back the client's$state" — type positions are erased, and at the time no client module read these arrays at runtime.schema.tsitself, whereArtifactKind,ArtifactSourceandArtifactCommentStatusare declared and travel the other way.SessionKindfive sites, not three;PreviewSchemeseven, not five.<option>markup; it now iterates the array.Plus two small ones: the illegal-import check is SvelteKit's plugin, not Vite's; and
types.tspointed atmcp-status-parity.test.ts, which does not exist.Confirmed unaffected:
mounts/andtokens/are untouched and both parity tests pass, so facts #22 and #24 stand; the five vocabularies collapse to identically ordered tuples, so the fourz.enumsites build identical schemas and identical error text; the re-exports areexport typeonly, so no runtime value leaves$lib/server; and$lib/api/types.tsimports nothing, so there is no cycle in either bundle (fact #31).Worth recording: every collapsed vocabulary also has a database
CHECKbackstop —migrations/0006forkind,0008forscheme,0001for the provider kind — so a future widening fails loudly at the row rather than silently on the wire.PROVIDER_KINDScarries a second guard on top,SUPPORTED_KINDS, which is whygithubparses and then 400s.Deliberately not done
MountSpecand the token scopes stay duplicated with their parity tests. AGENTS.md facts #22 and #24 name that duplication deliberate; this branch only makes the stated reasons true. AGENTS.md itself needed no edit —grepwith a positive control shows it never carried the false import rule.PREVIEW_STATUSESandPREVIEW_SOURCESstill have no runtime reader; they exist only as the source of their type aliases. A plain type alias would collapse the duplication equally well, but making two of the three preview vocabularies a different shape from the third buys nothing.:global(.needs-you)tints inSessionRow.svelteandWorkspaceRail.svelte, which a rename leaves dead with every gate green, and a parity test pinning each array against the migrationCHECKbehind it.[sessionId]/artifacts/+server.ts,[artifactId]/+server.ts,raw/+server.ts,[artifactId]/+page.server.ts). Pre-existing; the compiler still catches a droppedkindthere, because those selects feed the annotatedAuthorizedAgentSession.One consequence worth stating rather than fixing:
workerRowToDTOnow assigns the server'sMountSpec[]into the canonical one, adding a one-directional compile-time check between two declarations AGENTS.md requires to stay separate. The duplication is not weakened — it picked up a free partial guard on top ofmount-parity.test.ts.`$server/sessions/attention` re-exports `ATTENTION_STATES` from `$lib/api/types` instead of declaring its own copy. Server-side consumers keep importing it from where they already do — the Zod enum on POST /api/agent/events, `db/schema.ts`, hooks-parity.test.ts — so nothing else moves. The type is imported separately as well as re-exported, because a re-export does not bind the name in the module body and `recordAttention` takes it as a parameter. `session-attention-parity.test.ts` is deleted. Its premise ("the client cannot import server modules, so the set is genuinely written twice") had it backwards: the illegal direction is client → server, and this is server → client, which `db/schema.ts` has done for these same types all along. With one array there is no second copy to drift. What that test actually protected — that the set the hooks send and the set the endpoint accepts are the same — was never its job and is unaffected: hooks-parity.test.ts still reads the array and still checks it against worker/plugins/nexus/hooks/hooks.json. Verified by appending a fifth state to the canonical array: `covers every state at least once` fails, and the endpoint's `rejects a state the hooks never send` still passes on the unmutated set.Five routes carried a private copy while 17 others imported the one in `$server/lib/http`. All five were byte-identical to it — same signature, same `try { return await request.json() } catch { return null }`, no docblock — so each becomes an import and a deletion, with no behaviour to check.3be43ee3cdc23eabe4deDeclare each wire shape once, before the fleet store adds a fifthto Declare each wire shape and each row vocabulary onceReview fixes. Three claims this branch shipped were false, and one of them had a whole test file resting on it. **`app.css` was never unguarded.** `attention.test.ts:115` has carried a `describe('attention CSS parity')` since 2026-09-05 — twelve days before #181 item 4 said nothing checked it — and that block is STRONGER than the file this commit deletes: it loops the same `SESSION_MARKS` and demands a rule that actually PAINTS, filtering out `animation: none` overrides, where the new one only grepped for the selector. Measured: deleting the base `.status-dot.working` rule while its `@media (prefers-reduced-motion)` override survives — a realistic partial rename, and a case the deleted file's own mutation testing found it SURVIVING — fails the pre-existing assertion. So only the reverse direction was ever new: a stale `.status-dot.<mark>` for a mark that no longer exists, which nothing checked and which is how the next rename gets a false all-clear. That single `it` moves into the existing block, which already reads the stylesheet, and `attention-css.test.ts` is deleted — there is no `attention-css.ts` for it to sit beside, and two files reading `app.css` for marks would have to be kept in sync by hand. It strips CSS comments before scanning, which the deleted version did not: a selector inside a comment styles nothing, so it would have been reported as a mark that no longer exists. That also closes the other survivor the mutation pass found — a rule deleted with its name left behind in a comment. **The count was wrong.** "Eleven client modules import type from `$lib/server/artifacts/types`" is nine browser-shipped modules, plus two test files that are not evidence for the claim, since a test never goes through the client build. Taken from #181 and not re-derived — in a commit whose subject was docblock accuracy. (Re-derived here with `grep -F`: the regex form returns zero because `$` is not literal, which is the absence-grep trap.) **"Every vocabulary a row shares with the wire is declared once"** is false of schema.ts itself: `ArtifactKind`, `ArtifactSource` and `ArtifactCommentStatus` are declared IN that file, reach the wire through `ArtifactDTO`, and are imported by client components — the opposite direction, which is exactly the point the paragraph was making. Corrected to say so rather than overclaim. Negative controls, each diffed against a `cp` backup and restored from it: a rule for a mark that does not exist kills the new assertion alone; a rule deleted with its name left in a comment now kills three; `ended` → `ended_v2` is killed by the pre-existing assertion, so the two directions do not overlap into a gap.485a7400a160f0e5d4c760f0e5d4c7c83cd97ec1