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([issue-1433]): Legacy Export Phase 4 — richer decisions, deflate, size guard, GOALS status

Adam Eivy265f2834a660
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3f06782a27..214ad004ac 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,6 +35,8 @@
- **[issue-1432] Generate and download your Legacy Bundle from the UI.** Phase 3 of Legacy Export (#901): a new **Legacy** tab under Digital Twin (`/digital-twin/legacy`, reachable via ⌘K / voice as "legacy bundle") puts a user-facing surface on top of the Phase 1 server endpoints. It previews each identity section (with record counts and an estimated bundle size from `GET /api/legacy-export/preview`), lets you check/uncheck which sections to include — present sections default to selected — and on **Generate & Download** streams the `.zip` from `POST /api/legacy-export` straight to a browser download with a date-stamped filename and a success toast. Selecting *all* present sections sends no filter (so a future section is included by default); a subset sends the explicit list. Per-section build progress arrives over the existing `legacy-export:progress` / `:completed` socket events. The bundle preview now stamps each section with its human `label` so the UI need not duplicate a key→label map. A small shared `downloadBlob()` helper (`client/src/lib/downloadBlob.js`) collapses the inline object-URL + `<a download>` dance (also adopted by the soul ExportTab). (`client/src/components/digital-twin/tabs/LegacyExportTab.jsx`, `client/src/services/apiDigitalTwin.js`, `server/lib/navManifest.js`, `server/services/legacyExport.js`, #1432)
+- **[issue-1433] Legacy Export polish — richer Key Decisions, a smaller (compressed) download, and a large-bundle warning.** Phase 4 finishing work on the Legacy Export (#901). The **Key Decisions** section is now derived from more of your existing data: completed *goals* (not just completed milestones) plus Brain notes you tagged or titled as a decision (`decision`, `chose`, `pivot`, …), deduped and dated newest-first — so the section reflects the choices you already record without any new place to enter them (an architecture-decision record explains why this stays a *derivation* rather than a new entity). The downloaded `.zip` is now **compressed** (deflate, falling back to stored for files it wouldn't shrink), so a text-heavy identity bundle downloads much smaller — byte-for-byte identical on extract, and the manifest checksums are unchanged. And the Legacy tab now shows a **large-bundle warning** when the estimated export is unusually big (it tells you which section is driving the size and never silently truncates your data). The Knowledge Legacy goal status in `GOALS.md` is updated to reflect the shipped export. (`server/services/legacyExport.js`, `server/lib/zipWriter.js`, `client/src/components/digital-twin/tabs/LegacyExportTab.jsx`, `docs/decisions/2026-06-19-legacy-export-decisions-source.md`, #1433)
+
- **[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)
- **[issue-1309] Editorial checks flag thin sensory writing and ungrounded "white-room" scenes.** Two new prose checks (Create → Editorial Checks) target two of the most common reader gripes about flat scene writing. **Sensory balance** reads your drafted manuscript and flags scenes that lean almost entirely on sight while sound, smell, touch, and taste go neglected, plus sensory-bare scenes with almost no concrete grounding at all — naming exactly which sense is missing and suggesting a grounding detail to add. **White-room / ungrounded scene** flags "talking heads in a void": dialogue and action playing out with no setting, no physical blocking, and no spatial grounding the reader can stand in — distinct from sensory balance (which is about *senses*) and scene-component balance (narrative/action/dialogue mix) in that the gap here is specifically *place*. Both read your reverse-outline scene segmentation as context (using each scene's recorded setting as a white-room signal) and **degrade gracefully** to a whole-issue manuscript scan when no outline has been generated yet. Each finding anchors a verbatim quote + issue number so you can jump straight to the spot. Two new stage prompts (`pipeline-editorial-sensory-balance`, `pipeline-editorial-white-room`) ship + migrate for existing installs. (#1309)
diff --git a/GOALS.md b/GOALS.md
index 087b27d5d0..a3ec2bb8d6 100644
--- a/GOALS.md
+++ b/GOALS.md
@@ -100,7 +100,7 @@ The active roadmap lives in the GitHub issue tracker — open issues labeled
| Developer Productivity Toolkit | Complete | Shell, git, browser, history, usage, JIRA, code runner, submodules, reference repos, CyberCity all shipped. |
| Self-Improving Intelligence | Ongoing | Task learning, self-improvement analysis, autonomous jobs, self-healing metrics active. |
| Full Digital Autonomy | Ongoing | Agent tools, Moltworld, scheduling, skill system operational. Expanding platform coverage and autonomy tiers. |
-| Knowledge Legacy | Early | Autobiography, genome, behavioral profiles, written work, built worlds captured. Legacy export format not yet built. |
+| Knowledge Legacy | Ongoing | Autobiography, genome, behavioral profiles, written work, built worlds captured. Portable Legacy Export bundle (Digital Twin → Legacy Bundle) ships a self-contained Markdown + JSON + manifest archive, with optional rendered PDF. Richer key-decisions sourcing and deeper domain coverage continue. |
| Anywhere Access | Complete | Tailscale integration working. Mobile-responsive UI. All features accessible remotely. |
| Health & Longevity | Ongoing | MeatSpace shipped with death clock, LEV tracker, alcohol/blood/body/epigenetic/eye/genome/lifestyle tracking. Apple Health integration planned. |
| Personal Productivity & Life Management | Ongoing | Calendar (agenda/day/week/month/lifetime/review), Messages inbox + drafts, voice agent, Telegram bot, OpenClaw operator chat all shipped. Proactive CoS speech triggers and voice-tool coverage expanding. |
diff --git a/client/src/components/digital-twin/tabs/LegacyExportTab.jsx b/client/src/components/digital-twin/tabs/LegacyExportTab.jsx
index a5a1c73ce0..f188c0de6a 100644
--- a/client/src/components/digital-twin/tabs/LegacyExportTab.jsx
+++ b/client/src/components/digital-twin/tabs/LegacyExportTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
-import { Download, Archive, RefreshCw, Package } from 'lucide-react';
+import { Download, Archive, RefreshCw, Package, AlertTriangle } from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import socket from '../../../services/socket';
import * as api from '../../../services/api';
@@ -165,6 +165,19 @@ export default function LegacyExportTab() {
</span>
</div>
)}
+
+ {/* Large-bundle warning — the server flags an estimate over its soft cap
+ (it never truncates; the zip itself is compressed and smaller). */}
+ {preview?.sizeWarning && (
+ <div className="mt-3 flex items-start gap-2 rounded border border-port-warning/40 bg-port-warning/10 p-2.5 text-xs text-port-warning">
+ <AlertTriangle size={14} className="shrink-0 mt-0.5" />
+ <span>
+ Large bundle — about {formatBytes(preview.sizeWarning.estimatedBytes)} of identity data
+ {preview.sizeWarning.largestSection && `, mostly from “${preview.sizeWarning.largestSection}”`}.
+ The download is compressed and smaller; deselect sections you don't need to trim it.
+ </span>
+ </div>
+ )}
</div>
{/* Generate */}
diff --git a/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsx b/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsx
index a056ba9dfa..f0f4c975fa 100644
--- a/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsx
+++ b/client/src/components/digital-twin/tabs/LegacyExportTab.test.jsx
@@ -92,6 +92,24 @@ describe('LegacyExportTab', () => {
expect(downloadBlob).not.toHaveBeenCalled();
});
+ it('surfaces a large-bundle warning when the server flags one', async () => {
+ getLegacyExportPreview.mockResolvedValue({
+ ...PREVIEW,
+ estimatedBytes: 30 * 1024 * 1024,
+ sizeWarning: { thresholdBytes: 25 * 1024 * 1024, estimatedBytes: 30 * 1024 * 1024, largestSection: 'brain' },
+ });
+ render(<LegacyExportTab />);
+ await screen.findByText('Identity & Values');
+ expect(screen.getByText(/large bundle/i)).toBeInTheDocument();
+ expect(screen.getByText(/brain/)).toBeInTheDocument();
+ });
+
+ it('shows no warning when sizeWarning is null', async () => {
+ render(<LegacyExportTab />);
+ await screen.findByText('Identity & Values');
+ expect(screen.queryByText(/large bundle/i)).not.toBeInTheDocument();
+ });
+
it('shows an empty state and disables generate when no data is present', async () => {
getLegacyExportPreview.mockResolvedValue({
fileCount: 2,
diff --git a/docs/decisions/2026-06-19-legacy-export-decisions-source.md b/docs/decisions/2026-06-19-legacy-export-decisions-source.md
new file mode 100644
index 0000000000..1cb5ca523d
--- /dev/null
+++ b/docs/decisions/2026-06-19-legacy-export-decisions-source.md
@@ -0,0 +1,72 @@
+# ADR: Legacy Export "Key Decisions" — Derive, Don't Add a First-Class Entity
+
+- **Date:** 2026-06-19
+- **Status:** Accepted
+- **Related:** issue #901 (Legacy Export, open question #1), issue #1433
+ (Legacy Export Phase 4), [`server/services/legacyExport.js`](../../server/services/legacyExport.js).
+
+## Context
+
+The Legacy Export bundle (#901) carries a **Key Decisions** section meant to
+capture the consequential choices a person made over their life — part of the
+"how you think", not just "what you built", that the Knowledge Legacy goal aims
+to preserve.
+
+Phase 1 derived that section from **completed goal milestones** only, because
+PortOS has no first-class "life decision" record:
+
+- `decisionLog.js` is CoS *task-scheduling* telemetry (which agent ran, why a
+ task was picked) — operational, not autobiographical. It is the wrong store.
+- A milestone marked `completedAt` is the closest existing signal of "a choice
+ that was carried through", so v1 used it and the manifest documented the
+ provenance (`source:` on the section descriptor).
+
+Open question #1 from #901 asked whether to keep deriving or introduce a
+first-class life-decisions entity (its own store, CRUD, sync category, UI).
+
+## Decision
+
+**Keep deriving — do NOT add a first-class life-decisions entity — but broaden
+the derivation beyond completed milestones.**
+
+The Key Decisions section is now derived from three existing signals, deduped
+and ordered by date:
+
+1. **Completed goals** — a goal carried to `status: 'completed'` is itself a
+ decision that was seen through (Phase 1 only looked one level down, at
+ milestones).
+2. **Completed goal milestones** — the Phase 1 source, retained.
+3. **Decision-bearing brain entries** — `ideas`/`journals`/`projects` records
+ whose tags or title mark them as a decision (`decision`, `decided`,
+ `choice`, `chose`, `pivot`). This pulls in the deliberate-choice notes a
+ user already keeps in the Brain, without a new capture surface.
+
+The section descriptor's `source:` string is updated to state this richer
+provenance, so the bundle's manifest stays honest about where the data came
+from.
+
+## Rationale
+
+- **YAGNI.** A first-class entity means a new store, sanitizer, Zod schema, sync
+ category, migration, and UI — a multi-PR feature — to capture data the user is
+ *already* recording as goals and brain notes. The marginal value over deriving
+ does not justify a new top-level identity primitive.
+- **No migration, no schema churn.** Broadening the derivation reads existing
+ records through existing services; it ships in this PR with no on-disk change
+ and nothing for other installs/peers to migrate.
+- **Honest provenance.** The derived section is explicitly labelled as derived
+ (in both the Markdown source-note and the manifest `source:`), so it never
+ pretends to be a curated decision journal.
+- **Reversible.** If a dedicated decisions entity is ever warranted, it can be
+ added later and slotted in as a fourth (preferred) source ahead of the derived
+ ones — the section descriptor already isolates the sourcing behind
+ `collectDecisions(...)`.
+
+## Consequences
+
+- The Key Decisions section is richer (goals + milestones + tagged brain notes)
+ without new storage.
+- Users who want a specific choice to appear in their legacy bundle can tag a
+ brain note `decision` (or name it accordingly) rather than needing a new UI.
+- This ADR closes #901 open question #1. A future first-class entity remains an
+ option but is explicitly out of scope.
diff --git a/server/lib/zipWriter.js b/server/lib/zipWriter.js
index 31bfc4a67e..4ceb93176d 100644
--- a/server/lib/zipWriter.js
+++ b/server/lib/zipWriter.js
@@ -1,25 +1,32 @@
/**
* Minimal ZIP writer — the counterpart to the parser in `zipStream.js`.
*
- * Writes **stored (method 0, uncompressed)** entries only: local file headers,
- * a central directory, and the EOCD record. No new dependency — CRC-32 is a
- * small in-file table (Node's `zlib.crc32` only landed in v22, so we don't rely
- * on it). Output is deterministic (fixed DOS timestamp) so round-trip tests and
- * manifest hashes are stable.
+ * Writes **stored (method 0)** entries by default, with an opt-in **deflate
+ * (method 8)** path (`createZip(entries, { compress: true })`). Local file
+ * headers, a central directory, and the EOCD record. The only compression
+ * dependency is Node's built-in `zlib` — CRC-32 stays a small in-file table
+ * (Node's `zlib.crc32` only landed in v22, so we don't rely on it). Output is
+ * deterministic (fixed DOS timestamp + `zlib`'s deterministic raw-deflate) so
+ * round-trip tests and manifest hashes are stable.
*
* Usage:
* const buf = createZip([
* { name: 'README.md', data: '# Hello' },
* { name: 'data/manifest.json', data: Buffer.from('{}') },
- * ]);
- * // buf round-trips through parseZip() in zipStream.js
+ * ]); // stored entries
+ * const small = createZip(entries, { compress: true }); // deflate where it helps
+ * // both round-trip through parseZip() in zipStream.js (it reads methods 0 and 8)
*
- * Stored entries are the simplest correct format: every standard tool (`unzip`,
- * macOS Archive Utility, `parseZip`) reads them, and there is no compression
- * state to get wrong. Add a deflate path here only if bundle size becomes a
- * concern (see issue #901 open question 5).
+ * Compression is **per-entry and only kept when it actually shrinks the entry**:
+ * deflate is computed, and the stored form is used instead whenever the deflated
+ * payload isn't smaller (tiny or already-compressed files like PDFs/PNGs). So a
+ * compressed archive is never larger than the stored one, entry for entry.
+ * Stored remains the default because it is the simplest correct format every
+ * tool reads; deflate is for when bundle size matters (issue #901 open Q5).
*/
+import { deflateRawSync } from 'zlib';
+
// CRC-32 lookup table (IEEE 802.3 polynomial 0xEDB88320), built once at load.
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
@@ -61,8 +68,13 @@ function toBuffer(data) {
* entries. `name` is the in-archive path (forward slashes); `data` is a Buffer
* or string. Duplicate or empty names throw — a malformed bundle is worse than
* a loud failure.
+ *
+ * `opts.compress` (default false) deflates each entry, keeping the deflated form
+ * only when it is strictly smaller than the stored bytes; otherwise the entry is
+ * stored. The CRC-32 and the uncompressed size are always of the ORIGINAL data,
+ * per the ZIP spec, so a deflated entry round-trips identically through a reader.
*/
-export function createZip(entries) {
+export function createZip(entries, { compress = false } = {}) {
if (!Array.isArray(entries)) throw new Error('createZip: entries must be an array');
const seen = new Set();
@@ -80,23 +92,36 @@ export function createZip(entries) {
const nameBuf = Buffer.from(normalized, 'utf-8');
const dataBuf = toBuffer(entry.data ?? '');
const crc = crc32(dataBuf);
- const size = dataBuf.length;
+ const size = dataBuf.length; // uncompressed size (always the original)
+
+ // Per-entry deflate, kept only when it actually shrinks the payload. Empty
+ // entries are always stored (deflate of 0 bytes is non-empty overhead).
+ let method = 0;
+ let payload = dataBuf;
+ if (compress && size > 0) {
+ const deflated = deflateRawSync(dataBuf, { level: 9 });
+ if (deflated.length < size) {
+ method = 8;
+ payload = deflated;
+ }
+ }
+ const compSize = payload.length; // compressed size (== size when stored)
// Local file header (30 bytes fixed + name).
const local = Buffer.alloc(30);
local.writeUInt32LE(LOCAL_SIG, 0);
local.writeUInt16LE(VERSION, 4);
local.writeUInt16LE(UTF8_FLAG, 6);
- local.writeUInt16LE(0, 8); // method 0 (stored)
+ local.writeUInt16LE(method, 8); // 0 stored / 8 deflate
local.writeUInt16LE(DOS_TIME, 10);
local.writeUInt16LE(DOS_DATE, 12);
local.writeUInt32LE(crc, 14);
- local.writeUInt32LE(size, 18); // compressed size == size (stored)
+ local.writeUInt32LE(compSize, 18); // compressed size
local.writeUInt32LE(size, 22); // uncompressed size
local.writeUInt16LE(nameBuf.length, 26);
local.writeUInt16LE(0, 28); // extra length
- chunks.push(local, nameBuf, dataBuf);
+ chunks.push(local, nameBuf, payload);
// Central directory header (46 bytes fixed + name).
const cd = Buffer.alloc(46);
@@ -104,11 +129,11 @@ export function createZip(entries) {
cd.writeUInt16LE(VERSION, 4); // version made by
cd.writeUInt16LE(VERSION, 6); // version needed
cd.writeUInt16LE(UTF8_FLAG, 8);
- cd.writeUInt16LE(0, 10); // method
+ cd.writeUInt16LE(method, 10); // method
cd.writeUInt16LE(DOS_TIME, 12);
cd.writeUInt16LE(DOS_DATE, 14);
cd.writeUInt32LE(crc, 16);
- cd.writeUInt32LE(size, 20);
+ cd.writeUInt32LE(compSize, 20);
cd.writeUInt32LE(size, 24);
cd.writeUInt16LE(nameBuf.length, 28);
cd.writeUInt16LE(0, 30); // extra length
@@ -119,7 +144,7 @@ export function createZip(entries) {
cd.writeUInt32LE(offset, 42); // local header offset
central.push(Buffer.concat([cd, nameBuf]));
- offset += local.length + nameBuf.length + dataBuf.length;
+ offset += local.length + nameBuf.length + payload.length;
}
const centralBuf = Buffer.concat(central);
diff --git a/server/lib/zipWriter.test.js b/server/lib/zipWriter.test.js
index 102ab75a11..a8cd7e92c2 100644
--- a/server/lib/zipWriter.test.js
+++ b/server/lib/zipWriter.test.js
@@ -93,6 +93,63 @@ describe('createZip', () => {
expect(() => createZip('nope')).toThrow(/array/i);
});
+ it('round-trips deflated entries through parseZip (method 8)', async () => {
+ // A highly compressible payload so deflate is strictly smaller and kept.
+ const text = 'PortOS legacy export '.repeat(500);
+ const zip = createZip([
+ { name: 'big.md', data: text },
+ { name: 'data/manifest.json', data: '{"kind":"portos-legacy-export"}' },
+ ], { compress: true });
+ const entries = await collectEntries(zip);
+ const byPath = Object.fromEntries(entries.map(e => [e.path, e.data]));
+ expect(byPath['big.md'].toString()).toBe(text);
+ expect(JSON.parse(byPath['data/manifest.json'].toString())).toEqual({ kind: 'portos-legacy-export' });
+ });
+
+ it('a compressed archive is smaller than the stored one for compressible data', () => {
+ const text = 'PortOS legacy export '.repeat(500);
+ const stored = createZip([{ name: 'big.md', data: text }]);
+ const deflated = createZip([{ name: 'big.md', data: text }], { compress: true });
+ expect(deflated.length).toBeLessThan(stored.length);
+ });
+
+ it('falls back to stored for an entry deflate would not shrink', async () => {
+ // Random-ish bytes don't compress; the entry must still round-trip.
+ const incompressible = Buffer.from(Array.from({ length: 256 }, (_, i) => (i * 37 + 11) % 256));
+ const zip = createZip([{ name: 'blob.bin', data: incompressible }], { compress: true });
+ const entries = await collectEntries(zip);
+ expect(Buffer.compare(entries[0].data, incompressible)).toBe(0);
+ });
+
+ it('compressed output is still deterministic', () => {
+ const text = 'repeat '.repeat(200);
+ const a = createZip([{ name: 'a.txt', data: text }], { compress: true });
+ const b = createZip([{ name: 'a.txt', data: text }], { compress: true });
+ expect(Buffer.compare(a, b)).toBe(0);
+ });
+
+ it('produces a compressed archive the system unzip tool can extract', () => {
+ let unzipPath;
+ try {
+ unzipPath = execFileSync('which', ['unzip']).toString().trim();
+ } catch {
+ return; // no unzip on this host — skip
+ }
+ if (!unzipPath) return;
+ const dir = mkdtempSync(join(tmpdir(), 'zipwriter-deflate-'));
+ try {
+ const zipPath = join(dir, 'bundle.zip');
+ writeFileSync(zipPath, createZip([
+ { name: 'README.md', data: '# Legacy '.repeat(100) },
+ { name: 'data/manifest.json', data: '{"kind":"portos-legacy-export"}' },
+ ], { compress: true }));
+ const out = execFileSync(unzipPath, ['-t', zipPath]).toString();
+ expect(out).toMatch(/No errors detected/i);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
it('produces an archive the system unzip tool can extract', () => {
// Guards against subtle header-field mistakes that parseZip (which ignores
// the central directory) would tolerate but a real tool would reject.
diff --git a/server/services/legacyExport.js b/server/services/legacyExport.js
index bdc2a5dbe7..f33b6493df 100644
--- a/server/services/legacyExport.js
+++ b/server/services/legacyExport.js
@@ -54,6 +54,15 @@ const HEALTH_METRICS = [
['vo2_max', 'VO₂ max', ''],
];
+// Soft size guardrail (issue #901 open Q3). The bundle is intentionally a FULL
+// plaintext dump — silently truncating identity data would defeat its purpose —
+// so instead of capping, the preview surfaces a warning above this threshold so
+// the user knows a large export is coming (and which section drives it). The
+// estimate is of the uncompressed content; the delivered zip is deflated and
+// smaller. 25 MB is generous for text identity data; a bundle past it is almost
+// always a very large brain/memory corpus the user should be aware of.
+const SIZE_WARNING_BYTES = 25 * 1024 * 1024;
+
const HEALTH_CAVEAT =
'> ⚠️ **Source caveat:** the figures below are device-reported (Apple Health / manual lab entry) ' +
'and unvalidated. They are a personal-tracking snapshot, **not a verified medical record**, and ' +
@@ -212,15 +221,17 @@ const SECTIONS = [
key: 'decisions',
dir: 'decisions',
label: 'Key Decisions',
- // v1 source: completed goal milestones. PortOS has no first-class life
- // "decisions" store (decisionLog.js is CoS task scheduling), so the manifest
- // documents this provenance. Tracked for a richer source in a follow-up.
- present: (d) => collectMilestones(d.goals).length > 0,
- counts: (d) => ({ milestones: collectMilestones(d.goals).length }),
+ // Derived (never a first-class entity) from three existing signals:
+ // completed goals, completed goal milestones, and decision-tagged brain
+ // entries. PortOS has no dedicated life-decisions store (decisionLog.js is
+ // CoS task scheduling), and an ADR records why we keep deriving rather than
+ // add one (docs/decisions/2026-06-19-legacy-export-decisions-source.md).
+ present: (d) => collectDecisions(d).length > 0,
+ counts: (d) => ({ decisions: collectDecisions(d).length }),
files: (d) => [
- { name: 'decisions/key-decisions.md', data: buildDecisionsMd(d.goals) },
+ { name: 'decisions/key-decisions.md', data: buildDecisionsMd(d) },
],
- source: 'Derived from completed goal milestones (PortOS has no dedicated life-decisions store in v1).',
+ source: 'Derived from completed goals, completed goal milestones, and decision-tagged brain entries (PortOS has no dedicated life-decisions store; see ADR 2026-06-19-legacy-export-decisions-source).',
},
{
key: 'health',
@@ -342,23 +353,68 @@ function buildGoalsMd(goals) {
return out.join('\n\n');
}
-function collectMilestones(goals) {
+// Tokens that mark a brain entry (idea / journal / project) as a deliberate
+// life decision — matched case-insensitively against tags and the title.
+const DECISION_TOKENS = ['decision', 'decided', 'choice', 'chose', 'pivot'];
+
+function isDecisionEntry(record) {
+ const tags = Array.isArray(record?.tags) ? record.tags : [];
+ if (tags.some(t => DECISION_TOKENS.includes(String(t).toLowerCase()))) return true;
+ const title = String(record?.title || record?.name || record?.label || '').toLowerCase();
+ return DECISION_TOKENS.some(tok => title.includes(tok));
+}
+
+// Gather the decision signals into a single, dated, deduped list. Each item is
+// `{ kind, label, detail, date }`; `kind` orders within the same date so the
+// section reads consistently. Derivation, not a stored entity — see the ADR.
+function collectDecisions(d) {
const out = [];
+ const goals = Array.isArray(d?.goals) ? d.goals : [];
for (const g of goals) {
+ if (g.status === 'completed') {
+ out.push({ kind: 'goal', label: g.title || 'Goal', detail: g.description || '', date: g.completedAt || g.updatedAt || '' });
+ }
for (const m of (Array.isArray(g.milestones) ? g.milestones : [])) {
- if (m.completedAt) out.push({ goal: g.title, ...m });
+ if (m.completedAt) {
+ out.push({ kind: 'milestone', label: g.title || 'Goal', detail: m.title || m.description || '', date: m.completedAt });
+ }
}
}
- return out;
+ const brain = d?.brain || {};
+ for (const type of ['ideas', 'journals', 'projects']) {
+ for (const r of (Array.isArray(brain[type]) ? brain[type] : [])) {
+ if (!isDecisionEntry(r)) continue;
+ out.push({
+ kind: 'brain',
+ label: r.title || r.name || r.label || 'Note',
+ detail: r.content || r.body || r.text || r.notes || r.description || '',
+ date: r.updatedAt || r.createdAt || '',
+ });
+ }
+ }
+ // Dedup on label+detail (the same milestone could be reachable twice), then
+ // sort newest-first with undated items last.
+ const seen = new Set();
+ const deduped = out.filter(item => {
+ const key = `${item.label}${item.detail}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+ deduped.sort((a, b) => String(b.date || '').localeCompare(String(a.date || '')));
+ return deduped;
}
-function buildDecisionsMd(goals) {
- const milestones = collectMilestones(goals);
- const out = [mdHeader('Key Decisions', 'Derived from completed goal milestones')];
- out.push('> *Source note:* PortOS has no dedicated life-decisions store in v1, so this section is derived from completed milestones across goals.');
- for (const m of milestones) {
- const when = m.completedAt ? ` _(completed ${String(m.completedAt).slice(0, 10)})_` : '';
- out.push(`- **${redactSecrets(String(m.goal || 'Goal'))}** — ${redactSecrets(String(m.title || m.description || ''))}${when}`);
+function buildDecisionsMd(d) {
+ const decisions = collectDecisions(d);
+ const out = [mdHeader('Key Decisions', 'Derived from completed goals, milestones, and decision-tagged notes')];
+ out.push('> *Source note:* PortOS has no dedicated life-decisions store, so this section is **derived** — from goals carried to completion, completed milestones across goals, and Brain entries you tagged or titled as a decision. Tag a note `decision` to surface it here.');
+ for (const item of decisions) {
+ const when = item.date ? ` _(${String(item.date).slice(0, 10)})_` : '';
+ // The decisions section is a digest — truncate a long brain-entry body to a
+ // single-line summary (the full text already lives in the Brain section).
+ const detail = item.detail ? ` — ${redactSecrets(truncateOneLine(String(item.detail), 280))}` : '';
+ out.push(`- **${redactSecrets(String(item.label || 'Decision'))}**${detail}${when}`);
}
return out.join('\n\n');
}
@@ -377,6 +433,13 @@ function buildHealthMd(health) {
return out.join('\n\n');
}
+// Collapse whitespace/newlines and clip to `max` chars with an ellipsis — used
+// to keep the derived decisions digest to one line per item. Pure.
+function truncateOneLine(text, max) {
+ const flat = String(text || '').replace(/\s+/g, ' ').trim();
+ return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat;
+}
+
function titleize(s) {
return String(s || '')
.replace(/([A-Z])/g, ' $1')
@@ -658,7 +721,11 @@ export async function buildLegacyZip({ sections = null, io = null, includePdf =
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]);
+ // Deflate the bundle (per-entry, kept only where it shrinks the file) — the
+ // identity bundle is overwhelmingly text, so this is a large win for free and
+ // directly answers issue #901 open Q5. Manifest hashes are of the original
+ // (uncompressed) bytes, so they're unchanged by compression.
+ const buffer = createZip([...contentFiles, manifestFile], { compress: true });
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 };
@@ -672,7 +739,41 @@ export async function previewLegacyExport() {
const data = await gatherLegacyData();
const { files, sections } = buildBundleFiles(data, { sections: null });
const estimatedBytes = files.reduce((sum, f) => sum + f.data.length, 0);
- return { sections, fileCount: files.length + 2 /* README + manifest */, estimatedBytes };
+
+ // Soft size guardrail: warn (don't truncate) when the uncompressed estimate is
+ // large, and point at the biggest section so the user knows what's driving it.
+ let sizeWarning = null;
+ if (estimatedBytes > SIZE_WARNING_BYTES) {
+ const bySection = sectionByteEstimates(files);
+ const largest = Object.entries(bySection).sort((a, b) => b[1] - a[1])[0];
+ sizeWarning = {
+ thresholdBytes: SIZE_WARNING_BYTES,
+ estimatedBytes,
+ largestSection: largest ? largest[0] : null,
+ };
+ }
+
+ return {
+ sections,
+ fileCount: files.length + 2 /* README + manifest */,
+ estimatedBytes,
+ sizeWarning,
+ };
+}
+
+// Sum content bytes per section so the preview can name what's driving a large
+// bundle. A `data/<section>.json` mirror is attributed to its section (not a
+// generic "data" bucket); everything else uses its first path segment. Pure.
+function sectionByteEstimates(files) {
+ const out = {};
+ for (const f of files) {
+ let section;
+ const dataMirror = f.name.match(/^data\/([^/]+)\.json$/);
+ if (dataMirror) section = dataMirror[1];
+ else section = f.name.includes('/') ? f.name.slice(0, f.name.indexOf('/')) : f.name;
+ out[section] = (out[section] || 0) + f.data.length;
+ }
+ return out;
}
function emit(io, event, payload) {
diff --git a/server/services/legacyExport.test.js b/server/services/legacyExport.test.js
index f0f122a437..2880b03c91 100644
--- a/server/services/legacyExport.test.js
+++ b/server/services/legacyExport.test.js
@@ -172,6 +172,71 @@ describe('buildBundleFiles', () => {
});
});
+describe('key decisions section (enriched derivation)', () => {
+ // Helper: read the rendered decisions Markdown for a gathered-data object.
+ function decisionsMd(d) {
+ return buildBundleFiles(d).files.find(f => f.name === 'decisions/key-decisions.md')?.data.toString() || '';
+ }
+
+ it('derives decisions from completed goals, milestones, AND decision-tagged brain entries', () => {
+ const d = sampleData();
+ d.goals = [
+ { id: 'g1', title: 'Move to the coast', status: 'completed', description: 'Relocated in 2023.', completedAt: '2023-08-01T00:00:00Z' },
+ { id: 'g2', title: 'Write a book', status: 'active',
+ milestones: [{ id: 'ms1', title: 'Finish the outline', completedAt: '2024-05-01T00:00:00Z' }] },
+ ];
+ d.brain.ideas = [{ id: 'i1', title: 'Decision: leave the startup', content: 'Chose independence over equity.', tags: ['decision'] }];
+ d.brain.journals = [{ id: 'j1', title: 'A normal day', content: 'Nothing notable.' }];
+ const md = decisionsMd(d);
+ expect(md).toContain('Move to the coast'); // completed goal
+ expect(md).toContain('Finish the outline'); // completed milestone
+ expect(md).toContain('Decision: leave the startup'); // tagged brain entry
+ expect(md).not.toContain('A normal day'); // untagged brain entry excluded
+ });
+
+ it('matches a decision token in tags OR the title (case-insensitive)', () => {
+ const d = sampleData();
+ d.goals = [];
+ d.brain.projects = [{ id: 'p1', title: 'The big PIVOT', content: 'Switched markets.' }];
+ d.brain.ideas = [{ id: 'i2', title: 'untitled', content: 'x', tags: ['CHOICE'] }];
+ const md = decisionsMd(d);
+ expect(md).toContain('The big PIVOT');
+ expect(md).toContain('untitled');
+ });
+
+ it('counts derived decisions and reports the section absent when there are none', () => {
+ const d = sampleData();
+ d.goals = [];
+ d.brain = { people: [], projects: [], ideas: [], journals: [], links: [] };
+ const { sections } = buildBundleFiles(d);
+ expect(sections.decisions.present).toBe(false);
+ const withOne = sampleData(); // has one completed milestone
+ withOne.brain = { people: [], projects: [], ideas: [], journals: [], links: [] };
+ withOne.goals = [{ id: 'g', title: 'G', status: 'active', milestones: [{ id: 'm', title: 'Did it', completedAt: '2024-01-01' }] }];
+ expect(buildBundleFiles(withOne).sections.decisions.decisions).toBe(1);
+ });
+
+ it('truncates a long brain-entry body to a one-line digest', () => {
+ const d = sampleData();
+ d.goals = [];
+ d.brain.journals = [{ id: 'j', title: 'Decision', content: 'word '.repeat(200) }];
+ const md = decisionsMd(d);
+ expect(md).toContain('…');
+ // No raw newline run from the body — it's collapsed to one line.
+ const decisionLine = md.split('\n').find(l => l.startsWith('- **Decision**'));
+ expect(decisionLine.length).toBeLessThan(360);
+ });
+
+ it('redacts secrets pasted into a decision-tagged brain entry', () => {
+ const d = sampleData();
+ d.goals = [];
+ d.brain.ideas = [{ id: 'i', title: 'Decision', content: 'key ghp_0123456789abcdefghijklmnopqrstuvwx', tags: ['decision'] }];
+ const md = decisionsMd(d);
+ expect(md).toContain('[REDACTED]');
+ expect(md).not.toContain('ghp_0123');
+ });
+});
+
describe('buildManifest', () => {
it('hashes every file with a SHA-256 and stamps kind/schemaVersion', () => {
const { files, sections } = buildBundleFiles(sampleData());
@@ -286,6 +351,12 @@ describe('previewLegacyExport', () => {
expect(typeof preview.estimatedBytes).toBe('number');
expect(preview.fileCount).toBeGreaterThanOrEqual(2); // README + manifest at minimum
});
+
+ it('reports sizeWarning null for a normal-sized bundle', async () => {
+ // The test backends hold little data, so the estimate is well under the cap.
+ const preview = await previewLegacyExport();
+ expect(preview.sizeWarning).toBeNull();
+ });
});
describe('getSectionKeys', () => {