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 (claude): cap aggregate import memory, fix asset-buffer docstrings, test traversal guard

[._.]/ Adam Eivy5333b152600b
diff --git a/PLAN.md b/PLAN.md
index 605ad60bdd..68134e4ab6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -42,6 +42,8 @@ independently.
- [ ] [lora-training-phase-aware-soft-hang-stall-watchdog] **Phase-aware stall watchdog that SIGKILLs a wedged-but-not-rebooted mflux child and auto-resumes from the newest checkpoint.** From `reference-watch` review of Phosphene (2026-06-14). Phosphene proved an in-process daemon-thread watchdog can't fire during a Metal hang (the completion-handler dealloc chain holds the GIL — `docs/STATE.md:436`); the rescue must be out-of-process. PortOS's Node orchestrator is already out-of-process but its training idle watchdog is 30 min (`WATCHDOG_TRAINING_MS`). Add a **phase-aware** stall detector keyed off the wrapper's existing stage lines (`STAGE:load-model`, `STAGE:training`, `STEP:n:m:loss`, `STAGE:cooldown:heartbeat`): a tight budget during `STAGE:training` (consecutive `STEP:` lines should arrive within a few × the observed per-step time), and a generous/disabled budget during model load, dataset encode, preview generation, and cooldown — then SIGKILL + auto-resume from the newest checkpoint via the existing `--resume-checkpoint` path. **Important caveat / scope:** this does NOT address the observed *hard-reboot* kernel panics (the machine is gone before any userspace watchdog runs — checkpoint-resume already covers that); it only recovers *soft* GPU hangs faster, so it's defensive hygiene, not a fix for the incident. Must avoid false-killing a legitimately slow load/encode (derive the training budget from the first few observed step intervals, not a hardcoded 45s). Unit-test by feeding synthetic line streams. Estimated scope: medium.
+- [ ] [chatgpt-import-stream-assets-to-disk] **Stream ChatGPT-export `.dat` assets directly to disk instead of buffering them all in memory.** From claude review of the ChatGPT-ZIP-import PR (#1264). `extractChatgptZip` (`server/services/chatgptZipImport.js`) buffers every `.dat` asset into `pendingAssets` (a `Map<assetId, {buffer}>`) and holds them until the ZIP stream closes, then resolves extensions + writes them in a second loop — because the `conversation_asset_file_names.json` map can arrive *after* the `.dat` members, so the friendly-name fallback isn't known per-asset mid-stream. Peak RAM ≈ sum of all asset bytes; an aggregate `MAX_TOTAL_BUFFERED_BYTES` (1 GB) guard now fails fast rather than OOMing, but a legitimately large export (the route allows up to 2 GB) would be rejected. Proper fix: write each asset to a temp/served path as it streams (sniff the extension from the first chunk, which is enough for all current magic-byte types), recording `{assetId → tempPath}`; after the stream closes, rename/finalize using the now-complete name map (extension is already known from the sniff; the friendly NAME is metadata only, not part of the served filename). This removes the aggregate ceiling and bounds peak RAM to one chunk. Keep the magic-byte sniff (the `.dat` files have no extension). Estimated scope: medium.
+
### Trigger-gated (waiting for a precondition)
- [ ] [ref-watch-phosphene-spaced-lora-id-decode-validate] **Harden trained-character/LoRA id handling for spaced filenames + percent-encoded path segments.** From `reference-watch` review of Phosphene (commit `ce031395`, 2026-06-12). Upstream's character-id validation regex was a hard gate that ran *before* the sidecar was read, so a LoRA whose trigger/filename contained a space (e.g. `Annie Phosphene_v2.safetensors`) was misclassified as style-only and vanished from the Characters tab; the fix widened the id class to allow spaces and made the route `unquote()`-then-validate (staying traversal-safe because an encoded `../` or `/` decodes to chars the class still rejects). PortOS's equivalent is `server/services/loras.js#assertSafeLoraFilename()` plus the trained-LoRA `character` classification it surfaces. Fix (if applicable): audit whether any PortOS LoRA/character id route 404s or misclassifies spaced filenames and whether percent-encoded id segments are decoded before validation; if so, widen the allowed id class to permit spaces and decode-then-validate in the route. **Decision needed:** confirm PortOS actually exposes id-addressed character/LoRA routes (not just filename-addressed ones) and reproduces the spaced-name misclassification before investing — it may already be covered by `assertSafeLoraFilename`'s filename-only model. Estimated scope: small.
diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.js
index a69a6e5f48..b0271223e9 100644
--- a/server/services/chatgptImport.test.js
+++ b/server/services/chatgptImport.test.js
@@ -13,6 +13,7 @@ let parseExport;
let importConversations;
let extractMessages;
let formatTranscript;
+let readArchivedConversation;
describe('chatgptImport service', () => {
beforeEach(async () => {
@@ -31,6 +32,7 @@ describe('chatgptImport service', () => {
importConversations = mod.importConversations;
extractMessages = mod.extractMessages;
formatTranscript = mod.formatTranscript;
+ readArchivedConversation = mod.readArchivedConversation;
const storage = await import('./brainStorage.js');
createMemoryEntryMock = storage.createMemoryEntry;
});
@@ -239,4 +241,28 @@ describe('chatgptImport service', () => {
expect(transcript).toContain('What is 2+2?');
});
});
+
+ describe('readArchivedConversation', () => {
+ it('reads a legitimately-named archive file', async () => {
+ // importConversations writes the archive as `${safeFilename(id)}.json`.
+ await importConversations(parseExport([sampleConversation()]));
+ const archived = await readArchivedConversation('conv-1.json');
+ expect(archived).not.toBeNull();
+ expect(archived.transcript).toContain('What is 2+2?');
+ });
+
+ it('rejects path-traversal / non-flat names without reading outside the archive dir', async () => {
+ // The guard regex is the only thing standing between req.params.name and
+ // an arbitrary-file read — a future weakening (adding `.` or `/` to the
+ // class) must fail this test, not silently traverse.
+ for (const evil of ['../../etc/passwd', 'a/b.json', '..%2fx.json', '/etc/passwd', 'x.json.bak', 'x.txt', '']) {
+ // eslint-disable-next-line no-await-in-loop
+ expect(await readArchivedConversation(evil)).toBeNull();
+ }
+ });
+
+ it('returns null for a well-formed name with no matching file', async () => {
+ expect(await readArchivedConversation('does-not-exist.json')).toBeNull();
+ });
+ });
});
diff --git a/server/services/chatgptZipImport.js b/server/services/chatgptZipImport.js
index 6448a8ba30..e13b1b4e49 100644
--- a/server/services/chatgptZipImport.js
+++ b/server/services/chatgptZipImport.js
@@ -4,14 +4,19 @@
* Ingests the modern multi-file ChatGPT data export (a `.zip`, streamed up
* whole — no in-memory cap) end to end:
*
- * 1. Stream-extract the ZIP (`parseZip`) — never buffer the whole archive.
- * - `conversations*.json` + `conversation_asset_file_names.json` are small
- * relative to the assets and are buffered in memory.
- * - `*.dat` asset files (images / voice audio / PDFs) are written to the
- * served assets dir (`PATHS.brainImportAssets`) keyed by their global
- * asset id, with a real extension sniffed from magic bytes (falling back
- * to the friendly name in the asset-name map). `chat.html` and other
- * bulky members are drained without buffering.
+ * 1. Stream-extract the ZIP (`parseZip`) — never decompress the whole archive
+ * into one buffer; members are handled one at a time as they arrive.
+ * - `conversations*.json` + `conversation_asset_file_names.json` are
+ * buffered in memory (small relative to the assets).
+ * - `*.dat` asset files (images / voice audio / PDFs) are each buffered
+ * (so their magic bytes can be sniffed for the real extension) and then
+ * written to the served assets dir (`PATHS.brainImportAssets`) keyed by
+ * their global asset id, falling back to the friendly name in the
+ * asset-name map. `chat.html` and other bulky members are drained
+ * without buffering. A running `MAX_TOTAL_BUFFERED_BYTES` budget caps
+ * the aggregate held in memory so a pathological export can't OOM the
+ * process (the per-asset hold is bounded; true per-asset streaming to
+ * disk is tracked in PLAN.md).
* 2. Build a `pointer -> { url, name, mime }` resolver so transcript rendering
* can inline `![](url)` images and `[🔊 audio](url)` / `[📎 file](url)`
* links pointing at the extracted assets.
@@ -30,11 +35,20 @@ import { PATHS, getMimeType } from '../lib/fileUtils.js';
import { parseZip } from '../lib/zipStream.js';
import { parseExport, importConversations, assetPointerId } from './chatgptImport.js';
-// Cap an individual buffered JSON member. The largest conversation shard in a
-// real export is ~6 MB; 100 MB is a generous backstop against a malicious zip
-// claiming a JSON member is enormous. Asset `.dat` files are streamed to disk,
-// not buffered, so they aren't bound by this.
-const MAX_JSON_MEMBER_BYTES = 100 * 1024 * 1024;
+// Cap an individual buffered member (JSON shard or `.dat` asset). The largest
+// conversation shard in a real export is ~6 MB and assets run KB–few MB; 100 MB
+// is a generous per-member backstop against a malicious zip claiming one member
+// is enormous.
+const MAX_MEMBER_BYTES = 100 * 1024 * 1024;
+
+// Cap the AGGREGATE bytes held in memory at once. Asset buffers accumulate in
+// `pendingAssets` until the stream closes (the asset-name map may arrive after
+// the `.dat` members, so we can't resolve+flush each in isolation), so without
+// an aggregate ceiling a pathological multi-GB export — the route allows up to
+// 2 GB — could exhaust the heap before the write loop runs. 1 GB comfortably
+// holds any real export's assets; beyond that we fail fast rather than OOM.
+// (True per-asset stream-to-disk would remove this ceiling — tracked in PLAN.md.)
+const MAX_TOTAL_BUFFERED_BYTES = 1024 * 1024 * 1024;
// Magic-byte sniffers — `.dat` files carry no extension, so we detect the real
// type from the leading bytes and give the served file a correct extension.
@@ -114,12 +128,23 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA
// extensions + write files after, because the name map may arrive after the
// .dat members (member order in the ZIP isn't guaranteed).
const pendingAssets = new Map();
+ let totalBuffered = 0; // running aggregate-memory guard (see MAX_TOTAL_BUFFERED_BYTES)
await new Promise((resolve, reject) => {
let settled = false;
const settle = (fn) => (arg) => { if (!settled) { settled = true; fn(arg); } };
const onErr = settle(reject);
const inFlight = [];
+ // Charge buffered bytes against the aggregate budget the moment they land,
+ // failing fast before the heap is exhausted (collect()'s per-member cap
+ // alone can't bound the sum across hundreds of assets held until flush).
+ const charge = (buf) => {
+ totalBuffered += buf.length;
+ if (totalBuffered > MAX_TOTAL_BUFFERED_BYTES) {
+ throw new Error(`ChatGPT export exceeds the ${MAX_TOTAL_BUFFERED_BYTES}-byte in-memory budget`);
+ }
+ return buf;
+ };
createReadStream(zipPath)
.on('error', onErr)
@@ -127,18 +152,22 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA
.on('entry', (entry) => {
const { path } = entry;
if (IS_ASSET_NAME_MAP(path)) {
- inFlight.push(collect(entry, MAX_JSON_MEMBER_BYTES)
+ inFlight.push(collect(entry, MAX_MEMBER_BYTES)
+ .then(charge)
.then((buf) => { assetNameMap = JSON.parse(buf.toString('utf8')); })
.catch(onErr));
} else if (IS_CONVO_JSON(path)) {
- inFlight.push(collect(entry, MAX_JSON_MEMBER_BYTES)
+ inFlight.push(collect(entry, MAX_MEMBER_BYTES)
+ .then(charge)
.then((buf) => { convoBuffers.push({ path, buffer: buf }); })
.catch(onErr));
} else if (IS_DAT(path)) {
// Buffer the asset bytes. Asset `.dat` files in real exports are
- // individual media files (KB–few MB); collecting one at a time is
- // fine and lets us sniff magic bytes for the extension.
- inFlight.push(collect(entry, MAX_JSON_MEMBER_BYTES)
+ // individual media files (KB–few MB); collecting one at a time lets
+ // us sniff magic bytes for the extension. The aggregate `charge`
+ // guard bounds the sum held across all assets until the write loop.
+ inFlight.push(collect(entry, MAX_MEMBER_BYTES)
+ .then(charge)
.then((buf) => { pendingAssets.set(datAssetId(path), { datPath: path, buffer: buf }); })
.catch(onErr));
} else {
@@ -151,7 +180,9 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA
.on('error', onErr);
});
- // Resolve each buffered asset's extension + write it to the served dir.
+ // Resolve each buffered asset's extension + write it to the served dir,
+ // dropping each buffer from the Map as it's flushed so the held memory falls
+ // as the loop progresses rather than staying at its peak until the end.
const assets = new Map();
for (const [assetId, { datPath, buffer }] of pendingAssets) {
const friendlyName = assetNameMap[`${assetId}.dat`] || assetNameMap[datPath] || null;
@@ -161,6 +192,7 @@ export async function extractChatgptZip(zipPath, { assetDir = PATHS.brainImportA
// eslint-disable-next-line no-await-in-loop -- sequential write keeps peak
// disk/IO bounded; an export has a few hundred assets, not millions.
await writeFile(filePath, buffer);
+ pendingAssets.delete(assetId); // release the buffer for GC
assets.set(assetId, {
url: `/data/brain-imports/${fileName}`,
name: friendlyName || fileName,