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

stop catalog ingest extracting real people as fictional role tags (#7609)

[._.]/ Adam Eivy15d861274718
diff --git a/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md b/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md
index 13df7e1e22..1a74717976 100644
--- a/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md
+++ b/data.reference/prompts/stages/catalog-ideas-scenes-concepts.md
@@ -4,6 +4,13 @@ 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}}
+## 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}}
+
## Source text
```
@@ -18,6 +25,22 @@ You will return three arrays in a single JSON response: `ideas`, `scenes`, and `
- **concept** — an abstract structural, thematic, or world-building idea — a magic system, a piece of lore, a faction, a rule of how the world works, a recurring metaphor. NOT tied to one moment. Examples: "Magic costs sleep — every spell trades an hour of future sleep." / "The factions all worship the same dead god and disagree about which day to mourn." / "Memory is treated as currency by the merchant guild." NOT a character or a place.
+{{#factual}}
+## Lens: non-fiction
+
+This text is **the author's own lived material** — a memoir passage, journal entry, voice memo, or captured thought. It records things that happened; it is not invented story material. The three kinds still apply, but they mean this here, and these readings override the fiction examples above:
+
+- **idea** — a reflection, question, or theme the author keeps circling. Examples: "Why I apologize for things that were never mine." / "Whether leaving early was courage or just leaving." NOT a premise for a story to be written, and NOT a "what if?" about invented people.
+- **scene** — a **remembered moment**, concrete enough to return to: where it happened, who was there, and what happened. Examples: "The last dinner at the old kitchen table before the move." NOT a dramatic beat to be staged.
+- **concept** — a recurring pattern, family rule, belief, or way of doing things that shows up more than once. Examples: "Nobody in the house ever said sorry out loud." / "Money was discussed only as a number, never as a feeling." NOT a magic system, faction, or piece of world-building lore.
+
+Under this lens:
+
+- **Do not invent.** Rule 2 below is absolute here — this is a record of real events and real people, and a detail you supply becomes a false memory in the author's own catalog.
+- **Real people keep the names the author uses** (`Mom`, `Dad`, a first name) in `scenes[].actors`. Never an uppercase role tag like `MOM` or `THE MOTHER`.
+- **Name entries in the author's own words** where the text gives you the phrase. Do not dress a plain memory up as a logline.
+{{/factual}}
+
## Extraction rules
1. **Be selective.** Better to return fewer high-quality entries than to pad the lists. If the text contains zero of a given kind, return `[]` for that kind — not invented filler.
diff --git a/data.reference/prompts/stages/writers-room-characters.md b/data.reference/prompts/stages/writers-room-characters.md
index 48799e6dfb..d7040b7a57 100644
--- a/data.reference/prompts/stages/writers-room-characters.md
+++ b/data.reference/prompts/stages/writers-room-characters.md
@@ -16,6 +16,20 @@ The writer may have already edited some profiles. Treat any non-empty field belo
{{existingCharactersJson}}
```
+{{#factual}}
+## Lens: non-fiction
+
+This text is **first-person non-fiction about real people** — a memoir, journal entry, voice memo, or captured thought. The people in it exist. Read it as a record, not as a story, and let these rules override anything below that assumes invented material:
+
+- **Never mint a role-tag name.** The "for unnamed characters use a stable role tag like `THE BARTENDER`" instruction is for invented characters and does NOT apply here. An uppercase role tag turns a real family into stock cast.
+- **A person named by relation keeps that exact word as `name`, in the writer's own casing** — `Mom`, never `MOM` or `THE MOTHER`; likewise `Dad`, `Grandma`. When the text also gives a proper name, prefer the name and put the relation word in `aliases`.
+- **Do not extract the writer as a character.** The narrator of a memoir is the author, not a cast member — unless the text refers to them in the third person.
+- **`physicalDescription` may stay empty.** The "commit when prose is silent, then log it" rule is SUSPENDED for real people: inventing a real person's ethnicity, build, or wardrobe is a fabrication about someone who exists, not a useful image-gen default. Describe only what the text states, and omit the field entirely when it states nothing.
+- **`role` takes a plain descriptor the text supports** — `mother`, `neighbor`, `co-worker` — or is omitted. A real person is not a `protagonist` or an `antagonist`.
+- **Do not visually differentiate the cast.** Real people are not a cast to be spread across ethnicity, age, and silhouette axes for renderability.
+- The rule the framework fields already carry now covers the physical ones too: **A wrong guess is worse than a gap.**
+{{/factual}}
+
## Source prose
```
diff --git a/data.reference/prompts/stages/writers-room-objects.md b/data.reference/prompts/stages/writers-room-objects.md
index 3b9eba37aa..9e33f914f1 100644
--- a/data.reference/prompts/stages/writers-room-objects.md
+++ b/data.reference/prompts/stages/writers-room-objects.md
@@ -16,6 +16,16 @@ The writer may have already edited some entries. Treat any non-empty field below
{{existingObjectsJson}}
```
+{{#factual}}
+## Lens: non-fiction
+
+This text is **first-person non-fiction about real objects** — a memoir, journal entry, voice memo, or captured thought. The things in it existed. Read it as a record, not as a story:
+
+- **Name each object as the writer names it** — `Dad's watch`, `the blue car`. Keep the writer's article and possessive; do not rename a real belonging.
+- **Do not manufacture symbolism.** An object earns its entry by actually recurring or carrying weight in the text, not by being available to mean something.
+- **Describe only what the text states.** Omit `description` or `significance` rather than inventing provenance or meaning for a real possession. **A wrong guess is worse than a gap.**
+{{/factual}}
+
## Source prose
```
diff --git a/data.reference/prompts/stages/writers-room-places.md b/data.reference/prompts/stages/writers-room-places.md
index dc26de703d..2dde9cdf2d 100644
--- a/data.reference/prompts/stages/writers-room-places.md
+++ b/data.reference/prompts/stages/writers-room-places.md
@@ -16,6 +16,16 @@ The writer may have already edited some entries. Treat any non-empty field below
{{existingPlacesJson}}
```
+{{#factual}}
+## Lens: non-fiction
+
+This text is **first-person non-fiction about real places** — a memoir, journal entry, voice memo, or captured thought. The locations in it exist. Read it as a record, not as a story:
+
+- **Name each place as the writer names it** — `the kitchen`, `the back porch`, `the highway out of town`. Do not rename a real place into a genre-flavored invention.
+- **Build the slugline from the writer's own wording.** It is still the storyboard's match key, so keep it consistent across the text — but do not invent a cinematic location name to fill it.
+- **Describe only what the text states.** Omit `palette`, `era`, `weather`, or `recurringDetails` rather than inventing them: a guess about a place someone actually lived is a fabrication, not a helpful default. **A wrong guess is worse than a gap.**
+{{/factual}}
+
## Source prose
```
diff --git a/scripts/migrations/007-places-int-ext-time-of-day.js b/scripts/migrations/007-places-int-ext-time-of-day.js
index 1df63c534c..d8cfc76840 100644
--- a/scripts/migrations/007-places-int-ext-time-of-day.js
+++ b/scripts/migrations/007-places-int-ext-time-of-day.js
@@ -29,7 +29,7 @@ export const ACCEPTED_OLD_MD5 = {
};
export const NEW_SHIPPED_MD5 = {
- 'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4', // post-022 (setting → place rename)
+ 'writers-room-places.md': '5d323f7aea4c2658e7e29afae2bdb7a4', // post-394 (non-fiction lens); a7f68e5… lives on in 394's accepted-old
};
export default {
diff --git a/scripts/migrations/022-rename-bible-setting-to-place.js b/scripts/migrations/022-rename-bible-setting-to-place.js
index 089f3cf81b..64cb081888 100644
--- a/scripts/migrations/022-rename-bible-setting-to-place.js
+++ b/scripts/migrations/022-rename-bible-setting-to-place.js
@@ -92,7 +92,7 @@ export const ACCEPTED_OLD_MD5 = {
'bible-deference.md': '218f0e85643609ed85a12b1ccc7b5a8d',
};
export const NEW_SHIPPED_MD5 = {
- 'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',
+ 'writers-room-places.md': '5d323f7aea4c2658e7e29afae2bdb7a4', // post-394 (non-fiction lens)
'bible-deference.md': 'a4681348c27776e414acf6e0be566a99',
};
export const DRIFT_SUBDIRS = {
diff --git a/scripts/migrations/362-writers-room-character-framework.js b/scripts/migrations/362-writers-room-character-framework.js
index 3ebb0f65c8..d739c102ca 100644
--- a/scripts/migrations/362-writers-room-character-framework.js
+++ b/scripts/migrations/362-writers-room-character-framework.js
@@ -21,7 +21,9 @@ export const ACCEPTED_OLD_MD5 = {
]
};
export const NEW_SHIPPED_MD5 = {
- "writers-room-characters.md": "4b19f6538ff3a602007ef8e32c8e5047",
+ // Re-pointed at the post-394 body (non-fiction lens). 4b19f65… stays
+ // reachable as 394's accepted-old, so an install on it still upgrades.
+ "writers-room-characters.md": "73ec5bbfdad5c62ec5d5c30f0940febf",
"writers-room-evaluate.md": "995cfd92061b55730b0e081998e96f84"
};
const { applyMigration, up } = makePromptReplaceMigration({
diff --git a/scripts/migrations/394-factual-extraction-lens-prompts.js b/scripts/migrations/394-factual-extraction-lens-prompts.js
new file mode 100644
index 0000000000..c891ed285c
--- /dev/null
+++ b/scripts/migrations/394-factual-extraction-lens-prompts.js
@@ -0,0 +1,51 @@
+/**
+ * Give the four catalog-ingest extraction prompts a non-fiction lens (#7609).
+ *
+ * Pasting an autobiographical passage into Catalog Ingest used to come back as
+ * generic role tags — `MOM`, `DAD`, `NARRATOR` — because the extractor never
+ * told the prompts what they were reading. The fiction-shaped templates did
+ * exactly what they were told: "for unnamed characters use a stable role tag
+ * like THE BARTENDER", and "commit to a renderable detail when the prose is
+ * silent", both of which are wrong for a memoir about real people.
+ *
+ * Each template gains a `{{#factual}}` section that suspends the invent-to-fill
+ * rules, keeps a person named by relation as `Mom` rather than `MOM`, and lets
+ * the physical fields stay empty. The light stage additionally gains a `## Source`
+ * block carrying the scrap's own title and capture kind, which renders under
+ * both lenses — the catalog path previously rendered every framing slot empty.
+ *
+ * Both blocks are mustache-gated, so an install extracting invented fiction
+ * renders the same prompts it rendered before this migration. Hash replacement
+ * preserves a user-customized template.
+ */
+
+import { makePromptReplaceMigration } from './_lib.js';
+
+export const ACCEPTED_OLD_MD5 = {
+ 'writers-room-characters.md': ['4b19f6538ff3a602007ef8e32c8e5047'],
+ 'writers-room-places.md': ['a7f68e51dd6b4421d20f5bd9d855d9b4'],
+ 'writers-room-objects.md': ['1115d2d7d2e52e1e10c38325b88a4d94'],
+ 'catalog-ideas-scenes-concepts.md': ['98aa063cec8ad5c0e017dbc7bc949054'],
+};
+
+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',
+};
+
+const { applyMigration, up } = makePromptReplaceMigration({
+ accepted: ACCEPTED_OLD_MD5,
+ current: NEW_SHIPPED_MD5,
+ label: 'Factual extraction lens prompts',
+ 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' +
+ ' "## Source" block on catalog-ideas-scenes-concepts.md). Without it,\n' +
+ ' factual ingest keeps extracting real people as fictional role tags.',
+});
+
+export { applyMigration };
+export default { up };
diff --git a/scripts/migrations/394-factual-extraction-lens-prompts.test.js b/scripts/migrations/394-factual-extraction-lens-prompts.test.js
new file mode 100644
index 0000000000..7655ea1b79
--- /dev/null
+++ b/scripts/migrations/394-factual-extraction-lens-prompts.test.js
@@ -0,0 +1,80 @@
+import { readFileSync } from 'fs';
+import { describe, expect, it } from 'vitest';
+
+import { repoRoot, runPromptMigrationTests } 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 BIBLE_FILES = ['writers-room-characters.md', 'writers-room-places.md', 'writers-room-objects.md'];
+
+describe('migration 394 — factual extraction lens prompts', () => {
+ runPromptMigrationTests({
+ migration,
+ applyMigration,
+ ACCEPTED_OLD_MD5,
+ NEW_SHIPPED_MD5,
+ 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) => {
+ 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.**');
+ });
+
+ it('suspends the character prompt\'s two role-tag / invent-to-fill rules by name', () => {
+ const body = read('writers-room-characters.md');
+ // These two instructions are what mint `MOM` / `DAD` out of a memoir and
+ // what invent a real person's ethnicity and wardrobe. Naming them is the
+ // point — a generic "be accurate" line does not override a specific rule.
+ expect(body).toContain('THE BARTENDER');
+ expect(body).toContain('`Mom`, never `MOM`');
+ expect(body).toContain('"commit when prose is silent, then log it" rule is SUSPENDED');
+ expect(body).toContain('Do not visually differentiate the cast');
+ });
+
+ it('reframes all three light kinds for lived material', () => {
+ const body = read('catalog-ideas-scenes-concepts.md');
+ const lens = body.split('{{#factual}}')[1].split('{{/factual}}')[0];
+ // A factual section that redefined only one kind would leave the other two
+ // reading a memoir as invented world-building.
+ expect(lens).toContain('**idea**');
+ expect(lens).toContain('**scene**');
+ expect(lens).toContain('**concept**');
+ expect(lens).toContain('remembered moment');
+ 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', () => {
+ 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}}');
+ // 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}}'));
+ });
+});
diff --git a/scripts/setup-data-drift.test.js b/scripts/setup-data-drift.test.js
index 467530025c..eec7f52dd9 100644
--- a/scripts/setup-data-drift.test.js
+++ b/scripts/setup-data-drift.test.js
@@ -38,8 +38,10 @@ const EXPECTED_STAGE_OLD = {
'pipeline-arc-resolve.md': ['3f5ef41212890889811e4509a131c4e9', '122950b9f5ce84708ac1510ef13b1bce', '0611db539437083621e19bb88b005e8d', '0787128babf3c4c50e2f2cdb60214030', '5b340885c6e8f8afc63424d6b5bc7eb7', '87bc5c01f1a8a97b681727a38b05edc6', '8bb134554c122d1583c479ab3010e53d', '8e348f3d1894382889f9f0ee7d5c6792', '96f73a7e90526d65ef2bb100fb1cd4bf', 'a8677bbe1eb38f871fb152a5b0fec7c6', 'cc27b4da1d1a13c35e35d1c2d6183815', '31eca76b68f40de1b93734fe9bc9f4bb', '17fbb066d7957dc2e345df1795bb0d9d', 'ebd85d3a0b5949f16877c25ca498cce9', '2349bce80e9df8caafa391a6106327b6', 'aa2e463ebe0857859d79aa0c6ccb0256', '638b988c84b3e5599f7a2ce09fa149ce', '56926d795bd31f7e05e6bbbc646ecf9f'],
'pipeline-script-verify.md': ['ed6c8101644cfe56a100eb6bfe3587f3'],
'pipeline-extract-scenes.md': ['59fa5ee305ce53d91eb15224d8b546d3', 'c51fb208568d0d903eb43b437478b0ba'],
- 'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e'],
- 'writers-room-characters.md': ['cdd99c7a3ef92bf798f30fa2fb4465f1'],
+ 'writers-room-places.md': ['24a33628cc94d80fa5ca60831d973daf', '7f1f80eb63d67a21161994cde115045e', 'a7f68e51dd6b4421d20f5bd9d855d9b4'],
+ 'writers-room-characters.md': ['cdd99c7a3ef92bf798f30fa2fb4465f1', '4b19f6538ff3a602007ef8e32c8e5047'],
+ 'writers-room-objects.md': ['1115d2d7d2e52e1e10c38325b88a4d94'],
+ 'catalog-ideas-scenes-concepts.md': ['98aa063cec8ad5c0e017dbc7bc949054'],
'writers-room-evaluate.md': ['d3374472820df264731f435141e05270', 'd3b2b40bcabc9ca690fa67b69d64d628', '286e9498966187ed74126680da4a6a54'],
'universe-character-expand.md': ['ef109eb8e12ddb664c11c790271b5139', '67b6e73ed47f318451a730088b4cff14', '177b6e4e8bdf445308cf8ac423cd5ad8', '924fe8836f3014873d1789e98e997db2'],
'story-builder-idea-expand.md': ['778c86e2caa120856c36e4d5a4da3355', 'a23939626a226f7420cebfb45d47950c'],
@@ -95,8 +97,10 @@ const EXPECTED_STAGE_NEW = {
'pipeline-arc-resolve.md': '5fb659e459a296b7d378d7711f4b78cd',
'pipeline-script-verify.md': '722c62462d05462603cf67ca0ed1dee8',
'pipeline-extract-scenes.md': '9f404b0c4721b23932a6d2dcfc1fba43',
- 'writers-room-places.md': 'a7f68e51dd6b4421d20f5bd9d855d9b4',
- 'writers-room-characters.md': '4b19f6538ff3a602007ef8e32c8e5047',
+ 'writers-room-places.md': '5d323f7aea4c2658e7e29afae2bdb7a4',
+ 'writers-room-characters.md': '73ec5bbfdad5c62ec5d5c30f0940febf',
+ 'writers-room-objects.md': '10efde7fbb46b28223db03f38e7043e4',
+ 'catalog-ideas-scenes-concepts.md': '243074821ebc58eec63e26d284101b29',
'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 bd5d9880ac..8c11584366 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. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. 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` (`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`.
- **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/services/catalogExtraction.js b/server/services/catalogExtraction.js
index 9ff9cb02e3..d0f53c83d4 100644
--- a/server/services/catalogExtraction.js
+++ b/server/services/catalogExtraction.js
@@ -20,12 +20,12 @@
import { randomUUID } from 'crypto';
import { extractBible } from './bibleExtractor.js';
import { runStagedLLM } from './stageRunner.js';
-import { BIBLE_KINDS, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';
+import { BIBLE_KINDS, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS } from '../lib/storyBible.js';
import { CATALOG_TYPES } from '../lib/catalogTypes.js';
import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
import { catalogEvents } from './catalogEvents.js';
import { getScrap, listChildScraps, listIngredientsForRef } from './catalogDB.js';
-import { escapeRegExp } from '../lib/textUtils.js';
+import { countWords, escapeRegExp } from '../lib/textUtils.js';
// Light-shape ingredient type ids, sourced from the shared registry
// (`extractionShape === 'light'`). Adding a light type to `catalogTypes.js`
@@ -39,6 +39,60 @@ 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
+// from the scrap's lens — which is why this cannot be the type registry's
+// `defaultTags` (that table is per-type, and the same type is extracted under
+// both lenses).
+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.
+ *
+ * @param {{ title?: string, sourceKind?: string }} scrap
+ * @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;
+}
+
+// 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;
+ return entries.map((entry) => {
+ const tagged = withTag(entry, FACTUAL_TAG);
+ return isCharacter ? withTag(tagged, REAL_PERSON_TAG) : tagged;
+ });
+};
+
// Light-shape stage that bundles ideas/scenes/concepts into one LLM call.
// Surfaced to the UI as a single stage row — the three result arrays land
// in `draft.ideas` / `draft.scenes` / `draft.concepts` and the user reviews
@@ -133,8 +187,9 @@ function sanitizeLightEntry(kind, raw) {
* malformed response logs and yields empty arrays, mirroring extractBible's
* sanitizeBibleList tolerance for missing keys.
*/
-async function extractIdeasScenesConcepts({ corpus, providerOverride }) {
+async function extractIdeasScenesConcepts({ corpus, providerOverride, promptContext = {}, factual = false }) {
const result = await runStagedLLM('catalog-ideas-scenes-concepts', {
+ ...promptContext,
draftBody: corpus,
returnsJson: true,
}, {
@@ -150,7 +205,7 @@ async function extractIdeasScenesConcepts({ corpus, providerOverride }) {
for (const id of LIGHT_TYPE_IDS) {
const key = lightDraftKey(id);
const raw = Array.isArray(content[key]) ? content[key] : [];
- out[key] = raw.map((r) => sanitizeLightEntry(id, r)).filter(Boolean);
+ out[key] = stampFactualTags(raw.map((r) => sanitizeLightEntry(id, r)).filter(Boolean), { factual });
}
return out;
}
@@ -162,6 +217,9 @@ async function extractIdeasScenesConcepts({ corpus, providerOverride }) {
* @param {string} args.rawText The scrap body to extract from.
* @param {string} [args.scrapId] Scrap id to attach to progress frames.
* @param {string} [args.providerOverride] Override the staged-llm provider.
+ * @param {object} [args.context] Extraction lens — `{ title, sourceKind, factual }`
+ * from `scrapExtractionContext`. Fills the prompts'
+ * framing slots and gates the factual sections.
* @returns {Promise<{
* runId: string,
* characters: Array,
@@ -197,12 +255,28 @@ function neutralizeFenceDelimiters(text) {
// omitted, a fresh runId is minted (the normal single-scrap path). `emitStart`
// lets the chunked path suppress the per-child `start` frame, which would
// otherwise reset the client's stage checklist on every chunk.
-export async function extractIngredients({ rawText, scrapId = null, providerOverride, runId = randomUUID(), emitStart = true } = {}) {
+export async function extractIngredients({ rawText, scrapId = null, providerOverride, runId = randomUUID(), emitStart = true, context = {} } = {}) {
if (typeof rawText !== 'string' || !rawText.trim()) {
throw new Error('extractIngredients: rawText is required');
}
const corpus = neutralizeFenceDelimiters(rawText);
+
+ // 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;
+ const promptContext = {
+ work: { title: scrapTitle, kind: sourceKind, wordCount: countWords(corpus) },
+ scrapTitle,
+ sourceKind,
+ factual,
+ };
+
const emit = (frame) => {
try {
catalogEvents.emit('progress', { runId, scrapId, ...frame });
@@ -221,7 +295,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 });
+ const out = await extractIdeasScenesConcepts({ corpus, providerOverride, promptContext, factual });
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 };
@@ -230,11 +304,16 @@ export async function extractIngredients({ rawText, scrapId = null, providerOver
kind: stage.kind,
corpus,
existing: [],
+ context: promptContext,
providerOverride,
source: `catalog-extract-${stage.id}`,
});
- emit({ type: 'stage', id: stage.id, status: 'completed', count: result.extracted.length });
- return { id: stage.id, extracted: result.extracted, error: null };
+ const extracted = stampFactualTags(result.extracted, {
+ factual,
+ isCharacter: stage.kind === BIBLE_KIND.CHARACTER,
+ });
+ emit({ type: 'stage', id: stage.id, status: 'completed', count: extracted.length });
+ return { id: stage.id, extracted, error: null };
} catch (err) {
console.error(`❌ catalog extract ${stage.id} failed: ${err.message}`);
emit({ type: 'stage', id: stage.id, status: 'failed', error: err.message });
@@ -344,9 +423,14 @@ export async function extractIngredientsForScrap({ scrapId, providerOverride } =
const parent = await getScrap(scrapId);
if (!parent) throw new Error(`extractIngredientsForScrap: scrap ${scrapId} not found`);
+ // One lens for the whole scrap. Chunk children inherit the PARENT's context:
+ // a child row carries no title of its own and splitting a memoir mid-paragraph
+ // must not flip half of it back to the fiction lens.
+ const context = scrapExtractionContext(parent);
+
const children = await listChildScraps(parent.id);
if (children.length === 0) {
- return extractIngredients({ rawText: parent.rawText, scrapId: parent.id, providerOverride });
+ return extractIngredients({ rawText: parent.rawText, scrapId: parent.id, providerOverride, context });
}
// One shared run id for the whole chunked extraction so every child's
@@ -367,7 +451,7 @@ export async function extractIngredientsForScrap({ scrapId, providerOverride } =
// union the per-child drafts. Progress frames carry the parent scrapId + the
// shared runId 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, runId, emitStart: false }),
+ extractIngredients({ rawText: child.rawText, scrapId: parent.id, providerOverride, runId, emitStart: false, context }),
);
const merged = dedupDrafts(childDrafts);
diff --git a/server/services/catalogExtraction.test.js b/server/services/catalogExtraction.test.js
index 78a01197dc..d76055115c 100644
--- a/server/services/catalogExtraction.test.js
+++ b/server/services/catalogExtraction.test.js
@@ -31,6 +31,14 @@ const bibleExtractor = await import('./bibleExtractor.js');
const stageRunner = await import('./stageRunner.js');
const catalogDB = await import('./catalogDB.js');
const { catalogEvents } = await import('./catalogEvents.js');
+const { applyTemplate } = await import('../lib/promptTemplate.js');
+const { readFileSync } = await import('fs');
+const { join, dirname } = await import('path');
+const { fileURLToPath } = await import('url');
+
+// server/services → ../../data.reference is the shipped template directory.
+const stagePrompt = (name) =>
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'data.reference', 'prompts', 'stages', `${name}.md`), 'utf8');
const {
extractIngredients,
extractIngredientsForScrap,
@@ -357,6 +365,150 @@ describe('catalogExtraction — extractIngredientsForScrap', () => {
});
});
+// The scrap's title and source kind were loaded by getScrap and then dropped,
+// so the catalog path rendered every framing slot in the bible prompts empty
+// and the light stage had no idea what it was reading. A first-person memoir
+// then came back as `MOM` / `DAD` role tags, because the fiction-shaped
+// prompt did exactly what it was told (#7609).
+describe('catalogExtraction — extraction lens (#7609)', () => {
+ const scrap = (over = {}) => ({ id: 'cat-scrap-p', rawText: 'two words', parentScrapId: null, ...over });
+
+ beforeEach(() => {
+ catalogDB.listChildScraps.mockResolvedValue([]);
+ 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' }] });
+ stageRunner.runStagedLLM.mockResolvedValue({ content: { ideas: [{ name: 'A premise' }], scenes: [], concepts: [] } });
+
+ const out = await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+
+ expect(bibleExtractor.extractBible.mock.calls[0][0].context.factual).toBe(false);
+ expect(stageRunner.runStagedLLM.mock.calls[0][1].factual).toBe(false);
+ // No tag stamping under the fiction lens — a novel's cast is not a real person.
+ expect(out.characters[0].tags).toBeUndefined();
+ 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 }));
+
+ 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);
+ }
+ });
+
+ it('stamps real-person on characters and factual on every row under the lens', async () => {
+ catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Sunday', sourceKind: 'voice-memo' }));
+ bibleExtractor.extractBible.mockImplementation(async ({ kind }) => ({
+ extracted: [{ name: kind === 'character' ? 'Mom' : 'the kitchen', tags: ['seed'] }],
+ }));
+ stageRunner.runStagedLLM.mockResolvedValue({
+ content: { ideas: [{ name: 'Why I apologize' }], scenes: [], concepts: [] },
+ });
+
+ const out = await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+
+ // real-person is what keeps real people filterable apart from a cast; it
+ // rides the per-RUN lens, so it can never be the type registry's defaultTags.
+ expect(out.characters[0].tags).toEqual(['seed', 'factual', 'real-person']);
+ expect(out.places[0].tags).toEqual(['seed', 'factual']);
+ expect(out.ideas[0].tags).toEqual(['factual']);
+ });
+
+ it('does not double-stamp a tag the model already emitted', async () => {
+ catalogDB.getScrap.mockResolvedValue(scrap({ sourceKind: 'voice-memo' }));
+ bibleExtractor.extractBible.mockImplementation(async ({ kind }) => ({
+ extracted: kind === 'character' ? [{ name: 'Mom', tags: ['real-person'] }] : [],
+ }));
+
+ const out = await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+ expect(out.characters[0].tags).toEqual(['real-person', 'factual']);
+ });
+
+ it('gives every chunk of a chunked scrap the parent lens, with its OWN word count', async () => {
+ catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Sunday', sourceKind: 'voice-memo', rawText: 'a b c d' }));
+ catalogDB.listChildScraps.mockResolvedValue([
+ { id: 'c1', rawText: 'a b', chunkIndex: 1, parentScrapId: 'cat-scrap-p' },
+ { id: 'c2', rawText: 'c d e', chunkIndex: 2, parentScrapId: 'cat-scrap-p' },
+ ]);
+
+ await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+
+ const contexts = bibleExtractor.extractBible.mock.calls.map(([args]) => args.context);
+ // Splitting a memoir mid-paragraph must not flip half of it to fiction, and
+ // a child carries no title of its own.
+ expect(contexts.every((c) => c.factual === true && c.work.title === 'Sunday')).toBe(true);
+ // Word count is measured against the corpus the model actually receives —
+ // telling it "4 words" while handing it 2 is a lie about its own input.
+ expect(new Set(contexts.map((c) => c.work.wordCount))).toEqual(new Set([2, 3]));
+ });
+
+ // The two halves of the fix live in different files — the extractor names the
+ // variables, the shipped templates read them. Either side can be renamed
+ // without the other failing, and the symptom is a silently empty prompt
+ // section, which is the exact bug #7609 reports. Render the real templates
+ // with the real variables to keep them pinned together.
+ it('fills the shipped templates it hands those variables to', async () => {
+ catalogDB.getScrap.mockResolvedValue(scrap({ title: 'Kitchen table notes', sourceKind: 'voice-memo' }));
+
+ await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+
+ const bibleVars = bibleExtractor.extractBible.mock.calls[0][0].context;
+ 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');
+ expect(characters).toContain('- Kind: voice-memo');
+ expect(characters).toContain('- Word count: 2');
+ expect(characters).toContain('## Lens: non-fiction');
+
+ const [, lightVars] = stageRunner.runStagedLLM.mock.calls[0];
+ const light = applyTemplate(stagePrompt('catalog-ideas-scenes-concepts'), lightVars);
+ expect(light).toContain('- Title: Kitchen table notes');
+ expect(light).toContain('- Captured as: voice-memo');
+ expect(light).toContain('## Lens: non-fiction');
+ // Nothing unresolved is left staring at the model.
+ expect(characters).not.toMatch(/\{\{/);
+ expect(light).not.toMatch(/\{\{/);
+ });
+
+ it('renders a title-less paste exactly as it renders today', async () => {
+ catalogDB.getScrap.mockResolvedValue(scrap({ title: null, sourceKind: null }));
+
+ await extractIngredientsForScrap({ scrapId: 'cat-scrap-p' });
+
+ // Empty strings keep the mustache sections closed, so the prompt body is
+ // byte-identical to the pre-#7609 render.
+ const { context } = bibleExtractor.extractBible.mock.calls[0][0];
+ expect(context.work).toEqual({ title: '', kind: '', wordCount: 2 });
+ expect(context.factual).toBe(false);
+ });
+});
+
describe('catalogExtraction — scanProseForIngredientRefs', () => {
// Build the { ingredient, role } row shape listIngredientsForRef returns.
const row = (id, name) => ({ ingredient: { id, name }, role: 'cast' });