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(history): store action history as jsonl

Adam Eivy4c5f0c5c3f5b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 220308c83e..1513adfa53 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,6 +17,7 @@
- `server/services/universeBuilder.js` rewritten to consume `collectionStore` instead of `readJSONFile` + `atomicWrite` against a monolithic file. The per-entity `CURRENT_SCHEMA_VERSION = 4` (stamped INSIDE each universe record) is preserved unchanged — it describes record shape and is orthogonal to the new type-level `schemaVersion: 5` (storage layout). Cross-record state (`runs[]` history) moves to `data/universes/index.json` under `config.runs`. Per-record edits no longer serialize against unrelated universe edits — concurrent PATCHes on different universes now run in parallel.
- **[data-versioning-split-pipeline-issues] Split pipeline issues and series into collection stores.** `data/pipeline-issues.json` now migrates to `data/pipeline-issues/{id}/index.json` via migration 035, and `data/pipeline-series.json` migrates to `data/pipeline-series/{id}/index.json` via migration 036 so the pipeline area lands on one storage convention. The issue and series services now use `collectionStore` with boot-time schema verification, per-record saves for ordinary issue/series edits, series-scoped queues only where issue renumbering touches siblings, and sync snapshots read through the service APIs instead of monolithic files.
- `server/services/dataSync.js` universe-sync category points at the new `data/universes/` directory. `readFingerprintMap` walks two levels deep so per-record edits invalidate the cache; the dir layout's `index.json` mtime catches add/remove/edit at every nesting level. `getUniverseSnapshot()` reads via `listUniverses({ includeDeleted: true })` so peer sync sees the same set tombstones included.
+- `data/history.json` is now `data/history.jsonl`. Migration 037 converts the legacy `{ entries: [...] }` wrapper into one JSON record per line, renames the old file to `history.json.bak-037`, and the history service now appends new actions instead of rewriting the whole file on each log. `server/lib/fileUtils.js` also exposes shared `appendJSONLine`, `readJSONLines`, and `writeJSONLines` helpers for other JSONL logs.
- `/work <task>` Claude Code slash command (`.claude/commands/work.md`) — slugifies the task, spins up a fresh git worktree under `.claude/worktrees/<slug>/` branched off local `main` (NOT current HEAD), `cd`s into it, carries out the work without disturbing the originating checkout's uncommitted edits / branch / HEAD, and on completion always chains `/simplify` → `/do:review --with codex,gemini` → `/do:pr --review-with copilot` so codex + gemini findings are addressed locally *before* the PR opens (otherwise Copilot kicks in immediately on unreviewed code and burns review cycles). Branch / dir collision auto-suffixes with `-2`, `-3`, etc. `.claude/worktrees/` is already gitignored.
- **Fork-aware update flow.** The PortOS update tab now detects whether the local clone's `origin` remote points at upstream `atomantic/PortOS` or at a personal fork (`server/lib/gitRemote.js` parses SCP-style + HTTPS + ssh:// remote URLs, case-insensitive owner/repo match). When running from a fork the Update tab swaps the "Update Now" button for three explicit choices: **Sync Fork & Update** (runs `gh repo sync <owner>/<fork> --source atomantic/PortOS --branch main` then proceeds with the local update — fast-forward only, so it refuses to clobber divergent fork commits), **Sync Fork Only** (sync without applying), and **Update from Fork As-Is** (skip sync, pull from your fork's origin — useful if you already merged upstream into your fork via your own workflow). The server `/api/update/execute` endpoint now gates fork runs behind either a fresh `lastForkSync` record (≤10 min, same fullName) or an explicit `acknowledgeFork: true` to avoid the silent "I clicked Update and nothing happened" failure mode when a fork's main is behind upstream. The release-check still polls `atomantic/PortOS` so fork users continue to see upstream version notifications. `POST /api/update/sync-fork` exposes the gh-sync action; a 409 with `FORK_DIVERGED` is returned when the fork's main has commits not on upstream, with guidance pointing the user at PRs / feature branches / the explicit `--force` escape hatch they can run from a terminal. `update.sh` / `update.ps1` now log the active origin URL so users can confirm in the update log which repo they actually pulled from.
diff --git a/PLAN.md b/PLAN.md
index 12df3be82b..8f1f9c48a6 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -4,7 +4,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
## Next Up
-- [ ] [data-versioning-history-jsonl] **`data/history.json` → `data/history.jsonl` — proactive structural fix.** Data shape is append-only by definition; rewriting the whole array on every append is the wrong shape regardless of current size. Convert to line-delimited JSON so appends are O(1) instead of O(N) and `tail`-based reads / log rotation become trivial. Migration `037-history-json-to-jsonl.js`: read `data/history.json`, emit one line per entry, rename old file to `history.json.bak-037`. Add `appendJsonLine(path, obj)` + `readJsonLines(path, { from, limit })` helpers to `server/lib/fileUtils.js` (barrel + README) so `data/brain/digests.jsonl` and `data/brain/inbox_log.jsonl` (already JSONL but hand-rolled) can adopt the same primitives. Pair with a quick audit of other append-only-shaped monolithic files (`client-errors.json`?, `media-jobs.json`?) — convert any that match the shape in the same PR or a follow-up.
+- [ ] [test-autosubscribe-fanout-getpeers-guard-remaining] **Apply the `getPeers → []` test stub to the remaining record-creating test files (and consider a shared guard).** Root-caused 2026-05-23: `createUniverse` (universeBuilder.js:939) and `createSeries` (pipeline/series.js:223) fire a non-awaited `import('./sharing/peerSync.js').then(autoSubscribeRecordToAllPeers)`. `autoSubscribeRecordToAllPeers` reads the live peer registry via `getPeers()` (instances.js, `dataPath` closure to the REAL PATHS), so any test that creates a non-ephemeral universe/series and does NOT mock `getPeers` fans the fixture out to real peers (void/null/NaN), which persist it into real `data/`. Fixed in `universeBuilder.test.js`, `universeBuilderPromote.test.js`, `universeCanon.test.js` (this is how the "Moebius SciFi"/uuid-0000 leak happened). **Still unguarded** (create subscribable records, no `getPeers` mock — verified via `grep -L getPeers` against the createUniverse/createSeries/createIssue caller set): `pipeline/arcPlanner.test.js`, `pipeline/autoRunner.test.js`, `pipeline/coverUniverseFiler.test.js`, `pipeline/episodeVideo.test.js`, `pipeline/issues.test.js`, `pipeline/migrateSeriesCanon.test.js`, `pipeline/seasons.test.js`, `pipeline/series.test.js`, `pipeline/textStages.test.js`, `pipeline/volumeBeatsRunner.test.js`, `sharing/subscriptions.test.js`, `sharing/integration.test.js`, `universeBuilderAutoSort.test.js` (the last is safe-by-accident: its synthetic in-memory fileUtils mock lacks `dataPath`, which breaks the peerSync import chain — but that's fragile). These create *series*, so they'd pollute `data/pipeline-series/` not `data/universes/` (no residue found yet, but same race). The `sharing/*` ones likely set up real peers intentionally — handle carefully (don't blanket-stub). **Better fix to evaluate:** a shared `mockNoPeers()` helper in `server/lib/mockPathsDataRoot.js` (or a vitest `setupFiles` default stub that individual sharing tests can override) so every new record-creating test is protected by default instead of relying on each author remembering. Add the `getPeers→[]` convention to CLAUDE.md's test section.
- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. After the 2026-05-23 leaked-fixture cleanup (22 universes force-pruned), the matching subs are now orphaned — on `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count — saw 141). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves to an on-disk record) to the tombstone GC path, or call it from the prune helpers. Low urgency; cosmetic + minor wasted work per sync cycle. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.
- [ ] [propagate-runner-errorAnalysis-into-onRunFailed-context] **Propagate `metadata.errorAnalysis` into the `onRunFailed` event context** so `promptRunner.js#markProviderUnavailableFromError` doesn't re-run `analyzeError` on the same text the runner already analyzed. The runner writes `errorAnalysis` to `metadata` (`server/lib/aiToolkit/runner.js:245`, 343, 433) but `server/index.js:202` only forwards a subset to the error event, so the analysis pass is duplicated on every failure. Either add `errorAnalysis` to the event context AND to the rejected error thrown to promptRunner, or attach it to the metadata object that the rejection carries. Microsecond-class perf, but cleaner. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22).
- [ ] [upcoming-tasks-widget-drop-catch-to-empty] **Drop the `.catch(() => [])` in `UpcomingTasksWidget.jsx:21`.** Pre-existing tech debt (not touched in v2.6.0): `useAutoRefetch(() => api.getCosUpcomingTasks(6).catch(() => []), 60000)` wipes the prior list on transient errors. The seven sibling callers (Brain, DigitalTwin, QuickSummary, ActionableInsightsBanner, ProcessesTab, SystemHealthPage, CyberCity) were fixed during the v2.6.0 release review by dropping the catch and passing `{ silent: true }` to the API helper instead. Apply the same pattern here: add an `options` parameter to `getCosUpcomingTasks` (in `client/src/services/apiAgents.js`, mirroring `getCosQuickSummary`), drop the catch, and pass `{ silent: true }` in the call site. Surfaced by reviewer-4 in the v2.6.0 release review (2026-05-21).
diff --git a/data.reference/history.json b/data.reference/history.json
deleted file mode 100644
index 046955d4b9..0000000000
--- a/data.reference/history.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "entries": []
-}
diff --git a/data.reference/history.jsonl b/data.reference/history.jsonl
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/data.reference/history.jsonl
@@ -0,0 +1 @@
+
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index ea9ea6efe6..d5d4e01a6f 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -96,7 +96,7 @@ PortOS/
├── data/ # Runtime data (gitignored)
│ ├── apps.json # Registered apps (read by autofixer)
│ ├── providers.json # AI provider configs
-│ ├── history.json # Action history
+│ ├── history.jsonl # Action history (JSON Lines)
│ ├── browser-config.json # Browser CDP/health configuration
│ ├── TASKS.md # User task file
│ ├── COS-TASKS.md # System task file
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index df0bcdd048..382610b669 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -222,7 +222,7 @@ cat data/apps.json | jq .
**Symptom**: Action history clears on restart.
**Solution**:
-- Check `data/history.json` exists and is writable
+- Check `data/history.jsonl` exists and is writable
- Verify disk space available
## Performance Issues
diff --git a/scripts/migrations/037-history-json-to-jsonl.js b/scripts/migrations/037-history-json-to-jsonl.js
new file mode 100644
index 0000000000..59edb7446f
--- /dev/null
+++ b/scripts/migrations/037-history-json-to-jsonl.js
@@ -0,0 +1,107 @@
+/**
+ * Convert action history from the legacy monolithic JSON wrapper:
+ *
+ * data/history.json { "entries": [...] }
+ *
+ * to append-friendly JSON Lines:
+ *
+ * data/history.jsonl one history entry per line
+ *
+ * The live service appends to `history.jsonl`, so routine action logging no
+ * longer rewrites the full history file. The legacy file is renamed to
+ * `history.json.bak-037` after conversion for manual recovery.
+ */
+
+import { mkdir, readFile, rename, stat } from 'fs/promises';
+import { join, relative } from 'path';
+import { readJSONLFile, writeJSONLines } from '../../server/lib/fileUtils.js';
+
+const LEGACY_FILENAME = 'history.json';
+const JSONL_FILENAME = 'history.jsonl';
+const BACKUP_SUFFIX = '.bak-037';
+
+const fileExists = (path) => stat(path).then(() => true, (err) => {
+ if (err.code === 'ENOENT') return false;
+ throw err;
+});
+
+const readJsonTolerant = async (path) => {
+ const raw = await readFile(path, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ try { return JSON.parse(raw); } catch { return { __unreadable: true }; }
+};
+
+export default {
+ async up({ rootDir }) {
+ const dataDir = join(rootDir, 'data');
+ const legacyPath = join(dataDir, LEGACY_FILENAME);
+ const jsonlPath = join(dataDir, JSONL_FILENAME);
+ const backupPath = legacyPath + BACKUP_SUFFIX;
+
+ await mkdir(dataDir, { recursive: true });
+
+ const legacyExists = await fileExists(legacyPath);
+ const jsonlExists = await fileExists(jsonlPath);
+
+ if (!legacyExists) {
+ if (!jsonlExists) {
+ await writeJSONLines(jsonlPath, []);
+ console.log('📦 migration 037: fresh install — created empty data/history.jsonl');
+ return { ok: true, reason: 'fresh-install' };
+ }
+ console.log('📦 migration 037: data/history.jsonl already present — no-op');
+ return { ok: true, reason: 'already-jsonl' };
+ }
+
+ const legacy = await readJsonTolerant(legacyPath);
+ if (!legacy || typeof legacy !== 'object' || legacy.__unreadable || !Array.isArray(legacy.entries)) {
+ console.warn(`⚠️ migration 037: ${legacyPath} unreadable or not { entries: [...] } — skipping. Resolve manually before next boot.`);
+ return { ok: false, reason: 'unreadable' };
+ }
+
+ const existing = await readJSONLFile(jsonlPath, { logErrors: true });
+ const existingIds = new Set(existing.map((entry) => (
+ entry && typeof entry.id === 'string' ? entry.id : null
+ )).filter(Boolean));
+
+ const converted = [];
+ let skippedDuplicate = 0;
+ let skippedInvalid = 0;
+ for (const entry of legacy.entries) {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
+ skippedInvalid += 1;
+ continue;
+ }
+ if (typeof entry.id === 'string' && existingIds.has(entry.id)) {
+ skippedDuplicate += 1;
+ continue;
+ }
+ converted.push(entry);
+ if (typeof entry.id === 'string') existingIds.add(entry.id);
+ }
+
+ await writeJSONLines(jsonlPath, [...existing, ...converted]);
+
+ const finalBackupPath = await fileExists(backupPath)
+ ? `${backupPath}-${Date.now()}`
+ : backupPath;
+ await rename(legacyPath, finalBackupPath);
+
+ console.log(
+ `📦 migration 037: converted ${converted.length} history entr${converted.length === 1 ? 'y' : 'ies'} ` +
+ `to data/${JSONL_FILENAME} (${skippedDuplicate} duplicate, ${skippedInvalid} invalid); ` +
+ `legacy file backed up as ${relative(dataDir, finalBackupPath)}`,
+ );
+
+ return {
+ ok: true,
+ reason: 'converted',
+ converted: converted.length,
+ skippedDuplicate,
+ skippedInvalid,
+ };
+ },
+};
diff --git a/scripts/migrations/037-history-json-to-jsonl.test.js b/scripts/migrations/037-history-json-to-jsonl.test.js
new file mode 100644
index 0000000000..22aa4dea22
--- /dev/null
+++ b/scripts/migrations/037-history-json-to-jsonl.test.js
@@ -0,0 +1,106 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './037-history-json-to-jsonl.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+const readJsonl = (path) =>
+ readFileSync(path, 'utf-8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line));
+
+describe('migration 037 — history.json to history.jsonl', () => {
+ let rootDir;
+ let dataDir;
+ let legacyPath;
+ let jsonlPath;
+ let backupPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-037-'));
+ dataDir = join(rootDir, 'data');
+ mkdirSync(dataDir, { recursive: true });
+ legacyPath = join(dataDir, 'history.json');
+ jsonlPath = join(dataDir, 'history.jsonl');
+ backupPath = legacyPath + '.bak-037';
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('fresh install: no legacy file creates an empty JSONL file', async () => {
+ const result = await migration.up({ rootDir });
+
+ expect(result).toEqual({ ok: true, reason: 'fresh-install' });
+ expect(existsSync(jsonlPath)).toBe(true);
+ expect(readFileSync(jsonlPath, 'utf-8')).toBe('');
+ expect(existsSync(legacyPath)).toBe(false);
+ });
+
+ it('converts legacy entries in order and backs up history.json', async () => {
+ writeJson(legacyPath, {
+ entries: [
+ { id: 'a', action: 'start', timestamp: '2026-05-23T00:00:00.000Z' },
+ { id: 'b', action: 'stop', timestamp: '2026-05-23T00:01:00.000Z' },
+ ],
+ });
+
+ const result = await migration.up({ rootDir });
+
+ expect(result).toEqual({
+ ok: true,
+ reason: 'converted',
+ converted: 2,
+ skippedDuplicate: 0,
+ skippedInvalid: 0,
+ });
+ expect(readJsonl(jsonlPath).map((entry) => entry.id)).toEqual(['a', 'b']);
+ expect(existsSync(legacyPath)).toBe(false);
+ expect(readJson(backupPath).entries).toHaveLength(2);
+ });
+
+ it('dedupes against existing JSONL during partial recovery', async () => {
+ writeFileSync(jsonlPath, '{"id":"a","action":"start"}\n');
+ writeJson(legacyPath, {
+ entries: [
+ { id: 'a', action: 'start' },
+ { id: 'b', action: 'stop' },
+ null,
+ ],
+ });
+
+ const result = await migration.up({ rootDir });
+
+ expect(result).toEqual({
+ ok: true,
+ reason: 'converted',
+ converted: 1,
+ skippedDuplicate: 1,
+ skippedInvalid: 1,
+ });
+ expect(readJsonl(jsonlPath).map((entry) => entry.id)).toEqual(['a', 'b']);
+ expect(existsSync(backupPath)).toBe(true);
+ });
+
+ it('is idempotent after conversion', async () => {
+ writeJson(legacyPath, { entries: [{ id: 'a', action: 'start' }] });
+ await migration.up({ rootDir });
+
+ const result = await migration.up({ rootDir });
+
+ expect(result).toEqual({ ok: true, reason: 'already-jsonl' });
+ expect(readJsonl(jsonlPath).map((entry) => entry.id)).toEqual(['a']);
+ });
+
+ it('reports unreadable legacy content without renaming it', async () => {
+ writeFileSync(legacyPath, 'not json');
+
+ const result = await migration.up({ rootDir });
+
+ expect(result).toEqual({ ok: false, reason: 'unreadable' });
+ expect(existsSync(legacyPath)).toBe(true);
+ expect(existsSync(jsonlPath)).toBe(false);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 78f13f04c4..9400e9e98a 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -82,7 +82,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. |
| `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply on the comparator result so an upgraded sender can't corrupt a downstream peer. |
-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |
| `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |
| `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |
| `multipart.js` | Streaming multipart/form-data parser. |
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 9049ca0489..4b461001ed 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -4,7 +4,7 @@
* Shared utilities for file operations used across services.
*/
-import { mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
+import { appendFile, mkdir, readFile, readdir, stat, writeFile, rename, unlink } from 'fs/promises';
import { existsSync, statSync, createReadStream } from 'fs';
import { execFile } from 'child_process';
import { promisify } from 'util';
@@ -384,6 +384,66 @@ export async function readJSONLFile(filePath, { logErrors = false } = {}) {
return safeJSONLParse(content, { logErrors, context: filePath });
}
+/**
+ * Append one JSON-serializable value to a JSON Lines file.
+ * Creates the parent directory as needed and writes exactly one trailing
+ * newline so readers can stream or split the file without special-casing the
+ * final record.
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {*} value - JSON-serializable value to append
+ * @returns {Promise<void>}
+ */
+export async function appendJSONLine(filePath, value) {
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined) {
+ throw new TypeError('appendJSONLine value must be JSON-serializable');
+ }
+ await ensureDir(dirname(filePath));
+ await appendFile(filePath, serialized + '\n');
+}
+
+/**
+ * Read JSON Lines with optional offset/limit slicing.
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {Object} options - Options
+ * @param {number} [options.from=0] - Zero-based record offset
+ * @param {number} [options.limit] - Maximum number of records to return
+ * @param {boolean} [options.logErrors=false] - Log malformed JSONL lines
+ * @returns {Promise<Array>} Parsed records
+ */
+export async function readJSONLines(filePath, { from = 0, limit, logErrors = false } = {}) {
+ const entries = await readJSONLFile(filePath, { logErrors });
+ const start = Number.isFinite(from) && from > 0 ? Math.floor(from) : 0;
+ if (limit === undefined || limit === null) return entries.slice(start);
+ const count = Number.isFinite(limit) && limit >= 0 ? Math.floor(limit) : 0;
+ return entries.slice(start, start + count);
+}
+
+/**
+ * Replace a JSON Lines file with the supplied records.
+ * Intended for compaction/retention and delete/clear flows; hot append paths
+ * should use appendJSONLine().
+ *
+ * @param {string} filePath - Path to JSONL file
+ * @param {Array} values - JSON-serializable records
+ * @returns {Promise<void>}
+ */
+export async function writeJSONLines(filePath, values) {
+ if (!Array.isArray(values)) {
+ throw new TypeError('writeJSONLines values must be an array');
+ }
+ const lines = values.map((value) => {
+ const serialized = JSON.stringify(value);
+ if (serialized === undefined) {
+ throw new TypeError('writeJSONLines values must be JSON-serializable');
+ }
+ return serialized;
+ });
+ await atomicWrite(filePath, lines.length > 0 ? `${lines.join('\n')}\n` : '');
+}
+
/**
* Time constants in milliseconds.
* Single source of truth — import these instead of declaring inline.
diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.js
index d2d35d8954..d8d75e6062 100644
--- a/server/lib/fileUtils.test.js
+++ b/server/lib/fileUtils.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
-import { writeFile, rm, mkdir } from 'fs/promises';
+import { readFile, writeFile, rm, mkdir } from 'fs/promises';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
@@ -12,6 +12,9 @@ import {
safeJSONLParse,
readJSONFile,
readJSONLFile,
+ appendJSONLine,
+ readJSONLines,
+ writeJSONLines,
formatDuration,
sha256File,
resolveImageInputPath,
@@ -317,6 +320,52 @@ describe('fileUtils', () => {
});
});
+ describe('JSONL write helpers', () => {
+ let testDir;
+
+ beforeEach(async () => {
+ testDir = mkdtempSync(join(tmpdir(), 'fileutils-jsonl-write-test-'));
+ });
+
+ afterEach(async () => {
+ await rm(testDir, { recursive: true, force: true });
+ });
+
+ it('appendJSONLine creates parent dirs and appends one record per line', async () => {
+ const filePath = join(testDir, 'nested', 'events.jsonl');
+ await appendJSONLine(filePath, { id: 'a', n: 1 });
+ await appendJSONLine(filePath, { id: 'b', n: 2 });
+
+ expect(await readFile(filePath, 'utf-8')).toBe('{"id":"a","n":1}\n{"id":"b","n":2}\n');
+ expect(await readJSONLines(filePath)).toEqual([{ id: 'a', n: 1 }, { id: 'b', n: 2 }]);
+ });
+
+ it('readJSONLines supports offset and limit', async () => {
+ const filePath = join(testDir, 'events.jsonl');
+ await writeFile(filePath, '{"id":"a"}\n{"id":"b"}\n{"id":"c"}\n');
+
+ expect(await readJSONLines(filePath, { from: 1, limit: 1 })).toEqual([{ id: 'b' }]);
+ expect(await readJSONLines(filePath, { from: 2 })).toEqual([{ id: 'c' }]);
+ expect(await readJSONLines(filePath, { limit: 0 })).toEqual([]);
+ });
+
+ it('writeJSONLines atomically replaces the file', async () => {
+ const filePath = join(testDir, 'events.jsonl');
+ await appendJSONLine(filePath, { id: 'old' });
+ await writeJSONLines(filePath, [{ id: 'new-1' }, { id: 'new-2' }]);
+
+ expect(await readFile(filePath, 'utf-8')).toBe('{"id":"new-1"}\n{"id":"new-2"}\n');
+ expect(await readJSONLines(filePath)).toEqual([{ id: 'new-1' }, { id: 'new-2' }]);
+ });
+
+ it('rejects non-serializable values', async () => {
+ await expect(appendJSONLine(join(testDir, 'bad.jsonl'), undefined))
+ .rejects.toThrow(/JSON-serializable/);
+ await expect(writeJSONLines(join(testDir, 'bad.jsonl'), [undefined]))
+ .rejects.toThrow(/JSON-serializable/);
+ });
+ });
+
describe('formatDuration', () => {
it('should return "0m" for zero or falsy values', () => {
expect(formatDuration(0)).toBe('0m');
diff --git a/server/services/history.js b/server/services/history.js
index 554e6ea5ce..2b4e088b18 100644
--- a/server/services/history.js
+++ b/server/services/history.js
@@ -1,16 +1,17 @@
-import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from '../lib/uuid.js';
-import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { appendJSONLine, ensureDir, PATHS, readJSONLines, writeJSONLines } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
const DATA_DIR = PATHS.data;
-const HISTORY_FILE = join(DATA_DIR, 'history.json');
+const HISTORY_FILE = join(DATA_DIR, 'history.jsonl');
const MAX_ENTRIES = 500;
// In-memory cache with TTL
let historyCache = null;
let cacheTimestamp = 0;
const CACHE_TTL_MS = 2000; // 2 second cache TTL
+const queueHistoryWrite = createFileWriteQueue();
async function loadHistory() {
// Return cached data if still valid
@@ -21,7 +22,7 @@ async function loadHistory() {
await ensureDir(DATA_DIR);
- historyCache = await readJSONFile(HISTORY_FILE, { entries: [] });
+ historyCache = { entries: await readJSONLines(HISTORY_FILE, { logErrors: true }) };
cacheTimestamp = now;
return historyCache;
}
@@ -29,36 +30,47 @@ async function loadHistory() {
async function saveHistory(data) {
await ensureDir(DATA_DIR);
// Trim to max entries
- if (data.entries.length > MAX_ENTRIES) {
- data.entries = data.entries.slice(-MAX_ENTRIES);
- }
- // Update cache with new data
- historyCache = data;
+ const nextData = {
+ entries: data.entries.length > MAX_ENTRIES
+ ? data.entries.slice(-MAX_ENTRIES)
+ : data.entries,
+ };
+ await writeJSONLines(HISTORY_FILE, nextData.entries);
+ // Update cache only after the disk write succeeds.
+ historyCache = nextData;
cacheTimestamp = Date.now();
- await writeFile(HISTORY_FILE, JSON.stringify(data, null, 2));
}
/**
* Log an action to history
*/
export async function logAction(action, target, targetName, details = {}, success = true, error = null) {
- const data = await loadHistory();
-
- const entry = {
- id: uuidv4(),
- action,
- target,
- targetName,
- details,
- success,
- error,
- timestamp: new Date().toISOString()
- };
-
- data.entries.push(entry);
- await saveHistory(data);
-
- return entry;
+ return queueHistoryWrite(async () => {
+ const data = await loadHistory();
+
+ const entry = {
+ id: uuidv4(),
+ action,
+ target,
+ targetName,
+ details,
+ success,
+ error,
+ timestamp: new Date().toISOString()
+ };
+
+ const entries = [...data.entries, entry];
+
+ if (entries.length > MAX_ENTRIES) {
+ await saveHistory({ entries });
+ } else {
+ await appendJSONLine(HISTORY_FILE, entry);
+ historyCache = { entries };
+ cacheTimestamp = Date.now();
+ }
+
+ return entry;
+ });
}
/**
@@ -100,34 +112,38 @@ export async function getActionTypes() {
* Delete a single history entry by ID
*/
export async function deleteEntry(id) {
- const data = await loadHistory();
- const index = data.entries.findIndex(e => e.id === id);
-
- if (index === -1) {
- return { deleted: false, error: 'Entry not found' };
- }
-
- data.entries.splice(index, 1);
- await saveHistory(data);
- return { deleted: true };
+ return queueHistoryWrite(async () => {
+ const data = await loadHistory();
+ const index = data.entries.findIndex(e => e.id === id);
+
+ if (index === -1) {
+ return { deleted: false, error: 'Entry not found' };
+ }
+
+ await saveHistory({
+ entries: data.entries.filter((entry) => entry.id !== id),
+ });
+ return { deleted: true };
+ });
}
/**
* Clear history (optionally older than days)
*/
export async function clearHistory(olderThanDays = null) {
- const data = await loadHistory();
-
- if (olderThanDays === null) {
- data.entries = [];
- } else {
- const cutoff = new Date();
- cutoff.setDate(cutoff.getDate() - olderThanDays);
- data.entries = data.entries.filter(e => new Date(e.timestamp) >= cutoff);
- }
-
- await saveHistory(data);
- return { cleared: true };
+ return queueHistoryWrite(async () => {
+ const data = await loadHistory();
+
+ let entries = [];
+ if (olderThanDays !== null) {
+ const cutoff = new Date();
+ cutoff.setDate(cutoff.getDate() - olderThanDays);
+ entries = data.entries.filter(e => new Date(e.timestamp) >= cutoff);
+ }
+
+ await saveHistory({ entries });
+ return { cleared: true };
+ });
}
/**
diff --git a/server/services/history.test.js b/server/services/history.test.js
new file mode 100644
index 0000000000..ffb1a3a96e
--- /dev/null
+++ b/server/services/history.test.js
@@ -0,0 +1,135 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+const readLines = (path) =>
+ readFileSync(path, 'utf-8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line));
+
+describe('history service JSONL storage', () => {
+ let dataDir;
+ let historyFile;
+
+ beforeEach(() => {
+ vi.resetModules();
+ dataDir = mkdtempSync(join(tmpdir(), 'portos-history-service-'));
+ historyFile = join(dataDir, 'history.jsonl');
+ });
+
+ afterEach(() => {
+ vi.doUnmock('../lib/fileUtils.js');
+ rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ async function loadService(overrides = {}) {
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, data: dataDir },
+ ...overrides,
+ };
+ });
+ return import('./history.js');
+ }
+
+ it('appends log entries as JSONL records and returns newest entries first', async () => {
+ const history = await loadService();
+
+ const first = await history.logAction('start', 'app-1', 'App One');
+ const second = await history.logAction('restart', 'app-1', 'App One', { via: 'test' });
+
+ expect(existsSync(historyFile)).toBe(true);
+ expect(readLines(historyFile).map((entry) => entry.id)).toEqual([first.id, second.id]);
+
+ const result = await history.getHistory();
+ expect(result.total).toBe(2);
+ expect(result.entries.map((entry) => entry.id)).toEqual([second.id, first.id]);
+ });
+
+ it('filters entries and rewrites JSONL on delete', async () => {
+ const history = await loadService();
+
+ const success = await history.logAction('start', 'app-1', 'App One', {}, true);
+ const failure = await history.logAction('stop', 'app-2', 'App Two', {}, false, 'boom');
+
+ expect((await history.getHistory({ success: false })).entries).toMatchObject([{ id: failure.id }]);
+ expect((await history.getActionTypes())).toEqual(['start', 'stop']);
+
+ expect(await history.deleteEntry(success.id)).toEqual({ deleted: true });
+ expect(readLines(historyFile).map((entry) => entry.id)).toEqual([failure.id]);
+ expect(await history.deleteEntry('missing')).toEqual({ deleted: false, error: 'Entry not found' });
+ });
+
+ it('preserves the max-entry retention bound during appends', async () => {
+ const history = await loadService();
+
+ for (let i = 0; i < 501; i += 1) {
+ await history.logAction('run', `target-${i}`, `Target ${i}`);
+ }
+
+ const lines = readLines(historyFile);
+ expect(lines).toHaveLength(500);
+ expect(lines[0].target).toBe('target-1');
+ expect(lines[499].target).toBe('target-500');
+
+ const result = await history.getHistory({ limit: 1 });
+ expect(result.total).toBe(500);
+ expect(result.entries[0].target).toBe('target-500');
+ });
+
+ it('serializes concurrent appends so no entry is lost', async () => {
+ const history = await loadService();
+
+ await Promise.all(Array.from({ length: 20 }, (_, i) =>
+ history.logAction('run', `target-${i}`, `Target ${i}`),
+ ));
+
+ const lines = readLines(historyFile);
+ expect(lines).toHaveLength(20);
+ expect(new Set(lines.map((entry) => entry.target)).size).toBe(20);
+ });
+
+ it('does not cache an entry when the append fails', async () => {
+ const appendJSONLine = vi.fn().mockRejectedValue(new Error('disk full'));
+ const history = await loadService({ appendJSONLine });
+
+ await expect(history.logAction('start', 'app-1', 'App One')).rejects.toThrow(/disk full/);
+
+ expect(await history.getHistory()).toEqual({ total: 0, entries: [] });
+ expect(existsSync(historyFile)).toBe(false);
+ });
+
+ it('does not remove a cached entry when delete persistence fails', async () => {
+ const writeJSONLines = vi.fn().mockRejectedValue(new Error('disk full'));
+ const history = await loadService({ writeJSONLines });
+ const entry = await history.logAction('start', 'app-1', 'App One');
+
+ await expect(history.deleteEntry(entry.id)).rejects.toThrow(/disk full/);
+
+ expect((await history.getHistory()).entries.map((item) => item.id)).toEqual([entry.id]);
+ expect(readLines(historyFile).map((item) => item.id)).toEqual([entry.id]);
+ });
+
+ it('does not clear cached entries when clear persistence fails', async () => {
+ const writeJSONLines = vi.fn().mockRejectedValue(new Error('disk full'));
+ const history = await loadService({ writeJSONLines });
+ const entry = await history.logAction('start', 'app-1', 'App One');
+
+ await expect(history.clearHistory()).rejects.toThrow(/disk full/);
+
+ expect((await history.getHistory()).entries.map((item) => item.id)).toEqual([entry.id]);
+ expect(readLines(historyFile).map((item) => item.id)).toEqual([entry.id]);
+ });
+
+ it('clears all records by replacing the JSONL file with empty content', async () => {
+ const history = await loadService();
+
+ await history.logAction('start', 'app-1', 'App One');
+ expect(readFileSync(historyFile, 'utf-8')).not.toBe('');
+
+ expect(await history.clearHistory()).toEqual({ cleared: true });
+ expect(readFileSync(historyFile, 'utf-8')).toBe('');
+ expect(await history.getHistory()).toEqual({ total: 0, entries: [] });
+ });
+});