Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

add Brain threads: a bullet-journal record type with one shared (kind, id) ref registry (#7664)

[._.]/ Adam Eivyc4644b611e28
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 65797b6d61..a72e0d64cb 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -244,6 +244,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
| `textUtils.js` | `escapeRegExp(value)`, `countWords(text)`, `isStr(v)` and `isNonBlankStr(v)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. Also `pluralize(count, singular, pluralForm?)` — the shared "N item/items" phrasing helper for singular/plural counts. |
+| `threadRefKinds.js` | Re-export of `server/lib/threadRefKinds.js` — the Brain THREAD ref vocabulary and `(kind, id)` → label/URL route table (a *thread* is a tracked topic or commitment, never a message thread). Named exports only — just `threadRefLabel`/`threadRefUrl`, the two the client renders with. `pages/CatalogIngredient.jsx` renders its inbound-ref chips through `threadRefUrl`/`threadRefLabel` here instead of its own local switch, so the repo has exactly one kind→route table. |
| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. |
| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
| `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index e92d4db617..0f76028ab4 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -204,6 +204,7 @@ export * from './terminalFit.js';
export * from './terminalScroll.js';
export * from './terminalTheme.js';
export * from './textUtils.js';
+export * from './threadRefKinds.js';
export * from './threejsAnimation.js';
export * from './threejsEnvironment.js';
export * from './threejsExplode.js';
diff --git a/client/src/lib/threadRefKinds.js b/client/src/lib/threadRefKinds.js
new file mode 100644
index 0000000000..365cec2b62
--- /dev/null
+++ b/client/src/lib/threadRefKinds.js
@@ -0,0 +1,14 @@
+/**
+ * Thread ref vocabulary + route table.
+ *
+ * Re-export of `server/lib/threadRefKinds.js` — the one definition of this rule,
+ * imported rather than copied so the two runtimes cannot drift (the
+ * "One pure module, one definition" convention in this directory's README).
+ *
+ * A Brain *thread* is a tracked topic or commitment, not a message thread.
+ *
+ * Named exports only, and only the two the client renders with — the registry
+ * table and the server-side predicates stay out of the client barrel until
+ * something here needs them.
+ */
+export { threadRefLabel, threadRefUrl } from '../../../server/lib/threadRefKinds.js';
diff --git a/client/src/pages/CatalogIngredient.jsx b/client/src/pages/CatalogIngredient.jsx
index dc0e1033a5..90e7eae492 100644
--- a/client/src/pages/CatalogIngredient.jsx
+++ b/client/src/pages/CatalogIngredient.jsx
@@ -35,6 +35,7 @@ import { startMemoRecording, arrayBufferToBase64 } from '../lib/audioRecorder';
import { useGalleryPage } from '../hooks/useGalleryPage';
import { generateImage } from '../services/apiSystem';
import { composeCanonStyledPrompt } from '../lib/composeStyledPrompt';
+import { threadRefLabel, threadRefUrl } from '../lib/threadRefKinds.js';
import { getUniverse } from '../services/apiUniverseBuilder';
import useMounted from '../hooks/useMounted';
import MediaJobThumb from '../components/pipeline/MediaJobThumb';
@@ -52,29 +53,14 @@ import { timeAgo, formatDateTime } from '../utils/formatters';
// (`client/src/lib/catalogTypes.js`). Each editor entry is `[key, label, kind]`
// where `kind` is 'text' (single line) or 'textarea' (multi-line).
-// Map a refKind onto a click-through route. Returns null for kinds we don't
-// know how to deep-link to, so callers can render the chip without a link.
-function refPath(refKind, refId) {
- if (!refId) return null;
- switch (refKind) {
- case 'universe': return `/universes/${encodeURIComponent(refId)}`;
- case 'series': return `/pipeline/series/${encodeURIComponent(refId)}`;
- case 'issue': return `/pipeline/issues/${encodeURIComponent(refId)}/concept`;
- case 'creative-director': return `/creative-director/${encodeURIComponent(refId)}/overview`;
- case 'writers-room':
- case 'writersRoom': return '/writers-room';
- default: return null;
- }
-}
-
-function REFKIND_LABEL(kind) {
- if (kind === 'universe') return 'Universes';
- if (kind === 'series') return 'Series';
- if (kind === 'issue') return 'Issues';
- if (kind === 'creative-director') return 'Creative Director';
- if (kind === 'writers-room' || kind === 'writersRoom') return "Writers' Room";
- return kind;
-}
+// Ref chips deep-link through the SHARED kind→route registry
+// (`client/src/lib/threadRefKinds.js`, a re-export of the server leaf), not a
+// switch local to this page — one table, so a kind added for a Brain thread and
+// a kind stored on a catalog ingredient can never disagree about where it goes
+// (#7664). Same contract this page always had: `threadRefUrl` returns null for a
+// kind we can't deep-link (the chip renders unlinked) and `threadRefLabel` falls
+// back to the raw kind, so a ref synced from a newer peer still renders. The
+// legacy `writersRoom` spelling is aliased inside the registry.
// Build the image-generation prompt source from the (live, editable) payload:
// the type's primary content field first, then a curated set of *visual*
@@ -1502,11 +1488,11 @@ function RefsPanel({ refsByKind }) {
{kinds.map((kind) => (
<div key={kind}>
<div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">
- {REFKIND_LABEL(kind)}
+ {threadRefLabel(kind)}
</div>
<div className="flex flex-wrap gap-1.5">
{refsByKind[kind].map((r, i) => {
- const path = refPath(kind, r.refId);
+ const path = threadRefUrl(kind, r.refId);
const label = r.refName || r.refId || '(unnamed)';
const role = r.role ? ` · ${r.role}` : '';
const chip = (
diff --git a/data.reference/brain/threads.json b/data.reference/brain/threads.json
new file mode 100644
index 0000000000..79802cb55a
--- /dev/null
+++ b/data.reference/brain/threads.json
@@ -0,0 +1,3 @@
+{
+ "records": {}
+}
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 5241b4cb99..63a723bf2b 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -79,6 +79,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.
- Spotify brain playlist shelf — `data/spotify/playlists.json`. `file-primary`, intentionally machine-local and never federated: it is a bounded cache of Spotify playlist and track metadata used as local reference material, while listening evidence remains in the federated Brain activity record. No sync cursor or tombstone. Adapter: `server/services/spotifyPlaylists.js`.
- IdeaLoom lists — `data/brain/idealoom-lists/{uuid}/index.json` with a schema-stamped collection index holding the disabled-by-default local integration settings. Lists retain their ordered idea strings, prompt/title/category/status/help, timestamps, and importer-owned local sync metadata. Explicit exchange reads/writes only the configured vault's `Idea Loom/` folder through the specialized `server/services/idealoomObsidian.js` parser/renderer; new notes use a date/title filename and imported note paths remain stable. **Intentionally machine-local — never federated, reconciled, or memory-bridged**: a vault id, note path, and content hash are meaningful only on the install that configured them. Native Brain `ideas` remain a separate federated collection. Exchange is base-hash reconciled: a note and a list that both changed since the stored hash report `conflicted` and neither is written, and a note deleted in the vault reports `missing` rather than being recreated (an iCloud note that is merely un-downloaded is `unavailable`, a separate outcome). Opt-in automatic export (`autoSync`, off by default, debounced by `server/services/idealoomAutoSync.js`) can only update an existing note — it never deletes, recreates, or resolves a conflict. Backed up in full with the rest of `data/brain/`; the vault notes themselves are the user's Obsidian data and are outside PortOS's snapshot. Adapters: `server/services/idealoomLists.js` (records), `server/services/idealoomObsidian.js` (exchange).
+- Brain threads (the bullet journal of open loops, #7664) — `data/brain/threads/{uuid}/index.json`, one more member of `BRAIN_ENTITY_TYPES`. A *thread* is one tracked topic or commitment (status, priority, next action, due date, tags, markdown notes) plus a bounded `refs` array (≤100) of `{ kind, id, label }` tuples pointing at the PortOS records and external items that belong to it — vocabulary and routes in `server/lib/threadRefKinds.js`, existence/title lookups in `server/services/threadRefs.js`. `file-primary` rather than `db-primary` *against* this doc's default for related records, because Brain is an established file-primary domain whose federation, tombstone, parity and reconcile pipeline is all keyed off `BRAIN_ENTITY_TYPES`: splitting one Brain record kind into Postgres would fork the domain across two backends and require re-implementing every one of those paths. The refs are a bounded per-record array, not a join needing an index, and search is served by the existing `brainSearchIndex` projection. **Federated like every other Brain entity type** — the user's own open loops crossing to the user's own machines on the established Brain channel, the same posture as `ideas` and `projects`; the machine-local carve-out `idealoomLists.js` uses does NOT apply, because a bullet journal that exists only on one laptop is useless. `source`, `externalState` and `closedAt` are server-managed (no key in the write schemas, so Zod strips a client copy). No `schemaVersions.js` bump and no store migration: brain is intentionally ungated there and `collectionStore` creates its directory lazily. Empty `data.reference/brain/threads.json` seed. Adapters: `server/services/brainStorage.js` (records) and `server/routes/brainThreads.js` (API).
- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.
- Tailcat peer forwards — `data/tailcat-forwards.json`. `file-primary`, **intentionally machine-local — never federated**: each row stores the bearer `tc…` address needed to restart `tailcat forward` after a PortOS reboot or to retry one that failed to start, plus the local/remote port mapping, the optional peer Basic credential, and the last (redacted) startup error. A row is written *before* the forward is attempted, so a failed add stays retryable instead of discarding the operator's pasted capability. The capability must not cross the wire, reach an API response, or appear in logs in full — `listTailcatForwards()` returns only the redacted form (see [features/tailcat-peers.md](./features/tailcat-peers.md)). No sync cursor or tombstone. Adapter: `server/services/tailcatPeer.js`.
- Tailcat serve — `data/tailcat-serve.json`. `file-primary`, **intentionally machine-local — never federated**: enabled flag, status, local remote-ingress port (`5565`, migrated from the legacy main API port), key name (`portos-api`), last (redacted) startup error, and the listen `tc…` address needed to restore `tailcat serve` after reboot and to offer Copy in the Instances UI. Adapter: `server/services/tailcatServe.js`. See [features/tailcat-peers.md](./features/tailcat-peers.md).
diff --git a/server/lib/README.md b/server/lib/README.md
index 9050584ea8..cd4dc58254 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -126,6 +126,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `storyBuilderValidation.js` | Unified Story Builder session/step schemas. |
| `telegramValidation.js` | Telegram bot config + test schemas. |
| `terminalReplay.js` | `stripTerminalQueries(text)` — remove response-soliciting terminal sequences (DSR `ESC[6n`, DA, DECRQM, DECRQSS, OSC colour queries) from the re-attach replay buffer a PTY session hands a newly attached client. A TUI emits `ESC[6n` on nearly every render and the 50KB ring buffer stores PTY output verbatim, so replaying it makes the attaching xterm ANSWER every historical query as input — landing cursor-position reports (`56;3R56;3R…`) on the shell prompt the dead TUI left behind, which then echo back into the same buffer and re-flood on every later attach. Applied on the way out, over the joined buffer, so a sequence split across two stored chunks still matches; live output is untouched because a running TUI must still get its replies. Stateful sequences the replay needs (mouse tracking, bracketed paste, alternate screen, SGR) are deliberately preserved — this is NOT `ansiStrip.js`, which removes every sequence to recover plain text. `createTerminalModeTracker()` — `observe(chunk)` follows the same stream’s DEC private modes (alternate screen, mouse tracking and encoding, bracketed paste, DECCKM, cursor visibility) and `preamble()` re-asserts the ones still in force, prepended to the replay: a TUI declares them ONCE at startup, so a session that overflows the 50KB window would otherwise replay as a normal-buffer, mouse-less terminal and become unscrollable. **`createReplayBuffer({ maxBytes })` is the export callers want** — the ring buffer that owns the bytes and applies both corrections to them (`push(chunk)` records and evicts, `render()` returns what an attaching client is handed); `services/shell.js` holds one per PTY session. The two helpers above are its internals, exported for their own direct tests — reach for the buffer rather than re-composing them by hand. |
+| `threadRefKinds.js` | Brain THREAD ref vocabulary + route table (#7664) — the one `(kind, id)` → label/URL registry in the repo. A *thread* is a tracked topic or commitment (an open loop), never a message thread. `THREAD_REF_KINDS` is the frozen row-per-kind table (brain records, catalog scraps/ingredients, the five app-native creative kinds, goals/apps/messages/CoS tasks, and the external GitHub/GitLab/JIRA/URL kinds); `threadRefUrl(kind, id, context)` builds the deep link and `threadRefLabel(kind)` the chip text, both degrading to `null`/the raw kind for a kind this build does not know so a peer-sourced ref never throws. `isSafeExternalUrl` scheme-guards an external id before it can become an href. Pure (no zod, no db, no services) and re-exported by `client/src/lib/threadRefKinds.js`, which is how `pages/CatalogIngredient.jsx` renders its inbound-ref chips through the same table. Existence/title lookups live in `services/threadRefs.js`; a drift guard fails CI when a kind here has no resolver there. |
## Story & narrative
diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.js
index d6329e0c68..98d9d94856 100644
--- a/server/lib/brainValidation.js
+++ b/server/lib/brainValidation.js
@@ -2,6 +2,7 @@ import { z } from 'zod';
import { partialWithoutDefaults, optionalBooleanMap } from './zodCompat.js';
import { REPO_INTAKE_KEYS } from './repoIntakeActions.js';
import { EFFORT_LEVELS } from './providerModels.js';
+import { canonicalThreadRefKind } from './threadRefKinds.js';
import { MAX_QUALITY } from './spacedRepetition.js';
// Destination enum. `links` is reachable only from the bare-URL capture
@@ -781,6 +782,103 @@ export const songAttachmentUploadSchema = z.object({
label: z.string().max(300).optional().default('')
});
+// =============================================================================
+// THREAD SCHEMAS (/api/brain/threads/*)
+// =============================================================================
+//
+// A Brain *thread* is one tracked topic or commitment — an open loop in the
+// bullet-journal sense, NOT a message thread (see server/lib/threadRefKinds.js).
+//
+// `source`, `externalState` and `closedAt` are SERVER-managed: they have no key
+// in the write schemas below, so Zod's unknown-key stripping drops a
+// client-supplied value. `source` records where an auto-discovered thread came
+// from, `externalState` what the tracker last said, and `closedAt` is stamped by
+// the route when the status enters a terminal state.
+
+export const threadStatusEnum = z.enum(['open', 'waiting', 'someday', 'done', 'archived']);
+export const threadPriorityEnum = z.enum(['low', 'normal', 'high', 'urgent']);
+
+// Statuses that mean the loop is shut. The route stamps/clears `closedAt` on
+// this set so "when did I finish it" is answerable without scanning history.
+export const THREAD_TERMINAL_STATUSES = Object.freeze(['done', 'archived']);
+
+// A ref's `kind` is validated as a SHAPE, not against THREAD_REF_KIND_IDS. A
+// peer running newer code can sync a thread naming a kind this build has never
+// heard of, and a strict enum would reject the user's own record on the next
+// local edit; `resolveThreadRefs` degrades an unrecognized kind to
+// `{ resolved: false, reason: 'unknown-kind' }` instead. The pattern still
+// rejects a typo'd free-text kind and anything that could confuse a route param.
+// Canonicalized BEFORE the shape check so a legacy spelling a catalog ref row
+// still carries (`writersRoom`) is accepted and STORED canonically, rather than
+// 400ing on the slug pattern and stranding the attach.
+const threadRefKindValue = z.preprocess(
+ (value) => canonicalThreadRefKind(value),
+ z.string().trim().min(1).max(40)
+ .regex(/^[a-z0-9]+([-.][a-z0-9]+)*$/, 'kind must be a lowercase dot/dash slug'),
+);
+
+// An external ref's id IS its URL (up to 2000 chars), which is why this is not
+// bounded to an id-sized string.
+export const threadRefSchema = z.object({
+ kind: threadRefKindValue,
+ id: z.string().trim().min(1).max(2000),
+ // Cached display string so rendering a list of threads never fans out to N
+ // resolvers. Advisory only — `resolveThreadRefs` prefers what the live target
+ // says and falls back to this.
+ label: z.string().trim().max(300).optional().default('')
+}).strict();
+
+export const threadInputSchema = z.object({
+ title: z.string().trim().min(1).max(200),
+ status: threadStatusEnum.optional().default('open'),
+ priority: threadPriorityEnum.optional().default('normal'),
+ // The ONE concrete next step. Empty is meaningful ("nothing to do right now"),
+ // so it is a default rather than a required field.
+ nextAction: z.string().trim().max(500).optional().default(''),
+ notes: z.string().max(20000).optional().default(''),
+ waitingOn: z.string().trim().max(200).optional().default(''),
+ // Null is the explicit "no due date" value and must stay reachable on a PUT:
+ // threadUpdateSchema strips the default, so an OMITTED key preserves the
+ // stored date while an explicit `null` clears it (the absent-vs-empty rule).
+ dueAt: z.string().datetime().nullable().optional().default(null),
+ tags: z.array(z.string().trim().min(1).max(50)).max(50).optional().default([]),
+ pinned: z.boolean().optional().default(false),
+ // Bounded: a thread is a tracked topic, not a graph. 100 is the same ceiling
+ // the resolver's per-tuple probing is sized for.
+ refs: z.array(threadRefSchema).max(100).optional().default([])
+});
+
+// PUT /api/brain/threads/:id — defaults-free partial, so an omitted key
+// preserves the stored value instead of resetting it to its default.
+export const threadUpdateSchema = partialWithoutDefaults(threadInputSchema);
+
+// GET /api/brain/threads — list filters. `limit`/`offset` are absent on purpose:
+// `isPaginationRequested`/`paginateArray` read them straight off req.query, and
+// coercing them here would make every request look paginated.
+export const threadQuerySchema = z.object({
+ status: threadStatusEnum.optional(),
+ priority: threadPriorityEnum.optional(),
+ tag: z.string().trim().min(1).max(50).optional(),
+ refKind: threadRefKindValue.optional(),
+ // Tri-state on purpose: absent = don't filter, 'true'/'false' = filter to that
+ // value. A bare `?pinned` (empty string) reads as true, matching how the UI
+ // would emit a flag-shaped param.
+ pinned: z.enum(['true', 'false', '']).optional(),
+ q: z.string().trim().max(200).optional()
+});
+
+// POST /api/brain/threads/:id/refs — attach one ref to an existing thread.
+export const threadRefInputSchema = threadRefSchema;
+
+// POST /api/brain/threads/attach — attach a ref to an existing thread, or mint
+// one and attach, in a single call. `threadId` picks the target; without it a
+// new thread is created titled `title` (falling back to the ref's label).
+export const threadAttachSchema = z.object({
+ ref: threadRefSchema,
+ threadId: z.string().trim().min(1).max(128).optional(),
+ title: z.string().trim().min(1).max(200).optional()
+}).strict();
+
// =============================================================================
// YOUTUBE INGEST SCHEMAS (POST /api/brain/youtube/*)
// =============================================================================
diff --git a/server/lib/index.js b/server/lib/index.js
index e1350ccc29..6a4ea09ea5 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -77,6 +77,7 @@ export * from './validation.js';
// import (leaf module, no cycle). Flat because `validation.js` re-exports the
// same objects — same identity, so the collision detector is satisfied.
export * from './sharedSchemas.js';
+export * from './threadRefKinds.js';
export * from './threejsModel.js';
export * from './threejsModelAnimation.js';
export * from './threejsModelCoverage.js';
diff --git a/server/lib/threadRefKinds.js b/server/lib/threadRefKinds.js
new file mode 100644
index 0000000000..84556da7b6
--- /dev/null
+++ b/server/lib/threadRefKinds.js
@@ -0,0 +1,174 @@
+/**
+ * Thread ref VOCABULARY — the one `(kind, id)` → label/route table (#7664).
+ *
+ * A Brain *thread* is a tracked topic or commitment (an open loop in the bullet
+ * journal sense) — NOT a message thread. `messageSync.js` / `messageGmailSync.js`
+ * / `beeperSync.js` own that other sense of the word; nothing here touches it.
+ *
+ * A thread carries `refs: [{ kind, id, label? }]` pointing at the PortOS records
+ * and external items that belong to it. This module is the single source of
+ * truth for WHICH kinds exist and WHERE each one deep-links to — add a row here
+ * and `server/services/threadRefs.js` must gain a matching resolver (a drift
+ * guard fails CI otherwise).
+ *
+ * Deliberately PURE — no db, no services, no zod. `server/lib` may not import
+ * upward into `server/services` (see lib/taskTargetScope.js), and the client
+ * re-exports this leaf (`client/src/lib/threadRefKinds.js`) so the catalog
+ * ingredient page renders its inbound-ref chips through the SAME table instead
+ * of its own local switch. Existence/title lookups — everything that needs a
+ * store — live in the service.
+ *
+ * Shape of a row:
+ * label human name for the chip / group heading
+ * external true = the id IS an off-PortOS URL; no local target to probe
+ * navPath the NAV_COMMANDS page this kind lands on (guard-checked)
+ * basePath URL prefix for a per-record deep link (defaults to navPath;
+ * must start with navPath so the link stays on that page)
+ * segment true = append `/<id>` to basePath
+ * suffix appended after the id segment (e.g. an issue's default stage)
+ * param append `?<param>=<id>` instead of a path segment
+ * contextSegment a context key inserted as a path segment BEFORE the id
+ * (catalog ingredients live at /catalog/:type/:id, and the type
+ * is only known once the record is resolved)
+ *
+ * A kind with none of segment/param/contextSegment deep-links to its page only —
+ * that page has no per-record route yet. That is the pre-existing behavior of
+ * the catalog page's `writers-room` arm, kept rather than invented.
+ */
+
+export const THREAD_REF_KINDS = Object.freeze({
+ // ─── Brain records ───────────────────────────────────────────────────────
+ // Most Brain tabs keep their selection in local state rather than the URL, so
+ // there is no per-record route to point at yet; those land on the tab. The
+ // Daily Log is the exception — it is date-addressed (`?date=`), and a journal
+ // record's id IS its date key (brainJournal keys entries by date).
+ 'brain.idea': { label: 'Idea', external: false, navPath: '/brain/ideas' },
+ 'brain.project': { label: 'Project', external: false, navPath: '/brain/memory' },
+ 'brain.person': { label: 'Person', external: false, navPath: '/brain/memory' },
+ 'brain.admin': { label: 'Admin', external: false, navPath: '/brain/memory' },
+ 'brain.memory': { label: 'Memory', external: false, navPath: '/brain/memory' },
+ 'brain.link': { label: 'Link', external: false, navPath: '/brain/links' },
+ 'brain.journal': { label: 'Journal', external: false, navPath: '/brain/daily-log', param: 'date' },
+ 'brain.song': { label: 'Song', external: false, navPath: '/songbook', segment: true },
+
+ // ─── Creative catalog ────────────────────────────────────────────────────
+ 'catalog.scrap': { label: 'Scrap', external: false, navPath: '/catalog/ingest' },
+ 'catalog.ingredient': {
+ label: 'Ingredient',
+ external: false,
+ navPath: '/catalog',
+ segment: true,
+ contextSegment: 'catalogType',
+ },
+
+ // ─── App-native creative records ─────────────────────────────────────────
+ // These five are the vocabulary `catalog_ingredient_refs` already stores
+ // (server/services/catalogRefResolver.js REF_TARGET_TABLES). Their routes
+ // moved here from the hard-coded switch in client/src/pages/CatalogIngredient.jsx
+ // so there is exactly one kind→route table in the repo.
+ universe: { label: 'Universes', external: false, navPath: '/universes', segment: true },
+ series: { label: 'Series', external: false, navPath: '/pipeline', basePath: '/pipeline/series', segment: true },
+ issue: { label: 'Issues', external: false, navPath: '/pipeline', basePath: '/pipeline/issues', segment: true, suffix: '/concept' },
+ 'creative-director': { label: 'Creative Director', external: false, navPath: '/creative-director', segment: true, suffix: '/overview' },
+ 'writers-room': { label: "Writers' Room", external: false, navPath: '/writers-room' },
+
+ // ─── Other PortOS records ────────────────────────────────────────────────
+ goal: { label: 'Goal', external: false, navPath: '/goals/list', segment: true },
+ app: { label: 'App', external: false, navPath: '/apps', segment: true },
+ message: { label: 'Message', external: false, navPath: '/messages/inbox' },
+ 'cos.task': { label: 'Task', external: false, navPath: '/cos/tasks' },
+
+ // ─── External items ──────────────────────────────────────────────────────
+ // The id IS the canonical URL, so it is self-describing across machines and
+ // needs no local lookup. `threadRefUrl` scheme-guards it before it can become
+ // an href (see below).
+ 'github.issue': { label: 'GitHub issue', external: true },
+ 'gitlab.issue': { label: 'GitLab issue', external: true },
+ 'jira.issue': { label: 'JIRA issue', external: true },
+ url: { label: 'Link', external: true },
+});
+
+/** Every kind this build knows about. */
+export const THREAD_REF_KIND_IDS = Object.freeze(Object.keys(THREAD_REF_KINDS));
+
+/** The kinds whose target lives in this install (a resolver must exist). */
+export const INTERNAL_THREAD_REF_KINDS = Object.freeze(
+ THREAD_REF_KIND_IDS.filter((kind) => !THREAD_REF_KINDS[kind].external),
+);
+
+/** The kinds whose id is an off-PortOS URL. */
+export const EXTERNAL_THREAD_REF_KINDS = Object.freeze(
+ THREAD_REF_KIND_IDS.filter((kind) => THREAD_REF_KINDS[kind].external),
+);
+
+// Legacy spellings a stored ref (or a catalog ref row written before the
+// vocabulary settled) can still carry. Resolved to the canonical kind on read
+// so an old record keeps rendering; nothing WRITES these.
+const KIND_ALIASES = Object.freeze({
+ writersRoom: 'writers-room',
+});
+
+/**
+ * The canonical kind id for a possibly-aliased spelling, or the input unchanged.
+ * Never throws — an unknown kind stays unknown so the caller can degrade it.
+ */
+export function canonicalThreadRefKind(kind) {
+ if (typeof kind !== 'string') return kind;
+ return KIND_ALIASES[kind] || kind;
+}
+
+/**
+ * Display label for a kind. An unrecognized kind (a peer on newer code can sync
+ * one) renders as its own id rather than throwing or reading as empty.
+ */
+export function threadRefLabel(kind) {
+ const canonical = canonicalThreadRefKind(kind);
+ return THREAD_REF_KINDS[canonical]?.label || (typeof kind === 'string' ? kind : '');
+}
+
+// Only these schemes may become an href. A stored ref is user- OR peer-supplied
+// text, so `javascript:`/`data:` must never reach the DOM as a link.
+const SAFE_EXTERNAL_SCHEMES = new Set(['http:', 'https:']);
+
+/**
+ * Is this a link-safe absolute URL? Exported because both the URL builder and
+ * the write-schema guard need the same answer.
+ */
+export function isSafeExternalUrl(value) {
+ // `canParse` is false for anything that isn't ABSOLUTE, which is the right
+ // answer here: a relative string is not a usable external ref.
+ if (typeof value !== 'string' || !URL.canParse(value)) return false;
+ return SAFE_EXTERNAL_SCHEMES.has(new URL(value).protocol);
+}
+
+/**
+ * The click-through URL for one ref, or `null` when this build can't build one
+ * (unknown kind, missing id, or an external id that isn't a safe http(s) URL).
+ * Callers render the chip without a link on null — the pre-existing contract of
+ * the catalog page's `refPath`.
+ *
+ * `context` supplies the extra segment a kind declares via `contextSegment`
+ * (currently only a catalog ingredient's `catalogType`, which is known only once
+ * the record has been looked up). Without it the link degrades to the kind's
+ * page rather than producing a route that would 404.
+ */
+export function threadRefUrl(kind, id, context = {}) {
+ const canonical = canonicalThreadRefKind(kind);
+ const spec = THREAD_REF_KINDS[canonical];
+ if (!spec || typeof id !== 'string' || !id) return null;
+
+ if (spec.external) return isSafeExternalUrl(id) ? id : null;
+
+ const basePath = spec.basePath || spec.navPath;
+ if (spec.param) return `${basePath}?${spec.param}=${encodeURIComponent(id)}`;
+ if (!spec.segment) return basePath;
+
+ if (spec.contextSegment) {
+ const extra = context?.[spec.contextSegment];
+ // No context yet (an unresolved or not-yet-hydrated ref) — land on the page
+ // rather than emitting `/catalog/undefined/<id>`.
+ if (typeof extra !== 'string' || !extra) return basePath;
+ return `${basePath}/${encodeURIComponent(extra)}/${encodeURIComponent(id)}${spec.suffix || ''}`;
+ }
+ return `${basePath}/${encodeURIComponent(id)}${spec.suffix || ''}`;
+}
diff --git a/server/lib/threadRefKinds.test.js b/server/lib/threadRefKinds.test.js
new file mode 100644
index 0000000000..a6117083ae
--- /dev/null
+++ b/server/lib/threadRefKinds.test.js
@@ -0,0 +1,121 @@
+import { describe, it, expect } from 'vitest';
+import {
+ THREAD_REF_KINDS,
+ THREAD_REF_KIND_IDS,
+ INTERNAL_THREAD_REF_KINDS,
+ EXTERNAL_THREAD_REF_KINDS,
+ canonicalThreadRefKind,
+ isSafeExternalUrl,
+ threadRefLabel,
+ threadRefUrl,
+} from './threadRefKinds.js';
+import { NAV_COMMANDS } from './navManifest.js';
+
+// Every page the manifest knows about, query strings stripped (a nav row may be
+// declared as a `?settings=1` variant of the same page path).
+const NAV_PATHS = new Set(NAV_COMMANDS.map((c) => c.path.split('?')[0]));
+
+describe('threadRefKinds — registry shape', () => {
+ it('every kind carries a label and splits cleanly into internal/external', () => {
+ for (const [kind, spec] of Object.entries(THREAD_REF_KINDS)) {
+ expect(typeof spec.label, `${kind}.label`).toBe('string');
+ expect(spec.label.length, `${kind}.label`).toBeGreaterThan(0);
+ expect(typeof spec.external, `${kind}.external`).toBe('boolean');
+ }
+ expect([...INTERNAL_THREAD_REF_KINDS, ...EXTERNAL_THREAD_REF_KINDS].sort())
+ .toEqual([...THREAD_REF_KIND_IDS].sort());
+ });
+
+ // The acceptance guard from #7664: a link this table produces has to land on a
+ // page the app actually routes. Without it a renamed page leaves ref chips
+ // pointing at a 404 and nothing fails.
+ it('every internal kind lands on a real NAV_COMMANDS page', () => {
+ for (const kind of INTERNAL_THREAD_REF_KINDS) {
+ const spec = THREAD_REF_KINDS[kind];
+ expect(NAV_PATHS.has(spec.navPath), `${kind} → ${spec.navPath}`).toBe(true);
+ // A per-record deep link may go DEEPER than the nav row, but it must stay
+ // on that page — `/pipeline/series/:id` under `/pipeline`, never elsewhere.
+ const url = threadRefUrl(kind, 'target-id', { catalogType: 'character' });
+ expect(url?.startsWith(spec.navPath), `${kind} → ${url}`).toBe(true);
+ }
+ });
+
+ it('external kinds declare no route — their id IS the URL', () => {
+ for (const kind of EXTERNAL_THREAD_REF_KINDS) {
+ expect(THREAD_REF_KINDS[kind].navPath, kind).toBeUndefined();
+ }
+ });
+});
+
+describe('threadRefUrl', () => {
+ it('builds the four internal link shapes', () => {
+ // page-only (no per-record route exists yet)
+ expect(threadRefUrl('writers-room', 'w1')).toBe('/writers-room');
+ // path segment
+ expect(threadRefUrl('universe', 'u1')).toBe('/universes/u1');
+ // segment + suffix (an issue opens on its first stage)
+ expect(threadRefUrl('issue', 'i1')).toBe('/pipeline/issues/i1/concept');
+ // query param (the Daily Log is date-addressed and a journal id IS its date)
+ expect(threadRefUrl('brain.journal', '2026-09-19')).toBe('/brain/daily-log?date=2026-09-19');
+ });
+
+ it('encodes an id that would otherwise escape its segment or param', () => {
+ expect(threadRefUrl('universe', 'a/b?c')).toBe('/universes/a%2Fb%3Fc');
+ expect(threadRefUrl('brain.journal', 'a&b=c')).toBe('/brain/daily-log?date=a%26b%3Dc');
+ });
+
+ it('uses the resolved catalog type as the ingredient route segment', () => {
+ expect(threadRefUrl('catalog.ingredient', 'ing-1', { catalogType: 'character' }))
+ .toBe('/catalog/character/ing-1');
+ });
+
+ it('degrades an ingredient with no resolved type to the catalog page', () => {
+ // The alternative is `/catalog/undefined/ing-1`, which 404s. An unhydrated
+ // ref still deserves a link that works.
+ expect(threadRefUrl('catalog.ingredient', 'ing-1')).toBe('/catalog');
+ });
+
+ it('returns null rather than throwing for a kind this build does not know', () => {
+ // A peer on newer code can sync a thread naming a kind added after this
+ // build shipped; the chip renders unlinked instead of crashing the page.
+ expect(threadRefUrl('some.future.kind', 'x')).toBeNull();
+ expect(threadRefUrl('universe', '')).toBeNull();
+ expect(threadRefUrl('universe', undefined)).toBeNull();
+ });
+
+ it('passes an external id through only when it is a link-safe URL', () => {
+ expect(threadRefUrl('github.issue', 'https://github.com/o/r/issues/1'))
+ .toBe('https://github.com/o/r/issues/1');
+ // The injection this guard exists for: a stored ref is user- or peer-supplied
+ // text, and these must never become an href.
+ expect(threadRefUrl('url', 'javascript:alert(1)')).toBeNull();
+ expect(threadRefUrl('url', 'data:text/html,<script>')).toBeNull();
+ expect(threadRefUrl('url', '/relative/path')).toBeNull();
+ expect(threadRefUrl('url', 'not a url')).toBeNull();
+ });
+});
+
+describe('isSafeExternalUrl', () => {
+ it('accepts http(s) absolute URLs and nothing else', () => {
+ expect(isSafeExternalUrl('http://example.com')).toBe(true);
+ expect(isSafeExternalUrl('https://example.com/a?b=c#d')).toBe(true);
+ expect(isSafeExternalUrl('ftp://example.com')).toBe(false);
+ expect(isSafeExternalUrl('javascript:alert(1)')).toBe(false);
+ expect(isSafeExternalUrl('')).toBe(false);
+ expect(isSafeExternalUrl(null)).toBe(false);
+ });
+});
+
+describe('threadRefLabel / canonicalThreadRefKind', () => {
+ it('resolves the legacy writersRoom spelling to the canonical kind', () => {
+ // Catalog ref rows written before the vocabulary settled still carry this.
+ expect(canonicalThreadRefKind('writersRoom')).toBe('writers-room');
+ expect(threadRefLabel('writersRoom')).toBe("Writers' Room");
+ expect(threadRefUrl('writersRoom', 'w1')).toBe('/writers-room');
+ });
+
+ it('falls back to the raw kind rather than rendering empty', () => {
+ expect(threadRefLabel('some.future.kind')).toBe('some.future.kind');
+ expect(threadRefLabel(undefined)).toBe('');
+ });
+});
diff --git a/server/routes/brain.js b/server/routes/brain.js
index e9cc1e8ecc..333b040337 100644
--- a/server/routes/brain.js
+++ b/server/routes/brain.js
@@ -17,6 +17,7 @@ import syncRoutes from './brainSync.js';
import dailyLogRoutes from './brainDailyLog.js';
import onThisDayRoutes from './brainOnThisDay.js';
import songbookRoutes from './brainSongbook.js';
+import threadRoutes from './brainThreads.js';
import youtubeRoutes from './brainYoutube.js';
import ideaLoomRoutes from './brainIdeaLoom.js';
@@ -34,6 +35,7 @@ router.use(syncRoutes);
router.use(dailyLogRoutes);
router.use(onThisDayRoutes);
router.use('/songbook', songbookRoutes);
+router.use('/threads', threadRoutes);
router.use('/youtube', youtubeRoutes);
export default router;
diff --git a/server/routes/brainThreads.js b/server/routes/brainThreads.js
new file mode 100644
index 0000000000..baf83dccc8
--- /dev/null
+++ b/server/routes/brainThreads.js
@@ -0,0 +1,259 @@
+/**
+ * Brain Threads Routes — the bullet journal's open loops (#7664).
+ *
+ * A *thread* here is one tracked topic or commitment: a status, a next action,
+ * and the set of PortOS records and external items that belong to it. It is NOT
+ * a message thread — `messageSync.js` / `messageGmailSync.js` / `beeperSync.js`
+ * own that sense of the word and nothing in this file touches them.
+ *
+ * Stored as the Brain entity type `threads`, so every write rides brainStorage's
+ * generic API and inherits the sync-log / LWW / tombstone federation pipeline
+ * with no wire-version bump (brain is intentionally ungated in schemaVersions).
+ *
+ * Mounted from the brain barrel at /threads → /api/brain/threads/...
+ *
+ * `source`, `externalState` and `closedAt` are server-managed: the write schemas
+ * have no key for them, so Zod's unknown-key stripping drops a client-supplied
+ * value (the brainSongbook.js `practice`/`attachments` convention). `source` and
+ * `externalState` exist for the auto-ingest sync that lands later; this file
+ * only ever births them at their neutral values and stamps `closedAt` when the
+ * status enters a terminal state.
+ *
+ * Ref writes go through `updateWith` so two attach clicks — or an attach racing
+ * a peer-sync apply — merge against the freshest record instead of clobbering.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';
+import {
+ threadInputSchema,
+ threadUpdateSchema,
+ threadQuerySchema,
+ threadRefInputSchema,
+ threadAttachSchema,
+ THREAD_TERMINAL_STATUSES,
+} from '../lib/brainValidation.js';
+import { canonicalThreadRefKind } from '../lib/threadRefKinds.js';
+import * as brainStorage from '../services/brainStorage.js';
+import { resolveThreadRefs } from '../services/threadRefs.js';
+
+const router = Router();
+
+function requireThread(thread) {
+ if (!thread) {
+ throw new ServerError('Thread not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ return thread;
+}
+
+const isTerminal = (status) => THREAD_TERMINAL_STATUSES.includes(status);
+
+/**
+ * `closedAt` for a record whose status is MOVING to `nextStatus`.
+ *
+ * Stamped on the transition into a terminal status and cleared on the way out,
+ * but PRESERVED when the record was already terminal — re-saving a done thread
+ * must not rewrite when it was finished.
+ */
+function resolveClosedAt(previous, nextStatus, now) {
+ if (!isTerminal(nextStatus)) return null;
+ return isTerminal(previous?.status) && previous?.closedAt ? previous.closedAt : now;
+}
+
+// Identity of one ref. JSON-stringify so the two fields join on an unambiguous,
+// PRINTABLE delimiter — no in-band separator a ref id could itself contain, and
+// no non-printable byte (catalogRefResolver.js sets that rule).
+const refKey = (ref) => JSON.stringify([canonicalThreadRefKind(ref?.kind), ref?.id]);
+
+/**
+ * Append `ref` to `existing`, replacing a same-`(kind, id)` entry in place.
+ *
+ * In-place rather than move-to-end so attaching a ref twice (a double click, or
+ * an attach racing a peer apply) is idempotent in ORDER as well as content —
+ * two peers that both re-attach converge on the same array.
+ */
+function mergeRef(existing, ref) {
+ // `ref` is already schema-canonical (threadRefKindValue canonicalizes before
+ // validating); `refKey` canonicalizes the STORED side, which may predate an
+ // alias or have arrived from a peer.
+ const refs = Array.isArray(existing) ? existing : [];
+ const at = refs.findIndex((r) => refKey(r) === refKey(ref));
+ if (at === -1) return [...refs, ref];
+ const merged = [...refs];
+ merged[at] = ref;
+ return merged;
+}
+
+// The list projection: everything the Threads list and the dashboard widget
+// render, minus the markdown body. `notes` is capped at 20k per thread, so a
+// few hundred open loops would ship megabytes nobody reads; the full record
+// comes from GET /:id.
+const toListRow = ({ notes, ...rest }) => rest;
+
+// Case-insensitive substring match over the fields a user would expect `?q=` to
+// search. `notes` IS searched even though the list projection drops it — the
+// filter runs on the full record, and finding a thread by something written in
+// its body is the point of a search box.
+function matchesQuery(thread, q) {
+ const needle = q.toLowerCase();
+ const haystack = [
+ thread.title, thread.nextAction, thread.waitingOn, thread.notes,
+ ...(Array.isArray(thread.tags) ? thread.tags : []),
+ ...(Array.isArray(thread.refs) ? thread.refs.map((r) => r?.label) : []),
+ ];
+ return haystack.some((v) => typeof v === 'string' && v.toLowerCase().includes(needle));
+}
+
+// Sort key for the due date: a thread with no due date sorts AFTER every dated
+// one rather than poisoning the comparator with NaN.
+const dueSortKey = (thread) => {
+ const t = Date.parse(thread?.dueAt ?? '');
+ return Number.isNaN(t) ? Infinity : t;
+};
+
+// Pinned first, then soonest-due, then most recently touched, with the id as a
+// deterministic tiebreak — a stable order matters because the list paginates,
+// and an unstable one drops or duplicates rows at the slice boundary.
+function compareThreads(a, b) {
+ if (Boolean(b.pinned) !== Boolean(a.pinned)) return Boolean(b.pinned) - Boolean(a.pinned);
+ const due = dueSortKey(a) - dueSortKey(b);
+ if (due !== 0) return due;
+ const touched = Date.parse(b?.updatedAt ?? '') - Date.parse(a?.updatedAt ?? '');
+ if (!Number.isNaN(touched) && touched !== 0) return touched;
+ return String(a.id).localeCompare(String(b.id));
+}
+
+// =============================================================================
+// ATTACH (before /:id routes so 'attach' is never treated as an id)
+// =============================================================================
+
+// POST /attach — `{ ref, threadId?, title? }`. Attaches to an existing thread,
+// or mints one and attaches, in a single call: the one-click affordance every
+// "add this to a thread" button posts, without making the caller choose between
+// create and update first.
+router.post('/attach', asyncHandler(async (req, res) => {
+ const { ref, threadId, title } = validateRequest(threadAttachSchema, req.body);
+
+ if (threadId) {
+ const thread = requireThread(await brainStorage.updateWith('threads', threadId,
+ (fresh) => ({ refs: mergeRef(fresh.refs, ref) })));
+ console.log(`🧵 Attached ${ref.kind} ref to thread "${thread.title}"`);
+ return res.json({ thread, created: false });
+ }
+
+ const now = new Date().toISOString();
+ const data = validateRequest(threadInputSchema, {
+ title: title || ref.label || ref.id,
+ refs: [ref],
+ });
+ const thread = await brainStorage.create('threads', {
+ ...data,
+ source: null,
+ externalState: 'unknown',
+ closedAt: resolveClosedAt(null, data.status, now),
+ });
+ console.log(`🧵 Created thread "${thread.title}" from a ${ref.kind} ref`);
+ return res.status(201).json({ thread, created: true });
+}));
+
+// =============================================================================
+// THREAD CRUD
+// =============================================================================
+
+router.get('/', asyncHandler(async (req, res) => {
+ const filters = validateRequest(threadQuerySchema, req.query);
+ const all = await brainStorage.getAll('threads');
+
+ const matching = all.filter((thread) => {
+ if (filters.status && thread.status !== filters.status) return false;
+ if (filters.priority && thread.priority !== filters.priority) return false;
+ // A bare `?pinned` arrives as '' and reads as true; 'false' filters to the
+ // unpinned set. Absent means "don't filter" (the tri-state in the schema).
+ if (filters.pinned !== undefined && Boolean(thread.pinned) !== (filters.pinned !== 'false')) return false;
+ if (filters.tag && !(Array.isArray(thread.tags) && thread.tags.includes(filters.tag))) return false;
+ if (filters.refKind) {
+ const wanted = canonicalThreadRefKind(filters.refKind);
+ const refs = Array.isArray(thread.refs) ? thread.refs : [];
+ if (!refs.some((r) => canonicalThreadRefKind(r?.kind) === wanted)) return false;
+ }
+ if (filters.q && !matchesQuery(thread, filters.q)) return false;
+ return true;
+ }).sort(compareThreads);
+
+ const rows = matching.map(toListRow);
+ if (isPaginationRequested(req.query)) {
+ const { items, total, limit, offset } = paginateArray(rows, req.query);
+ return res.json({ threads: items, total, limit, offset });
+ }
+ return res.json({ threads: rows, total: rows.length });
+}));
+
+router.get('/:id', asyncHandler(async (req, res) => {
+ const thread = requireThread(await brainStorage.getById('threads', req.params.id));
+ // Hydrated for display only — the stored `refs` array is untouched, so a
+ // target this build can't resolve still round-trips through a later write.
+ res.json({ ...thread, resolvedRefs: await resolveThreadRefs(thread.refs) });
+}));
+
+router.post('/', asyncHandler(async (req, res) => {
+ const data = validateRequest(threadInputSchema, req.body);
+ const thread = await brainStorage.create('threads', {
+ ...data,
+ // Born unsourced: only the auto-ingest sync sets `source`, and only it knows
+ // what a tracker last said about the item.
+ source: null,
+ externalState: 'unknown',
+ closedAt: resolveClosedAt(null, data.status, new Date().toISOString()),
+ });
+ console.log(`🧵 Created thread: "${thread.title}" (${thread.status})`);
+ res.status(201).json(thread);
+}));
+
+router.put('/:id', asyncHandler(async (req, res) => {
+ // threadUpdateSchema is defaults-free, so an omitted field is genuinely absent
+ // instead of resetting to its default, and it has no key for the
+ // server-managed trio — Zod's unknown-key stripping drops a client copy.
+ const data = validateRequest(threadUpdateSchema, req.body);
+ const now = new Date().toISOString();
+ // Derive closedAt inside the store write lock, against the FRESH record: the
+ // stamp depends on the status the thread is coming FROM, and reading that
+ // before the lock would race a concurrent edit or a peer-sync apply.
+ const thread = requireThread(await brainStorage.updateWith('threads', req.params.id, (fresh) => (
+ data.status === undefined
+ ? data
+ : { ...data, closedAt: resolveClosedAt(fresh, data.status, now) }
+ )));
+ res.json(thread);
+}));
+
+router.delete('/:id', asyncHandler(async (req, res) => {
+ // Tombstone delete so the deletion federates rather than resurrecting from a
+ // peer that still holds the record.
+ requireThread(await brainStorage.remove('threads', req.params.id));
+ res.json({ id: req.params.id });
+}));
+
+// =============================================================================
+// REFS
+// =============================================================================
+
+// POST /:id/refs — attach one ref. Idempotent by `(kind, id)`.
+router.post('/:id/refs', asyncHandler(async (req, res) => {
+ const ref = validateRequest(threadRefInputSchema, req.body);
+ const thread = requireThread(await brainStorage.updateWith('threads', req.params.id,
+ (fresh) => ({ refs: mergeRef(fresh.refs, ref) })));
+ res.status(201).json(thread);
+}));
+
+// DELETE /:id/refs/:kind/:refId — detach one ref. `:refId` is URL-encoded by the
+// caller, so an external ref whose id is a full URL survives the round trip.
+router.delete('/:id/refs/:kind/:refId', asyncHandler(async (req, res) => {
+ const target = refKey({ kind: req.params.kind, id: req.params.refId });
+ const thread = requireThread(await brainStorage.updateWith('threads', req.params.id, (fresh) => ({
+ refs: (Array.isArray(fresh.refs) ? fresh.refs : []).filter((r) => refKey(r) !== target),
+ })));
+ res.json(thread);
+}));
+
+export default router;
diff --git a/server/routes/brainThreads.test.js b/server/routes/brainThreads.test.js
new file mode 100644
index 0000000000..d1e92b29db
--- /dev/null
+++ b/server/routes/brainThreads.test.js
@@ -0,0 +1,393 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/brainStorage.js', () => ({
+ getAll: vi.fn(),
+ getById: vi.fn(),
+ create: vi.fn(),
+ updateWith: vi.fn(),
+ remove: vi.fn(),
+}));
+
+// The resolver has its own suite (services/threadRefs.test.js) and reaches
+// Postgres; here it is a seam so these tests assert the ROUTE's contract.
+vi.mock('../services/threadRefs.js', () => ({ resolveThreadRefs: vi.fn() }));
+
+import * as brainStorage from '../services/brainStorage.js';
+import { resolveThreadRefs } from '../services/threadRefs.js';
+import threadRoutes from './brainThreads.js';
+
+const THREAD_ID = '11111111-1111-4111-8111-111111111111';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/brain/threads', threadRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+// Mirror updateWith's contract against a given "fresh" record: run the route's
+// fn, capture the partial updates it produced, and return the merged record (or
+// null when the record is gone). `seen.updates` lets a test assert exactly what
+// the route asked to persist.
+const mockUpdateWith = (freshThread) => {
+ const seen = { updates: null };
+ brainStorage.updateWith.mockImplementation(async (type, id, fn) => {
+ if (!freshThread) return null;
+ const updates = await fn({ ...freshThread });
+ seen.updates = updates;
+ return updates ? { ...freshThread, ...updates } : null;
+ });
+ return seen;
+};
+
+const baseThread = (overrides = {}) => ({
+ id: THREAD_ID,
+ title: 'Renew the domain',
+ status: 'open',
+ priority: 'normal',
+ nextAction: 'Check the registrar',
+ notes: 'Long markdown body',
+ waitingOn: '',
+ dueAt: null,
+ tags: [],
+ pinned: false,
+ refs: [],
+ source: null,
+ externalState: 'unknown',
+ closedAt: null,
+ createdAt: '2026-09-01T00:00:00.000Z',
+ updatedAt: '2026-09-01T00:00:00.000Z',
+ ...overrides,
+});
+
+describe('Brain Threads routes', () => {
+ let app;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resolveThreadRefs.mockResolvedValue([]);
+ app = buildApp();
+ });
+
+ // ===========================================================================
+ // CREATE — server-managed fields
+ // ===========================================================================
+
+ it('creates a thread with the defaults the record shape promises', async () => {
+ brainStorage.create.mockImplementation(async (type, data) => ({ id: THREAD_ID, ...data }));
+ const res = await request(app).post('/api/brain/threads').send({ title: 'Renew the domain' });
+
+ expect(res.status).toBe(201);
+ expect(brainStorage.create).toHaveBeenCalledWith('threads', expect.objectContaining({
+ title: 'Renew the domain',
+ status: 'open',
+ priority: 'normal',
+ nextAction: '',
+ dueAt: null,
+ tags: [],
+ pinned: false,
+ refs: [],
+ }));
+ });
+
+ it('strips the server-managed fields from a client write', async () => {
+ // `source`/`externalState`/`closedAt` belong to the auto-ingest sync. A
+ // client that sets them could forge provenance or backdate a completion.
+ brainStorage.create.mockImplementation(async (type, data) => ({ id: THREAD_ID, ...data }));
+ await request(app).post('/api/brain/threads').send({
+ title: 'Forged',
+ source: { kind: 'github.issue', key: 'o/r#1' },
+ externalState: 'closed',
+ closedAt: '2020-01-01T00:00:00.000Z',
+ });
+
+ const [, persisted] = brainStorage.create.mock.calls[0];
+ expect(persisted.source).toBeNull();
+ expect(persisted.externalState).toBe('unknown');
+ expect(persisted.closedAt).toBeNull();
+ });
+
+ it('stamps closedAt when a thread is born in a terminal status', async () => {
+ brainStorage.create.mockImplementation(async (type, data) => ({ id: THREAD_ID, ...data }));
+ await request(app).post('/api/brain/threads').send({ title: 'Already done', status: 'done' });
+ const [, persisted] = brainStorage.create.mock.calls[0];
+ expect(persisted.closedAt).toEqual(expect.any(String));
+ });
+
+ it('rejects a thread with no title', async () => {
+ const res = await request(app).post('/api/brain/threads').send({ status: 'open' });
+ expect(res.status).toBe(400);
+ expect(brainStorage.create).not.toHaveBeenCalled();
+ });
+
+ // ===========================================================================
+ // UPDATE — partial semantics + closedAt lifecycle
+ // ===========================================================================
+
+ it('persists only the keys a partial update names', async () => {
+ // Defaults-free partial: an omitted key must preserve the stored value
+ // rather than resetting it to its schema default.
+ const seen = mockUpdateWith(baseThread({ priority: 'high', tags: ['ops'] }));
+ const res = await request(app).put(`/api/brain/threads/${THREAD_ID}`)
+ .send({ nextAction: 'Email the registrar' });
+
+ expect(res.status).toBe(200);
+ expect(seen.updates).toEqual({ nextAction: 'Email the registrar' });
+ expect(res.body.priority).toBe('high');
+ expect(res.body.tags).toEqual(['ops']);
+ });
+
+ it('stamps closedAt on the transition into a terminal status', async () => {
+ const seen = mockUpdateWith(baseThread({ status: 'open', closedAt: null }));
+ await request(app).put(`/api/brain/threads/${THREAD_ID}`).send({ status: 'done' });
+ expect(seen.updates.closedAt).toEqual(expect.any(String));
+ });
+
+ it('preserves the original closedAt when a done thread is re-saved', async () => {
+ // Re-saving a finished thread must not rewrite when it was finished.
+ const seen = mockUpdateWith(baseThread({ status: 'done', closedAt: '2026-09-02T00:00:00.000Z' }));
+ await request(app).put(`/api/brain/threads/${THREAD_ID}`).send({ status: 'archived' });
+ expect(seen.updates.closedAt).toBe('2026-09-02T00:00:00.000Z');
+ });
+
+ it('clears closedAt when a thread is reopened', async () => {
+ const seen = mockUpdateWith(baseThread({ status: 'done', closedAt: '2026-09-02T00:00:00.000Z' }));
+ await request(app).put(`/api/brain/threads/${THREAD_ID}`).send({ status: 'open' });
+ expect(seen.updates.closedAt).toBeNull();
+ });
+
+ it('leaves closedAt untouched when the update does not move the status', async () => {
+ const seen = mockUpdateWith(baseThread({ status: 'done', closedAt: '2026-09-02T00:00:00.000Z' }));
+ await request(app).put(`/api/brain/threads/${THREAD_ID}`).send({ title: 'Renamed' });
+ expect(seen.updates).toEqual({ title: 'Renamed' });
+ });
+
+ it('404s an update against a thread that is gone', async () => {
+ mockUpdateWith(null);
+ const res = await request(app).put(`/api/brain/threads/${THREAD_ID}`).send({ title: 'x' });
+ expect(res.status).toBe(404);
+ });
+
+ // ===========================================================================
+ // READ
+ // ===========================================================================
+
+ it('hydrates refs on the detail read without mutating the stored array', async () => {
+ const stored = [{ kind: 'brain.idea', id: 'idea-1', label: 'cached' }];
+ brainStorage.getById.mockResolvedValue(baseThread({ refs: stored }));
+ resolveThreadRefs.mockResolvedValue([
+ { kind: 'brain.idea', id: 'idea-1', label: 'Live title', url: '/brain/ideas', resolved: true },
+ ]);
+
+ const res = await request(app).get(`/api/brain/threads/${THREAD_ID}`);
+ expect(res.status).toBe(200);
+ expect(res.body.resolvedRefs[0].label).toBe('Live title');
+ // The stored array round-trips untouched, so a target this build can't
+ // resolve is not quietly stripped by the next write.
+ expect(res.body.refs).toEqual(stored);
+ });
+
+ it('omits the markdown body from list rows', async () => {
+ brainStorage.getAll.mockResolvedValue([baseThread()]);
+ const res = await request(app).get('/api/brain/threads');
+ expect(res.body.threads[0]).not.toHaveProperty('notes');
+ expect(res.body.threads[0].title).toBe('Renew the domain');
+ });
+
+ it('filters by status, tag, pinned and refKind', async () => {
+ brainStorage.getAll.mockResolvedValue([
+ baseThread({ id: 'a', status: 'open', tags: ['ops'], pinned: true, refs: [{ kind: 'github.issue', id: 'https://example.com/1' }] }),
+ baseThread({ id: 'b', status: 'waiting', tags: ['ops'], pinned: false, refs: [] }),
+ baseThread({ id: 'c', status: 'open', tags: ['home'], pinned: false, refs: [] }),
+ ]);
+
+ const ids = async (qs) => (await request(app).get(`/api/brain/threads${qs}`)).body.threads.map((t) => t.id);
+ expect(await ids('?status=open')).toEqual(['a', 'c']);
+ expect(await ids('?tag=ops')).toEqual(['a', 'b']);
+ expect(await ids('?pinned=true')).toEqual(['a']);
+ expect(await ids('?pinned=false')).toEqual(['b', 'c']);
+ expect(await ids('?refKind=github.issue')).toEqual(['a']);
+ });
+
+ it('searches title, next action and notes with ?q=', async () => {
+ brainStorage.getAll.mockResolvedValue([
+ baseThread({ id: 'a', title: 'Renew the domain', notes: '' }),
+ baseThread({ id: 'b', title: 'Other', nextAction: '', notes: 'registrar paperwork' }),
+ baseThread({ id: 'c', title: 'Other', nextAction: '', notes: '' }),
+ ]);
+ const res = await request(app).get('/api/brain/threads?q=REGISTRAR');
+ expect(res.body.threads.map((t) => t.id)).toEqual(['a', 'b']);
+ });
+
+ it('sorts pinned first, then soonest-due', async () => {
+ brainStorage.getAll.mockResolvedValue([
+ baseThread({ id: 'undated', dueAt: null, pinned: false }),
+ baseThread({ id: 'later', dueAt: '2026-10-01T00:00:00.000Z', pinned: false }),
+ baseThread({ id: 'sooner', dueAt: '2026-09-20T00:00:00.000Z', pinned: false }),
+ baseThread({ id: 'pinned', dueAt: null, pinned: true }),
+ ]);
+ const res = await request(app).get('/api/brain/threads');
+ expect(res.body.threads.map((t) => t.id)).toEqual(['pinned', 'sooner', 'later', 'undated']);
+ });
+
+ it('returns the paginated envelope only when a pagination param is passed', async () => {
+ brainStorage.getAll.mockResolvedValue([baseThread({ id: 'a' }), baseThread({ id: 'b' })]);
+ const plain = await request(app).get('/api/brain/threads');
+ expect(plain.body).not.toHaveProperty('limit');
+ expect(plain.body.total).toBe(2);
+
+ const paged = await request(app).get('/api/brain/threads?limit=1');
+ expect(paged.body).toMatchObject({ total: 2, limit: 1, offset: 0 });
+ expect(paged.body.threads).toHaveLength(1);
+ });
+
+ it('404s a detail read for a thread that does not exist', async () => {
+ brainStorage.getById.mockResolvedValue(null);
+ const res = await request(app).get(`/api/brain/threads/${THREAD_ID}`);
+ expect(res.status).toBe(404);
+ });
+
+ // ===========================================================================
+ // REFS
+ // ===========================================================================
+
+ it('attaches a ref against the fresh record', async () => {
+ const seen = mockUpdateWith(baseThread({ refs: [{ kind: 'brain.idea', id: 'idea-1', label: '' }] }));
+ const res = await request(app).post(`/api/brain/threads/${THREAD_ID}/refs`)
+ .send({ kind: 'github.issue', id: 'https://github.com/o/r/issues/7', label: 'o/r#7' });
+
+ expect(res.status).toBe(201);
+ expect(seen.updates.refs).toEqual([
+ { kind: 'brain.idea', id: 'idea-1', label: '' },
+ { kind: 'github.issue', id: 'https://github.com/o/r/issues/7', label: 'o/r#7' },
+ ]);
+ });
+
+ it('replaces a same-(kind,id) ref in place instead of duplicating it', async () => {
+ // Attaching twice — a double click, or an attach racing a peer apply — must
+ // be idempotent in ORDER as well as content, so two peers converge.
+ const seen = mockUpdateWith(baseThread({
+ refs: [
+ { kind: 'brain.idea', id: 'idea-1', label: 'stale' },
+ { kind: 'app', id: 'app-1', label: 'App' },
+ ],
+ }));
+ await request(app).post(`/api/brain/threads/${THREAD_ID}/refs`)
+ .send({ kind: 'brain.idea', id: 'idea-1', label: 'fresh' });
+
+ expect(seen.updates.refs).toEqual([
+ { kind: 'brain.idea', id: 'idea-1', label: 'fresh' },
+ { kind: 'app', id: 'app-1', label: 'App' },
+ ]);
+ });
+
+ it('detaches a ref whose id is a full URL', async () => {
+ const url = 'https://github.com/o/r/issues/7';
+ const seen = mockUpdateWith(baseThread({
+ refs: [{ kind: 'github.issue', id: url, label: '' }, { kind: 'app', id: 'app-1', label: '' }],
+ }));
+ const res = await request(app)
+ .delete(`/api/brain/threads/${THREAD_ID}/refs/github.issue/${encodeURIComponent(url)}`);
+
+ expect(res.status).toBe(200);
+ expect(seen.updates.refs).toEqual([{ kind: 'app', id: 'app-1', label: '' }]);
+ });
+
+ it('canonicalizes a legacy ref kind on write', async () => {
+ const seen = mockUpdateWith(baseThread());
+ await request(app).post(`/api/brain/threads/${THREAD_ID}/refs`)
+ .send({ kind: 'writersRoom', id: 'w1' });
+ expect(seen.updates.refs[0].kind).toBe('writers-room');
+ });
+
+ it('rejects a ref whose kind is not a slug', async () => {
+ const res = await request(app).post(`/api/brain/threads/${THREAD_ID}/refs`)
+ .send({ kind: 'Not A Kind!', id: 'x' });
+ expect(res.status).toBe(400);
+ expect(brainStorage.updateWith).not.toHaveBeenCalled();
+ });
+
+ it('accepts a kind this build does not know', async () => {
+ // Forward compatibility: a peer on newer code syncs a thread naming a kind
+ // added after this build shipped, and the user must still be able to save
+ // it. The resolver degrades it at render time instead.
+ const seen = mockUpdateWith(baseThread());
+ const res = await request(app).post(`/api/brain/threads/${THREAD_ID}/refs`)
+ .send({ kind: 'some.future.kind', id: 'x' });
+ expect(res.status).toBe(201);
+ expect(seen.updates.refs[0].kind).toBe('some.future.kind');
+ });
+
+ // ===========================================================================
+ // ATTACH
+ // ===========================================================================
+
+ it('attaches to an existing thread when threadId is given', async () => {
+ const seen = mockUpdateWith(baseThread());
+ const res = await request(app).post('/api/brain/threads/attach')
+ .send({ threadId: THREAD_ID, ref: { kind: 'app', id: 'app-1', label: 'PortOS' } });
+
+ expect(res.status).toBe(200);
+ expect(res.body.created).toBe(false);
+ expect(seen.updates.refs).toEqual([{ kind: 'app', id: 'app-1', label: 'PortOS' }]);
+ expect(brainStorage.create).not.toHaveBeenCalled();
+ });
+
+ it('mints a thread and attaches in one call when no threadId is given', async () => {
+ brainStorage.create.mockImplementation(async (type, data) => ({ id: THREAD_ID, ...data }));
+ const res = await request(app).post('/api/brain/threads/attach')
+ .send({ ref: { kind: 'app', id: 'app-1', label: 'PortOS' }, title: 'Ship the app' });
+
+ expect(res.status).toBe(201);
+ expect(res.body.created).toBe(true);
+ expect(res.body.thread).toMatchObject({
+ title: 'Ship the app',
+ status: 'open',
+ refs: [{ kind: 'app', id: 'app-1', label: 'PortOS' }],
+ });
+ });
+
+ it('titles a minted thread from the ref when no title is given', async () => {
+ brainStorage.create.mockImplementation(async (type, data) => ({ id: THREAD_ID, ...data }));
+ const res = await request(app).post('/api/brain/threads/attach')
+ .send({ ref: { kind: 'app', id: 'app-1', label: 'PortOS' } });
+ expect(res.body.thread.title).toBe('PortOS');
+ });
+
+ it('routes /attach to the attach handler, not to /:id', async () => {
+ // The static route has to mount before `/:id`, or "attach" reads as a
+ // thread id and every attach 404s.
+ brainStorage.create.mockImplementation(async (type, data) => ({ id: THREAD_ID, ...data }));
+ const res = await request(app).post('/api/brain/threads/attach')
+ .send({ ref: { kind: 'app', id: 'app-1' } });
+ expect(res.status).toBe(201);
+ });
+
+ it('404s an attach against a thread that is gone', async () => {
+ mockUpdateWith(null);
+ const res = await request(app).post('/api/brain/threads/attach')
+ .send({ threadId: THREAD_ID, ref: { kind: 'app', id: 'app-1' } });
+ expect(res.status).toBe(404);
+ });
+
+ // ===========================================================================
+ // DELETE
+ // ===========================================================================
+
+ it('tombstone-deletes so the deletion federates', async () => {
+ brainStorage.remove.mockResolvedValue({ id: THREAD_ID });
+ const res = await request(app).delete(`/api/brain/threads/${THREAD_ID}`);
+ expect(res.status).toBe(200);
+ expect(brainStorage.remove).toHaveBeenCalledWith('threads', THREAD_ID);
+ });
+
+ it('404s a delete for a thread that does not exist', async () => {
+ brainStorage.remove.mockResolvedValue(null);
+ const res = await request(app).delete(`/api/brain/threads/${THREAD_ID}`);
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 61435f6728..80833c3d60 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -3,7 +3,7 @@
*
* Handles file-based persistence for the Brain feature.
* - Per-record `collectionStore` dirs for entity stores (people, projects,
- * ideas, admin, …, journals, inbox, songs) — `data/brain/<type>/<id>/index.json`
+ * ideas, admin, …, journals, inbox, songs, threads) — `data/brain/<type>/<id>/index.json`
* - JSON for the single `meta.json` settings doc
* - JSONL for append-only generated logs (digests, reviews)
*
@@ -58,7 +58,7 @@ const DATA_DIR = PATHS.brain;
// originInstanceId backfill all cover them with no per-type branching.
export const BRAIN_ENTITY_TYPES = Object.freeze([
'people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets',
- 'journals', 'inbox', 'songs',
+ 'journals', 'inbox', 'songs', 'threads',
]);
// The type-level storage-layout version. Bumped by a migration that changes the
@@ -1150,6 +1150,19 @@ export const updateBucket = (id, data) => update('buckets', id, data);
export const reorderBuckets = (updates) => updateManyWithBatchLog('buckets', updates);
export const deleteBucket = (id) => remove('buckets', id);
+// Threads (#7664)
+//
+// A thread is one tracked topic or commitment — an open loop in the bullet
+// journal sense, NOT a message thread (messageSync.js owns that word too). The
+// accessors are the generic store API under thread-shaped names, exactly like
+// the siblings above; the ref registry that gives a thread its links lives in
+// lib/threadRefKinds.js + services/threadRefs.js.
+export const getThreads = (filters) => filters ? query('threads', filters) : getAll('threads');
+export const getThreadById = (id) => getById('threads', id);
+export const createThread = (data) => create('threads', data);
+export const updateThread = (id, data) => update('threads', id, data);
+export const deleteThread = (id) => remove('threads', id);
+
// =============================================================================
// REMOTE SYNC OPERATIONS (no per-record events, no sync log — echo prevention)
// =============================================================================
diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.js
index 90963a788d..6acd7836a6 100644
--- a/server/services/brainStorage.test.js
+++ b/server/services/brainStorage.test.js
@@ -370,6 +370,42 @@ describe('songs entity enrollment (SongBook)', () => {
});
});
+describe('threads entity enrollment (bullet journal open loops, #7664)', () => {
+ it('lists threads in BRAIN_ENTITY_TYPES so sync/GC/backfill all cover it', () => {
+ // Membership is the WHOLE wiring: the delta log, LWW peer apply, reconcile,
+ // parity audit, tombstone GC and the boot verifier all derive from this list.
+ expect(brainStorage.BRAIN_ENTITY_TYPES).toContain('threads');
+ });
+
+ it('round-trips create → update → tombstone through the generic entity API', async () => {
+ const created = await brainStorage.createThread({
+ title: 'Renew the domain',
+ status: 'open',
+ priority: 'high',
+ nextAction: 'Check the registrar',
+ refs: [{ kind: 'github.issue', id: 'https://example.com/issues/1', label: 'example#1' }],
+ });
+ expect(created.id).toBeDefined();
+ expect(created.originInstanceId).toBe('local-instance');
+
+ const all = await brainStorage.getThreads();
+ expect(all.find((t) => t.id === created.id)).toMatchObject({ title: 'Renew the domain' });
+
+ const updated = await brainStorage.updateThread(created.id, { status: 'waiting' });
+ expect(updated).toMatchObject({ status: 'waiting', priority: 'high' });
+ // The ref array survives a partial update — it is the thread's whole point.
+ expect(updated.refs).toHaveLength(1);
+ expect(await brainStorage.getThreadById(created.id)).toMatchObject({ status: 'waiting' });
+
+ expect(await brainStorage.deleteThread(created.id)).toBe(true);
+ expect(await brainStorage.getThreadById(created.id)).toBeNull();
+ // Tombstone retained in place (not hard-deleted) so the delete federates and
+ // a stale create echoed back from a peer can't resurrect it.
+ const raw = await rawRecord('threads', created.id);
+ expect(raw._deleted).toBe(true);
+ });
+});
+
describe('listLiveIds (embedding-coverage id index, issue #3508)', () => {
it('returns only live ids — archived and tombstoned records are excluded', async () => {
const live = await brainStorage.create('ideas', { title: 'Live Idea' });
diff --git a/server/services/threadRefs.drift.test.js b/server/services/threadRefs.drift.test.js
new file mode 100644
index 0000000000..d4a8af4f64
--- /dev/null
+++ b/server/services/threadRefs.drift.test.js
@@ -0,0 +1,57 @@
+/**
+ * Drift guard: the thread ref VOCABULARY and its RESOLVERS live in two files by
+ * necessity (`server/lib` may not import upward into `server/services`), so
+ * nothing but this test stops someone adding a kind to one and forgetting the
+ * other. A ref of a half-added kind degrades silently to `unknown-kind` — it
+ * renders as an unlinked chip forever and no behavioral test notices.
+ *
+ * Reads the two source files rather than importing the resolver's runtime, so
+ * the assertion holds without a database.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ THREAD_REF_KINDS,
+ INTERNAL_THREAD_REF_KINDS,
+ EXTERNAL_THREAD_REF_KINDS,
+ threadRefUrl,
+} from '../lib/threadRefKinds.js';
+
+// Reached through a DYNAMIC import on purpose: a static one would charge every
+// module in the resolver closure to this suite in the server import budget
+// (lib/importScoping.test.js), and the guard only needs one exported list.
+const { RESOLVABLE_THREAD_REF_KINDS } = await import('./threadRefs.js');
+
+describe('thread ref registry ↔ resolver parity', () => {
+ it('every internal kind has a resolver', () => {
+ const missing = INTERNAL_THREAD_REF_KINDS.filter((k) => !RESOLVABLE_THREAD_REF_KINDS.includes(k));
+ expect(missing, `add a lookup in server/services/threadRefs.js for: ${missing.join(', ')}`).toEqual([]);
+ });
+
+ it('every resolver has a kind — and no external kind has one', () => {
+ // The inverse drift: a lookup for a kind that was renamed or dropped is dead
+ // code the resolver can never reach, and an external kind has no local
+ // target to probe, so a lookup for one would be a contradiction.
+ for (const kind of RESOLVABLE_THREAD_REF_KINDS) {
+ expect(THREAD_REF_KINDS[kind], `resolver for unknown kind "${kind}"`).toBeDefined();
+ expect(THREAD_REF_KINDS[kind].external, `resolver for external kind "${kind}"`).toBe(false);
+ }
+ });
+
+ it('declares each internal kind exactly once across the three lookup groups', () => {
+ // Two groups claiming one kind would make which store wins depend on the
+ // order of the if-chain in `lookupTarget`.
+ const seen = new Set();
+ for (const kind of RESOLVABLE_THREAD_REF_KINDS) {
+ expect(seen.has(kind), `"${kind}" is declared in two lookup groups`).toBe(false);
+ seen.add(kind);
+ }
+ });
+
+ it('every external kind builds a URL from its own id', () => {
+ for (const kind of EXTERNAL_THREAD_REF_KINDS) {
+ expect(threadRefUrl(kind, 'https://example.com/item/1'), kind)
+ .toBe('https://example.com/item/1');
+ }
+ });
+});
diff --git a/server/services/threadRefs.js b/server/services/threadRefs.js
new file mode 100644
index 0000000000..ce85d49453
--- /dev/null
+++ b/server/services/threadRefs.js
@@ -0,0 +1,213 @@
+/**
+ * Thread ref RESOLUTION — `(kind, id)` → `{ label, url, state }` (#7664).
+ *
+ * A Brain *thread* is a tracked topic or commitment (an open loop), NOT a
+ * message thread — see server/lib/threadRefKinds.js for that distinction.
+ *
+ * This is the service half of the ref registry: `threadRefKinds.js` owns the
+ * pure vocabulary and route table (and is re-exported to the client), this file
+ * owns the existence/title lookups that need a store. The split is forced —
+ * `server/lib` may not import upward into `server/services`.
+ *
+ * Modelled on `catalogRefResolver.resolveRefs`: batch, dedupe by a
+ * JSON-stringified `(kind, id)` cache key, and DEGRADE an unresolvable ref to
+ * `{ resolved: false, reason }` rather than throwing or dropping it — a ref can
+ * name a kind this build does not know (a peer on newer code synced the thread)
+ * or a target that was deleted, and a thread must still render.
+ *
+ * Sentinel discipline (AGENTS.md): `resolved: false` means this build genuinely
+ * established the target is unknown or gone. A store that is unreachable is NOT
+ * that — its error bubbles, so "the database was down" can never be recorded as
+ * "the target was deleted".
+ *
+ * Import scoping: only the two stores most refs land in (the Brain collection
+ * stores and Postgres) are static imports. The single-kind resolvers reach their
+ * service through a lazy `await import()` so a thread list that references no
+ * goal never instantiates the goals module — see "Import scoping" in
+ * server/AGENTS.md.
+ */
+
+import { query } from '../lib/db.js';
+import * as brainStorage from './brainStorage.js';
+import {
+ THREAD_REF_KINDS,
+ canonicalThreadRefKind,
+ threadRefLabel,
+ threadRefUrl,
+} from '../lib/threadRefKinds.js';
+
+// ─── Brain-backed kinds ──────────────────────────────────────────────────────
+// kind → the BRAIN_ENTITY_TYPES store its id lives in. People and projects key
+// their display string off `name`; everything else off `title`.
+const BRAIN_REF_TYPES = Object.freeze({
+ 'brain.idea': 'ideas',
+ 'brain.project': 'projects',
+ 'brain.person': 'people',
+ 'brain.admin': 'admin',
+ 'brain.memory': 'memories',
+ 'brain.link': 'links',
+ 'brain.journal': 'journals',
+ 'brain.song': 'songs',
+});
+
+// ─── Postgres-backed kinds ───────────────────────────────────────────────────
+// kind → `{ table, titleExpr, liveClause }`. `titleExpr` is a SQL expression,
+// not a bare column, because several of these keep their display name inside
+// the record's `data` JSONB rather than in a column of its own. Every one of
+// these tables soft-deletes, so a live target is `deleted = FALSE` throughout —
+// the same predicate catalogRefResolver's REF_TARGET_TABLES uses.
+const DB_REF_TABLES = Object.freeze({
+ universe: { table: 'universes', titleExpr: 'name', liveClause: 'deleted = FALSE' },
+ series: { table: 'pipeline_series', titleExpr: 'name', liveClause: 'deleted = FALSE' },
+ issue: { table: 'pipeline_issues', titleExpr: "COALESCE(NULLIF(data->>'title', ''), 'Issue ' || COALESCE(number::text, id))", liveClause: 'deleted = FALSE' },
+ 'writers-room': { table: 'writers_room_works', titleExpr: 'title', liveClause: 'deleted = FALSE' },
+ 'creative-director': { table: 'creative_director_projects', titleExpr: "NULLIF(data->>'title', '')", liveClause: 'deleted = FALSE' },
+ 'catalog.ingredient': { table: 'catalog_ingredients', titleExpr: 'name', liveClause: 'deleted = FALSE', contextExpr: 'type' },
+ 'catalog.scrap': { table: 'catalog_scraps', titleExpr: "NULLIF(title, '')", liveClause: 'deleted = FALSE' },
+});
+
+// ─── Single-kind resolvers ───────────────────────────────────────────────────
+// Each returns `{ title }` for a live target, or `null` when it is gone. Lazily
+// imported so a thread set that never references one costs nothing.
+const SERVICE_REF_LOOKUPS = Object.freeze({
+ goal: async (id) => {
+ const { getGoals } = await import('./identity/goals.js');
+ const { goals } = await getGoals();
+ const goal = (goals || []).find((g) => g?.id === id);
+ return goal ? { title: goal.title } : null;
+ },
+ app: async (id) => {
+ const { getAppById } = await import('./apps.js');
+ const app = await getAppById(id);
+ return app ? { title: app.name || app.id } : null;
+ },
+ message: async (id) => {
+ const { getMessage } = await import('./messageSync.js');
+ // A message is addressed by (accountId, messageId); the ref packs both as
+ // `<accountId>:<messageId>`. Split on the FIRST colon only — a provider
+ // message id may itself contain one.
+ const separator = id.indexOf(':');
+ if (separator <= 0) return null;
+ const message = await getMessage(id.slice(0, separator), id.slice(separator + 1));
+ return message ? { title: message.subject || message.snippet || message.id } : null;
+ },
+ 'cos.task': async (id) => {
+ const { getTaskById } = await import('./cosTaskStore.js');
+ const task = await getTaskById(id);
+ return task ? { title: task.text || task.title || task.id } : null;
+ },
+});
+
+// Every kind THREAD_REF_KINDS calls internal must appear in exactly one of the
+// three lookup groups. `threadRefs.drift.test.js` asserts that; this derived set
+// is what it checks against (and what `hasThreadRefResolver` answers from).
+export const RESOLVABLE_THREAD_REF_KINDS = Object.freeze([
+ ...Object.keys(BRAIN_REF_TYPES),
+ ...Object.keys(DB_REF_TABLES),
+ ...Object.keys(SERVICE_REF_LOOKUPS),
+]);
+
+/** Does this build know how to look up a target of this kind? */
+export function hasThreadRefResolver(kind) {
+ return RESOLVABLE_THREAD_REF_KINDS.includes(canonicalThreadRefKind(kind));
+}
+
+// Cache key for one (kind, id) pair. JSON-stringify so the two fields join on an
+// unambiguous printable delimiter no id can forge — catalogRefResolver's rule.
+const cacheKey = (kind, id) => JSON.stringify([kind, id]);
+
+// The display string for a resolved target, preferring what the target actually
+// says over the ref's cached copy (which can be stale) over the kind's label
+// (which is at least never empty).
+const displayLabel = (targetTitle, cachedLabel, kind) => {
+ if (typeof targetTitle === 'string' && targetTitle.trim()) return targetTitle.trim();
+ if (typeof cachedLabel === 'string' && cachedLabel.trim()) return cachedLabel.trim();
+ return threadRefLabel(kind);
+};
+
+async function lookupTarget(kind, id) {
+ const brainType = BRAIN_REF_TYPES[kind];
+ if (brainType) {
+ const record = await brainStorage.getById(brainType, id);
+ if (!record) return null;
+ // A journal record is keyed by its date and carries no title of its own.
+ return { title: record.title || record.name || (brainType === 'journals' ? id : '') };
+ }
+
+ const table = DB_REF_TABLES[kind];
+ if (table) {
+ const context = table.contextExpr ? `, ${table.contextExpr} AS context` : '';
+ const { rows } = await query(
+ `SELECT ${table.titleExpr} AS title${context} FROM ${table.table} WHERE id = $1 AND ${table.liveClause}`,
+ [id],
+ );
+ if (rows.length === 0) return null;
+ return { title: rows[0].title, context: rows[0].context };
+ }
+
+ const lookup = SERVICE_REF_LOOKUPS[kind];
+ return lookup ? lookup(id) : null;
+}
+
+/**
+ * Hydrate a thread's `refs` array for display.
+ *
+ * Returns one entry per INPUT ref, in input order, never fewer — a caller
+ * rendering chips must be able to show every ref the record holds, including
+ * the broken ones:
+ *
+ * `{ kind, id, label, url, state: 'live', resolved: true }` internal, found
+ * `{ kind, id, label, url, state: 'unknown', resolved: true }` external (not probed)
+ * `{ kind, id, label, url: null, resolved: false, reason }` unknown-kind /
+ * missing-ref-id /
+ * missing-target /
+ * unsafe-url
+ *
+ * Distinct (kind, id) pairs are probed once each; duplicates reuse the result.
+ * A thread's ref set is bounded at 100, so per-tuple probes are fine.
+ */
+export async function resolveThreadRefs(refs) {
+ if (!Array.isArray(refs) || refs.length === 0) return [];
+ const cache = new Map();
+ const out = [];
+
+ for (const ref of refs) {
+ const kind = canonicalThreadRefKind(ref?.kind);
+ const id = ref?.id;
+ const key = cacheKey(kind, id);
+
+ if (!cache.has(key)) {
+ const spec = THREAD_REF_KINDS[kind];
+ if (!spec) {
+ cache.set(key, { resolved: false, reason: 'unknown-kind', url: null });
+ } else if (typeof id !== 'string' || !id) {
+ cache.set(key, { resolved: false, reason: 'missing-ref-id', url: null });
+ } else if (spec.external) {
+ // Nothing local to probe. The id IS the URL, so the only failure mode is
+ // an id that must never become an href.
+ const url = threadRefUrl(kind, id);
+ cache.set(key, url
+ ? { resolved: true, state: 'unknown', url, title: '' }
+ : { resolved: false, reason: 'unsafe-url', url: null });
+ } else {
+ const target = await lookupTarget(kind, id);
+ cache.set(key, target
+ ? { resolved: true, state: 'live', url: threadRefUrl(kind, id, { catalogType: target.context }), title: target.title }
+ : { resolved: false, reason: 'missing-target', url: null });
+ }
+ }
+
+ const hit = cache.get(key);
+ out.push({
+ kind,
+ id,
+ label: displayLabel(hit.title, ref?.label, kind),
+ kindLabel: threadRefLabel(kind),
+ ...(hit.resolved
+ ? { url: hit.url, state: hit.state, resolved: true }
+ : { url: null, resolved: false, reason: hit.reason }),
+ });
+ }
+
+ return out;
+}
diff --git a/server/services/threadRefs.test.js b/server/services/threadRefs.test.js
new file mode 100644
index 0000000000..d88b7d59c2
--- /dev/null
+++ b/server/services/threadRefs.test.js
@@ -0,0 +1,170 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const query = vi.fn();
+const getById = vi.fn();
+const getAppById = vi.fn();
+
+vi.mock('../lib/db.js', () => ({ query: (...args) => query(...args) }));
+vi.mock('./brainStorage.js', () => ({ getById: (...args) => getById(...args) }));
+vi.mock('./apps.js', () => ({ getAppById: (...args) => getAppById(...args) }));
+
+const { resolveThreadRefs } = await import('./threadRefs.js');
+
+beforeEach(() => {
+ query.mockReset();
+ getById.mockReset();
+ getAppById.mockReset();
+ query.mockResolvedValue({ rows: [] });
+ getById.mockResolvedValue(null);
+ getAppById.mockResolvedValue(null);
+});
+
+describe('resolveThreadRefs — hydration', () => {
+ it('hydrates a Brain-backed ref from its entity store', async () => {
+ getById.mockResolvedValue({ id: 'idea-1', title: 'Ship the bullet journal' });
+ const [ref] = await resolveThreadRefs([{ kind: 'brain.idea', id: 'idea-1' }]);
+ expect(getById).toHaveBeenCalledWith('ideas', 'idea-1');
+ expect(ref).toMatchObject({
+ kind: 'brain.idea',
+ id: 'idea-1',
+ label: 'Ship the bullet journal',
+ kindLabel: 'Idea',
+ url: '/brain/ideas',
+ state: 'live',
+ resolved: true,
+ });
+ });
+
+ it('hydrates a Postgres-backed ref and uses its context for the route', async () => {
+ // A catalog ingredient lives at /catalog/:type/:id, and the type is only
+ // knowable once the row has been read — the reason `threadRefUrl` takes a
+ // context at all.
+ query.mockResolvedValue({ rows: [{ title: 'Ada', context: 'character' }] });
+ const [ref] = await resolveThreadRefs([{ kind: 'catalog.ingredient', id: 'ing-1' }]);
+ expect(ref).toMatchObject({
+ label: 'Ada',
+ url: '/catalog/character/ing-1',
+ state: 'live',
+ resolved: true,
+ });
+ });
+
+ it('hydrates a service-backed ref through its lazy import', async () => {
+ getAppById.mockResolvedValue({ id: 'app-1', name: 'PortOS' });
+ const [ref] = await resolveThreadRefs([{ kind: 'app', id: 'app-1' }]);
+ expect(ref).toMatchObject({ label: 'PortOS', url: '/apps/app-1', resolved: true });
+ });
+
+ it('keys a journal off its date id, which is the only name it has', async () => {
+ getById.mockResolvedValue({ id: '2026-09-19', entries: [] });
+ const [ref] = await resolveThreadRefs([{ kind: 'brain.journal', id: '2026-09-19' }]);
+ expect(ref).toMatchObject({ label: '2026-09-19', url: '/brain/daily-log?date=2026-09-19' });
+ });
+
+ it('prefers the live target title over the ref cached label', async () => {
+ // The cached label exists so a LIST render needs no resolver; once we have
+ // resolved the target, a stale cached copy must not win.
+ getById.mockResolvedValue({ id: 'idea-1', title: 'Renamed' });
+ const [ref] = await resolveThreadRefs([{ kind: 'brain.idea', id: 'idea-1', label: 'Old name' }]);
+ expect(ref.label).toBe('Renamed');
+ });
+});
+
+describe('resolveThreadRefs — degradation (never drops a ref)', () => {
+ it('reports an unknown kind rather than throwing or omitting it', async () => {
+ // A peer running newer code can sync a thread naming a kind this build has
+ // never heard of; the thread must still render.
+ const [ref] = await resolveThreadRefs([{ kind: 'some.future.kind', id: 'x' }]);
+ expect(ref).toMatchObject({ resolved: false, reason: 'unknown-kind', url: null });
+ expect(ref.label).toBe('some.future.kind');
+ });
+
+ it('reports a deleted target as missing-target, not as absent', async () => {
+ getById.mockResolvedValue(null);
+ const [ref] = await resolveThreadRefs([{ kind: 'brain.idea', id: 'gone', label: 'Deleted idea' }]);
+ expect(ref).toMatchObject({ resolved: false, reason: 'missing-target', url: null });
+ // Falls back to the cached label so the chip still says what it pointed at.
+ expect(ref.label).toBe('Deleted idea');
+ });
+
+ it('reports a ref with no id', async () => {
+ const [ref] = await resolveThreadRefs([{ kind: 'brain.idea' }]);
+ expect(ref).toMatchObject({ resolved: false, reason: 'missing-ref-id' });
+ });
+
+ it('returns one entry per input ref, in input order', async () => {
+ getById.mockResolvedValue(null);
+ const out = await resolveThreadRefs([
+ { kind: 'brain.idea', id: 'a' },
+ { kind: 'nope', id: 'b' },
+ { kind: 'url', id: 'https://example.com/c' },
+ ]);
+ expect(out.map((r) => r.id)).toEqual(['a', 'b', 'https://example.com/c']);
+ });
+
+ it('never lets a store failure read as a deleted target', async () => {
+ // Sentinel discipline (AGENTS.md): "the store was unreachable" must not be
+ // recorded as "the target is gone", which would strike a live ref off a
+ // thread. The error bubbles instead.
+ getById.mockRejectedValue(new Error('store unavailable'));
+ await expect(resolveThreadRefs([{ kind: 'brain.idea', id: 'a' }]))
+ .rejects.toThrow('store unavailable');
+ });
+});
+
+describe('resolveThreadRefs — external kinds', () => {
+ it('passes a safe external URL through without probing anything', async () => {
+ const [ref] = await resolveThreadRefs([
+ { kind: 'github.issue', id: 'https://github.com/o/r/issues/7', label: 'o/r#7' },
+ ]);
+ expect(ref).toMatchObject({
+ label: 'o/r#7',
+ kindLabel: 'GitHub issue',
+ url: 'https://github.com/o/r/issues/7',
+ // Nothing local says whether the issue is still open — Phase 4's sync
+ // records that on the thread, not on the ref.
+ state: 'unknown',
+ resolved: true,
+ });
+ expect(query).not.toHaveBeenCalled();
+ expect(getById).not.toHaveBeenCalled();
+ });
+
+ it('refuses an external id that must never become an href', async () => {
+ const [ref] = await resolveThreadRefs([{ kind: 'url', id: 'javascript:alert(1)' }]);
+ expect(ref).toMatchObject({ resolved: false, reason: 'unsafe-url', url: null });
+ });
+});
+
+describe('resolveThreadRefs — batching', () => {
+ it('probes each distinct (kind, id) once', async () => {
+ getById.mockResolvedValue({ id: 'idea-1', title: 'One' });
+ await resolveThreadRefs([
+ { kind: 'brain.idea', id: 'idea-1' },
+ { kind: 'brain.idea', id: 'idea-1' },
+ { kind: 'brain.idea', id: 'idea-1' },
+ ]);
+ expect(getById).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not conflate two kinds that share an id', async () => {
+ getById.mockImplementation(async (type) => ({ title: type === 'ideas' ? 'An idea' : 'A person' }));
+ const out = await resolveThreadRefs([
+ { kind: 'brain.idea', id: 'shared' },
+ { kind: 'brain.person', id: 'shared' },
+ ]);
+ expect(out.map((r) => r.label)).toEqual(['An idea', 'A person']);
+ });
+
+ it('resolves the legacy writersRoom spelling to the canonical kind', async () => {
+ query.mockResolvedValue({ rows: [{ title: 'The Work' }] });
+ const [ref] = await resolveThreadRefs([{ kind: 'writersRoom', id: 'w1' }]);
+ expect(ref.kind).toBe('writers-room');
+ expect(ref.url).toBe('/writers-room');
+ });
+
+ it('returns [] for an absent or empty ref list', async () => {
+ expect(await resolveThreadRefs(undefined)).toEqual([]);
+ expect(await resolveThreadRefs([])).toEqual([]);
+ });
+});