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
test: cover sync-critical pure modules lwwTimestamp/pgTimestamp/validation/agentGuard (#1847)
[._.]/ Adam Eivyd0988babafa1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0e914fe14c..1dc370d8ac 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -59,3 +59,4 @@- **[issue-1837] On-disk JSON writes are now crash-safe across ~50 service/route files** — ~73 persistence sites used a raw `writeFile(path, JSON.stringify(data, null, 2))`, which truncates the JSON file if the process crashes mid-write (leaving an unparseable half-record on disk). Each was swapped to the canonical `atomicWrite` helper (`server/lib/fileUtils.js`), which writes to a temp file and atomically renames it over the target so readers never see a partial write. Covers brain storage, run/agent metadata, decision log, meatspace (calendar/alcohol/nicotine/health/post), mortal-loom store, identity goals, image/video sidecars, GitHub/Google/Obsidian configs, taste/usage/genome/epigenetic stores, and the scaffolding routes. Sites that intentionally append a trailing newline keep their exact byte output (passed as a pre-stringified string), and `videoGen/local.js`'s `{ flag: 'wx' }` exclusive-create write is left as-is (atomicWrite can't replicate exclusive-create). (#1837)- **[issue-1846] Replaced vacuous inline-copy tests with coverage of real production logic** — `subAgentSpawner.test.js` had four `describe` blocks that re-implemented production logic inline and tested the copies, so the real code could regress while the suite stayed green: an inline `ERROR_PATTERNS`/`categorizeError`, an inline `resolveFailedTaskStatus` (which omitted the `MAX_TOTAL_SPAWNS` short-circuit and `compaction` metadata that the real `resolveFailedTaskUpdate` has), and stub `exitCodeMessages`/`buildSpawnArgs` literals exported from no production module. The error-classification and retry-decision blocks now live in `agentErrorAnalysis.test.js` against the real exported `ERROR_PATTERNS` (via `analyzeAgentFailure`) and a new pure `resolveFailedTaskDecision` helper extracted from `resolveFailedTaskUpdate` (the async wrapper delegates to it and just stamps timestamps + creates the investigation task — behavior-preserving); the exit-code block is replaced by a new `agentRunTracking.test.js` covering the real `extractErrorFromOutput` mapping; and the redundant spawn-args stub is dropped since `agentCliSpawning.test.js` already covers the real `buildCliSpawnConfig`. The genuine imported-helper tests (`isTruthyMeta`/`isFalsyMeta`/`applyAppWorktreeDefault`) are kept. (#1846)- **[issue-1876] Consolidated four private XML-entity decoders into a shared `server/lib/xmlEntities.js`** — `decodeXmlEntities`/`decodeEntities`/inline `stripHtml` had drifted into near-identical copies across `appleHealthXmlParser.js`, `claudeChangelog.js`, `pinterestFeed.js`, `feeds.js`, and `messageGmailSync.js`, so an entity-handling fix had to be applied in up to five places. The most complete implementation (named + decimal `&#NN;` + hex `&#xNN;` via a single double-decode-safe pass, out-of-range-tolerant) is promoted to a shared, barrel-registered helper that also takes an optional extra-named-entity map (`{ nbsp: ' ', zwnj: '' }`) for the mail-specific entities Gmail's HTML-to-text needs; every call site now imports it. Behavior-preserving (each site's existing tests pass on the shared single-pass decoder); covered by a new `xmlEntities.test.js`. (#1876)+- **[issue-1847] Added tests for four sync-critical pure modules that shipped without one** — `server/lib/lwwTimestamp.js` (the last-writer-wins polarity behind every cross-instance merge), `server/lib/pgTimestamp.js` (`mirrorTimestamp`'s TIMESTAMPTZ bind-safety guards), `server/lib/agentGuard/index.js` (`agentGuardEnv`'s PATH-prepend + `PORTOS_REAL_PM2` pm2-kill shim), and the previously-untested `providerSchema`/`validate` exports of `server/lib/aiToolkit/validation.js`. Coverage hits the real branch points: `parseTsMs` non-string/unparseable returns, `compareNewerWins`/`compareEarlierWins` tie + unparseable-side + ISO-vs-non-ISO + antisymmetry; `mirrorTimestamp` calendar-rollover normalization, year-0000 rejection, ±expanded-year rejection, 0001/9999 bounds; `agentGuardEnv` guard-dir-first PATH order, `Path` fallback, real-pm2 resolution; `providerSchema` endpoint `''`/`null`→undefined coercion, id slug regex + 80-char max, `numCtx` 512–1048576 bounds, and `validate`'s `{path, message}` error shape. Tests only. (#1847)diff --git a/server/lib/agentGuard/index.test.js b/server/lib/agentGuard/index.test.jsnew file mode 100644index 0000000000..7649c748c4--- /dev/null+++ b/server/lib/agentGuard/index.test.js@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest';+import { delimiter, dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { agentGuardEnv, AGENT_GUARD_BIN } from './index.js';++const HERE = dirname(fileURLToPath(import.meta.url));++describe('AGENT_GUARD_BIN', () => {+ it('points at the bin/ directory holding the guarded pm2 shim', () => {+ expect(AGENT_GUARD_BIN).toBe(join(HERE, 'bin'));+ });+});++describe('agentGuardEnv', () => {+ it('prepends the guard bin to the front of PATH, ahead of the base PATH', () => {+ const { PATH } = agentGuardEnv({ PATH: '/usr/bin:/bin' });+ expect(PATH).toBe(`${AGENT_GUARD_BIN}${delimiter}/usr/bin:/bin`);+ // Guard dir must be the FIRST entry so the shim shadows the real pm2.+ expect(PATH.split(delimiter)[0]).toBe(AGENT_GUARD_BIN);+ });++ it('still ends with delimiter+base when base PATH is empty', () => {+ const { PATH } = agentGuardEnv({ PATH: '' });+ expect(PATH).toBe(`${AGENT_GUARD_BIN}${delimiter}`);+ expect(PATH.split(delimiter)[0]).toBe(AGENT_GUARD_BIN);+ });++ it('falls back to the Windows-style Path key when PATH is absent', () => {+ const { PATH } = agentGuardEnv({ Path: 'C:\\Windows' });+ expect(PATH).toBe(`${AGENT_GUARD_BIN}${delimiter}C:\\Windows`);+ });++ it('treats a fully empty env as an empty base PATH', () => {+ const { PATH } = agentGuardEnv({});+ expect(PATH).toBe(`${AGENT_GUARD_BIN}${delimiter}`);+ });++ it('sets PORTOS_REAL_PM2 to the resolved real pm2 binary (pm2 is installed here)', () => {+ const patch = agentGuardEnv({ PATH: '/usr/bin' });+ // pm2 is a dependency of this repo, so it resolves and the shim is pointed at it.+ expect(patch.PORTOS_REAL_PM2).toBeTruthy();+ expect(patch.PORTOS_REAL_PM2.endsWith(join('bin', 'pm2'))).toBe(true);+ // The real pm2 must NOT be the guarded shim — that would defeat the guard.+ expect(patch.PORTOS_REAL_PM2.startsWith(AGENT_GUARD_BIN)).toBe(false);+ });++ it('reads PATH from process.env by default', () => {+ const { PATH } = agentGuardEnv();+ expect(PATH.startsWith(`${AGENT_GUARD_BIN}${delimiter}`)).toBe(true);+ expect(PATH).toBe(`${AGENT_GUARD_BIN}${delimiter}${process.env.PATH || ''}`);+ });++ it('returns only PATH (and PORTOS_REAL_PM2 when resolved) — no other keys leak', () => {+ const patch = agentGuardEnv({ PATH: '/usr/bin', FOO: 'bar' });+ expect(Object.keys(patch).sort()).toEqual(['PATH', 'PORTOS_REAL_PM2']);+ expect(patch.FOO).toBeUndefined();+ });+});diff --git a/server/lib/aiToolkit/validation.test.js b/server/lib/aiToolkit/validation.test.jsindex c9c8a259bd..e276a9c5f3 100644--- a/server/lib/aiToolkit/validation.test.js+++ b/server/lib/aiToolkit/validation.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { sanitizeScreenshotRefs } from './validation.js';+import { sanitizeScreenshotRefs, providerSchema, validate } from './validation.js';describe('sanitizeScreenshotRefs — POST /api/runs screenshot hardening (#1870)', () => {it('keeps an in-dir image basename unchanged', () => {@@ -63,3 +63,120 @@ describe('sanitizeScreenshotRefs — POST /api/runs screenshot hardening (#1870)expect(sanitizeScreenshotRefs('x.png')).toEqual({ safe: [], rejected: [] });});});++const minimalProvider = { name: 'Codex CLI', type: 'cli' };++describe('providerSchema', () => {+ it('accepts a minimal cli provider (name + type only)', () => {+ expect(providerSchema.safeParse(minimalProvider).success).toBe(true);+ });++ describe('endpoint empty-string/null → undefined coercion', () => {+ it('coerces endpoint: "" to undefined so the URL check is skipped for CLI providers', () => {+ const r = providerSchema.safeParse({ ...minimalProvider, endpoint: '' });+ expect(r.success).toBe(true);+ expect(r.data.endpoint).toBeUndefined();+ });++ it('coerces endpoint: null to undefined', () => {+ const r = providerSchema.safeParse({ ...minimalProvider, endpoint: null });+ expect(r.success).toBe(true);+ expect(r.data.endpoint).toBeUndefined();+ });++ it('keeps a valid URL endpoint', () => {+ const r = providerSchema.safeParse({ ...minimalProvider, type: 'api', endpoint: 'https://api.example.com' });+ expect(r.success).toBe(true);+ expect(r.data.endpoint).toBe('https://api.example.com');+ });++ it('rejects a non-empty, non-URL endpoint', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, endpoint: 'not-a-url' }).success).toBe(false);+ });+ });++ describe('id slug regex', () => {+ it('accepts a lowercase-alphanumeric-with-hyphens id', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'codex' }).success).toBe(true);+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'claude-ollama-1' }).success).toBe(true);+ });++ it('rejects uppercase, leading hyphen, and disallowed characters', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'Codex' }).success).toBe(false);+ expect(providerSchema.safeParse({ ...minimalProvider, id: '-codex' }).success).toBe(false);+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'codex_cli' }).success).toBe(false);+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'codex cli' }).success).toBe(false);+ });++ it('rejects an id over the 80-char max', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'a'.repeat(81) }).success).toBe(false);+ expect(providerSchema.safeParse({ ...minimalProvider, id: 'a'.repeat(80) }).success).toBe(true);+ });+ });++ describe('numCtx 512–1048576 bounds', () => {+ it('accepts values at the inclusive bounds', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, numCtx: 512 }).success).toBe(true);+ expect(providerSchema.safeParse({ ...minimalProvider, numCtx: 1048576 }).success).toBe(true);+ });++ it('rejects values below 512 and above 1048576', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, numCtx: 511 }).success).toBe(false);+ expect(providerSchema.safeParse({ ...minimalProvider, numCtx: 1048577 }).success).toBe(false);+ });++ it('rejects a non-integer numCtx', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, numCtx: 1024.5 }).success).toBe(false);+ });++ it('accepts null (unset)', () => {+ expect(providerSchema.safeParse({ ...minimalProvider, numCtx: null }).success).toBe(true);+ });+ });++ describe('type enum + required name', () => {+ it('rejects an unknown type and a missing/empty name', () => {+ expect(providerSchema.safeParse({ name: 'X', type: 'magic' }).success).toBe(false);+ expect(providerSchema.safeParse({ type: 'cli' }).success).toBe(false);+ expect(providerSchema.safeParse({ name: '', type: 'cli' }).success).toBe(false);+ });++ it('accepts each valid type', () => {+ for (const type of ['cli', 'api', 'tui']) {+ expect(providerSchema.safeParse({ name: 'X', type }).success).toBe(true);+ }+ });+ });+});++describe('validate', () => {+ it('returns { success: true, data } for valid input', () => {+ const result = validate(providerSchema, minimalProvider);+ expect(result.success).toBe(true);+ expect(result.data).toMatchObject({ name: 'Codex CLI', type: 'cli' });+ expect(result.errors).toBeUndefined();+ });++ it('returns { success: false, errors: [{ path, message }] } for invalid input', () => {+ const result = validate(providerSchema, { type: 'magic' });+ expect(result.success).toBe(false);+ expect(Array.isArray(result.errors)).toBe(true);+ expect(result.errors.length).toBeGreaterThan(0);+ for (const e of result.errors) {+ expect(typeof e.path).toBe('string');+ expect(typeof e.message).toBe('string');+ }+ // name is missing and type is invalid — both should surface.+ const paths = result.errors.map(e => e.path);+ expect(paths).toContain('name');+ expect(paths).toContain('type');+ });++ it('joins a nested error path with dots', () => {+ // models must be an array of strings — a numeric element produces a path+ // like 'models.0'.+ const result = validate(providerSchema, { ...minimalProvider, models: [42] });+ expect(result.success).toBe(false);+ expect(result.errors.some(e => e.path === 'models.0')).toBe(true);+ });+});diff --git a/server/lib/lwwTimestamp.test.js b/server/lib/lwwTimestamp.test.jsnew file mode 100644index 0000000000..f10d883c7f--- /dev/null+++ b/server/lib/lwwTimestamp.test.js@@ -0,0 +1,117 @@+import { describe, it, expect } from 'vitest';+import { parseTsMs, compareNewerWins, compareEarlierWins } from './lwwTimestamp.js';++describe('parseTsMs', () => {+ it('parses an ISO-8601 string to epoch ms', () => {+ expect(parseTsMs('1970-01-01T00:00:00.000Z')).toBe(0);+ expect(parseTsMs('2026-06-30T00:00:00.000Z')).toBe(Date.parse('2026-06-30T00:00:00.000Z'));+ });++ it('parses a non-ISO but Date.parse-able string', () => {+ // RFC-2822 style — not ISO, but Date.parse accepts it.+ expect(parseTsMs('Tue, 30 Jun 2026 00:00:00 GMT')).toBe(Date.parse('Tue, 30 Jun 2026 00:00:00 GMT'));+ });++ it('returns null for an unparseable string', () => {+ expect(parseTsMs('not-a-date')).toBeNull();+ expect(parseTsMs('')).toBeNull();+ });++ it('returns null for non-string inputs', () => {+ expect(parseTsMs(null)).toBeNull();+ expect(parseTsMs(undefined)).toBeNull();+ expect(parseTsMs(0)).toBeNull();+ expect(parseTsMs(1719705600000)).toBeNull(); // a number is NOT parsed+ expect(parseTsMs(new Date())).toBeNull();+ expect(parseTsMs({})).toBeNull();+ });++ it('orders two parseable-but-different-format timestamps by epoch, not lexically', () => {+ // Lexicographically 'Jan' < 'Feb' is false but here the ISO form sorts the+ // other way from the RFC form — the point is both resolve to the same ms.+ const iso = parseTsMs('2026-01-02T03:04:05.000Z');+ const rfc = parseTsMs('Fri, 02 Jan 2026 03:04:05 GMT');+ expect(iso).toBe(rfc);+ });+});++describe('compareNewerWins', () => {+ it('returns true when candidate is strictly newer', () => {+ expect(compareNewerWins('2026-06-30T00:00:01.000Z', '2026-06-30T00:00:00.000Z')).toBe(true);+ });++ it('returns false when candidate is older', () => {+ expect(compareNewerWins('2026-06-30T00:00:00.000Z', '2026-06-30T00:00:01.000Z')).toBe(false);+ });++ it('breaks an exact tie to the incumbent (returns false)', () => {+ const t = '2026-06-30T00:00:00.000Z';+ expect(compareNewerWins(t, t)).toBe(false);+ });++ it('never lets an unparseable candidate override', () => {+ expect(compareNewerWins('garbage', '2026-06-30T00:00:00.000Z')).toBe(false);+ expect(compareNewerWins(null, '2026-06-30T00:00:00.000Z')).toBe(false);+ });++ it('lets a valid candidate beat an unparseable incumbent', () => {+ expect(compareNewerWins('2026-06-30T00:00:00.000Z', 'garbage')).toBe(true);+ expect(compareNewerWins('2026-06-30T00:00:00.000Z', null)).toBe(true);+ });++ it('breaks a both-unparseable tie to the incumbent (returns false)', () => {+ expect(compareNewerWins('garbage', 'also-garbage')).toBe(false);+ expect(compareNewerWins(null, undefined)).toBe(false);+ });++ it('compares ISO vs non-ISO formats by epoch value', () => {+ // RFC form is one second newer than the ISO form despite different shapes.+ expect(compareNewerWins('Fri, 02 Jan 2026 03:04:06 GMT', '2026-01-02T03:04:05.000Z')).toBe(true);+ });++ it('is antisymmetric for two distinct valid timestamps', () => {+ const a = '2026-06-30T00:00:01.000Z';+ const b = '2026-06-30T00:00:00.000Z';+ // exactly one direction wins+ expect(compareNewerWins(a, b)).toBe(true);+ expect(compareNewerWins(b, a)).toBe(false);+ });+});++describe('compareEarlierWins', () => {+ it('returns -1 when a is earlier (a wins)', () => {+ expect(compareEarlierWins('2026-06-30T00:00:00.000Z', '2026-06-30T00:00:01.000Z')).toBe(-1);+ });++ it('returns 1 when b is earlier (b wins)', () => {+ expect(compareEarlierWins('2026-06-30T00:00:01.000Z', '2026-06-30T00:00:00.000Z')).toBe(1);+ });++ it('returns 0 on an exact tie', () => {+ const t = '2026-06-30T00:00:00.000Z';+ expect(compareEarlierWins(t, t)).toBe(0);+ });++ it('returns 0 when both sides are unparseable', () => {+ expect(compareEarlierWins('garbage', 'also-garbage')).toBe(0);+ expect(compareEarlierWins(null, undefined)).toBe(0);+ });++ it('lets the parseable side win against an unparseable side', () => {+ // a unparseable → b wins (1)+ expect(compareEarlierWins('garbage', '2026-06-30T00:00:00.000Z')).toBe(1);+ // b unparseable → a wins (-1)+ expect(compareEarlierWins('2026-06-30T00:00:00.000Z', 'garbage')).toBe(-1);+ });++ it('is antisymmetric for two distinct valid timestamps', () => {+ const early = '2026-06-30T00:00:00.000Z';+ const late = '2026-06-30T00:00:01.000Z';+ expect(compareEarlierWins(early, late)).toBe(-1 * compareEarlierWins(late, early));+ });++ it('compares ISO vs non-ISO formats by epoch value', () => {+ // RFC form is one second earlier → a wins.+ expect(compareEarlierWins('Fri, 02 Jan 2026 03:04:04 GMT', '2026-01-02T03:04:05.000Z')).toBe(-1);+ });+});diff --git a/server/lib/pgTimestamp.test.js b/server/lib/pgTimestamp.test.jsnew file mode 100644index 0000000000..ee7bf6304f--- /dev/null+++ b/server/lib/pgTimestamp.test.js@@ -0,0 +1,75 @@+import { describe, it, expect } from 'vitest';+import { mirrorTimestamp } from './pgTimestamp.js';++const FALLBACK = '__fallback__';++describe('mirrorTimestamp', () => {+ it('normalizes a valid ISO timestamp to canonical toISOString form', () => {+ // Offset form gets normalized to the canonical Z form.+ expect(mirrorTimestamp('2026-06-30T00:00:00+00:00', FALLBACK)).toBe('2026-06-30T00:00:00.000Z');+ });++ it('returns the canonical ISO string (not the raw input) for an in-range value', () => {+ const out = mirrorTimestamp('2026-01-02T03:04:05.000Z', FALLBACK);+ expect(out).toBe('2026-01-02T03:04:05.000Z');+ expect(new Date(out).toISOString()).toBe(out); // round-trips cleanly+ });++ it('normalizes an out-of-range calendar date that Date.parse rolls over', () => {+ // 2026-02-31 does not exist; Date.parse rolls it to Mar 3. The normalized+ // canonical string is what PG can actually bind.+ const out = mirrorTimestamp('2026-02-31T00:00:00.000Z', FALLBACK);+ expect(out).toBe('2026-03-03T00:00:00.000Z');+ expect(out).not.toBe(FALLBACK);+ });++ it('accepts a non-ISO but Date.parse-able string and normalizes it', () => {+ expect(mirrorTimestamp('Tue, 30 Jun 2026 00:00:00 GMT', FALLBACK)).toBe('2026-06-30T00:00:00.000Z');+ });++ it('falls back for an unparseable string', () => {+ expect(mirrorTimestamp('not-a-date', FALLBACK)).toBe(FALLBACK);+ expect(mirrorTimestamp('', FALLBACK)).toBe(FALLBACK);+ });++ it('falls back for non-string inputs', () => {+ expect(mirrorTimestamp(null, FALLBACK)).toBe(FALLBACK);+ expect(mirrorTimestamp(undefined, FALLBACK)).toBe(FALLBACK);+ expect(mirrorTimestamp(1719705600000, FALLBACK)).toBe(FALLBACK);+ expect(mirrorTimestamp(new Date(), FALLBACK)).toBe(FALLBACK);+ });++ it('rejects year 0000 (no Gregorian year zero) and falls back', () => {+ // Date.parse('0000-01-01...') is accepted and toISOString emits '0000-...',+ // which PG would still reject — so mirrorTimestamp must fall back.+ const iso = new Date(Date.parse('0000-01-01T00:00:00.000Z')).toISOString();+ expect(iso.startsWith('0000-')).toBe(true); // confirm the precondition+ expect(mirrorTimestamp('0000-01-01T00:00:00.000Z', FALLBACK)).toBe(FALLBACK);+ });++ it('accepts a low but non-zero 4-digit year (0001)', () => {+ const out = mirrorTimestamp('0001-01-01T00:00:00.000Z', FALLBACK);+ expect(out).toBe('0001-01-01T00:00:00.000Z');+ });++ it('accepts the top of the 4-digit year range (9999)', () => {+ const out = mirrorTimestamp('9999-12-31T23:59:59.000Z', FALLBACK);+ expect(out).toBe('9999-12-31T23:59:59.000Z');+ });++ it('rejects a positive expanded-year form (+275760) that PG cannot bind', () => {+ // Far-future date toISOString emits the signed +YYYYYY- expanded form.+ const out = mirrorTimestamp('+275760-09-13T00:00:00.000Z', FALLBACK);+ expect(out).toBe(FALLBACK);+ });++ it('rejects a negative expanded-year (BCE) form that PG cannot bind', () => {+ const out = mirrorTimestamp('-100000-01-01T00:00:00.000Z', FALLBACK);+ expect(out).toBe(FALLBACK);+ });++ it('passes the fallback through verbatim (any type)', () => {+ expect(mirrorTimestamp(null, null)).toBeNull();+ expect(mirrorTimestamp('bad', undefined)).toBeUndefined();+ });+});