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

chunk long catalog scraps into parent + child rows so extraction unions per-chunk

[._.]/ Adam Eivy0deaf286da1c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5907f89ea9..806442f288 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,8 @@
## Added
+- **[catalog-scrap-chunking] Long scrap pastes are now chunked so extraction doesn't silently degrade.** Pasting (or ingesting via URL / file / voice) a very long scrap — a whole screenplay, a 50k-word manuscript — used to land as a single row and a single LLM extraction pass, quietly overflowing the model's context and dropping ingredients from the tail. Inputs over ~12k characters now split into a parent row plus N child chunks (preferring paragraph, then sentence, then word boundaries so nothing is cut mid-word and the text reassembles exactly); the extractor runs each chunk independently (two at a time) and unions the results, de-duplicating by name + type so the same character mentioned in three chunks appears once. Short pastes behave exactly as before — one row, one pass. The chunk parent/child structure federates to peers (the catalog sync wire version is bumped, so a peer on an older catalog schema declines a forward-shaped push cleanly rather than mis-applying it); existing scraps are left as-is.
+
- **[catalog-ask-retrieval] Ask now draws on your Creative Catalog.** Asking a question (`/api/ask`, the Ask page, voice) now retrieves matching catalog ingredients — characters, places, objects, ideas, scenes, concepts — alongside memory, brain notes, goals, autobiography, and calendar. Matches use a hybrid Reciprocal-Rank-Fusion search (full-text + vector embedding) sharing the same scoring/budget model as memory retrieval, capped at 4 catalog sources per answer and weighted between brain-notes and autobiography. Each surfaced ingredient is a clickable source chip that deep-links to its catalog detail page. Full-text matching works immediately; semantic (vector) matches appear once you've configured an embedding model and run the catalog embeddings backfill. A catalog hiccup never blocks an answer (the retriever is isolated in the parallel fan-out).
- **[catalog-federation-orchestrator] The creative catalog now auto-replicates between peers.** The catalog sync routes existed but nothing pulled from peers — orphan ingredients (ideas / scenes / concepts not attached to a universe) and the universe→ingredient ref links stayed local. The sync orchestrator now runs `catalog` as a delta-based PostgreSQL category alongside Memory: on every peer-online event and on the background interval it pulls `GET /api/catalog/sync` (the seven independent per-kind BIGSERIAL cursors: scraps / ingredients / sources / refs / relations / tags / media) and applies each batch locally with the same last-writer-wins + per-row isolation + schema-version gate as direct sync. A peer ahead on the `catalog` schema records a gap on the Instances page (the existing SchemaGapBadge) and pauses draining instead of looping. Toggle it per peer under Instances → Sync Categories → "Catalog"; Postgres-only (a non-Postgres peer simply never enables it).
diff --git a/PLAN.md b/PLAN.md
index 0f7b188084..e315bad691 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -19,7 +19,6 @@ _Re-triaged then cleared 2026-05-30 (post-merge follow-up pass): the 6 review-su
The v1 catalog hardcodes six types (`character|place|object|idea|scene|concept`) in at least eight places: the Postgres CHECK constraint (`server/scripts/init-db.sql` + `server/lib/db.js:ensureSchema`), the Zod enum in `server/lib/catalogValidation.js`, the extraction prompt in `server/services/catalogExtraction.js`, the `TYPES` array + `PRIMARY_CONTENT_KEY` + `PRIMARY_CONTENT_LABEL` + `payloadSnippet` fallback chain in `client/src/pages/Catalog.jsx`, the type-specific editor branches in `client/src/pages/CatalogIngredient.jsx`, the `IngredientPicker.jsx` type filter, and the `search_tsv` generated column expression. Adding a seventh type today is an 8-file touch across server, client, and a Postgres migration. The items below collapse that surface so the catalog can grow into the long tail of creative shards (lore fragments, factions, magic systems, vehicles, wardrobe, dialogue snippets, beat cards, prompt fragments, voice-memo transcripts, mood references, etc.) without each new shard being a multi-PR effort.
- [ ] [catalog-user-defined-types] **Allow user-defined ingredient types in the Settings → Catalog section.** Once `[catalog-type-table-vs-check]` lands, expose a Settings UI to add a user type: `{ id, label, primaryContentKey, fields: [{ key, label, kind: 'string'|'longtext'|'tags'|'ref', maxLength? }] }`. Persisted in the new `catalog_ingredient_types` table with `system: false`; the registry merges seeded + user types at boot. Editor component for user types is a generic form renderer driven by the `fields` array (no per-type React file). Unblocks the long tail of personal creative shards (wardrobe, vehicle, faction, magic-system, voice-line, prompt-fragment, etc.) without a code change per shard. Decision needed on whether user types federate to peers (probably yes, with the type row riding the catalog sync envelope and gated by `PORTOS_SCHEMA_VERSIONS.catalog`). _Precondition resolved 2026-05-30: `[catalog-type-table-vs-check]` landed as **option (b)** (DB `CHECK` dropped + `type VARCHAR(32)`; validity gated by the `INGREDIENT_TYPES` registry + Zod enum) — so user types do NOT need a `catalog_ingredient_types` table; they can persist in settings and merge into the registry at boot, and a user-typed row already inserts at the DB layer. Still open as a larger Settings-UI + generic-form-renderer feature; remains deferred until picked up deliberately._
-- [ ] [catalog-scrap-chunking] **Chunk long scraps into multiple `(parent_scrap_id, chunk_index)` rows.** Today `raw_text` is a single TEXT column with no enforced cap, but a 50k-word screenplay paste lands as one row and one LLM call — context overflow is silent and extraction degrades. Add `chunk_index INT DEFAULT 0` + `parent_scrap_id TEXT REFERENCES catalog_scraps(id)` and split inputs over ~12k chars into N child rows; the extractor processes each child and unions the results, dedup by name+type. Surfaced by anticipation, not yet by user pain — defer until a long-input failure is reported.
_Batch-cleared 2026-05-25: 23 Next Up items shipped together via parallel sub-agents (env-file helper, formatBytes migration, lazy voice UI text, voice long-term-memory routing, voice tool expansion + `ui_describe_visually`, three phosphene generate_ltx2.py hardenings, the peer-sync snapshot-coverage P1 refactor + ephemeralize-then-delete, per-record tombstone-ack clamp, MediaLightbox→MediaImage, global vitest peer mock, videoHistory sync category, reverse-sub UI broadcast, palette Health disambiguation, insertXxxWithId resurrection side-effects, importer tombstone detection, TUI finish-rejection note, mortalLoom errno widen, VideoGen stale-model toast, Universes sidebar grandchildren). See `git log` + `.changelog/NEXT.md`._
@@ -27,6 +26,7 @@ _Batch-cleared 2026-05-29 (catalog batch 2): 4 catalog items shipped via paralle
- [ ] [chrome-canary-followups] **Hardening for the custom-Chrome-binary feature (xhigh code-review 2026-05-25).** _DONE in the v2.10.0 release review: (b) both `spawn()` calls now have `.on('error', …)` listeners; (d) `browser/server.js#loadConfig` now try/catches the `JSON.parse`; (e) `setup-browser.js#loadConfig` now warns + returns `null` and `applyCanaryToConfig` skips the save when the existing config is unreadable; (f) top-level `runCanarySetup()` is now `.catch()`-wrapped. (c) is tracked separately in `[setup-browser-canary-headless]`. Remaining: (a), (g)–(o)._ **High-severity:** (a) On macOS headed mode (the default), `browser/server.js:208` uses `macAppBundle` only and silently ignores `chromePath` — a UI user who fills in `chromePath` for Canary/Chromium/Brave but leaves `macAppBundle` empty gets stock Chrome and the log misreports the binary; couple the two fields in the UI (or auto-derive `macAppBundle` from `chromePath` when the latter is inside a `.app`). (b) Neither `spawn(chromePath, …)` (line 216) nor `spawn('/usr/bin/open', …)` (line 208) has an `.on('error', …)` listener — a typo in `chromePath` emits 'error' with no listener → `uncaughtException` → portos-browser PM2 child crashes and restart-loops. (c) `scripts/setup-browser.js#applyCanaryToConfig` writes `chromePath` + `macAppBundle` but doesn't flip `headless: false`; combined with the seed default of `headless: true` (`data.reference/browser-config.json`), a fresh install accepting Canary runs Canary invisibly. (d) `browser/server.js#loadConfig` does bare `JSON.parse(raw)` with no try/catch — combined with setup-browser's non-atomic `writeFileSync` and the `cachedConfig` race, a partial-file write crashes the supervisor on next start (PM2 restart-loop forever). **Medium-severity:** (e) `setup-browser.js#loadConfig` silently catches all JSON parse errors and returns `{}`, then `applyCanaryToConfig` saves `{chromePath, macAppBundle}` only — wiping every other user-customized key. (f) Top-level `await runCanarySetup()` has no try/catch — any EACCES on data/browser-config.json aborts `npm run setup` / `update.sh` at what was previously a no-op step. (g) Idempotency guard only checks `chromePath`: users who decline get re-prompted on every update, and users who set only `macAppBundle` keep getting re-prompted. (h) `PORTOS_USE_CANARY` only matches literal `'0'`/`'false'` (opt-out) or `'1'`/`'true'` (opt-in) — `'no'`/`'off'`/`'yes'`/`'on'`/`'True'` fall through both branches. (i) `spawnSync(install.cmd, …, { stdio: 'inherit' })` for brew/winget can hang on a sudo password prompt under non-TTY + `PORTOS_USE_CANARY=1` (update.sh stalls). (j) `cachedConfig` in `browserService.js` is stale relative to setup-browser's direct write — GET /api/browser/config returns pre-update values until process restart. (k) `saveConfig` uses bare `writeFileSync` — switch to the canonical `atomicWrite` pattern (`server/lib/fileUtils.js`). **Low-severity:** (l) `spawnSync` failure-status check `result.status !== 0` treats `status: null` (spawn-failure / signal kill) identically to a non-zero exit and never logs `result.error` — masks ENOENT/EPERM/SIGKILL. (m) `optionalPath` Zod schema accepts any string up to 1024 chars; no `.app`/`.exe` sanity check — user pastes the bundle into `chromePath` → spawn() EISDIR. (n) `launchBrowser`'s reuse-existing-Chrome early-return (line 167) fires BEFORE `headlessMode = config.headless === true` (line 170), leaving the module-level default `false` after a PM2 restart that reuses Chrome — /health reports wrong mode (pre-existing, but in a function touched by this change). (o) `detectCanary` on macOS only checks `/Applications/...`; misses per-user `~/Applications/Google Chrome Canary.app` installs (corporate Macs, `HOMEBREW_CASK_OPTS=--appdir=$HOME/Applications`).
- [ ] [strip-malloc-env-ffmpeg-children] **Extend `stripDebugMallocEnv` coverage to ffmpeg child spawns if Pinokio users still see the warning.** The Malloc-strip PR (`[ref-watch-phosphene-strip-malloc-subprocess-env]`) routed every direct Node→Python spawn through `stripDebugMallocEnv`, but ffmpeg children (`server/lib/ffmpeg.js:81`, the ffmpeg/ffprobe calls in `server/services/mediaService.js`, `server/services/videoTimeline/local.js`, and the post-render thumbnail/optimize/upscale paths in `server/services/videoGen/local.js`) still inherit `process.env`. ffmpeg on macOS links libSystem (which includes libmalloc) so it can in principle emit the same `MallocStackLogging: can't turn off…` line — unverified whether it actually does. Trigger: if Pinokio-launched installs still report stderr noise after the Python-spawn fix lands, wrap each ffmpeg spawn `env` the same way. Surfaced by reuse-review subagent during the original PR (2026-05-29).
+- [ ] [shared-bounded-concurrency-mapper] **Extract a generic `mapWithConcurrency(items, n, fn)` to `server/lib/` and reuse it in `embedBatch` + the catalog chunk extractor.** The worker-pool idiom (cursor + N workers draining a shared array, order-preserving result) is now hand-rolled in at least two places: `embedBatch` in `server/services/embeddings.js` (~line 158, specialized to `embedText`) and `mapWithConcurrency` in `server/services/catalogExtraction.js` (~line 317, added by `[catalog-scrap-chunking]`). A pure `server/lib/` helper would collapse both onto one tested mechanism (barrel + README row per the maintenance rule). Deferred from the scrap-chunking PR's `/simplify` pass — extracting it cleanly touches `embeddings.js` and other call sites outside that diff's scope. Surfaced by reuse/altitude review (2026-05-30).
- [ ] [mediajobqueue-shared-provider-kind-predicate] **Share a `getJobProviderKind(job)` predicate between `getGenModuleForJob` and `resolveLiveParams` in `server/services/mediaJobQueue/index.js`.** Both now encode the same `video | image+codex | image+local` partition by hand (`getGenModuleForJob` at ~line 109, `resolveLiveParams.usesLocalPython` at ~line 122). A shared `getJobProviderKind(job) → 'video-local' | 'image-local' | 'image-codex' | null` would let both branches derive from one predicate and extend cleanly to future providers. Surfaced by reuse-review during the resolveLiveParams extract (2026-05-29); deferred because today's duplication is two lines and the seam is still small.
- [ ] [ref-watch-phosphene-teacache-extend-a2v-denoise] **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision needed:** ride along with the `[ref-watch-phosphene-bump-ltx2-pin-v0148]` pin bump (the calibration constants are part of the same upstream surface that gets renamed) or land independently against today's pin? Scope: small/medium.
## Deferred Architecture (human-led planning)
diff --git a/scripts/migrations/054-catalog-scrap-chunking.js b/scripts/migrations/054-catalog-scrap-chunking.js
new file mode 100644
index 0000000000..8401a5f8ad
--- /dev/null
+++ b/scripts/migrations/054-catalog-scrap-chunking.js
@@ -0,0 +1,32 @@
+/**
+ * Registration stub for the catalog scrap-chunking schema change.
+ *
+ * Long scrap pastes now split into a parent row (chunk_index 0, parent_scrap_id
+ * NULL, raw_text = the FULL original text) plus N child rows (parent_scrap_id →
+ * parent, chunk_index 1..N, raw_text = the chunk slice). The catalog extractor
+ * runs per-child and unions the drafts (dedup by name+type, keep first).
+ *
+ * The two new columns (`chunk_index INT NOT NULL DEFAULT 0`,
+ * `parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE`) and
+ * the `idx_catalog_scraps_parent` index are ADDITIVE + idempotent, so they're
+ * applied at boot by `ensureSchema()` in server/lib/db.js (ALTER TABLE ... ADD
+ * COLUMN IF NOT EXISTS) and inline in server/scripts/init-db.sql for fresh
+ * installs. The `scripts/migrations/` runner executes BEFORE the Postgres pool
+ * is initialized, so the real DDL can't run here — same reason migrations
+ * 048–053 are boot-time + stub-registered.
+ *
+ * Existing rows default to chunk_index 0 / parent_scrap_id NULL — a plain
+ * non-chunked scrap, unchanged behavior. We do NOT retro-chunk existing scraps.
+ *
+ * This stub exists so the change is *registered the standard way*: it lands in
+ * `data/migrations.applied.json` so the migration ledger and `git log` show when
+ * scrap chunking was introduced.
+ *
+ * No-op + idempotent: nothing to do in the file runner.
+ */
+
+export default {
+ async up() {
+ console.log('🧩 catalog scrap chunking: additive columns apply at boot via ensureSchema(); nothing to do in the file runner');
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index 214df1f995..416969ea64 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -51,6 +51,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `seasonStructure.js` | Season/episode structure recommendation. |
| `bibleExtractor.js` | LLM bible-extraction stage + sanitization. |
| `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |
+| `catalogChunking.js` | Pure lossless scrap-text chunker (`chunkRawText`, `CATALOG_CHUNK_MAX_CHARS`) — splits a long paste into ≤maxChars chunks on paragraph/newline/sentence/whitespace boundaries so the catalog extractor processes each child and unions results. |
| `catalogTypes.js` | Shared catalog ingredient TYPE REGISTRY — one entry per type drives validation enum, ID prefix, FTS field set, extraction shape, per-record `payloadSchemaVersion` + upgraders, per-type `defaultTags`. Also exports the relation-kind registry and the tag-taxonomy helpers (`canonicalTagKey`, `tagIdForKey`, `defaultTagsForType`). Mirrored on the client at `client/src/lib/catalogTypes.js`. |
| `catalogUniverseTags.js` | Pure transform that rewrites legacy machine universe tags (`from-universe`, `universe:<id>`) on backfilled catalog ingredients into friendly universe-NAME tags, preserving user tags + the structured `catalog_ingredient_refs` link. Used by the boot-time repair and the bible→catalog backfill. |
| `comicScriptParser.js` | Marvel/DC-format comic script parser. |
diff --git a/server/lib/catalogChunking.js b/server/lib/catalogChunking.js
new file mode 100644
index 0000000000..4129095a6a
--- /dev/null
+++ b/server/lib/catalogChunking.js
@@ -0,0 +1,110 @@
+/**
+ * Catalog scrap chunking — pure, side-effect-free.
+ *
+ * A long scrap paste is split into chunks so the catalog extractor can process
+ * each chunk independently (bounded concurrency) and union the per-chunk drafts.
+ * Short inputs return a single chunk and behave exactly as the pre-chunking
+ * code did.
+ *
+ * Design contract (relied on by catalogDB.createChunkedScrap + the extractor):
+ * - Lossless: concatenating the returned chunks reproduces the input EXACTLY
+ * (no characters dropped, no separators injected). Tests assert join('') ===
+ * input.
+ * - Boundary preference: when a chunk would exceed maxChars, split at the
+ * latest paragraph break (\n\n) within the window, else the latest newline,
+ * else the latest sentence boundary, else the latest whitespace, else a hard
+ * character cut (pathological no-whitespace input).
+ * - maxChunks ceiling: never emit more than maxChunks entries; the last chunk
+ * holds the entire remainder even if it exceeds maxChars.
+ *
+ * NO db / llm / fs imports — keep it unit-testable in isolation.
+ */
+
+// Default per-chunk character ceiling. Counted by JS string length (UTF-16 code
+// units), matching how the rest of the catalog measures scrap length.
+export const CATALOG_CHUNK_MAX_CHARS = 12_000;
+
+// Default ceiling on how many chunks one scrap can split into. Bounds the number
+// of LLM extraction passes a single huge paste can trigger.
+const DEFAULT_MAX_CHUNKS = 40;
+
+// Sentence-terminator followed by whitespace. Used to find the last sentence
+// boundary inside a candidate window when no paragraph/newline break exists.
+const SENTENCE_BOUNDARY = /[.!?]["')\]]?\s/g;
+
+/**
+ * Find the best split offset inside `text[start .. start+limit]`. Returns an
+ * absolute index in `text` (exclusive end of the chunk). Prefers, in order:
+ * paragraph break (\n\n) → newline → sentence boundary → any whitespace →
+ * hard cut at `start + limit`. The returned index is always > start (so we make
+ * forward progress) and ≤ start + limit.
+ */
+function findSplit(text, start, limit) {
+ const hardEnd = start + limit;
+ const window = text.slice(start, hardEnd);
+
+ // Paragraph break — split AFTER the blank line so the separator rides with the
+ // preceding chunk (lossless either way; trailing-with-chunk keeps the next
+ // chunk's leading content clean).
+ const para = window.lastIndexOf('\n\n');
+ if (para > 0) return start + para + 2;
+
+ const nl = window.lastIndexOf('\n');
+ if (nl > 0) return start + nl + 1;
+
+ // Latest sentence boundary inside the window.
+ let lastSentenceEnd = -1;
+ SENTENCE_BOUNDARY.lastIndex = 0;
+ let m;
+ while ((m = SENTENCE_BOUNDARY.exec(window)) !== null) {
+ // End of the match (after the trailing whitespace char) so the punctuation
+ // and the following space stay with the current chunk.
+ lastSentenceEnd = m.index + m[0].length;
+ }
+ if (lastSentenceEnd > 0) return start + lastSentenceEnd;
+
+ // Any whitespace — avoid splitting mid-word.
+ const ws = window.search(/\s\S*$/);
+ if (ws > 0) return start + ws + 1;
+
+ // Pathological no-whitespace run: hard char cut.
+ return hardEnd;
+}
+
+/**
+ * Split raw scrap text into lossless chunks.
+ *
+ * @param {string} text
+ * @param {object} [opts]
+ * @param {number} [opts.maxChars=CATALOG_CHUNK_MAX_CHARS] per-chunk ceiling
+ * @param {number} [opts.maxChunks=40] chunk-count ceiling
+ * @returns {string[]} one entry when text ≤ maxChars, else N entries. Always
+ * reassembles losslessly: chunks.join('') === text.
+ */
+export function chunkRawText(text, { maxChars = CATALOG_CHUNK_MAX_CHARS, maxChunks = DEFAULT_MAX_CHUNKS } = {}) {
+ if (typeof text !== 'string') return [];
+ const cap = Math.max(1, Math.floor(maxChars));
+ const ceiling = Math.max(1, Math.floor(maxChunks));
+
+ if (text.length <= cap) return [text];
+
+ const chunks = [];
+ let start = 0;
+ while (start < text.length) {
+ // Last allowed chunk: take the entire remainder even if it exceeds cap, so
+ // we never exceed the maxChunks ceiling and never drop characters.
+ if (chunks.length === ceiling - 1) {
+ chunks.push(text.slice(start));
+ break;
+ }
+ const remaining = text.length - start;
+ if (remaining <= cap) {
+ chunks.push(text.slice(start));
+ break;
+ }
+ const end = findSplit(text, start, cap);
+ chunks.push(text.slice(start, end));
+ start = end;
+ }
+ return chunks;
+}
diff --git a/server/lib/catalogChunking.test.js b/server/lib/catalogChunking.test.js
new file mode 100644
index 0000000000..c76929f2dd
--- /dev/null
+++ b/server/lib/catalogChunking.test.js
@@ -0,0 +1,127 @@
+import { describe, it, expect } from 'vitest';
+import { chunkRawText, CATALOG_CHUNK_MAX_CHARS } from './catalogChunking.js';
+
+describe('catalogChunking.chunkRawText', () => {
+ it('returns a single chunk for short input (≤ maxChars)', () => {
+ const text = 'a short paste';
+ expect(chunkRawText(text)).toEqual([text]);
+ });
+
+ it('returns a single chunk exactly at the cap', () => {
+ const text = 'x'.repeat(CATALOG_CHUNK_MAX_CHARS);
+ const chunks = chunkRawText(text);
+ expect(chunks).toHaveLength(1);
+ expect(chunks[0]).toBe(text);
+ });
+
+ it('splits input larger than maxChars into N chunks each ≤ cap', () => {
+ const maxChars = 100;
+ // 5 paragraphs of ~80 chars each, separated by blank lines.
+ const para = 'word '.repeat(15).trim(); // ~74 chars
+ const text = Array.from({ length: 8 }, () => para).join('\n\n');
+ expect(text.length).toBeGreaterThan(maxChars);
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks.length).toBeGreaterThan(1);
+ for (const c of chunks) {
+ expect(c.length).toBeLessThanOrEqual(maxChars);
+ }
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('prefers paragraph boundaries when splitting', () => {
+ const maxChars = 60;
+ const a = 'A'.repeat(40);
+ const b = 'B'.repeat(40);
+ const text = `${a}\n\n${b}`;
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks).toHaveLength(2);
+ // First chunk ends with the paragraph separator, second starts clean.
+ expect(chunks[0]).toBe(`${a}\n\n`);
+ expect(chunks[1]).toBe(b);
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('falls back to newline, then sentence boundary', () => {
+ const maxChars = 50;
+ const text = `${'a'.repeat(30)}\n${'b'.repeat(15)}. ${'c'.repeat(15)}`;
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks.length).toBeGreaterThan(1);
+ // First split should land on the newline.
+ expect(chunks[0]).toBe(`${'a'.repeat(30)}\n`);
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('splits on sentence boundary when no paragraph/newline break exists', () => {
+ const maxChars = 40;
+ const text = `${'one '.repeat(8).trim()}. ${'two '.repeat(8).trim()}.`;
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks.length).toBeGreaterThan(1);
+ // The boundary after ". " keeps the period+space with the first chunk.
+ expect(chunks[0].endsWith('. ')).toBe(true);
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('avoids splitting mid-word when only whitespace is available', () => {
+ const maxChars = 20;
+ const text = 'alpha bravo charlie delta echo foxtrot golf';
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks.length).toBeGreaterThan(1);
+ for (const c of chunks.slice(0, -1)) {
+ // Each non-final chunk ends on a whitespace boundary (no truncated word
+ // at the seam): the char after the chunk is non-space, the chunk's last
+ // char is a space.
+ expect(c.endsWith(' ')).toBe(true);
+ }
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('hard-cuts pathological no-whitespace input at the cap', () => {
+ const maxChars = 50;
+ const text = 'x'.repeat(230); // single run, no break opportunities
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks.length).toBe(Math.ceil(230 / 50));
+ for (const c of chunks.slice(0, -1)) {
+ expect(c.length).toBe(maxChars);
+ }
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('respects the maxChunks ceiling, last chunk holds the remainder', () => {
+ const maxChars = 10;
+ const maxChunks = 3;
+ const text = 'y'.repeat(100); // would be 10 chunks unbounded
+ const chunks = chunkRawText(text, { maxChars, maxChunks });
+ expect(chunks).toHaveLength(maxChunks);
+ // First two chunks at cap, last chunk holds everything else.
+ expect(chunks[0].length).toBe(maxChars);
+ expect(chunks[1].length).toBe(maxChars);
+ expect(chunks[2].length).toBe(100 - 2 * maxChars);
+ expect(chunks.join('')).toBe(text);
+ });
+
+ it('reassembles losslessly for mixed content', () => {
+ const maxChars = 64;
+ const text = [
+ 'Title line here.',
+ '',
+ 'A paragraph with several sentences. It keeps going. And going more.',
+ '',
+ 'Anotherlongunbrokenword'.repeat(8),
+ '',
+ 'Final paragraph\twith\tmixed whitespace.',
+ ].join('\n');
+ const chunks = chunkRawText(text, { maxChars });
+ expect(chunks.join('')).toBe(text);
+ // Every non-final chunk respects the cap (final may exceed only via the
+ // remainder path, which doesn't apply here since maxChunks default is high).
+ for (const c of chunks) {
+ expect(c.length).toBeLessThanOrEqual(maxChars);
+ }
+ });
+
+ it('returns [] for non-string input', () => {
+ expect(chunkRawText(null)).toEqual([]);
+ expect(chunkRawText(undefined)).toEqual([]);
+ expect(chunkRawText(42)).toEqual([]);
+ });
+});
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 8c996500cf..f5e7f0f22c 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -338,6 +338,11 @@ export const catalogSyncScrapSchema = z.object({
embedding: syncEmbedding,
embeddingModel: z.string().max(100).nullable().optional(),
originInstanceId: z.string().max(64).nullable().optional(),
+ // Scrap chunking (catalog v7). Optional so a ≤v6 peer's scrap rows (which
+ // carry neither field) still validate: chunkIndex defaults to 0 and
+ // parentScrapId to null on the receiver — a plain non-chunked scrap.
+ chunkIndex: z.number().int().min(0).optional(),
+ parentScrapId: z.string().max(80).nullable().optional(),
createdAt: isoDate,
updatedAt: isoDate,
deleted: z.boolean().optional(),
diff --git a/server/lib/catalogValidation.test.js b/server/lib/catalogValidation.test.js
index a38c1831d1..b2e80fa36d 100644
--- a/server/lib/catalogValidation.test.js
+++ b/server/lib/catalogValidation.test.js
@@ -172,6 +172,35 @@ describe('catalogValidation — catalogSyncEnvelopeSchema', () => {
expect(() => catalogSyncEnvelopeSchema.parse(env)).not.toThrow();
});
+ it('accepts a v7 chunked-scrap envelope (chunkIndex + parentScrapId)', () => {
+ const env = {
+ scraps: [
+ { id: 'cat-scrap-parent', rawText: 'full', chunkIndex: 0, parentScrapId: null, createdAt: isoNow, updatedAt: isoNow },
+ { id: 'cat-scrap-c1', rawText: 'chunk one', chunkIndex: 1, parentScrapId: 'cat-scrap-parent', createdAt: isoNow, updatedAt: isoNow },
+ ],
+ };
+ const out = catalogSyncEnvelopeSchema.parse(env);
+ expect(out.scraps[1].chunkIndex).toBe(1);
+ expect(out.scraps[1].parentScrapId).toBe('cat-scrap-parent');
+ });
+
+ it('accepts a ≤v6 scrap envelope without chunk fields (mixed-version peer)', () => {
+ const env = {
+ scraps: [{ id: 'cat-scrap-old', rawText: 'hi', createdAt: isoNow, updatedAt: isoNow }],
+ };
+ const out = catalogSyncEnvelopeSchema.parse(env);
+ // Absent on the wire — the receiver defaults chunk_index 0 / parent NULL.
+ expect(out.scraps[0].chunkIndex).toBeUndefined();
+ expect(out.scraps[0].parentScrapId).toBeUndefined();
+ });
+
+ it('rejects a negative chunkIndex', () => {
+ const env = {
+ scraps: [{ id: 'cat-scrap-bad', rawText: 'hi', chunkIndex: -1, createdAt: isoNow, updatedAt: isoNow }],
+ };
+ expect(() => catalogSyncEnvelopeSchema.parse(env)).toThrow();
+ });
+
it('accepts an ingredients envelope with v2 tombstone fields', () => {
const env = {
ingredients: [
diff --git a/server/lib/db.js b/server/lib/db.js
index e1ef2103b8..9c32db8fae 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -122,6 +122,8 @@ export async function ensureSchema() {
embedding vector(768),
embedding_model VARCHAR(100),
origin_instance_id VARCHAR(36),
+ chunk_index INT NOT NULL DEFAULT 0,
+ parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE,
@@ -138,6 +140,18 @@ export async function ensureSchema() {
`CREATE INDEX IF NOT EXISTS idx_catalog_scraps_sync_seq ON catalog_scraps (sync_sequence)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_scraps_created_at ON catalog_scraps (created_at)`,
`CREATE INDEX IF NOT EXISTS idx_catalog_scraps_origin_instance ON catalog_scraps (origin_instance_id)`,
+ // Scrap chunking (catalog v7): a long paste is split into a parent row
+ // (chunk_index 0, raw_text = the FULL original text so the FTS index stays
+ // populated) plus N child rows (parent_scrap_id → parent, chunk_index 1..N,
+ // raw_text = the chunk slice). The extractor processes each child and unions
+ // results. The columns are declared inline in the CREATE above (fresh
+ // installs) AND re-added idempotently here for EXISTING installs (CREATE IF
+ // NOT EXISTS won't add columns to a pre-existing table). Existing rows
+ // default to chunk_index 0 / parent_scrap_id NULL — a plain non-chunked
+ // scrap, unchanged behavior. We do NOT retro-chunk existing rows.
+ `ALTER TABLE catalog_scraps ADD COLUMN IF NOT EXISTS chunk_index INT NOT NULL DEFAULT 0`,
+ `ALTER TABLE catalog_scraps ADD COLUMN IF NOT EXISTS parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE`,
+ `CREATE INDEX IF NOT EXISTS idx_catalog_scraps_parent ON catalog_scraps (parent_scrap_id)`,
`CREATE TABLE IF NOT EXISTS catalog_ingredients (
id TEXT PRIMARY KEY,
diff --git a/server/lib/index.js b/server/lib/index.js
index 00f9afc928..0f5ecbfdb2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -33,6 +33,7 @@ export * from './validation.js';
// === Story & narrative ===
export * from './bibleExtractor.js';
export * as catalogBulkParsers from './catalogBulkParsers.js';
+export * from './catalogChunking.js';
export * from './catalogTypes.js';
export * as catalogUniverseTags from './catalogUniverseTags.js';
export * from './canonPrompt.js';
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index c2f63d526c..e3278a34bd 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -104,7 +104,13 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// no `media` block. Media keys that don't resolve against the receiver's own
// library surface via the metadata-missing integrity endpoint rather than
// failing the apply.
- catalog: 6,
+ // v7 = `catalog_scraps` gained `chunk_index` + `parent_scrap_id` (a long paste
+ // chunks into a parent + N child rows; the extractor unions per-child drafts).
+ // Both fields ride the scrap sync envelope. Same gating rationale as v4–v6: a
+ // ≤v6 receiver doesn't understand child scrap rows, so a v7 sender pushing to
+ // it is sender-ahead and gets a 412. A v7 receiver still accepts ≤v6 senders
+ // (their scraps carry no chunk fields → chunkIndex 0 / parentScrapId null).
+ catalog: 7,
// NOTE: `videoHistory` is intentionally NOT listed here. The version gate
// rejects the ENTIRE snapshot/push payload on ANY ahead-mismatch (the
// comparator walks the union of keys), so declaring a brand-new key would
diff --git a/server/routes/catalog.js b/server/routes/catalog.js
index 29a42f34bf..8b816c1ba2 100644
--- a/server/routes/catalog.js
+++ b/server/routes/catalog.js
@@ -36,7 +36,7 @@ import {
import { parseBulkPayload, bundleToMarkdown, toYamlString } from '../lib/catalogBulkParsers.js';
import { resolveImageInputPath } from '../lib/fileUtils.js';
import { embedIngredient, embedBatch, ingredientEmbedSeed } from '../services/embeddings.js';
-import { extractIngredients } from '../services/catalogExtraction.js';
+import { extractIngredientsForScrap } from '../services/catalogExtraction.js';
import { ingestFromUrl, ingestFromFile, ingestFromVoice } from '../services/catalogIngestSources.js';
import { migrateBibleToCatalog } from '../scripts/migrateBibleToCatalog.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
@@ -66,7 +66,11 @@ router.post('/scraps', asyncHandler(async (req, res) => {
// semantic-search route or "find similar scraps" UI. Removed pending a search endpoint
// that justifies the LLM round-trip; the catalog_scraps.embedding column remains for
// future backfill (and peer sync still accepts embeddings from peers that have them).
- const scrap = await catalogDB.createScrap({
+ // Chunk long pastes into a parent + N child rows (short inputs stay a single
+ // row). The response still returns the PARENT scrap, so the client flow is
+ // unchanged — extraction (POST /scraps/:id/extract) transparently unions the
+ // children.
+ const scrap = await catalogDB.createChunkedScrap({
title: req.body.title,
rawText: req.body.rawText,
sourceKind: req.body.sourceKind,
@@ -91,8 +95,13 @@ router.post('/scraps/:id/extract', asyncHandler(async (req, res) => {
validateRequest(catalogExtractRequestSchema, req.body || {});
const scrap = await catalogDB.getScrap(req.params.id);
if (!scrap) throw new ServerError('Scrap not found', { status: 404 });
- const draft = await extractIngredients({
- rawText: scrap.rawText,
+ // Extraction runs on the PARENT scrap (it unions across its child chunks).
+ // A request against a child row is a client bug — reject rather than extract
+ // a single chunk in isolation and silently lose the rest of the corpus.
+ if (scrap.parentScrapId) {
+ throw new ServerError('extract runs on the parent scrap, not a chunk', { status: 400 });
+ }
+ const draft = await extractIngredientsForScrap({
scrapId: scrap.id,
providerOverride: req.body?.providerOverride,
});
diff --git a/server/routes/catalog.test.js b/server/routes/catalog.test.js
index 17391d7e71..2b815459ec 100644
--- a/server/routes/catalog.test.js
+++ b/server/routes/catalog.test.js
@@ -121,6 +121,61 @@ describe.skipIf(!dbReady)('POST /api/catalog/bulk-import — scrap persistence',
});
});
+describe.skipIf(!dbReady)('POST /api/catalog/scraps — chunking', () => {
+ it('chunks a long paste into a parent + children but returns the parent scrap', async () => {
+ // Over the 12k cap so createChunkedScrap splits it.
+ const para = `Para body ${NONCE} `.repeat(300); // ~5400 chars
+ const rawText = Array.from({ length: 4 }, (_, i) => `Section ${i}\n\n${para}`).join('\n\n');
+ expect(rawText.length).toBeGreaterThan(12_000);
+
+ const r = await request(makeApp())
+ .post('/api/catalog/scraps')
+ .send({ title: `Long ${NONCE}`, rawText, sourceKind: 'paste' });
+
+ expect(r.status).toBe(201);
+ const parent = r.body.scrap;
+ createdScrapIds.add(parent.id); // CASCADE drops children
+ // Response is the PARENT: chunk_index 0, no parent, FULL text.
+ expect(parent.chunkIndex).toBe(0);
+ expect(parent.parentScrapId).toBeNull();
+ expect(parent.rawText).toBe(rawText);
+
+ const children = await catalogDB.listChildScraps(parent.id);
+ expect(children.length).toBeGreaterThan(1);
+ expect(children.map((c) => c.rawText).join('')).toBe(rawText);
+ });
+
+ it('rejects an extract request against a child chunk with 400', async () => {
+ const para = `Child reject ${NONCE} `.repeat(300);
+ const rawText = Array.from({ length: 4 }, () => para).join('\n\n');
+ const create = await request(makeApp())
+ .post('/api/catalog/scraps')
+ .send({ rawText });
+ const parentId = create.body.scrap.id;
+ createdScrapIds.add(parentId);
+ const children = await catalogDB.listChildScraps(parentId);
+ expect(children.length).toBeGreaterThan(0);
+
+ const r = await request(makeApp())
+ .post(`/api/catalog/scraps/${children[0].id}/extract`)
+ .send({});
+ expect(r.status).toBe(400);
+ expect(r.body.error || r.body.message).toMatch(/parent scrap/i);
+ });
+
+ it('keeps a short paste as a single non-chunked scrap', async () => {
+ const r = await request(makeApp())
+ .post('/api/catalog/scraps')
+ .send({ rawText: `A brief note ${NONCE}.` });
+ expect(r.status).toBe(201);
+ const scrap = r.body.scrap;
+ createdScrapIds.add(scrap.id);
+ expect(scrap.parentScrapId).toBeNull();
+ const children = await catalogDB.listChildScraps(scrap.id);
+ expect(children).toHaveLength(0);
+ });
+});
+
describe.skipIf(!dbReady)('POST /api/catalog/bulk-import — export-bundle ref recreation', () => {
it('recreates the bundle ref link from `bundleRef` and honors per-row role', async () => {
const seriesId = `test-series-${NONCE}`;
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 96704ca3dc..2bb054ba11 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -132,6 +132,13 @@ CREATE TABLE IF NOT EXISTS catalog_scraps (
embedding vector(768),
embedding_model VARCHAR(100),
origin_instance_id VARCHAR(36),
+ -- Scrap chunking (catalog v7): a long paste splits into a parent (chunk_index
+ -- 0, parent_scrap_id NULL, raw_text = FULL original) plus N child rows
+ -- (chunk_index 1..N, parent_scrap_id → parent, raw_text = chunk slice). A
+ -- plain scrap is just a parent with no children. ensureSchema in
+ -- server/lib/db.js mirrors these as ADD COLUMN IF NOT EXISTS for existing installs.
+ chunk_index INT NOT NULL DEFAULT 0,
+ parent_scrap_id TEXT REFERENCES catalog_scraps(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
deleted BOOLEAN DEFAULT FALSE,
@@ -148,6 +155,7 @@ CREATE INDEX IF NOT EXISTS idx_catalog_scraps_fts
CREATE INDEX IF NOT EXISTS idx_catalog_scraps_sync_seq ON catalog_scraps (sync_sequence);
CREATE INDEX IF NOT EXISTS idx_catalog_scraps_created_at ON catalog_scraps (created_at);
CREATE INDEX IF NOT EXISTS idx_catalog_scraps_origin_instance ON catalog_scraps (origin_instance_id);
+CREATE INDEX IF NOT EXISTS idx_catalog_scraps_parent ON catalog_scraps (parent_scrap_id);
-- Extracted, structured ingredients. Char/place/object payloads follow the
-- shape sanitized by server/lib/storyBible.js so backfill and fresh ingest
diff --git a/server/services/catalogDB.js b/server/services/catalogDB.js
index 816e17581c..c07db65fa4 100644
--- a/server/services/catalogDB.js
+++ b/server/services/catalogDB.js
@@ -20,6 +20,7 @@ import {
defaultTagsForType,
} from '../lib/catalogTypes.js';
import { resolveImageInputPath } from '../lib/fileUtils.js';
+import { chunkRawText } from '../lib/catalogChunking.js';
import { getInstanceId } from './instances.js';
function newIngredientId(type) {
@@ -60,6 +61,8 @@ function rowToScrap(row) {
embedding: row.embedding ? pgvectorToArray(row.embedding) : null,
embeddingModel: row.embedding_model,
originInstanceId: row.origin_instance_id,
+ chunkIndex: row.chunk_index ?? 0,
+ parentScrapId: row.parent_scrap_id ?? null,
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString(),
deleted: !!row.deleted,
@@ -174,15 +177,15 @@ function rowToRevision(row) {
// alongside the ingredients + source links (see POST /api/catalog/bulk-import).
// Absent, falls through to the pool-level `query` as before. Mirrors the same
// option on `createIngredient` / `linkIngredientToSource`.
-export async function createScrap({ title, rawText, sourceKind = 'paste', metadata = {}, embedding = null, embeddingModel = null } = {}, { client } = {}) {
+export async function createScrap({ title, rawText, sourceKind = 'paste', metadata = {}, embedding = null, embeddingModel = null, chunkIndex = 0, parentScrapId = null } = {}, { client } = {}) {
if (!rawText) throw new Error('rawText is required');
const id = newScrapId();
const originInstanceId = await getInstanceId();
const exec = client ? client.query.bind(client) : query;
const result = await exec(
`INSERT INTO catalog_scraps
- (id, title, raw_text, source_kind, metadata, embedding, embedding_model, origin_instance_id)
- VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8)
+ (id, title, raw_text, source_kind, metadata, embedding, embedding_model, origin_instance_id, chunk_index, parent_scrap_id)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10)
RETURNING *`,
[
id,
@@ -193,11 +196,73 @@ export async function createScrap({ title, rawText, sourceKind = 'paste', metada
embedding ? arrayToPgvector(embedding) : null,
embeddingModel,
originInstanceId,
+ chunkIndex,
+ parentScrapId,
],
);
return rowToScrap(result.rows[0]);
}
+/**
+ * Create a scrap, chunking a long `rawText` into a parent row + N child rows.
+ *
+ * The parent (chunk_index 0, parent_scrap_id NULL) stores the FULL original
+ * text so the existing scrap FTS index + "view source" UI keep working. When
+ * `chunkRawText` returns more than one chunk, each chunk slice is written as a
+ * child row (parent_scrap_id = parent.id, chunk_index 1..N, raw_text = the
+ * slice). The catalog extractor then runs per-child and unions the drafts.
+ *
+ * Short inputs (≤ one chunk) insert a single parent row identical to the
+ * pre-chunking behavior — no children. Returns the PARENT scrap.
+ *
+ * Wrapped in `withTransaction` so the parent + every child commit-or-rollback
+ * together — a half-written chunk set would leave the extractor unioning a
+ * partial corpus.
+ */
+export async function createChunkedScrap({ title, rawText, sourceKind = 'paste', metadata = {} } = {}) {
+ if (!rawText) throw new Error('rawText is required');
+ const chunks = chunkRawText(rawText);
+ if (chunks.length <= 1) {
+ return createScrap({ title, rawText, sourceKind, metadata });
+ }
+ return withTransaction(async (client) => {
+ // Parent carries the FULL text (chunk_index 0, no parent).
+ const parent = await createScrap(
+ { title, rawText, sourceKind, metadata, chunkIndex: 0, parentScrapId: null },
+ { client },
+ );
+ for (let i = 0; i < chunks.length; i++) {
+ await createScrap(
+ {
+ title,
+ rawText: chunks[i],
+ sourceKind,
+ metadata,
+ chunkIndex: i + 1,
+ parentScrapId: parent.id,
+ },
+ { client },
+ );
+ }
+ return parent;
+ });
+}
+
+/**
+ * Live child scraps for a chunked parent, ordered by chunk_index so the
+ * extractor processes the corpus in document order. Returns [] for a
+ * non-chunked scrap (no children).
+ */
+export async function listChildScraps(parentId) {
+ const result = await query(
+ `SELECT * FROM catalog_scraps
+ WHERE parent_scrap_id = $1 AND deleted = false
+ ORDER BY chunk_index ASC`,
+ [parentId],
+ );
+ return result.rows.map(rowToScrap);
+}
+
export async function getScrap(id) {
const result = await query(
`SELECT * FROM catalog_scraps WHERE id = $1 AND deleted = false`,
@@ -1188,11 +1253,18 @@ export async function getRefChangesSince(since = '0', limit = 100) {
export async function upsertScrapFromPeer(scrap) {
- const result = await query(
+ // A child scrap (parent_scrap_id set) may arrive in the envelope BEFORE its
+ // parent row — the sync apply path sorts parents first within one envelope,
+ // but a parent can still lag a child across pagination pages. Mirror the
+ // catalog_tags parent-less retry: on FK violation, NULL the parent so the
+ // child still lands, and a later page carrying the parent re-runs this upsert
+ // (LWW) to restore the link. chunk_index has no FK, so it always rides.
+ const apply = async (parentScrapId) => query(
`INSERT INTO catalog_scraps
(id, title, raw_text, source_kind, metadata, embedding, embedding_model,
- origin_instance_id, created_at, updated_at, deleted, deleted_at)
- VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11, $12)
+ origin_instance_id, chunk_index, parent_scrap_id,
+ created_at, updated_at, deleted, deleted_at)
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (id) DO UPDATE SET
title = EXCLUDED.title,
raw_text = EXCLUDED.raw_text,
@@ -1200,6 +1272,8 @@ export async function upsertScrapFromPeer(scrap) {
metadata = EXCLUDED.metadata,
embedding = EXCLUDED.embedding,
embedding_model = EXCLUDED.embedding_model,
+ chunk_index = EXCLUDED.chunk_index,
+ parent_scrap_id = EXCLUDED.parent_scrap_id,
updated_at = EXCLUDED.updated_at,
deleted = EXCLUDED.deleted,
deleted_at = EXCLUDED.deleted_at
@@ -1214,12 +1288,26 @@ export async function upsertScrapFromPeer(scrap) {
scrap.embedding ? arrayToPgvector(scrap.embedding) : null,
scrap.embeddingModel || null,
scrap.originInstanceId || null,
+ Number.isInteger(scrap.chunkIndex) ? scrap.chunkIndex : 0,
+ parentScrapId,
scrap.createdAt,
scrap.updatedAt,
!!scrap.deleted,
scrap.deletedAt || null,
],
);
+ const parentId = scrap.parentScrapId ?? null;
+ let result;
+ try {
+ result = await apply(parentId);
+ } catch (err) {
+ // 23503 = foreign_key_violation (parent not present yet). Retry parent-less.
+ if (err?.code === '23503' && parentId !== null) {
+ result = await apply(null);
+ } else {
+ throw err;
+ }
+ }
return { applied: result.rows.length > 0, isInsert: result.rows[0]?.is_insert ?? false };
}
diff --git a/server/services/catalogDB.test.js b/server/services/catalogDB.test.js
index efe3716716..8f7bdd145d 100644
--- a/server/services/catalogDB.test.js
+++ b/server/services/catalogDB.test.js
@@ -235,6 +235,50 @@ describe.skipIf(!dbReady)('catalogDB (Postgres CRUD round-trip)', () => {
expect(hydrated[0].rawText).toContain('long coat');
});
+ it('createChunkedScrap stores one parent for short input and no children', async () => {
+ if (!requireDb('chunked scrap short')) return;
+ const parent = await catalogDB.createChunkedScrap({
+ title: 'Short note',
+ rawText: 'A single short paragraph that fits in one chunk.',
+ sourceKind: 'paste',
+ });
+ createdScrapIds.add(parent.id);
+ expect(parent.chunkIndex).toBe(0);
+ expect(parent.parentScrapId).toBeNull();
+ const children = await catalogDB.listChildScraps(parent.id);
+ expect(children).toHaveLength(0);
+ });
+
+ it('createChunkedScrap splits a long paste into a parent + ordered children', async () => {
+ if (!requireDb('chunked scrap long')) return;
+ // 5 paragraphs well over the 12k cap so chunkRawText returns multiple slices.
+ const para = 'lorem ipsum dolor sit amet '.repeat(200); // ~5400 chars
+ const rawText = Array.from({ length: 5 }, (_, i) => `Para ${i}: ${para}`).join('\n\n');
+ expect(rawText.length).toBeGreaterThan(12_000);
+
+ const parent = await catalogDB.createChunkedScrap({
+ title: 'Long paste',
+ rawText,
+ sourceKind: 'paste',
+ });
+ createdScrapIds.add(parent.id); // CASCADE drops children on cleanup
+
+ // Parent holds the FULL text so the existing FTS index stays populated.
+ expect(parent.chunkIndex).toBe(0);
+ expect(parent.parentScrapId).toBeNull();
+ expect(parent.rawText).toBe(rawText);
+
+ const children = await catalogDB.listChildScraps(parent.id);
+ expect(children.length).toBeGreaterThan(1);
+ // chunk_index is 1..N in document order, parent_scrap_id points back.
+ children.forEach((child, i) => {
+ expect(child.chunkIndex).toBe(i + 1);
+ expect(child.parentScrapId).toBe(parent.id);
+ });
+ // Lossless: concatenating child slices reproduces the original text.
+ expect(children.map((c) => c.rawText).join('')).toBe(rawText);
+ });
+
it('exportSliceForRef bundles ingredients + scraps + refs for a ref', async () => {
if (!requireDb('export slice')) return;
const ing = await catalogDB.createIngredient({
diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.js
index 76558c1d49..e77d819bb7 100644
--- a/server/services/catalogExtraction.js
+++ b/server/services/catalogExtraction.js
@@ -23,7 +23,7 @@ import { runStagedLLM } from '../lib/stageRunner.js';
import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';
import { CATALOG_TYPES } from '../lib/catalogTypes.js';
import { catalogEvents } from './catalogEvents.js';
-import { listIngredientsForRef } from './catalogDB.js';
+import { getScrap, listChildScraps, listIngredientsForRef } from './catalogDB.js';
// Light-shape ingredient type ids, sourced from the shared registry
// (`extractionShape === 'light'`). Adding a light type to `catalogTypes.js`
@@ -271,6 +271,130 @@ export async function extractIngredients({ rawText, scrapId = null, providerOver
return { runId, ...draft, stages };
}
+// Every draft-array key `extractIngredients` can return — the bible plurals
+// (`characters`/`places`/`objects`) plus the light plurals (`ideas`/`scenes`/
+// `concepts`). Each KEY encodes the ingredient type, so deduping by name WITHIN
+// a key is a dedup by (name, type). Driven by the same registries the extractor
+// uses so a new type flows through without a manual edit.
+const DRAFT_ARRAY_KEYS = Object.freeze([
+ ...BIBLE_TYPE_IDS.map((kind) => BIBLE_FIELD[kind]),
+ ...LIGHT_TYPE_IDS.map(lightDraftKey),
+]);
+
+/**
+ * Union the per-child draft arrays from N chunk extractions into one draft,
+ * deduping by `<draftKey>|<lowercased name>` and KEEPING THE FIRST occurrence
+ * (chunk order = document order). Each draft key encodes the ingredient type,
+ * so this is a dedup by (name, type). Non-array / missing keys are tolerated.
+ *
+ * @param {Array<object>} drafts per-child draft objects ({ characters: [...], ... }).
+ * @returns {object} one merged draft with the same array keys.
+ */
+export function dedupDrafts(drafts = []) {
+ const merged = {};
+ for (const key of DRAFT_ARRAY_KEYS) merged[key] = [];
+ const seen = new Set();
+ for (const draft of drafts) {
+ if (!draft || typeof draft !== 'object') continue;
+ for (const key of DRAFT_ARRAY_KEYS) {
+ const arr = Array.isArray(draft[key]) ? draft[key] : [];
+ for (const entry of arr) {
+ const name = typeof entry?.name === 'string' ? entry.name.trim().toLowerCase() : '';
+ if (!name) continue;
+ const dedupKey = `${key}|${name}`;
+ if (seen.has(dedupKey)) continue;
+ seen.add(dedupKey);
+ merged[key].push(entry);
+ }
+ }
+ }
+ return merged;
+}
+
+// Map over an array with a bounded number of in-flight promises. Preserves
+// input order in the result. Used so a heavily-chunked scrap doesn't fan out
+// dozens of concurrent LLM extraction passes at once.
+async function mapWithConcurrency(items, concurrency, fn) {
+ const results = new Array(items.length);
+ let cursor = 0;
+ const worker = async () => {
+ while (cursor < items.length) {
+ const i = cursor++;
+ results[i] = await fn(items[i], i);
+ }
+ };
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, worker);
+ await Promise.all(workers);
+ return results;
+}
+
+// How many child-chunk extractions run concurrently. Bounded so a long paste
+// (up to CATALOG_CHUNK_MAX_CHARS-sized chunks × maxChunks) doesn't slam the
+// provider with dozens of parallel LLM calls.
+const CHUNK_EXTRACT_CONCURRENCY = 2;
+
+/**
+ * Extract candidate ingredients for a stored scrap, transparently handling
+ * chunked scraps. Loads the parent scrap; if it has child rows (a long paste
+ * that `createChunkedScrap` split), runs `extractIngredients` per child corpus
+ * with bounded concurrency and unions the drafts (dedup by name+type, keep
+ * first). A non-chunked scrap falls back to a single `extractIngredients` over
+ * the parent's full text — identical to the pre-chunking behavior.
+ *
+ * Always extracts against the PARENT scrap id (the route rejects extract calls
+ * on a child). Returns the same `{ runId, ...draft, stages }` shape as
+ * `extractIngredients` so the route + client review flow are unchanged.
+ *
+ * @param {object} args
+ * @param {string} args.scrapId Parent scrap id.
+ * @param {string} [args.providerOverride] Override the staged-llm provider.
+ */
+export async function extractIngredientsForScrap({ scrapId, providerOverride } = {}) {
+ const parent = await getScrap(scrapId);
+ if (!parent) throw new Error(`extractIngredientsForScrap: scrap ${scrapId} not found`);
+
+ const children = await listChildScraps(parent.id);
+ if (children.length === 0) {
+ return extractIngredients({ rawText: parent.rawText, scrapId: parent.id, providerOverride });
+ }
+
+ // Run each child corpus through the extractor with bounded concurrency, then
+ // union the per-child drafts. Progress frames still carry the parent scrapId
+ // so the UI's existing live checklist keeps tracking one scrap.
+ const childDrafts = await mapWithConcurrency(children, CHUNK_EXTRACT_CONCURRENCY, (child) =>
+ extractIngredients({ rawText: child.rawText, scrapId: parent.id, providerOverride }),
+ );
+
+ const merged = dedupDrafts(childDrafts);
+
+ // Aggregate per-stage status so the response's `stages` reflects the whole
+ // run: a stage is 'failed' only if it failed in EVERY child (a transient
+ // single-chunk failure shouldn't fail the stage when other chunks succeeded);
+ // count is the deduped merged total for that stage's keys.
+ const stageMap = new Map();
+ for (const draft of childDrafts) {
+ for (const stage of draft.stages || []) {
+ const prev = stageMap.get(stage.id);
+ if (!prev) {
+ stageMap.set(stage.id, { ...stage });
+ } else {
+ // Any success clears the failed flag; keep the first error seen.
+ if (stage.status !== 'failed') prev.status = 'completed';
+ if (!prev.error && stage.error) prev.error = stage.error;
+ }
+ }
+ }
+ const stages = [...stageMap.values()].map((stage) => {
+ const keys = stage.id === LIGHT_STAGE_ID
+ ? LIGHT_TYPE_IDS.map(lightDraftKey)
+ : [stage.id];
+ const count = keys.reduce((n, key) => n + merged[key].length, 0);
+ return { ...stage, count };
+ });
+
+ return { runId: randomUUID(), ...merged, stages };
+}
+
// (refKind, refId) pairs the scan is allowed to consider. Only catalog
// ingredients linked to one of the provided targets are eligible — a draft
// shouldn't claim a reference to a character that lives in an unrelated
diff --git a/server/services/catalogExtraction.test.js b/server/services/catalogExtraction.test.js
index ee20517209..cf17f45439 100644
--- a/server/services/catalogExtraction.test.js
+++ b/server/services/catalogExtraction.test.js
@@ -23,13 +23,21 @@ vi.mock('../lib/stageRunner.js', () => ({
// extractor consumes so scanProseForIngredientRefs stays a pure unit test.
vi.mock('./catalogDB.js', () => ({
listIngredientsForRef: vi.fn(),
+ getScrap: vi.fn(),
+ listChildScraps: vi.fn(),
}));
const bibleExtractor = await import('../lib/bibleExtractor.js');
const stageRunner = await import('../lib/stageRunner.js');
const catalogDB = await import('./catalogDB.js');
const { catalogEvents } = await import('./catalogEvents.js');
-const { extractIngredients, EXTRACTION_STAGES, scanProseForIngredientRefs } = await import('./catalogExtraction.js');
+const {
+ extractIngredients,
+ extractIngredientsForScrap,
+ dedupDrafts,
+ EXTRACTION_STAGES,
+ scanProseForIngredientRefs,
+} = await import('./catalogExtraction.js');
const emptyLightResponse = { content: { ideas: [], scenes: [], concepts: [] } };
@@ -248,6 +256,107 @@ describe('catalogExtraction — bundled light stage', () => {
});
});
+describe('catalogExtraction — dedupDrafts', () => {
+ it('unions per-child draft arrays under each type key', () => {
+ const merged = dedupDrafts([
+ { characters: [{ name: 'Alice' }], ideas: [{ name: 'Memory genes' }] },
+ { characters: [{ name: 'Bob' }], scenes: [{ name: 'Rooftop' }] },
+ ]);
+ expect(merged.characters.map((c) => c.name)).toEqual(['Alice', 'Bob']);
+ expect(merged.ideas.map((c) => c.name)).toEqual(['Memory genes']);
+ expect(merged.scenes.map((c) => c.name)).toEqual(['Rooftop']);
+ });
+
+ it('dedups by name+type keeping the FIRST occurrence (case-insensitive)', () => {
+ const merged = dedupDrafts([
+ { characters: [{ name: 'Echo', summary: 'first' }] },
+ { characters: [{ name: 'echo', summary: 'second' }, { name: 'Nova' }] },
+ ]);
+ expect(merged.characters).toHaveLength(2);
+ expect(merged.characters[0]).toMatchObject({ name: 'Echo', summary: 'first' });
+ expect(merged.characters[1]).toMatchObject({ name: 'Nova' });
+ });
+
+ it('a same name under DIFFERENT type keys is NOT a dup', () => {
+ const merged = dedupDrafts([
+ { characters: [{ name: 'Harbor' }], places: [{ name: 'Harbor' }] },
+ ]);
+ expect(merged.characters).toHaveLength(1);
+ expect(merged.places).toHaveLength(1);
+ });
+
+ it('tolerates missing / non-array keys and nameless entries', () => {
+ const merged = dedupDrafts([
+ { characters: 'oops', ideas: [{ name: '' }, { summary: 'no name' }, null] },
+ null,
+ undefined,
+ ]);
+ expect(merged.characters).toEqual([]);
+ expect(merged.ideas).toEqual([]);
+ });
+});
+
+describe('catalogExtraction — extractIngredientsForScrap', () => {
+ it('falls back to a single extraction when the scrap has no children', async () => {
+ catalogDB.getScrap.mockResolvedValue({ id: 'cat-scrap-p', rawText: 'whole text', parentScrapId: null });
+ catalogDB.listChildScraps.mockResolvedValue([]);
+ bibleExtractor.extractBible.mockImplementation(async ({ kind, corpus }) => ({
+ extracted: [{ name: `${kind}:${corpus}` }],
+ }));
+
+ const out = await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+ expect(catalogDB.listChildScraps).toHaveBeenCalledWith('cat-scrap-p');
+ // Single pass over the parent's full text.
+ expect(bibleExtractor.extractBible).toHaveBeenCalledTimes(3); // 3 bible kinds, one pass
+ expect(out.characters).toEqual([{ name: 'character:whole text' }]);
+ });
+
+ it('runs per-child and unions the drafts (dedup by name+type, keep first)', async () => {
+ catalogDB.getScrap.mockResolvedValue({ id: 'cat-scrap-p', rawText: 'A|B', parentScrapId: null });
+ catalogDB.listChildScraps.mockResolvedValue([
+ { id: 'cat-scrap-c1', rawText: 'chunkA', chunkIndex: 1, parentScrapId: 'cat-scrap-p' },
+ { id: 'cat-scrap-c2', rawText: 'chunkB', chunkIndex: 2, parentScrapId: 'cat-scrap-p' },
+ ]);
+ // Both chunks surface a 'Shared' character; chunk B adds 'OnlyB'.
+ bibleExtractor.extractBible.mockImplementation(async ({ kind, corpus }) => {
+ if (kind !== 'character') return { extracted: [] };
+ if (corpus === 'chunkA') return { extracted: [{ name: 'Shared', summary: 'fromA' }] };
+ return { extracted: [{ name: 'Shared', summary: 'fromB' }, { name: 'OnlyB' }] };
+ });
+
+ const out = await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+ // bible called once per kind per child (3 kinds × 2 children).
+ expect(bibleExtractor.extractBible).toHaveBeenCalledTimes(6);
+ expect(out.characters.map((c) => c.name)).toEqual(['Shared', 'OnlyB']);
+ // First occurrence wins — chunk A's summary, not chunk B's.
+ expect(out.characters[0].summary).toBe('fromA');
+ });
+
+ it('a stage failing in only ONE child is not marked failed overall', async () => {
+ catalogDB.getScrap.mockResolvedValue({ id: 'cat-scrap-p', rawText: 'x', parentScrapId: null });
+ catalogDB.listChildScraps.mockResolvedValue([
+ { id: 'c1', rawText: 'chunkA', chunkIndex: 1, parentScrapId: 'cat-scrap-p' },
+ { id: 'c2', rawText: 'chunkB', chunkIndex: 2, parentScrapId: 'cat-scrap-p' },
+ ]);
+ bibleExtractor.extractBible.mockImplementation(async ({ kind, corpus }) => {
+ if (kind === 'place' && corpus === 'chunkA') throw new Error('llm timeout');
+ return { extracted: kind === 'place' ? [{ name: 'Harbor' }] : [] };
+ });
+
+ const out = await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+ const placeStage = out.stages.find((s) => s.id === 'places');
+ // chunk B's success clears the failed flag.
+ expect(placeStage.status).toBe('completed');
+ expect(out.places.map((p) => p.name)).toEqual(['Harbor']);
+ });
+
+ it('throws when the scrap does not exist', async () => {
+ catalogDB.getScrap.mockResolvedValue(null);
+ await expect(extractIngredientsForScrap({ scrapId: 'missing' }))
+ .rejects.toThrow(/not found/);
+ });
+});
+
describe('catalogExtraction — scanProseForIngredientRefs', () => {
// Build the { ingredient, role } row shape listIngredientsForRef returns.
const row = (id, name) => ({ ingredient: { id, name }, role: 'cast' });
diff --git a/server/services/catalogIngestSources.js b/server/services/catalogIngestSources.js
index 79c712c49e..978a16d0aa 100644
--- a/server/services/catalogIngestSources.js
+++ b/server/services/catalogIngestSources.js
@@ -22,7 +22,7 @@ import { randomUUID } from 'crypto';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import * as catalogDB from './catalogDB.js';
-import { extractIngredients } from './catalogExtraction.js';
+import { extractIngredientsForScrap } from './catalogExtraction.js';
import { transcribe } from './voice/stt.js';
import {
navigateToUrl,
@@ -55,8 +55,10 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
* contract the module header describes. `log` receives the created scrap.
*/
async function createScrapAndExtract({ title, rawText, sourceKind, metadata, providerOverride, log }) {
- const scrap = await catalogDB.createScrap({ title, rawText, sourceKind, metadata });
- const draft = await extractIngredients({ rawText, scrapId: scrap.id, providerOverride });
+ // Chunk long pastes identically to the textarea flow — createChunkedScrap
+ // returns the PARENT scrap and extractIngredientsForScrap unions the children.
+ const scrap = await catalogDB.createChunkedScrap({ title, rawText, sourceKind, metadata });
+ const draft = await extractIngredientsForScrap({ scrapId: scrap.id, providerOverride });
if (log) console.log(log(scrap));
return { scrap, draft };
}
diff --git a/server/services/catalogIngestSources.test.js b/server/services/catalogIngestSources.test.js
index 93146a505d..fb0eb917a6 100644
--- a/server/services/catalogIngestSources.test.js
+++ b/server/services/catalogIngestSources.test.js
@@ -15,9 +15,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('./catalogDB.js', () => ({
createScrap: vi.fn(),
+ createChunkedScrap: vi.fn(),
}));
vi.mock('./catalogExtraction.js', () => ({
extractIngredients: vi.fn(),
+ extractIngredientsForScrap: vi.fn(),
}));
vi.mock('./voice/stt.js', () => ({
transcribe: vi.fn(),
@@ -54,8 +56,8 @@ const DRAFT = { runId: 'r1', characters: [], stages: [] };
beforeEach(() => {
vi.clearAllMocks();
- catalogExtraction.extractIngredients.mockResolvedValue(DRAFT);
- catalogDB.createScrap.mockImplementation(async (args) => ({ id: 'cat-scrap-1', ...args }));
+ catalogExtraction.extractIngredientsForScrap.mockResolvedValue(DRAFT);
+ catalogDB.createChunkedScrap.mockImplementation(async (args) => ({ id: 'cat-scrap-1', ...args }));
// Hostnames resolve to a safe public address by default (the DNS SSRF guard).
dnsp.lookup.mockResolvedValue({ address: '93.184.216.34', family: 4 });
});
@@ -79,7 +81,7 @@ describe('fetchUrlMainText', () => {
browserService.evaluateOnPage.mockResolvedValue(JSON.stringify({ title: '', text: ' ' }));
await expect(fetchUrlMainText('https://ex.com/a', { settleMs: 0 })).rejects.toThrow(/no readable text/);
- expect(catalogDB.createScrap).not.toHaveBeenCalled();
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
});
it('refuses to ingest a hostname that resolves to a blocked address (DNS SSRF) before navigating', async () => {
@@ -127,12 +129,12 @@ describe('ingestFromUrl', () => {
const { scrap, draft } = await ingestFromUrl({ url: 'https://ex.com/a', settleMs: 0 });
expect(draft).toBe(DRAFT);
- const createArgs = catalogDB.createScrap.mock.calls[0][0];
+ const createArgs = catalogDB.createChunkedScrap.mock.calls[0][0];
expect(createArgs.sourceKind).toBe('url');
expect(createArgs.rawText).toBe('Body.');
expect(createArgs.metadata).toEqual({ url: 'https://ex.com/a', title: 'Article A' });
- expect(catalogExtraction.extractIngredients).toHaveBeenCalledWith(
- expect.objectContaining({ rawText: 'Body.', scrapId: scrap.id }),
+ expect(catalogExtraction.extractIngredientsForScrap).toHaveBeenCalledWith(
+ expect.objectContaining({ scrapId: scrap.id }),
);
});
});
@@ -141,7 +143,7 @@ describe('ingestFromFile', () => {
it('records filename + mime on a file scrap', async () => {
const { draft } = await ingestFromFile({ text: 'Notes body', filename: 'notes.md', mime: 'text/markdown' });
expect(draft).toBe(DRAFT);
- const createArgs = catalogDB.createScrap.mock.calls[0][0];
+ const createArgs = catalogDB.createChunkedScrap.mock.calls[0][0];
expect(createArgs.sourceKind).toBe('file');
expect(createArgs.title).toBe('notes.md');
expect(createArgs.metadata).toEqual({ filename: 'notes.md', mime: 'text/markdown' });
@@ -149,7 +151,7 @@ describe('ingestFromFile', () => {
it('throws on empty file text before creating a scrap', async () => {
await expect(ingestFromFile({ text: ' ', filename: 'empty.txt' })).rejects.toThrow(/no extractable text/);
- expect(catalogDB.createScrap).not.toHaveBeenCalled();
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
});
});
@@ -169,7 +171,7 @@ describe('ingestFromVoice', () => {
expect(persistFn).toHaveBeenCalledTimes(1);
expect(mediaKey).toBe('voice-memo-abc.wav');
expect(draft).toBe(DRAFT);
- const createArgs = catalogDB.createScrap.mock.calls[0][0];
+ const createArgs = catalogDB.createChunkedScrap.mock.calls[0][0];
expect(createArgs.sourceKind).toBe('voice-memo');
expect(createArgs.rawText).toBe('spoken memo text');
expect(createArgs.metadata).toEqual({ mediaKey: 'voice-memo-abc.wav', mimeType: 'audio/wav' });
@@ -183,7 +185,7 @@ describe('ingestFromVoice', () => {
ingestFromVoice({ audioBase64: wavBase64 }, { transcribeFn, persistFn }),
).rejects.toThrow(/empty transcript/);
expect(persistFn).not.toHaveBeenCalled();
- expect(catalogDB.createScrap).not.toHaveBeenCalled();
+ expect(catalogDB.createChunkedScrap).not.toHaveBeenCalled();
});
it('throws on empty audio before transcription', async () => {
diff --git a/server/services/catalogSync.js b/server/services/catalogSync.js
index 027268359b..0f8bf65cb4 100644
--- a/server/services/catalogSync.js
+++ b/server/services/catalogSync.js
@@ -235,9 +235,20 @@ export async function applyRemoteChanges(envelope = {}) {
});
// Scraps next (sources FK to BOTH so we want the parents present before the
- // join rows land).
+ // join rows land). Chunked scraps self-FK: a child carries
+ // `parentScrapId` → another scrap row, so order PARENT rows (no
+ // parentScrapId) before CHILD rows within this envelope to avoid an FK
+ // violation on the child insert. (`upsertScrapFromPeer` also retries
+ // parent-less on FK error to cover a parent lagging across pages.)
+ const orderedScraps = Array.isArray(envelope.scraps)
+ ? [...envelope.scraps].sort((a, b) => {
+ const aChild = a?.parentScrapId ? 1 : 0;
+ const bChild = b?.parentScrapId ? 1 : 0;
+ return aChild - bChild;
+ })
+ : envelope.scraps;
await applyKind({
- items: envelope.scraps, upsertFn: upsertScrapFromPeer, tally: stats.scraps, lww: true,
+ items: orderedScraps, upsertFn: upsertScrapFromPeer, tally: stats.scraps, lww: true,
errLabel: 'scrap', idFor: (s) => s?.id,
});
diff --git a/server/services/catalogSync.test.js b/server/services/catalogSync.test.js
index 088bc7f669..23f46d37d5 100644
--- a/server/services/catalogSync.test.js
+++ b/server/services/catalogSync.test.js
@@ -178,6 +178,27 @@ describe('applyRemoteChanges — dispatch + stats', () => {
// ingredient upserts.
expect(order).toEqual(['tag', 'scrap', 'ingredient', 'source', 'ref', 'relation']);
});
+
+ it('orders PARENT scraps before CHILD scraps so the self-FK lands (chunking)', async () => {
+ const seenIds = [];
+ catalogDB.upsertScrapFromPeer.mockImplementation(async (scrap) => {
+ seenIds.push(scrap.id);
+ return { applied: true, isInsert: true };
+ });
+
+ await applyRemoteChanges({
+ // Intentionally CHILD-first in the envelope — the apply path must reorder
+ // so the parent (parentScrapId null) is upserted before its children.
+ scraps: [
+ { id: 'child-2', rawText: 'b', chunkIndex: 2, parentScrapId: 'parent-1', createdAt: 't', updatedAt: 't' },
+ { id: 'child-1', rawText: 'a', chunkIndex: 1, parentScrapId: 'parent-1', createdAt: 't', updatedAt: 't' },
+ { id: 'parent-1', rawText: 'full', chunkIndex: 0, parentScrapId: null, createdAt: 't', updatedAt: 't' },
+ ],
+ });
+
+ expect(seenIds[0]).toBe('parent-1');
+ expect(seenIds.slice(1).sort()).toEqual(['child-1', 'child-2']);
+ });
});
describe('applyRemoteChanges — schema-version gate', () => {