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

address review: handle raw-array characters bucket shape, cap canon prompt rendering, drift-catch + OLD→NEW migration test via applyMigration helper

[._.]/ Adam Eivy0e25e7b907d9
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.js
index faaea35b8c..ce6044f97a 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js
@@ -68,56 +68,64 @@ const NEW_SHIPPED_MD5 = {
'pipeline-volume-verify.md': '49458d36700cb94e34806d536ffe2940',
};
+// Pure core — exposed for unit tests so the OLD→NEW upgrade branch can be
+// exercised with synthetic hash tables instead of pinning to a git commit.
+export async function applyMigration({ rootDir, accepted = ACCEPTED_OLD_MD5, current = NEW_SHIPPED_MD5 }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
+
+ let updated = 0;
+ let alreadyCurrent = 0;
+ let skipped = 0;
+
+ for (const filename of Object.keys(accepted)) {
+ const dataPath = join(stagesDir, filename);
+ const samplePath = join(sampleDir, filename);
+
+ const existing = await readFile(dataPath, 'utf-8').catch((err) => {
+ if (err.code !== 'ENOENT') throw err;
+ return null;
+ });
+
+ if (existing === null) {
+ // setup-data.js will copy it on next run; nothing for us to do.
+ console.log(`📄 arc-prompt ${filename}: not present in data/, will be created by setup-data.js`);
+ continue;
+ }
+
+ const existingMd5 = md5(existing);
+
+ if (existingMd5 === current[filename]) {
+ alreadyCurrent++;
+ continue;
+ }
+
+ const acceptedOld = accepted[filename];
+ if (!acceptedOld.includes(existingMd5)) {
+ console.warn(
+ `⚠️ arc-prompt ${filename} has been customized — skipping auto-update.\n` +
+ ` To pick up {{worldCanonText}} manually, diff:\n` +
+ ` data.sample/prompts/stages/${filename}\n` +
+ ` against your current:\n` +
+ ` data/prompts/stages/${filename}\n` +
+ ` and add the new "World canon" block in the same position as in the sample template.`,
+ );
+ skipped++;
+ continue;
+ }
+
+ const sampleContent = await readFile(samplePath, 'utf-8');
+ await writeFile(dataPath, sampleContent);
+ console.log(`✅ updated arc-prompt: ${filename}`);
+ updated++;
+ }
+
+ return { updated, alreadyCurrent, skipped };
+}
+
export default {
async up({ rootDir }) {
- const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
- const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');
-
- let updated = 0;
- let alreadyCurrent = 0;
- let skipped = 0;
-
- for (const filename of Object.keys(ACCEPTED_OLD_MD5)) {
- const dataPath = join(stagesDir, filename);
- const samplePath = join(sampleDir, filename);
-
- const existing = await readFile(dataPath, 'utf-8').catch((err) => {
- if (err.code !== 'ENOENT') throw err;
- return null;
- });
-
- if (existing === null) {
- // setup-data.js will copy it on next run; nothing for us to do.
- console.log(`📄 arc-prompt ${filename}: not present in data/, will be created by setup-data.js`);
- continue;
- }
-
- const existingMd5 = md5(existing);
-
- if (existingMd5 === NEW_SHIPPED_MD5[filename]) {
- alreadyCurrent++;
- continue;
- }
-
- const acceptedOld = ACCEPTED_OLD_MD5[filename];
- if (!acceptedOld.includes(existingMd5)) {
- console.warn(
- `⚠️ arc-prompt ${filename} has been customized — skipping auto-update.\n` +
- ` To pick up {{worldCanonText}} manually, diff:\n` +
- ` data.sample/prompts/stages/${filename}\n` +
- ` against your current:\n` +
- ` data/prompts/stages/${filename}\n` +
- ` and add the new "World canon" block in the same position as in the sample template.`,
- );
- skipped++;
- continue;
- }
-
- const sampleContent = await readFile(samplePath, 'utf-8');
- await writeFile(dataPath, sampleContent);
- console.log(`✅ updated arc-prompt: ${filename}`);
- updated++;
- }
+ const { updated, alreadyCurrent, skipped } = await applyMigration({ rootDir });
if (updated > 0) {
console.log(`📝 arc-prompt canon-context migration: ${updated} updated, ${alreadyCurrent} already current, ${skipped} skipped (customized)`);
diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
index 10e8ed7bb5..cdd6c38ae9 100644
--- a/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.test.js
@@ -9,8 +9,13 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
+import { createHash } from 'crypto';
-import migration from './019-arc-volume-prompts-canon-context.js';
+import migration, { applyMigration } from './019-arc-volume-prompts-canon-context.js';
+
+const md5 = (str) => createHash('md5')
+ .update(str.replace(/\r\n/g, '\n').replace(/\r/g, '\n'))
+ .digest('hex');
// Mirror of the migration's hash table — when these change the test fixtures
// below need to mirror the change too.
@@ -94,26 +99,36 @@ describe('migration 019 — arc/volume prompt canon context', () => {
}
});
- it('upgrades a pre-Phase B file (matching ACCEPTED_OLD_MD5[0]) to the new sample content', async () => {
- // Fetches the pre-Phase B body via git so we can plant a fixture whose
- // hash genuinely matches `ACCEPTED_OLD_MD5['pipeline-arc-resolve.md'][0]`.
- // Pinned to commit d4002a39 (the merge-base before Phase B landed). If
- // git isn't on PATH or the commit is gone (e.g. shallow clone), skip —
- // the no-op + customized-skip + idempotent paths cover the other branches.
- let preBody;
- try {
- const { execSync } = await import('node:child_process');
- preBody = execSync('git show d4002a39:data.sample/prompts/stages/pipeline-arc-resolve.md', {
- cwd: repoRoot,
- encoding: 'utf-8',
- });
- } catch {
- return; // git unavailable — exercise via the other branches.
+ it('NEW_SHIPPED_MD5 matches the live data.sample bodies (drift catch)', () => {
+ // Without this assertion, a future template edit that forgets to bump
+ // NEW_SHIPPED_MD5 would make the migration classify the sample-shaped
+ // file as "customized" and silently skip the upgrade — the idempotency
+ // test below would still pass (it checks "stays unchanged"), masking
+ // the regression. This assertion fails loudly at release time.
+ for (const filename of Object.keys(NEW_SHIPPED_MD5)) {
+ const liveHash = md5(sampleBody(filename));
+ expect(liveHash).toBe(NEW_SHIPPED_MD5[filename]);
}
- writeFileSync(join(stagesDir, 'pipeline-arc-resolve.md'), preBody);
- await migration.up({ rootDir });
- expect(readFileSync(join(stagesDir, 'pipeline-arc-resolve.md'), 'utf-8'))
- .toBe(sampleBody('pipeline-arc-resolve.md'));
+ });
+
+ it('upgrades when on-disk hash matches an accepted-old entry (synthetic fixture)', async () => {
+ // Plants a fixture body, registers its MD5 as the migration's "accepted
+ // old" hash via the pure applyMigration helper, then asserts the file
+ // gets rewritten to the data.sample version. Exercises the OLD→NEW
+ // upgrade branch without depending on git history (shallow clones +
+ // archive downloads work).
+ const filename = 'pipeline-arc-resolve.md';
+ const fakeOldBody = `# synthetic pre-migration body for ${filename}\n`;
+ const fakeOldHash = md5(fakeOldBody);
+
+ writeFileSync(join(stagesDir, filename), fakeOldBody);
+ const result = await applyMigration({
+ rootDir,
+ accepted: { [filename]: [fakeOldHash] },
+ current: { [filename]: md5(sampleBody(filename)) },
+ });
+ expect(result).toMatchObject({ updated: 1, skipped: 0 });
+ expect(readFileSync(join(stagesDir, filename), 'utf-8')).toBe(sampleBody(filename));
});
it('skips (does not clobber) a customized file whose hash matches neither old nor new', async () => {
diff --git a/server/lib/universePromptRenderers.js b/server/lib/universePromptRenderers.js
index fe71c04716..f46bb715c6 100644
--- a/server/lib/universePromptRenderers.js
+++ b/server/lib/universePromptRenderers.js
@@ -32,15 +32,32 @@ export function renderCompositesForPrompt(composites, { showLocked = false } = {
.join('\n');
}
+// Caps for canon → prompt rendering. Sanitized universes can hold up to
+// BIBLE_LIMITS.ENTRIES_PER_BIBLE_MAX (200) entries per kind with multi-KB
+// descriptions; rendering all of them into every arc/verify prompt would
+// inflate token cost + latency by orders of magnitude. Truncate at the
+// rendering layer (not in canon storage) so the on-disk universe stays rich
+// while LLM context stays bounded.
+export const CANON_PROMPT_ENTRIES_PER_KIND_MAX = 40;
+export const CANON_PROMPT_DESCRIPTION_MAX = 300;
+
+const truncDesc = (s) => {
+ if (typeof s !== 'string') return '';
+ const trimmed = s.trim();
+ if (trimmed.length <= CANON_PROMPT_DESCRIPTION_MAX) return trimmed;
+ return `${trimmed.slice(0, CANON_PROMPT_DESCRIPTION_MAX - 1).trimEnd()}…`;
+};
+
// Per-canon-kind formatting table — header label + per-entry line builder.
// One row per canon trunk; renderCanonForPrompt iterates this so a future
-// kind addition (or field tweak) is a one-line change.
+// kind addition (or field tweak) is a one-line change. formatEntry truncates
+// the long description field so a single entry can't dominate the prompt.
const CANON_SECTIONS = [
{
field: 'characters',
header: 'characters',
formatEntry: (c) => {
- const desc = c.physicalDescription || c.description || '';
+ const desc = truncDesc(c.physicalDescription || c.description || '');
const role = c.role ? ` [${c.role}]` : '';
return ` - ${c.name}${role}${desc ? `: ${desc}` : ''}`;
},
@@ -50,7 +67,7 @@ const CANON_SECTIONS = [
header: 'places',
formatEntry: (s) => {
const label = s.name || s.slugline || '(unnamed)';
- const desc = s.description || '';
+ const desc = truncDesc(s.description || '');
const palette = s.palette ? ` palette: ${s.palette}` : '';
return ` - ${label}${desc ? `: ${desc}` : ''}${palette}`;
},
@@ -59,8 +76,8 @@ const CANON_SECTIONS = [
field: 'objects',
header: 'objects',
formatEntry: (o) => {
- const desc = o.description || '';
- const sig = o.significance ? ` (${o.significance})` : '';
+ const desc = truncDesc(o.description || '');
+ const sig = o.significance ? ` (${truncDesc(o.significance)})` : '';
return ` - ${o.name}${desc ? `: ${desc}` : ''}${sig}`;
},
},
@@ -70,13 +87,22 @@ const CANON_SECTIONS = [
// prompt-friendly text block. Distinct from renderCategoriesForPrompt because
// canon entries are first-class named entities with rich metadata, not
// exploratory variations — the arc planner references them by name.
+// Caps each section at CANON_PROMPT_ENTRIES_PER_KIND_MAX entries; an
+// "(… + N more)" footer signals truncation so the LLM doesn't assume the
+// canon is complete.
export function renderCanonForPrompt(world) {
if (!world || typeof world !== 'object') return '';
const sections = [];
for (const { field, header, formatEntry } of CANON_SECTIONS) {
const entries = Array.isArray(world[field]) ? world[field] : [];
if (!entries.length) continue;
- sections.push(`${header}:\n${entries.map(formatEntry).join('\n')}`);
+ const shown = entries.slice(0, CANON_PROMPT_ENTRIES_PER_KIND_MAX);
+ const hiddenCount = entries.length - shown.length;
+ const lines = shown.map(formatEntry);
+ if (hiddenCount > 0) {
+ lines.push(` - (… + ${hiddenCount} more ${header} not shown — prompt budget reached)`);
+ }
+ sections.push(`${header}:\n${lines.join('\n')}`);
}
return sections.join('\n\n');
}
diff --git a/server/services/universeBuilderExpand.js b/server/services/universeBuilderExpand.js
index 18649d3652..52388d015c 100644
--- a/server/services/universeBuilderExpand.js
+++ b/server/services/universeBuilderExpand.js
@@ -435,8 +435,22 @@ export async function expandWorldTemplate({
const rawCategories = parsed.categories && typeof parsed.categories === 'object' ? parsed.categories : {};
const retiredCharBucket = rawCategories.characters;
let rawCharacters = Array.isArray(parsed.characters) ? [...parsed.characters] : [];
- if (retiredCharBucket && Array.isArray(retiredCharBucket.variations)) {
- for (const v of retiredCharBucket.variations) {
+ // Accept both shapes normalizeCategories accepts: object with `variations`
+ // OR raw array. Without the raw-array branch, an LLM emitting
+ // `categories: { characters: ["Ash", ...] }` would have its entries dropped
+ // by sanitizeCategories on save instead of folding into canon.
+ const retiredVariations = Array.isArray(retiredCharBucket)
+ ? retiredCharBucket
+ : Array.isArray(retiredCharBucket?.variations)
+ ? retiredCharBucket.variations
+ : null;
+ if (retiredVariations) {
+ for (const v of retiredVariations) {
+ if (typeof v === 'string') {
+ const trimmed = v.trim();
+ if (trimmed) rawCharacters.push({ name: trimmed });
+ continue;
+ }
if (!v || typeof v !== 'object' || !v.label) continue;
rawCharacters.push({ name: v.label, prompt: v.prompt });
}