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

feat: render legacy-export PDF via pdf-lib (#1431)

Adam Eivy69de36042b23
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3e15703058..1d33f95313 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -3,6 +3,7 @@
## Added
- **Enrich a Universe noun — and refine a Universe style — from a reference image.** The Universe Bible's "Describe from image" modal now takes reference images from your **gallery** as well as uploads, and for **characters** it can do more than write the descriptor paragraph: a new **Build character details** action has a vision model read the reference image(s) and *propose* values for the character's still-blank structured fields (pronouns, age, visual notes, color palette, expressions, …). The proposals are shown for review — uncheck any, edit the text inline — and applied through the normal entry-patch path, so existing values are never overwritten (no-clobber, characters-only). Separately, the **Refine Prompts** form gains an optional **style-reference image**: pick one from the gallery and the refiner runs through a vision-capable provider, folding the image's palette/lighting/mood into the universe's `influences` + `styleNotes`. Both vision paths require an API provider with a vision model and reject a silent fallback to a non-vision provider rather than hallucinating from text alone; the vision provider/model pickers scope local (Ollama/LM Studio) backends to vision-capable models. Relatedly, a **model-not-found error no longer benches the whole provider** — that's a bad model id in one request, not a provider outage, so (like a content refusal) the single call still falls back but the provider stays available for its other working models (previously one bad model id could take Ollama offline for 30 minutes). (`server/services/universeVisionExpand.js`, `server/services/universeBuilderRefine.js`, `server/routes/universeBuilder.js`, `server/lib/promptRunner.js`, `client/src/components/universe/VisionDescribeModal.jsx`, `client/src/pages/UniverseBuilder.jsx`)
+- **[issue-1431] Legacy Export can now include a rendered PDF portrait.** Phase 2 of the Legacy Export (#901) bundle: pass `includePdf: true` to `POST /api/legacy-export` and the `.zip` gains a `legacy-portrait.pdf` rendered from the same per-section Markdown the bundle already produces — title page, per-section pages, heading sizing, word-wrapped body, and bullet/quote handling. It uses the already-present `pdf-lib` dependency (the same primitives as the comic-pages PDF — no new package) and degrades non-ASCII glyphs (VO₂, smart quotes, em-dashes, ⚠️) to WinAnsi-safe text so a stray Unicode character can't fail the render. The PDF is hashed into `manifest.json` like every other file and the manifest's `pdf.included` flag (previously hard-false) now reflects it, with the file name recorded under `pdf.file`. Default `includePdf` is **false** — the Markdown/JSON bundle stays the primary artifact. (`server/services/legacyExport.js`, `server/routes/legacyExport.js`, `server/lib/validation.js`, #1431)
- **[issue-1300] Editorial checks flag five prose anti-patterns (weak openings, mirror self-description, empty pleasantries, italic thoughts, darlings).** A bundle of line/scene-level checks (Create → Editorial Checks) for the well-known tells that pull readers out. Four are LLM checks over the drafted manuscript: **Weak opening** flags clichéd or mis-placed openers — "he wakes up" / alarm-clock / dream starts, weather-and-scenery preambles, and scenes that begin before the interesting moment; **Mirror self-description** catches the tired trick of a character studying their reflection so the prose can catalog their looks, while leaving reflections that do real story work alone; **Empty greeting / small-talk openings** flags scenes that open on greeting rituals or logistical filler that carry no tension or information, while sparing pleasantries laced with subtext; **Kill your darlings** surfaces precious, self-indulgent passages — showpiece descriptions, digressions, over-explaining, favorite lines that stop the scene — as cut candidates, judged by story need rather than quality (complementing the dead-metaphor check, which targets stock rather than precious prose). The fifth, **Italicized internal thoughts**, is a deterministic, high-precision scan that flags multi-word `*…*` / `_…_` italic thought runs (the prose is already in the character's perspective, so italicizing a thought is a tell) while leaving single-word emphasis, bold, and `snake_case` alone, with a configurable word threshold. All findings anchor a verbatim quote + issue number; the LLM checks ship four new stage prompts (`pipeline-editorial-{opening-start,mirror-description,dialogue-pleasantries,kill-your-darlings}`) that migrate for existing installs (103–106), the deterministic check needs no model. (`server/lib/editorial/{italicThoughts,checkRegistry}.js`) (#1300)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 6970ba1a8f..b85fd351a8 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1763,7 +1763,10 @@ export const documentUpdateSchema = z.object({
// services (cycle), so the keys are inlined here.
export const LEGACY_EXPORT_SECTIONS = ['identity', 'autobiography', 'brain', 'goals', 'decisions', 'health'];
export const legacyExportSchema = z.object({
- sections: z.array(z.enum(LEGACY_EXPORT_SECTIONS)).optional()
+ sections: z.array(z.enum(LEGACY_EXPORT_SECTIONS)).optional(),
+ // Phase 2: render a `legacy-portrait.pdf` from the section Markdown. Default
+ // false — the Markdown/JSON bundle is the primary artifact.
+ includePdf: z.boolean().optional()
});
// =============================================================================
diff --git a/server/routes/legacyExport.js b/server/routes/legacyExport.js
index 96776c2375..ee3e0e2241 100644
--- a/server/routes/legacyExport.js
+++ b/server/routes/legacyExport.js
@@ -15,9 +15,9 @@ router.get('/preview', asyncHandler(async (req, res) => {
// POST /api/legacy-export — build and stream the identity bundle as a zip
// attachment. `sections` (optional) narrows the bundle; omitted means "all".
router.post('/', asyncHandler(async (req, res) => {
- const { sections } = validateRequest(legacyExportSchema, req.body || {});
+ const { sections, includePdf } = validateRequest(legacyExportSchema, req.body || {});
const io = req.app.get('io');
- const { buffer } = await buildLegacyZip({ sections: sections || null, io });
+ const { buffer } = await buildLegacyZip({ sections: sections || null, includePdf: !!includePdf, io });
// Date-stamped filename, mirroring the catalog download pattern.
const date = new Date().toISOString().slice(0, 10);
diff --git a/server/routes/legacyExport.test.js b/server/routes/legacyExport.test.js
index 5ccfcf3ad0..1a9e862b53 100644
--- a/server/routes/legacyExport.test.js
+++ b/server/routes/legacyExport.test.js
@@ -57,6 +57,26 @@ describe('POST /api/legacy-export', () => {
expect(buildLegacyZip).toHaveBeenCalledWith(expect.objectContaining({ sections: ['goals', 'health'] }));
});
+ it('threads includePdf through to the service', async () => {
+ const app = await makeApp();
+ const res = await request(app).post('/api/legacy-export').send({ includePdf: true });
+ expect(res.status).toBe(200);
+ expect(buildLegacyZip).toHaveBeenCalledWith(expect.objectContaining({ includePdf: true }));
+ });
+
+ it('defaults includePdf to false when omitted', async () => {
+ const app = await makeApp();
+ await request(app).post('/api/legacy-export').send({});
+ expect(buildLegacyZip).toHaveBeenCalledWith(expect.objectContaining({ includePdf: false }));
+ });
+
+ it('rejects a non-boolean includePdf with 400', async () => {
+ const app = await makeApp();
+ const res = await request(app).post('/api/legacy-export').send({ includePdf: 'yes' });
+ expect(res.status).toBe(400);
+ expect(buildLegacyZip).not.toHaveBeenCalled();
+ });
+
it('rejects an unknown section with 400', async () => {
const app = await makeApp();
const res = await request(app).post('/api/legacy-export').send({ sections: ['not-a-section'] });
diff --git a/server/services/legacyExport.js b/server/services/legacyExport.js
index 717753b094..9250a15ecc 100644
--- a/server/services/legacyExport.js
+++ b/server/services/legacyExport.js
@@ -18,6 +18,7 @@
import { createHash } from 'crypto';
import { hostname } from 'os';
+import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import { createZip } from '../lib/zipWriter.js';
import { getCurrentVersion } from './updateChecker.js';
import { exportDigitalTwin } from './digital-twin-export.js';
@@ -446,7 +447,7 @@ export function buildBundleFiles(data, { sections: selected = null } = {}) {
* Build the manifest object (SHA-256 per file). `kind`/`schemaVersion` let a
* future reader (or `parseZip` round-trip verifier) validate the bundle.
*/
-export function buildManifest(files, { sections, portosVersion, generatedAt }) {
+export function buildManifest(files, { sections, portosVersion, generatedAt, pdfIncluded = false }) {
const fileHashes = {};
for (const f of files) fileHashes[f.name] = sha256(f.data);
return {
@@ -458,15 +459,169 @@ export function buildManifest(files, { sections, portosVersion, generatedAt }) {
sections,
files: fileHashes,
fileCount: files.length,
- pdf: { included: false }, // PDF is a follow-up (Phase 2)
+ pdf: { included: !!pdfIncluded, ...(pdfIncluded ? { file: 'legacy-portrait.pdf' } : {}) },
};
}
+// === PDF rendering (Phase 2) ===
+// A rendered, human-readable portrait of the same per-section Markdown the
+// bundle already produces. Uses pdf-lib (already a dependency, shared with
+// `pipeline/comicPdf.js`) — Helvetica family, basic word-wrap, heading sizing.
+// No images, no external fonts: the Markdown bundle stays the primary artifact;
+// the PDF is a convenience for reading/printing offline.
+
+const PDF_PAGE = { width: 612, height: 792 }; // US Letter, in points
+const PDF_MARGIN = 56; // ~0.78in
+const PDF_LINE_GAP = 4; // extra leading between lines
+const PDF_TEXT_WIDTH = PDF_PAGE.width - PDF_MARGIN * 2;
+
+// Heading sizes by Markdown level (`#`=1 … `###`=3); anything deeper uses level 3.
+const PDF_HEADING_SIZE = { 1: 22, 2: 16, 3: 13 };
+const PDF_BODY_SIZE = 11;
+
+// Strip the inline Markdown emphasis/link syntax pdf-lib can't render so it
+// doesn't print literal `**`/`*`/`[text](url)` markers. Pure.
+function stripInlineMarkdown(text) {
+ return String(text)
+ .replace(/!?\[([^\]]*)\]\(([^)]*)\)/g, '$1') // [label](url) / ![alt](src) → label
+ .replace(/\*\*([^*]+)\*\*/g, '$1') // **bold**
+ .replace(/(^|[^*])\*([^*]+)\*/g, '$1$2') // *italic* (leave bare * alone)
+ .replace(/`([^`]+)`/g, '$1'); // `code`
+}
+
+// WinAnsi (pdf-lib's StandardFont encoding) can't encode arbitrary Unicode —
+// an unencodable glyph throws at draw time. Map the few non-ASCII characters
+// our Markdown builders actually emit (VO₂, ⚠️, smart quotes) to safe ASCII,
+// then drop anything still outside the encodable range. Pure.
+function toWinAnsi(text) {
+ return String(text)
+ .replace(/[‘’]/g, "'")
+ .replace(/[“”]/g, '"')
+ .replace(/[–—]/g, '-')
+ .replace(/…/g, '...')
+ .replace(/₂/g, '2') // subscript 2 (VO₂)
+ .replace(/[✅⚠️⚡]/g, '') // ✅ ⚠ emoji-variation ⚡
+ // eslint-disable-next-line no-control-regex
+ .replace(/[^\x00-\xFF]/g, '');
+}
+
+// Word-wrap a single logical line to fit `maxWidth` at `size`. A single token
+// longer than the line (e.g. a long URL) is hard-broken so it never overflows.
+// Pure given the font's metrics.
+function wrapLine(text, font, size, maxWidth) {
+ const words = text.split(/\s+/).filter(Boolean);
+ if (words.length === 0) return [''];
+ const lines = [];
+ let current = '';
+ for (const word of words) {
+ const candidate = current ? `${current} ${word}` : word;
+ if (font.widthOfTextAtSize(candidate, size) <= maxWidth) {
+ current = candidate;
+ continue;
+ }
+ if (current) lines.push(current);
+ // The word itself overflows — hard-break it character by character.
+ if (font.widthOfTextAtSize(word, size) > maxWidth) {
+ let chunk = '';
+ for (const ch of word) {
+ if (font.widthOfTextAtSize(chunk + ch, size) > maxWidth && chunk) {
+ lines.push(chunk);
+ chunk = ch;
+ } else {
+ chunk += ch;
+ }
+ }
+ current = chunk;
+ } else {
+ current = word;
+ }
+ }
+ if (current) lines.push(current);
+ return lines;
+}
+
+/**
+ * Render the per-section Markdown into a single PDF. Pure-ish (async only for
+ * pdf-lib's font embedding) — takes the same `{ name, data }` content files
+ * `buildBundleFiles` produces and walks the `.md` ones in bundle order.
+ * Returns the PDF bytes (Uint8Array). `meta` stamps the title page.
+ *
+ * @returns {Promise<{ bytes: Uint8Array, pageCount: number }>}
+ */
+export async function buildLegacyPdf(contentFiles, { portosVersion = '0.0.0', generatedAt = '' } = {}) {
+ const pdf = await PDFDocument.create();
+ pdf.setTitle('PortOS Legacy Export');
+ pdf.setProducer('PortOS');
+ pdf.setCreator('PortOS legacy export');
+
+ const font = await pdf.embedFont(StandardFonts.Helvetica);
+ const fontBold = await pdf.embedFont(StandardFonts.HelveticaBold);
+
+ let page = pdf.addPage([PDF_PAGE.width, PDF_PAGE.height]);
+ let cursor = PDF_PAGE.height - PDF_MARGIN;
+
+ // Draw one wrapped block; paginates when the cursor runs past the bottom margin.
+ const draw = (raw, { size = PDF_BODY_SIZE, bold = false, color = rgb(0.12, 0.12, 0.12), gapAfter = PDF_LINE_GAP } = {}) => {
+ const f = bold ? fontBold : font;
+ const text = toWinAnsi(stripInlineMarkdown(raw));
+ for (const line of wrapLine(text, f, size, PDF_TEXT_WIDTH)) {
+ if (cursor - size < PDF_MARGIN) {
+ page = pdf.addPage([PDF_PAGE.width, PDF_PAGE.height]);
+ cursor = PDF_PAGE.height - PDF_MARGIN;
+ }
+ page.drawText(line, { x: PDF_MARGIN, y: cursor - size, size, font: f, color });
+ cursor -= size + gapAfter;
+ }
+ };
+ const space = (h = PDF_BODY_SIZE) => { cursor -= h; };
+
+ // Title page.
+ draw('PortOS Legacy Export', { size: 28, bold: true, color: rgb(0, 0, 0) });
+ space(6);
+ draw('A self-contained portrait of identity, knowledge, and life story.', { size: 12, color: rgb(0.35, 0.35, 0.35) });
+ if (generatedAt) draw(`Generated: ${generatedAt.slice(0, 19).replace('T', ' ')} UTC`, { size: 10, color: rgb(0.45, 0.45, 0.45) });
+ draw(`PortOS ${portosVersion}`, { size: 10, color: rgb(0.45, 0.45, 0.45) });
+
+ const markdownFiles = contentFiles.filter(f => f.name.endsWith('.md'));
+ for (const file of markdownFiles) {
+ page = pdf.addPage([PDF_PAGE.width, PDF_PAGE.height]);
+ cursor = PDF_PAGE.height - PDF_MARGIN;
+ const lines = file.data.toString('utf-8').split('\n');
+ for (const rawLine of lines) {
+ const line = rawLine.replace(/\s+$/, '');
+ const heading = line.match(/^(#{1,6})\s+(.*)$/);
+ if (heading) {
+ const level = Math.min(heading[1].length, 3);
+ space(6);
+ draw(heading[2], { size: PDF_HEADING_SIZE[level], bold: true, color: rgb(0, 0, 0), gapAfter: 6 });
+ continue;
+ }
+ if (line.trim() === '') { space(6); continue; }
+ const quote = line.match(/^>\s?(.*)$/);
+ if (quote) {
+ draw(quote[1], { color: rgb(0.4, 0.4, 0.4) });
+ continue;
+ }
+ const bullet = line.match(/^[-*]\s+\[[ xX]\]\s+(.*)$/) || line.match(/^[-*]\s+(.*)$/);
+ if (bullet) {
+ draw(`• ${bullet[1]}`);
+ continue;
+ }
+ draw(line);
+ }
+ }
+
+ const bytes = await pdf.save();
+ return { bytes, pageCount: pdf.getPageCount() };
+}
+
/**
* Build the full legacy-export zip. Returns `{ buffer, manifest }`.
* `io` (optional) receives `legacy-export:*` progress events.
+ * `includePdf` adds a rendered `legacy-portrait.pdf` (Phase 2); default false —
+ * the Markdown bundle is the primary artifact.
*/
-export async function buildLegacyZip({ sections = null, io = null } = {}) {
+export async function buildLegacyZip({ sections = null, io = null, includePdf = false } = {}) {
emit(io, 'legacy-export:started', { sections });
const data = await gatherLegacyData();
emit(io, 'legacy-export:progress', { phase: 'gathered' });
@@ -475,16 +630,24 @@ export async function buildLegacyZip({ sections = null, io = null } = {}) {
const portosVersion = await getCurrentVersion().catch(() => '0.0.0');
const generatedAt = new Date().toISOString();
- // README first, then content files, then the manifest (which hashes the
- // content files — build it before adding manifest.json so it doesn't hash
- // itself).
+ // README first, then content files. The optional rendered PDF is derived from
+ // those same Markdown files (so it carries no data the bundle doesn't already
+ // expose) and joins the hashed file set. The manifest hashes every content
+ // file — build it before adding manifest.json so it doesn't hash itself.
const readme = { name: 'README.md', data: Buffer.from(README_PRIVACY_BANNER, 'utf-8') };
const contentFiles = [readme, ...files];
- const manifest = buildManifest(contentFiles, { sections: sectionMeta, portosVersion, generatedAt });
+
+ if (includePdf) {
+ const { bytes, pageCount } = await buildLegacyPdf(contentFiles, { portosVersion, generatedAt });
+ contentFiles.push({ name: 'legacy-portrait.pdf', data: Buffer.from(bytes) });
+ emit(io, 'legacy-export:progress', { phase: 'pdf', pageCount });
+ }
+
+ const manifest = buildManifest(contentFiles, { sections: sectionMeta, portosVersion, generatedAt, pdfIncluded: includePdf });
const manifestFile = { name: 'manifest.json', data: Buffer.from(jsonFile(manifest), 'utf-8') };
const buffer = createZip([...contentFiles, manifestFile]);
- console.log(`📦 Legacy export: ${manifest.fileCount} files, ${(buffer.length / 1024).toFixed(1)} KB`);
+ console.log(`📦 Legacy export: ${manifest.fileCount} files${includePdf ? ' (+PDF)' : ''}, ${(buffer.length / 1024).toFixed(1)} KB`);
emit(io, 'legacy-export:completed', { fileCount: manifest.fileCount, bytes: buffer.length });
return { buffer, manifest };
}
diff --git a/server/services/legacyExport.test.js b/server/services/legacyExport.test.js
index f40b5aa413..2cae4e58ca 100644
--- a/server/services/legacyExport.test.js
+++ b/server/services/legacyExport.test.js
@@ -5,6 +5,7 @@ import {
buildBundleFiles,
buildManifest,
buildLegacyZip,
+ buildLegacyPdf,
previewLegacyExport,
getSectionKeys,
} from './legacyExport.js';
@@ -199,6 +200,62 @@ describe('buildLegacyZip', () => {
});
});
+describe('buildManifest pdf flag', () => {
+ it('defaults pdf.included false with no pdf file entry', () => {
+ const { files, sections } = buildBundleFiles(sampleData());
+ const manifest = buildManifest(files, { sections, portosVersion: '1.0.0', generatedAt: '2026-06-18T00:00:00Z' });
+ expect(manifest.pdf.included).toBe(false);
+ expect(manifest.pdf.file).toBeUndefined();
+ });
+
+ it('records pdf.included + file name when pdfIncluded is true', () => {
+ const { files, sections } = buildBundleFiles(sampleData());
+ const manifest = buildManifest(files, { sections, portosVersion: '1.0.0', generatedAt: '2026-06-18T00:00:00Z', pdfIncluded: true });
+ expect(manifest.pdf.included).toBe(true);
+ expect(manifest.pdf.file).toBe('legacy-portrait.pdf');
+ });
+});
+
+describe('buildLegacyPdf', () => {
+ it('renders a non-empty multi-page PDF from the section Markdown', async () => {
+ const { files } = buildBundleFiles(sampleData());
+ const contentFiles = [{ name: 'README.md', data: Buffer.from('# PortOS Legacy Export\n\nPrivacy notice.') }, ...files];
+ const { bytes, pageCount } = await buildLegacyPdf(contentFiles, { portosVersion: '1.2.3', generatedAt: '2026-06-18T12:00:00Z' });
+ expect(bytes.length).toBeGreaterThan(0);
+ // Title page + one page per Markdown file (each starts on a fresh page).
+ const mdCount = contentFiles.filter(f => f.name.endsWith('.md')).length;
+ expect(pageCount).toBeGreaterThanOrEqual(1 + mdCount);
+ // PDF magic header.
+ expect(Buffer.from(bytes.slice(0, 5)).toString('latin1')).toBe('%PDF-');
+ });
+
+ it('does not throw on non-ASCII glyphs (VO₂, em-dash, smart quotes, ⚠️)', async () => {
+ const contentFiles = [{ name: 'identity/profile.md', data: Buffer.from('# Health\n\n- **VO₂ max**: 52 — “great” … ⚠️') }];
+ const { bytes } = await buildLegacyPdf(contentFiles, {});
+ expect(bytes.length).toBeGreaterThan(0);
+ });
+});
+
+describe('buildLegacyZip includePdf', () => {
+ it('adds a non-empty legacy-portrait.pdf and reflects it in the manifest', async () => {
+ const { buffer, manifest } = await buildLegacyZip({ includePdf: true });
+ expect(manifest.pdf.included).toBe(true);
+ expect(manifest.pdf.file).toBe('legacy-portrait.pdf');
+ expect(manifest.files['legacy-portrait.pdf']).toMatch(/^[0-9a-f]{64}$/);
+ const entries = await unzip(buffer);
+ expect(entries['legacy-portrait.pdf']).toBeDefined();
+ expect(entries['legacy-portrait.pdf'].length).toBeGreaterThan(0);
+ expect(entries['legacy-portrait.pdf'].slice(0, 5).toString('latin1')).toBe('%PDF-');
+ });
+
+ it('omits the PDF by default and leaves manifest pdf.included false', async () => {
+ const { buffer, manifest } = await buildLegacyZip({});
+ expect(manifest.pdf.included).toBe(false);
+ const entries = await unzip(buffer);
+ expect(entries['legacy-portrait.pdf']).toBeUndefined();
+ });
+});
+
describe('previewLegacyExport', () => {
it('returns section metadata and an estimated size without throwing', async () => {
const preview = await previewLegacyExport();