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

move the scrap source-kind registry to a leaf module that declares its lens

[._.]/ Adam Eivy8fd8cf920955
diff --git a/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md b/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md
index 1a74717976..56bcb06a92 100644
--- a/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md
+++ b/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md
@@ -4,12 +4,12 @@ You are a creative analyst surfacing reusable narrative fragments from raw autho
You will return three arrays in a single JSON response: `ideas`, `scenes`, and `concepts`. The author has pasted prose, notes, or stream-of-consciousness into a personal creative catalog. They will review each candidate and selectively commit. Quality matters more than coverage — surface only what is genuinely reusable.
-{{#sourceKind}}
+{{#work.kind}}
## Source
-{{#scrapTitle}}- Title: {{scrapTitle}} — the author's own handle for this piece. Use it to read the text in context; do not extract it as an entry.
-{{/scrapTitle}}- Captured as: {{sourceKind}}
-{{/sourceKind}}
+{{#work.title}}- Title: {{work.title}} — the author's own handle for this piece. Use it to read the text in context; do not extract it as an entry.
+{{/work.title}}- Captured as: {{work.kind}}
+{{/work.kind}}
## Source text
diff --git a/scripts/migrations/394-factual-extraction-lens-prompts.js b/scripts/migrations/394-factual-extraction-lens-prompts.js
index c891ed285c..74523e98ac 100644
--- a/scripts/migrations/394-factual-extraction-lens-prompts.js
+++ b/scripts/migrations/394-factual-extraction-lens-prompts.js
@@ -32,7 +32,7 @@ export const NEW_SHIPPED_MD5 = {
'writers-room-characters.md': '73ec5bbfdad5c62ec5d5c30f0940febf',
'writers-room-places.md': '5d323f7aea4c2658e7e29afae2bdb7a4',
'writers-room-objects.md': '10efde7fbb46b28223db03f38e7043e4',
- 'catalog-ideas-scenes-concepts.md': '243074821ebc58eec63e26d284101b29',
+ 'catalog-ideas-scenes-concepts.md': 'e6cce39c76689ea9c5233f233cd0f153',
};
const { applyMigration, up } = makePromptReplaceMigration({
@@ -42,7 +42,7 @@ const { applyMigration, up } = makePromptReplaceMigration({
customizedHint: (filename) =>
` To upgrade it manually, diff data.reference/prompts/stages/${filename}\n` +
` against data/prompts/stages/${filename} and adopt the\n` +
- ' "{{#factual}} / ## Lens: non-fiction" section (plus the {{#sourceKind}}\n' +
+ ' "{{#factual}} / ## Lens: non-fiction" section (plus the {{#work.kind}}\n' +
' "## Source" block on catalog-ideas-scenes-concepts.md). Without it,\n' +
' factual ingest keeps extracting real people as fictional role tags.',
});
diff --git a/scripts/migrations/394-factual-extraction-lens-prompts.test.js b/scripts/migrations/394-factual-extraction-lens-prompts.test.js
index 7655ea1b79..da82ebca56 100644
--- a/scripts/migrations/394-factual-extraction-lens-prompts.test.js
+++ b/scripts/migrations/394-factual-extraction-lens-prompts.test.js
@@ -1,17 +1,24 @@
-import { readFileSync } from 'fs';
import { describe, expect, it } from 'vitest';
-import { repoRoot, runPromptMigrationTests } from './_testHelpers.js';
+import { runPromptMigrationTests, sampleBody } from './_testHelpers.js';
import migration, {
ACCEPTED_OLD_MD5,
NEW_SHIPPED_MD5,
applyMigration,
} from './394-factual-extraction-lens-prompts.js';
-const read = (filename) =>
- readFileSync(`${repoRoot}/data.reference/prompts/stages/${filename}`, 'utf8');
+const read = (filename) => sampleBody(filename);
-const BIBLE_FILES = ['writers-room-characters.md', 'writers-room-places.md', 'writers-room-objects.md'];
+// Per file: the refrains its lens section must carry. The three bible prompts
+// state the non-fiction frame and the absolute no-guess rule; the light stage
+// reframes its three kinds instead, pinned separately below.
+const NO_GUESS = '**A wrong guess is worse than a gap.**';
+const LENS_CONTENT = Object.freeze({
+ 'writers-room-characters.md': ['## Lens: non-fiction', NO_GUESS],
+ 'writers-room-places.md': ['## Lens: non-fiction', NO_GUESS],
+ 'writers-room-objects.md': ['## Lens: non-fiction', NO_GUESS],
+ 'catalog-ideas-scenes-concepts.md': ['## Lens: non-fiction'],
+});
describe('migration 394 — factual extraction lens prompts', () => {
runPromptMigrationTests({
@@ -22,24 +29,22 @@ describe('migration 394 — factual extraction lens prompts', () => {
prefix: 'migration-394-factual-extraction-lens-prompts-',
});
- it.each(Object.keys(NEW_SHIPPED_MD5))(
- '%s gates the lens behind the flag catalogExtraction supplies',
- (filename) => {
- const body = read(filename);
- // Without the SECTION the non-fiction rules would apply to every Writers
- // Room extraction, which is the opposite of the fix. The flag is the only
- // thing separating a memoir from a novel on this path.
- expect(body).toContain('{{#factual}}');
- expect(body).toContain('{{/factual}}');
- },
- );
-
- it.each(BIBLE_FILES)('%s tells the model the material is non-fiction about real subjects', (filename) => {
+ it.each(Object.entries(LENS_CONTENT))('%s gates its lens behind the flag catalogExtraction supplies', (filename, refrains) => {
const body = read(filename);
- expect(body).toContain('## Lens: non-fiction');
- // The rule every bible kind shares: the fiction prompts' invent-to-fill
- // instructions become fabrications about something that actually exists.
- expect(body).toContain('**A wrong guess is worse than a gap.**');
+ // Without the SECTION the non-fiction rules would apply to every Writers
+ // Room extraction, which is the opposite of the fix. The flag is the only
+ // thing separating a memoir from a novel on this path.
+ expect(body).toContain('{{#factual}}');
+ expect(body).toContain('{{/factual}}');
+ // And the fiction prompts' invent-to-fill instructions become fabrications
+ // about something that actually exists, so the no-guess rule is absolute.
+ for (const refrain of refrains) expect(body).toContain(refrain);
+ });
+
+ it('keeps every managed file in the lens-content table', () => {
+ // Otherwise a file added to the migration silently ships with no lens and
+ // no test naming it.
+ expect(Object.keys(LENS_CONTENT).sort()).toEqual(Object.keys(NEW_SHIPPED_MD5).sort());
});
it('suspends the character prompt\'s two role-tag / invent-to-fill rules by name', () => {
@@ -65,16 +70,17 @@ describe('migration 394 — factual extraction lens prompts', () => {
expect(lens).toContain('NOT a magic system, faction, or piece of world-building lore');
});
- it('gives the light stage a Source block that renders under both lenses', () => {
+ it('gives the light stage a Source block on the shared work.* framing', () => {
const body = read('catalog-ideas-scenes-concepts.md');
- const sourceBlock = body.split('{{#sourceKind}}')[1].split('{{/sourceKind}}')[0];
- // Gated on sourceKind rather than the title so an UNTITLED paste still tells
- // the model how the text was captured; gated at all so the block never
- // renders as an empty stub (the bug this issue reports on the catalog path).
- expect(sourceBlock).toContain('{{#scrapTitle}}- Title: {{scrapTitle}}');
- expect(sourceBlock).toContain('- Captured as: {{sourceKind}}');
+ const sourceBlock = body.split('{{#work.kind}}')[1].split('{{/work.kind}}')[0];
+ // Reads the same slots the three bible prompts declare, rather than aliases
+ // that can drift from them. Gated on the capture kind rather than the title
+ // so an UNTITLED paste still tells the model how the text was captured, and
+ // gated at all so the block never renders as the empty stub #7609 reports.
+ expect(sourceBlock).toContain('{{#work.title}}- Title: {{work.title}}');
+ expect(sourceBlock).toContain('- Captured as: {{work.kind}}');
// It must sit OUTSIDE the factual section — the title frames a novel excerpt
// just as usefully as a journal entry.
- expect(body.indexOf('{{#sourceKind}}')).toBeLessThan(body.indexOf('{{#factual}}'));
+ expect(body.indexOf('{{#work.kind}}')).toBeLessThan(body.indexOf('{{#factual}}'));
});
});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index eec7f52dd9..c22e7b4008 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -100,7 +100,7 @@ const EXPECTED_STAGE_NEW = {
'writers-room-places.md': '5d323f7aea4c2658e7e29afae2bdb7a4',
'writers-room-characters.md': '73ec5bbfdad5c62ec5d5c30f0940febf',
'writers-room-objects.md': '10efde7fbb46b28223db03f38e7043e4',
- 'catalog-ideas-scenes-concepts.md': '243074821ebc58eec63e26d284101b29',
+ 'catalog-ideas-scenes-concepts.md': 'e6cce39c76689ea9c5233f233cd0f153',
'writers-room-evaluate.md': '995cfd92061b55730b0e081998e96f84',
'cos-agent-briefing.md': 'a01c81d3a7f4ac0ca9e8d5137735c0e3',
'universe-character-expand.md': '961b73ba6e50df5d49f0cc76505e50bd',
diff --git a/server/AGENTS.md b/server/AGENTS.md
index 8c11584366..4c024d957d 100644
--- a/server/AGENTS.md
+++ b/server/AGENTS.md
@@ -43,6 +43,6 @@ These apply to Express/service/model code. Universal constraints (no try/catch o
## Prompt templates
-- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. Build it with `makePromptReplaceMigration` (`scripts/migrations/_lib.js`) and export `ACCEPTED_OLD_MD5` / `NEW_SHIPPED_MD5` from the migration — **never hand-mirror a hash table into `scripts/setup-data.js`.** `buildPromptDriftTables` sweeps those exports out of every migration and builds the drift warning (auto-updatable, i.e. still on a known old hash, vs customized) itself, so the migration performing the upgrade is the single source of truth. `scripts/migrations/394-factual-extraction-lens-prompts.js` is the worked example; a `makeSeedMigration` (e.g. `048-catalog-ideas-scenes-concepts-stage.js`) only copies MISSING files and will not upgrade an installed template. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.
+- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. Build it with `makePromptReplaceMigration` and export `ACCEPTED_OLD_MD5` / `NEW_SHIPPED_MD5` — **never hand-mirror a hash table into `scripts/setup-data.js`**, which sweeps those exports itself via `buildPromptDriftTables`. Worked example: `scripts/migrations/394-factual-extraction-lens-prompts.js`. A `makeSeedMigration` only copies MISSING files and will NOT upgrade an installed template. Re-point every earlier migration naming the same file at the new hash (`_shippedHashDrift.test.js` fails otherwise) and keep the superseded hash in the new migration's accepted-old set. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.
- **A `PROMPT_VERSIONS` bump for a scheduled-task prompt (`server/services/taskPromptDefaults.js`) needs NO migration** — its second step is `node scripts/regen-prompt-integrity-snapshot.js`, which retires the outgoing hash (root `AGENTS.md` "Distribution model"). `readSchedule()` in `server/services/taskScheduleStore.js` already upgrades every uncustomized stored prompt to the shipped default on the next `loadSchedule()` and persists the result — the first schedule read after the update converges the install regardless of whether a migration ran. Six migrations re-implemented that same loop against `data/task-schedule.json` (a path the store never reads — it reads `data/cos/task-schedule.json`) before this was written down: `281-reconcile-missing-releases-prompt.js`, `293-agents-md-prompt-rename.js`, `297-release-check-slashdo-review-prompt.js`, `308-release-check-advisory-review-prompt.js`, `332-release-check-fix-blockers-prompt.js`, `338-claim-issue-volunteer-claim-contract.js`. They stay — the distribution model forbids deleting applied migrations — but they are closed precedent, not a pattern to repeat. `scripts/migrations/promptBumpMigrations.guard.test.js` fails if a seventh copy imports `taskPromptDefaults.js` and writes `task-schedule.json`.
- **Creative prompts carry the IP-latitude clause automatically — never stamp it by hand.** PortOS is a professional artist's tool; a model that silently renames, genericizes, or disclaimers a deliberate reference to existing IP produces defective output, and rights/clearance is the operator's responsibility, not the model's. `server/lib/creativeLatitude.js` owns the clause and the single table that classifies what gets it, applied at each of the three LLM transports: `promptService.buildPrompt` (stage templates, keyed on the stage name — fails SAFE, so a stage the tables never saw is stamped), `promptRunner.runPromptThroughProvider` (every hand-rolled prompt, keyed on the run `source` tag it already requires — an allowlist, since ops calls dominate there), and `aiProvider.callProviderAISimple` (its own fetch, so creative callers pass `creative: true`). So **a new creative stage or LLM-calling service is covered only once its stage name / `source` is classified in that module** — add the prefix or exact name there rather than wrapping a call site. Two guard tests force the decision: `creativeLatitude.test.js` walks `data.reference/prompts/stage-config.json`, and `creativeLatitude.sources.test.js` scans every `source:` literal handed to the shared runners — both fail on an unclassified entry. A caller that budgets a context window before the stamp lands (the inline editorial check) must reserve `CREATIVE_LATITUDE_TOKENS`.
diff --git a/server/lib/README.md b/server/lib/README.md
index ba70605cd7..5866445e5f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -159,6 +159,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. |
| `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. |
+| `catalogSourceKinds.js` | Catalog scrap SOURCE-KIND registry — one `{ id, label, factual }` entry per ingest path that mints a `catalog_scraps` row. A pure leaf (no zod, no db) so the extractor can read a path's lens without pulling the validation layer in behind it. `SCRAP_SOURCE_KIND_IDS` is the id list `catalogValidation.js` builds its local-ingest Zod enum from; `isFactualSourceKind(id)` answers "is this lived material rather than invented fiction?" and gates the `{{#factual}}` sections in the four catalog extraction prompts — an unknown kind (including one a newer peer synced in) reads as non-factual, which is the pre-#7609 behavior. Declaring the lens beside the id is what stops a new ingest source silently extracting a memoir as fictional role tags. |
| `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`). The client projects its UI registry from this one (`client/src/lib/catalogTypes.js`) rather than copying it. |
| `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/catalogSourceKinds.js b/server/lib/catalogSourceKinds.js
new file mode 100644
index 0000000000..1fbfadd73c
--- /dev/null
+++ b/server/lib/catalogSourceKinds.js
@@ -0,0 +1,51 @@
+/**
+ * Catalog scrap SOURCE-KIND registry — one entry per ingest path that mints a
+ * `catalog_scraps` row, and the extraction lens that path implies.
+ *
+ * A pure leaf (no zod, no db) so both the validation layer and the extractor
+ * can read it. That split is the point: the lens used to live as a private
+ * two-element Set inside `catalogExtraction.js`, so adding an ingest source
+ * gave you a working route that silently extracted a memoir through the
+ * fiction lens — the exact bug #7609 reports. Declaring `factual` HERE, beside
+ * the id, makes a new source decide its lens at the moment it is registered.
+ *
+ * `factual: true` means the path produces the user's own lived capture (a
+ * memoir, journal entry, or recorded thought about real people and places)
+ * rather than invented story material. It drives the `{{#factual}}` sections
+ * in the four catalog extraction prompts. Phase 2 of #7609 binds ingest to a
+ * universe whose own `factual` flag becomes the primary signal, with the
+ * source kind as the fallback for a scrap catalogued into no universe.
+ */
+
+export const SCRAP_SOURCE_KINDS = Object.freeze([
+ { id: 'paste', label: 'Pasted text', factual: false },
+ // POST /catalog/ingest/brain — an existing brain record (idea / memory /
+ // project / admin). The user's own captured thought.
+ { id: 'brain-bridge', label: 'Brain record', factual: true },
+ { id: 'importer-handoff', label: 'Importer handoff', factual: false },
+ { id: 'manual', label: 'Manual entry', factual: false },
+ // POST /catalog/ingest/url — fetched + main-text-extracted page
+ { id: 'url', label: 'Web page', factual: false },
+ // POST /catalog/ingest/file — uploaded .txt/.md/.pdf
+ { id: 'file', label: 'Uploaded file', factual: false },
+ // POST /catalog/ingest/voice — recorded memo, Whisper-transcribed. Spoken
+ // first-person capture.
+ { id: 'voice-memo', label: 'Voice memo', factual: true },
+].map(Object.freeze));
+
+/**
+ * The bare ids, for the Zod enum that gates the LOCAL ingest routes. The
+ * sync-apply path deliberately uses a looser `z.string().max(32)` instead, so
+ * a newer peer can push a kind this build does not enumerate.
+ */
+export const SCRAP_SOURCE_KIND_IDS = Object.freeze(SCRAP_SOURCE_KINDS.map((k) => k.id));
+
+const FACTUAL_IDS = new Set(SCRAP_SOURCE_KINDS.filter((k) => k.factual).map((k) => k.id));
+
+/**
+ * Does this source kind produce lived material rather than invented fiction?
+ * An unknown kind (including one a newer peer synced in) reads as non-factual:
+ * the fiction lens is what every extraction rendered before #7609, so it is the
+ * safe answer for a kind this build cannot classify.
+ */
+export const isFactualSourceKind = (sourceKind) => FACTUAL_IDS.has(sourceKind);
diff --git a/server/lib/catalogSourceKinds.test.js b/server/lib/catalogSourceKinds.test.js
new file mode 100644
index 0000000000..34e94f73b2
--- /dev/null
+++ b/server/lib/catalogSourceKinds.test.js
@@ -0,0 +1,55 @@
+/**
+ * The registry's job is to make a new ingest source DECLARE its extraction
+ * lens. These pin that contract — the lens used to be a private two-element
+ * Set inside catalogExtraction.js, where adding a source kind gave you a
+ * working route that silently read a memoir through the fiction lens (#7609).
+ */
+import { describe, it, expect } from 'vitest';
+
+import {
+ SCRAP_SOURCE_KINDS,
+ SCRAP_SOURCE_KIND_IDS,
+ isFactualSourceKind,
+} from './catalogSourceKinds.js';
+
+describe('catalogSourceKinds', () => {
+ it('forces every source kind to declare its lens explicitly', () => {
+ // An entry that merely OMITS `factual` would read as fiction by accident
+ // rather than by decision — which is the failure this registry exists to
+ // stop. A new ingest path must answer the question.
+ for (const kind of SCRAP_SOURCE_KINDS) {
+ expect(typeof kind.id, `${kind.id} id`).toBe('string');
+ expect(typeof kind.label, `${kind.id} label`).toBe('string');
+ expect(typeof kind.factual, `${kind.id} must declare factual`).toBe('boolean');
+ }
+ });
+
+ it('keeps the Zod enum ids in lockstep with the registry', () => {
+ // catalogValidation.js gates the local ingest routes on these ids; a
+ // registry entry missing from the enum is an ingest route that 400s.
+ expect([...SCRAP_SOURCE_KIND_IDS]).toEqual(SCRAP_SOURCE_KINDS.map((k) => k.id));
+ expect(new Set(SCRAP_SOURCE_KIND_IDS).size).toBe(SCRAP_SOURCE_KIND_IDS.length);
+ });
+
+ it('reads first-person capture as factual and everything else as fiction', () => {
+ expect(isFactualSourceKind('voice-memo')).toBe(true);
+ expect(isFactualSourceKind('brain-bridge')).toBe(true);
+ expect(isFactualSourceKind('paste')).toBe(false);
+ expect(isFactualSourceKind('url')).toBe(false);
+ });
+
+ it('reads an unknown kind as non-factual', () => {
+ // A newer peer can sync a kind this build does not enumerate (the
+ // sync-apply path takes a loose string, not this enum). The fiction lens
+ // is what every extraction rendered before #7609, so it is the safe answer
+ // for a kind we cannot classify — never a guess that invents a real person.
+ expect(isFactualSourceKind('kind-from-a-newer-peer')).toBe(false);
+ expect(isFactualSourceKind(undefined)).toBe(false);
+ expect(isFactualSourceKind('')).toBe(false);
+ });
+
+ it('is frozen against mutation by a consumer', () => {
+ expect(Object.isFrozen(SCRAP_SOURCE_KINDS)).toBe(true);
+ expect(SCRAP_SOURCE_KINDS.every(Object.isFrozen)).toBe(true);
+ });
+});
diff --git a/server/lib/catalogValidation.js b/server/lib/catalogValidation.js
index 0dcc513863..2e73c76c7d 100644
--- a/server/lib/catalogValidation.js
+++ b/server/lib/catalogValidation.js
@@ -20,6 +20,7 @@ import {
isActiveType,
} from './catalogTypes.js';
import { csvIdsParam } from './sharedSchemas.js';
+import { SCRAP_SOURCE_KIND_IDS } from './catalogSourceKinds.js';
// Derived from the shared type registry (`catalogTypes.js`) — adding a SYSTEM
// type there flows through to consumers automatically. Kept as a frozen
@@ -77,17 +78,10 @@ const payload = z.record(z.string(), z.unknown())
// Scrap source kinds. The DB column is a free VARCHAR(32) so peers running a
// newer build can push kinds an older build doesn't enumerate (the sync-apply
// path uses the looser `z.string().max(32)` below, NOT this enum). This enum
-// gates the LOCAL ingest routes only — every value here is one a local ingest
-// path actually produces.
-export const SCRAP_SOURCE_KINDS = Object.freeze([
- 'paste',
- 'brain-bridge',
- 'importer-handoff',
- 'manual',
- 'url', // POST /catalog/ingest/url — fetched + main-text-extracted page
- 'file', // POST /catalog/ingest/file — uploaded .txt/.md/.pdf
- 'voice-memo', // POST /catalog/ingest/voice — recorded memo, Whisper-transcribed
-]);
+// gates the LOCAL ingest routes only — every id here is one a local ingest
+// path actually produces. The registry itself (ids, labels, and the extraction
+// lens each path implies) lives in the leaf `catalogSourceKinds.js`, so the
+// extractor can read the lens without pulling zod in behind it.
// --- User-defined catalog types (PostgreSQL `catalog_user_types`, #1001) --
// A user type is a DB-persisted (formerly settings.json), federated definition
@@ -141,7 +135,7 @@ export const catalogUserTypesSettingsSchema = z.array(catalogUserTypeSchema).max
export const catalogScrapCreateSchema = z.object({
title: z.string().trim().max(300).optional().nullable(),
rawText: z.string().min(1).max(2_000_000),
- sourceKind: z.enum(SCRAP_SOURCE_KINDS).optional(),
+ sourceKind: z.enum(SCRAP_SOURCE_KIND_IDS).optional(),
metadata: payload,
}).strict();
diff --git a/server/lib/index.js b/server/lib/index.js
index 8255bb5365..b915ee5381 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -91,6 +91,7 @@ export * from './threejsTransform.js';
// === Story & narrative ===
export * as catalogBulkParsers from './catalogBulkParsers.js';
export * from './catalogChunking.js';
+export * from './catalogSourceKinds.js';
export * from './catalogTypes.js';
export * as catalogUniverseTags from './catalogUniverseTags.js';
export * from './canonPrompt.js';
diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.js
index d0f53c83d4..f9a5c6b83f 100644
--- a/server/services/catalogExtraction.js
+++ b/server/services/catalogExtraction.js
@@ -21,7 +21,8 @@ import { randomUUID } from 'crypto';
import { extractBible } from './bibleExtractor.js';
import { runStagedLLM } from './stageRunner.js';
import { BIBLE_KINDS, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';
-import { CATALOG_TYPES } from '../lib/catalogTypes.js';
+import { CATALOG_TYPES, canonicalTagKey } from '../lib/catalogTypes.js';
+import { isFactualSourceKind } from '../lib/catalogSourceKinds.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { catalogEvents } from './catalogEvents.js';
import { getScrap, listChildScraps, listIngredientsForRef } from './catalogDB.js';
@@ -39,14 +40,6 @@ const BIBLE_TYPE_IDS = CATALOG_TYPES.filter((t) => t.extractionShape === 'bible'
// prompt's JSON keys + the draft scaffolding key results by this plural.
const lightDraftKey = (id) => `${id}s`;
-// Scrap source kinds whose text is the user's own lived capture rather than
-// invented fiction. A voice memo and a bridged brain record are first-person
-// by construction, so reading them through the fiction lens is exactly what
-// mints role tags (`MOM` / `DAD` / `NARRATOR`) out of a memoir. Phase 2 of
-// #7609 replaces this with the target universe's own `factual` flag, at which
-// point the source kind becomes the fallback rather than the only signal.
-const FACTUAL_SOURCE_KINDS = Object.freeze(new Set(['brain-bridge', 'voice-memo']));
-
// Tags stamped on rows extracted under the factual lens. `factual` marks every
// row as lived material; `real-person` additionally marks an extracted
// character so "real people" stays filterable in the catalog. Stamped per RUN
@@ -57,39 +50,35 @@ const FACTUAL_TAG = 'factual';
const REAL_PERSON_TAG = 'real-person';
/**
- * Derive the extraction lens from a stored scrap row. Returns only the keys
- * that carry a value so a title-less paste renders exactly the prompt it
- * renders today.
+ * Derive the extraction lens from a stored scrap row. Empty strings (not
+ * omitted keys) are what keep the prompts' mustache sections closed, so a
+ * title-less paste renders exactly the prompt it renders today.
*
* @param {{ title?: string, sourceKind?: string }} scrap
- * @returns {{ title?: string, sourceKind?: string, factual?: boolean }}
+ * @returns {{ title: string, sourceKind: string, factual: boolean }}
*/
function scrapExtractionContext(scrap) {
- if (!scrap || typeof scrap !== 'object') return {};
- const title = typeof scrap.title === 'string' ? scrap.title.trim() : '';
- const sourceKind = typeof scrap.sourceKind === 'string' ? scrap.sourceKind.trim() : '';
- const context = {};
- if (title) context.title = title;
- if (sourceKind) context.sourceKind = sourceKind;
- if (FACTUAL_SOURCE_KINDS.has(sourceKind)) context.factual = true;
- return context;
+ const trim = (value) => (typeof value === 'string' ? value.trim() : '');
+ const sourceKind = trim(scrap?.sourceKind);
+ return { title: trim(scrap?.title), sourceKind, factual: isFactualSourceKind(sourceKind) };
}
-// Append a tag without mutating the extractor's entry or duplicating a tag the
-// model already emitted.
-const withTag = (entry, tag) => {
- const tags = Array.isArray(entry?.tags) ? entry.tags : [];
- if (tags.includes(tag)) return entry;
- return { ...entry, tags: [...tags, tag] };
-};
-
-// Stamp the factual lens onto a sanitized entry list. A no-op under the fiction
-// lens, so every non-factual extraction keeps today's tags byte-for-byte.
-const stampFactualTags = (entries, { factual, isCharacter = false }) => {
- if (!factual || !Array.isArray(entries)) return entries;
+/**
+ * Append tags to a sanitized entry list without mutating the entries or
+ * duplicating a tag the model already emitted. An empty tag list returns the
+ * list unchanged, so every fiction-lens extraction keeps today's tags
+ * byte-for-byte and allocates nothing.
+ */
+const stampTags = (entries, tags) => {
+ if (tags.length === 0) return entries;
return entries.map((entry) => {
- const tagged = withTag(entry, FACTUAL_TAG);
- return isCharacter ? withTag(tagged, REAL_PERSON_TAG) : tagged;
+ const existing = Array.isArray(entry.tags) ? entry.tags : [];
+ // Compare by the catalog's own tag identity, so a model that emitted
+ // `Real-Person` or `factual ` doesn't put a visible duplicate in the
+ // review draft that `normalizeTags` would only collapse at persist time.
+ const seen = new Set(existing.map(canonicalTagKey));
+ const missing = tags.filter((tag) => !seen.has(canonicalTagKey(tag)));
+ return missing.length === 0 ? entry : { ...entry, tags: [...existing, ...missing] };
});
};
@@ -187,7 +176,7 @@ function sanitizeLightEntry(kind, raw) {
* malformed response logs and yields empty arrays, mirroring extractBible's
* sanitizeBibleList tolerance for missing keys.
*/
-async function extractIdeasScenesConcepts({ corpus, providerOverride, promptContext = {}, factual = false }) {
+async function extractIdeasScenesConcepts({ corpus, providerOverride, promptContext = {} }) {
const result = await runStagedLLM('catalog-ideas-scenes-concepts', {
...promptContext,
draftBody: corpus,
@@ -198,6 +187,8 @@ async function extractIdeasScenesConcepts({ corpus, providerOverride, promptCont
source: 'catalog-extract-ideas-scenes-concepts',
});
const content = result?.content || {};
+ // Lived material is tagged `factual`; an invented-fiction run stamps nothing.
+ const lightTags = promptContext.factual ? [FACTUAL_TAG] : [];
// One sanitized array per light type, keyed by plural draft key. Driven by
// the registry so a new light type (with its prompt JSON key) is picked up
// here without an extra line.
@@ -205,7 +196,7 @@ async function extractIdeasScenesConcepts({ corpus, providerOverride, promptCont
for (const id of LIGHT_TYPE_IDS) {
const key = lightDraftKey(id);
const raw = Array.isArray(content[key]) ? content[key] : [];
- out[key] = stampFactualTags(raw.map((r) => sanitizeLightEntry(id, r)).filter(Boolean), { factual });
+ out[key] = stampTags(raw.map((r) => sanitizeLightEntry(id, r)).filter(Boolean), lightTags);
}
return out;
}
@@ -264,16 +255,14 @@ export async function extractIngredients({ rawText, scrapId = null, providerOver
// The lens the scrap gives the model. `work.{title,kind,wordCount}` fills the
// three slots every writers-room bible prompt already declares and that the
- // catalog path used to render empty; `scrapTitle` / `sourceKind` fill the
- // light stage's own Source block; `factual` gates the non-fiction sections in
- // both families. Word count is measured against THIS corpus (a chunk's own
- // length), not the parent's, so a chunked run never tells the model it is
- // reading more text than it was handed.
- const { title: scrapTitle = '', sourceKind = '', factual = false } = context;
+ // catalog path used to render empty — the light stage's Source block reads the
+ // same three rather than carrying aliases that can drift. `factual` gates the
+ // non-fiction sections in both families. Word count is measured against THIS
+ // corpus (a chunk's own length), not the parent's, so a chunked run never
+ // tells the model it is reading more text than it was handed.
+ const { title = '', sourceKind = '', factual = false } = context;
const promptContext = {
- work: { title: scrapTitle, kind: sourceKind, wordCount: countWords(corpus) },
- scrapTitle,
- sourceKind,
+ work: { title, kind: sourceKind, wordCount: countWords(corpus) },
factual,
};
@@ -295,7 +284,7 @@ export async function extractIngredients({ rawText, scrapId = null, providerOver
emit({ type: 'stage', id: stage.id, status: 'running' });
try {
if (stage.id === LIGHT_STAGE_ID) {
- const out = await extractIdeasScenesConcepts({ corpus, providerOverride, promptContext, factual });
+ const out = await extractIdeasScenesConcepts({ corpus, providerOverride, promptContext });
const count = LIGHT_TYPE_IDS.reduce((n, id) => n + (out[lightDraftKey(id)]?.length || 0), 0);
emit({ type: 'stage', id: stage.id, status: 'completed', count });
return { id: stage.id, light: out, error: null };
@@ -308,10 +297,11 @@ export async function extractIngredients({ rawText, scrapId = null, providerOver
providerOverride,
source: `catalog-extract-${stage.id}`,
});
- const extracted = stampFactualTags(result.extracted, {
- factual,
- isCharacter: stage.kind === BIBLE_KIND.CHARACTER,
- });
+ // A real person additionally earns `real-person`, which is what keeps
+ // them filterable apart from an invented cast.
+ const extracted = stampTags(result.extracted, factual
+ ? [FACTUAL_TAG, ...(stage.kind === BIBLE_KIND.CHARACTER ? [REAL_PERSON_TAG] : [])]
+ : []);
emit({ type: 'stage', id: stage.id, status: 'completed', count: extracted.length });
return { id: stage.id, extracted, error: null };
} catch (err) {
diff --git a/server/services/catalogExtraction.test.js b/server/services/catalogExtraction.test.js
index d76055115c..af87981871 100644
--- a/server/services/catalogExtraction.test.js
+++ b/server/services/catalogExtraction.test.js
@@ -378,21 +378,6 @@ describe('catalogExtraction — extraction lens (#7609)', () => {
bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });
});
- it('threads the scrap title and source kind into BOTH prompt families', async () => {
- catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Kitchen table notes', sourceKind: 'paste' }));
-
- await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
-
- // Bible prompts declare {{work.title}} / {{work.kind}} / {{work.wordCount}};
- // the catalog path used to render all three empty.
- for (const call of bibleExtractor.extractBible.mock.calls) {
- expect(call[0].context.work).toEqual({ title: 'Kitchen table notes', kind: 'paste', wordCount: 2 });
- }
- // The light stage has its own {{scrapTitle}} / {{sourceKind}} Source block.
- const [, lightVars] = stageRunner.runStagedLLM.mock.calls[0];
- expect(lightVars).toMatchObject({ scrapTitle: 'Kitchen table notes', sourceKind: 'paste' });
- });
-
it('leaves the lens off for an invented-fiction paste', async () => {
catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Chapter one', sourceKind: 'paste' }));
bibleExtractor.extractBible.mockResolvedValue({ extracted: [{ name: 'THE BARTENDER' }] });
@@ -407,19 +392,13 @@ describe('catalogExtraction — extraction lens (#7609)', () => {
expect(out.ideas[0].tags).toEqual([]);
});
- it('raises the factual lens for a voice memo and a bridged brain record', async () => {
- for (const sourceKind of ['voice-memo', 'brain-bridge']) {
- vi.clearAllMocks();
- stageRunner.runStagedLLM.mockResolvedValue(emptyLightResponse);
- bibleExtractor.extractBible.mockResolvedValue({ extracted: [] });
- catalogDB.listChildScraps.mockResolvedValue([]);
- catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Sunday', sourceKind }));
+ it.each(['voice-memo', 'brain-bridge'])('raises the factual lens for %s', async (sourceKind) => {
+ catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Sunday', sourceKind }));
- await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+ await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
- expect(bibleExtractor.extractBible.mock.calls[0][0].context.factual).toBe(true);
- expect(stageRunner.runStagedLLM.mock.calls[0][1].factual).toBe(true);
- }
+ expect(bibleExtractor.extractBible.mock.calls[0][0].context.factual).toBe(true);
+ expect(stageRunner.runStagedLLM.mock.calls[0][1].factual).toBe(true);
});
it('stamps real-person on characters and factual on every row under the lens', async () => {
@@ -479,6 +458,10 @@ describe('catalogExtraction — extraction lens (#7609)', () => {
await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
const bibleVars = bibleExtractor.extractBible.mock.calls[0][0].context;
+ // Every bible kind is framed identically — one lens per scrap, not per stage.
+ for (const [args] of bibleExtractor.extractBible.mock.calls) {
+ expect(args.context.work).toEqual({ title: 'Kitchen table notes', kind: 'voice-memo', wordCount: 2 });
+ }
const characters = applyTemplate(stagePrompt('writers-room-characters'), { ...bibleVars, draftBody: 'x' });
// The framing block the catalog path used to render as three empty labels.
expect(characters).toContain('- Title: Kitchen table notes');
@@ -487,6 +470,8 @@ describe('catalogExtraction — extraction lens (#7609)', () => {
expect(characters).toContain('## Lens: non-fiction');
const [, lightVars] = stageRunner.runStagedLLM.mock.calls[0];
+ // One vocabulary: the light template reads the same {{work.*}} slots the
+ // three bible templates declare, so the framing cannot drift between them.
const light = applyTemplate(stagePrompt('catalog-ideas-scenes-concepts'), lightVars);
expect(light).toContain('- Title: Kitchen table notes');
expect(light).toContain('- Captured as: voice-memo');