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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
sort Brain memory list by source recency so ChatGPT imports aren't in export order
[._.]/ Adam Eivy9ec836a1b10b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 791a7f6a79..9bc4df770b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -34,6 +34,8 @@## Fixed+- **Imported ChatGPT conversations now sort by their original recency in the Brain ▸ Memory list, instead of arbitrary export order.** A ChatGPT export isn't ordered chronologically, and a bulk import stamps every entry's `createdAt`/`updatedAt` with the same import time — so the memory list (which returned records in insertion order and showed "Updated {import time}" on every card) left imports jumbled and indistinguishable. The importer now persists **both** source clocks (`sourceCreatedAt` *and* the previously-dropped `sourceUpdatedAt`, the conversation's last-activity time), `getMemoryEntries()` orders entries newest-first by an effective recency timestamp (`memoryRecencyMs`: prefers the source clock for imports, falls back to the storage clock for hand-written notes), and the card footer shows "Conversation {N ago}" using the source date for imported entries (matching the sort) rather than the misleading bulk-import time. Existing imports (which already carry `sourceCreatedAt`) sort correctly without a migration. The memory create/update Zod schema (`memoryInputSchema`) gains the provenance fields (`source`, `sourceRef`, `sourceCreatedAt`, `sourceUpdatedAt`) for schema parity with what `createMemoryEntry` persists. (`server/services/brainStorage.js`, `server/services/chatgptImport.js`, `server/lib/brainValidation.js`, `client/src/components/brain/tabs/MemoryTab.jsx`)+- **The pipeline Nouns stage showed "No description yet" for characters that are actually described.** Characters store their renderable text in `physicalDescription`, but `NounsStage`'s per-kind config omitted `descField`, so `CanonCard` fell back to reading the (usually empty) `description` field — making a fully-described character like `ASTER-9 CHANDELIER` (457 chars of `physicalDescription`) read as undescribed, and also leaving its description un-editable inline (the editor gates on `descField`). Wired `NounsStage`'s `KINDS` to the same `descField`/`descFieldFallback`/`descFieldMax` the universe view (`UniverseCanonSection`) already uses — characters → `physicalDescription` (fallback `description`), objects → `description` (fallback `significance`), places → `description` — so the pipeline and universe canon views render and edit identically. (`client/src/components/pipeline/stages/NounsStage.jsx`)- **A TUI run whose model id is rejected by the backend now fails (and falls back) instead of returning a screen-scrape of the error.** When a Claude Code TUI run hit a non-recoverable model-id rejection — e.g. a bare Anthropic id like `claude-opus-4-8` passed to a Bedrock-backed Claude Code, which answers `API Error (…): 400 The provided model identifier is invalid` and suggests `global.anthropic.…` — the TUI just sat at an unanswered prompt. The one-shot runner saw output go idle, marked the run `success`, and (no `tui-response.txt` having been written) scraped the error *screen* and returned it as the model's "response." Downstream that surfaced as a baffling failure: AI manuscript Reformat reported `AI reformat changed the wording` (its integrity guard correctly rejecting the screen garbage), while other TUI-backed stages silently consumed the noise. The one-shot TUI runner now recognizes Claude Code's terminal model-id rejection (Bedrock 400 "model identifier is invalid" and Anthropic 404 `not_found_error`) and fails the run as `MODEL_NOT_FOUND`, so `runPromptThroughProvider` benches the provider and retries its configured fallback (e.g. `claude-code-tui` → `claude-code-bedrock`, whose Bedrock ids are valid) — turning a silent corruption into a transparent recovery, or, with no fallback, an actionable error. The check is line-anchored, requires the 400/404 to immediately follow the `API Error` prefix (so a retryable 429/500 Claude Code auto-retries is left alone), and is deliberately scoped to the one-shot runner — *not* the shared fallback detector the long-running agent spawn paths use, so an agent that merely echoes the error line in its own output (cat-ing a log, running the tests, investigating this very failure) can't have its run killed and misclassified. (`server/lib/aiToolkit/errorDetection.js`, `server/lib/tuiPromptRunner.js`)diff --git a/client/src/components/brain/tabs/MemoryTab.jsx b/client/src/components/brain/tabs/MemoryTab.jsxindex 66d2b05d87..71b91adc9c 100644--- a/client/src/components/brain/tabs/MemoryTab.jsx+++ b/client/src/components/brain/tabs/MemoryTab.jsx@@ -556,7 +556,11 @@ export default function MemoryTab({ onRefresh }) {)}<p className="text-xs text-gray-500 mt-2">- Updated {timeAgo(record.updatedAt)}+ {activeType === 'memories' && record.source === 'chatgpt-import'+ // Imported entries all share the bulk-import updatedAt, so show the+ // original conversation recency instead (matches the list sort order).+ ? `Conversation ${timeAgo(record.sourceUpdatedAt || record.sourceCreatedAt || record.updatedAt)}`+ : `Updated ${timeAgo(record.updatedAt)}`}</p></div>diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 65166f6974..afb12f5910 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -235,7 +235,15 @@ export const memoryInputSchema = z.object({title: z.string().min(1).max(200),content: z.string().max(10000).optional(),mood: z.string().max(50).optional(),- tags: z.array(z.string().max(50)).optional()+ tags: z.array(z.string().max(50)).optional(),+ // Provenance fields stamped by importers (e.g. chatgptImport) — kept on the+ // create/update payload shape so schema validation matches what createMemoryEntry+ // persists. `sourceCreatedAt`/`sourceUpdatedAt` drive the recency sort in the+ // memory list (see memoryRecencyMs in brainStorage.js).+ source: z.string().max(100).optional(),+ sourceRef: z.string().max(300).optional(),+ sourceCreatedAt: z.string().datetime().nullable().optional(),+ sourceUpdatedAt: z.string().datetime().nullable().optional()});// Settings update input schemadiff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.jsindex d6c2ea746b..71d6722ef0 100644--- a/server/lib/brainValidation.test.js+++ b/server/lib/brainValidation.test.js@@ -33,7 +33,8 @@ import {bucketUpdateInputSchema,bucketReorderSchema,brainSyncQuerySchema,- brainSyncPushSchema+ brainSyncPushSchema,+ memoryInputSchema} from './brainValidation.js';describe('brainValidation.js', () => {@@ -727,4 +728,27 @@ describe('brainValidation.js', () => {expect(result.success).toBe(true);});});++ describe('memoryInputSchema', () => {+ it('accepts a minimal hand-written memory', () => {+ expect(memoryInputSchema.safeParse({ title: 'A thought' }).success).toBe(true);+ });++ it('accepts importer provenance fields, including null source clocks', () => {+ const result = memoryInputSchema.safeParse({+ title: 'Imported chat',+ content: 'transcript',+ source: 'chatgpt-import',+ sourceRef: 'conv-1.json',+ sourceCreatedAt: '2024-07-14T18:16:33.622Z',+ sourceUpdatedAt: null+ });+ expect(result.success).toBe(true);+ });++ it('rejects a non-ISO source timestamp', () => {+ const result = memoryInputSchema.safeParse({ title: 'x', sourceCreatedAt: 'last week' });+ expect(result.success).toBe(false);+ });+ });});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex 2cb2ad322b..00b5018240 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -12,7 +12,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import EventEmitter from 'events';-import { ensureDir, readJSONFile, safeJSONParse, PATHS } from '../lib/fileUtils.js';+import { ensureDir, readJSONFile, safeJSONParse, safeDate, PATHS } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { getInstanceId } from './instances.js';import * as brainSyncLog from './brainSyncLog.js';@@ -698,7 +698,40 @@ export const updateAdminItem = (id, data) => update('admin', id, data);export const deleteAdminItem = (id) => remove('admin', id);// Memories-export const getMemoryEntries = () => getAll('memories');+/**+ * Effective recency timestamp (ms epoch) for ordering a memory entry newest-first.+ *+ * Imported conversations (ChatGPT) carry the original conversation clock in+ * `sourceUpdatedAt` / `sourceCreatedAt`. A ChatGPT export is NOT ordered+ * chronologically, and every entry from one bulk import shares the same+ * `createdAt`/`updatedAt` (the import time) — so sorting on the storage clock+ * leaves imports in arbitrary export order (the user-reported bug). Prefer the+ * source clock when present, falling back to the storage clock for hand-written+ * entries. Returns 0 for a missing/unparseable timestamp so it sorts last.+ */+export const memoryRecencyMs = (record) => {+ for (const candidate of [+ record?.sourceUpdatedAt,+ record?.sourceCreatedAt,+ record?.updatedAt,+ record?.createdAt,+ ]) {+ const t = safeDate(candidate); // epoch ms, or 0 for missing/unparseable+ if (t) return t;+ }+ return 0;+};++export const getMemoryEntries = async () => {+ const entries = await getAll('memories');+ // Decorate-sort-undecorate: compute each record's recency once (a bulk ChatGPT+ // import can be hundreds of entries — recomputing it inside the comparator+ // would parse every timestamp O(n log n) times).+ return entries+ .map((entry) => ({ entry, recency: memoryRecencyMs(entry) }))+ .sort((a, b) => b.recency - a.recency)+ .map(({ entry }) => entry);+};export const getMemoryEntryById = (id) => getById('memories', id);export const createMemoryEntry = (data) => create('memories', data);export const updateMemoryEntry = (id, data) => update('memories', id, data);diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex ff4e74ff5f..cd517c1452 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -196,6 +196,48 @@ describe('brainStorage tombstones', () => {});});+describe('memory recency ordering', () => {+ it('memoryRecencyMs prefers source clocks over storage clocks', () => {+ // sourceUpdatedAt wins+ expect(brainStorage.memoryRecencyMs({+ sourceUpdatedAt: ISO('2024-07-14'), sourceCreatedAt: ISO('2024-01-01'),+ updatedAt: ISO('2026-06-16'),+ })).toBe(Date.parse(ISO('2024-07-14')));+ // falls back to sourceCreatedAt, then updatedAt, then createdAt+ expect(brainStorage.memoryRecencyMs({ sourceCreatedAt: ISO('2023-03-03'), updatedAt: ISO('2026-01-01') }))+ .toBe(Date.parse(ISO('2023-03-03')));+ expect(brainStorage.memoryRecencyMs({ updatedAt: ISO('2025-05-05') }))+ .toBe(Date.parse(ISO('2025-05-05')));+ expect(brainStorage.memoryRecencyMs({ createdAt: ISO('2025-02-02') }))+ .toBe(Date.parse(ISO('2025-02-02')));+ // missing/unparseable → 0 (sorts last)+ expect(brainStorage.memoryRecencyMs({})).toBe(0);+ expect(brainStorage.memoryRecencyMs({ sourceUpdatedAt: 'not-a-date', updatedAt: null })).toBe(0);+ });++ it('getMemoryEntries returns imports newest-first by source recency, not export/insertion order', async () => {+ // Imported in non-chronological export order (the ChatGPT-export bug): the+ // bulk import stamps every record's createdAt/updatedAt with ~the same time,+ // so only the source clock distinguishes them.+ await brainStorage.create('memories', {+ title: 'oldest', source: 'chatgpt-import',+ sourceCreatedAt: ISO('2024-07-14'), sourceUpdatedAt: ISO('2024-07-14'),+ });+ await brainStorage.create('memories', {+ title: 'newest', source: 'chatgpt-import',+ sourceCreatedAt: ISO('2026-01-10'), sourceUpdatedAt: ISO('2026-02-01'),+ });+ await brainStorage.create('memories', {+ title: 'middle', source: 'chatgpt-import',+ sourceCreatedAt: ISO('2025-05-05'), sourceUpdatedAt: ISO('2025-05-06'),+ });++ const entries = await brainStorage.getMemoryEntries();+ const imported = entries.filter((e) => e.source === 'chatgpt-import');+ expect(imported.map((e) => e.title)).toEqual(['newest', 'middle', 'oldest']);+ });+});+// Read the raw stored record (including tombstones) by bypassing the read filter.async function rawRecord(type, id) {const { readFile } = await import('fs/promises');diff --git a/server/services/chatgptImport.js b/server/services/chatgptImport.jsindex 985ca6f155..5e5788f795 100644--- a/server/services/chatgptImport.js+++ b/server/services/chatgptImport.js@@ -396,7 +396,11 @@ export async function importConversations(parsed, options = {}) {tags,source: 'chatgpt-import',sourceRef: archiveName,- sourceCreatedAt: summary.createTime || null+ // Both source clocks are persisted so the memory list can order imports by+ // the original conversation recency (updateTime preferred) rather than the+ // shared bulk-import timestamp. See `memoryRecencyMs` in brainStorage.js.+ sourceCreatedAt: summary.createTime || null,+ sourceUpdatedAt: summary.updateTime || null});results.push({diff --git a/server/services/chatgptImport.test.js b/server/services/chatgptImport.test.jsindex b0271223e9..7072d41841 100644--- a/server/services/chatgptImport.test.js+++ b/server/services/chatgptImport.test.js@@ -194,6 +194,10 @@ describe('chatgptImport service', () => {expect(firstCall.tags).toEqual(expect.arrayContaining(['chatgpt-import', 'archive']));expect(firstCall.source).toBe('chatgpt-import');expect(firstCall.content).toContain('What is 2+2?');+ // Both source clocks persist so the memory list can order imports by the+ // original conversation recency (not the shared bulk-import timestamp).+ expect(firstCall.sourceCreatedAt).toBe(new Date(1700000000 * 1000).toISOString());+ expect(firstCall.sourceUpdatedAt).toBe(new Date(1700000100 * 1000).toISOString());const archives = await readdir(join(TMP, 'imports', 'chatgpt'));expect(archives.length).toBe(2);