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 the agentGuard bin/pm2 shim's actual kill-blocking behavior (#1847)
[._.]/ Adam Eivyc0336aa8d608
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1dc370d8ac..240e7ad56a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -59,4 +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)+- **[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, plus the `bin/pm2` bash shim's actual block behavior (spawns the shim with a stub real-pm2 to assert `pm2 kill`/`startup`/`unstartup` and `delete/stop/restart all` are blocked case-insensitively while scoped/read-only commands pass through, and the no-pm2-found 127 path); `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.jsindex 7649c748c4..a6b4dbfc42 100644--- a/server/lib/agentGuard/index.test.js+++ b/server/lib/agentGuard/index.test.js@@ -1,6 +1,9 @@-import { describe, it, expect } from 'vitest';+import { describe, it, expect, beforeAll, afterAll } from 'vitest';import { delimiter, dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync, chmodSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';import { agentGuardEnv, AGENT_GUARD_BIN } from './index.js';const HERE = dirname(fileURLToPath(import.meta.url));@@ -56,3 +59,96 @@ describe('agentGuardEnv', () => {expect(patch.FOO).toBeUndefined();});});++// The PATH-prepend is only half the safety mechanism — the actual kill-blocking+// lives in the bin/pm2 bash shim. Exercise it directly with a STUB real-pm2 so a+// passed-through command is observable (and no real pm2 ever runs). POSIX-only:+// the shim is bash, so skip on Windows (where the prepend is a documented no-op).+const SHIM = join(AGENT_GUARD_BIN, 'pm2');+const describeShim = process.platform === 'win32' ? describe.skip : describe;++describeShim('pm2 guard shim (bin/pm2)', () => {+ let workDir;+ let stubPm2;+ let marker;++ beforeAll(() => {+ workDir = mkdtempSync(join(tmpdir(), 'agentguard-'));+ marker = join(workDir, 'execed.txt');+ stubPm2 = join(workDir, 'pm2');+ // Stub real-pm2: records the args it was invoked with, then exits 0. If the+ // shim blocks, this never runs and the marker stays absent.+ writeFileSync(stubPm2, `#!/usr/bin/env bash\nprintf '%s\\n' "$*" > '${marker}'\nexit 0\n`);+ chmodSync(stubPm2, 0o755);+ });++ afterAll(() => {+ rmSync(workDir, { recursive: true, force: true });+ });++ const runShim = (args) => {+ if (existsSync(marker)) rmSync(marker);+ const res = spawnSync('bash', [SHIM, ...args], {+ env: { ...process.env, PORTOS_REAL_PM2: stubPm2 },+ encoding: 'utf8',+ });+ return { code: res.status, execedArgs: existsSync(marker) ? readFileSync(marker, 'utf8').trim() : null };+ };++ it('ships an executable shim file', () => {+ expect(existsSync(SHIM)).toBe(true);+ // Owner-executable bit set (0o100) — an un-chmod'd shim would silently not run.+ expect(statSync(SHIM).mode & 0o100).toBe(0o100);+ });++ it('blocks `pm2 kill` (exit 1, never reaches real pm2)', () => {+ const { code, execedArgs } = runShim(['kill']);+ expect(code).toBe(1);+ expect(execedArgs).toBeNull();+ });++ it('blocks `pm2 startup` and `pm2 unstartup`', () => {+ expect(runShim(['startup']).code).toBe(1);+ expect(runShim(['unstartup']).code).toBe(1);+ });++ it('blocks the subcommand case-insensitively (`pm2 KILL`)', () => {+ const { code, execedArgs } = runShim(['KILL']);+ expect(code).toBe(1);+ expect(execedArgs).toBeNull();+ });++ it('blocks `pm2 delete all` / `pm2 stop all` / `pm2 restart all`', () => {+ for (const verb of ['delete', 'stop', 'restart']) {+ const { code, execedArgs } = runShim([verb, 'all']);+ expect(code).toBe(1);+ expect(execedArgs).toBeNull();+ }+ });++ it('blocks `all` case-insensitively (`pm2 delete ALL`)', () => {+ expect(runShim(['delete', 'ALL']).code).toBe(1);+ });++ it('passes a scoped `pm2 restart <name>` through to the real pm2', () => {+ const { code, execedArgs } = runShim(['restart', 'my-app']);+ expect(code).toBe(0);+ expect(execedArgs).toBe('restart my-app');+ });++ it('passes a read-only `pm2 list` through to the real pm2', () => {+ const { code, execedArgs } = runShim(['list']);+ expect(code).toBe(0);+ expect(execedArgs).toBe('list');+ });++ it('exits 127 when no real pm2 can be resolved', () => {+ // Empty PORTOS_REAL_PM2 + a curated coreutils PATH that has no pm2 (but still+ // resolves bash/tr/dirname the shim needs) → the resolver finds none.+ const res = spawnSync('bash', [SHIM, 'list'], {+ env: { PORTOS_REAL_PM2: '', PATH: '/usr/bin:/bin' },+ encoding: 'utf8',+ });+ expect(res.status).toBe(127);+ });+});