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
fix: validate detached update process identity (#5134)
[._.]/ Adam Eivy100889db1280
diff --git a/server/lib/README.md b/server/lib/README.mdindex 1f4c85a8bd..e8ac57cbac 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -247,7 +247,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. |-| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |+| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows has no double-fork (plain-spawn fallback), so its handle's `kill` delegates to `killProcessTree` (`taskkill /T /F`) — a cancel there takes the runner's children with it. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. || `execGit.js` | `execGit(args, cwd, options)` utility imported by `git.js` + worktree manager. `cwd` is REQUIRED — it rejects on a missing/blank one rather than letting `spawn` fall back to `process.cwd()` and run git against PortOS's own checkout (#4554). || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). Includes `probeFrameCount(videoPath)` (metadata `nb_frames`, falling back to a real `-count_frames` pass — expensive, so call it once per file) and `trimVideoFromFrame(videoPath, outPath, {startFrame, fps})` — a frame-EXACT head cut via the `trim` filter (an `-ss` seek can drift a frame, which reads as a stutter at a stitch seam), keeping audio in sync with `atrim` when the clip has a soundtrack and taking `-an` when it doesn't. Re-encodes by necessity, so a later concat must re-encode too; `outPath` may equal the input (temp-file + rename install). Used by the chained-render context window — see `videoContinuity.js`. `buildTrimConcatArgs({inputs, outPath, width, height, fps, withAudio})` builds the argv for the other half of that job: a concat that drops leading frames from some of its inputs inside a `filter_complex` graph, so the cuts ride along with the timeline encode instead of costing one pre-encode per clip (pass `withAudio` only when EVERY input has an audio stream — check with `hasAudioStream`). `H264_ENCODE_ARGS` / `AAC_ENCODE_ARGS` are the shared encode profile: clips produced by different paths here get concatenated together, so a mismatch shows up as one segment graded differently from its neighbours — spread these rather than re-typing the flags. Every re-encode here also pins BT.709: `BT709_CONTAINER_ARGS` (the `colr` atom, always emitted) plus `bt709TagFilter()` → the `BT709_TAG_FILTER` `setparams=…` string, or `null` on an ffmpeg without that filter (`supportsSetparamsFilter()` probes `-filters` once per process; `null` = not probed, and a probe that couldn't run stays uncached). Both halves are required — from ffmpeg 8 the encoder reads color properties off the FRAMES, silently overriding the container flags, so a flags-only output decodes washed-out. `buildTrimConcatArgs` takes the filter as its `colorTagFilter` option rather than probing, to stay pure. |diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.jsindex 6f32a7c21e..8553d5766d 100644--- a/server/lib/detachedSpawn.js+++ b/server/lib/detachedSpawn.js@@ -43,15 +43,19 @@// the supervisor records the exit status — exactly as if the original handle// had never gone away (#1332).-import { spawn } from './childProcess.js';+import { execFile, spawn } from './childProcess.js';import { EventEmitter } from 'events';import { constants as osConstants } from 'os';-import { join } from 'path';+import { basename, join } from 'path';import { open, readFile, writeFile, rm, stat, readdir } from 'fs/promises';+import { promisify } from 'util';import { killProcessTree } from './bufferedSpawn.js';import { ensureDir, sleep } from './fileUtils.js';+import { safeChildProcessOptions } from './processEnv.js';import { withSpawnCwdEnv } from './spawnCwd.js';+const execFileAsync = promisify(execFile);+// Default cadence for tailing the job's log files and polling for completion.// 250ms matches the high-frequency-write batching cadence used elsewhere — far// below human perception for progress, cheap enough to run for hours.@@ -532,8 +536,13 @@ export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, c* (dataManagerBusy, #3342). So an ABSENT control file reads as "never launched",* but any other read failure is rethrown rather than silently synthesized into* "not running": "we could not look" must not answer as "nothing is there".+ * Callers that reuse one control dir for one fixed command may also provide+ * its expected executable and arguments. That identity check prevents a stale+ * PID file from treating an unrelated process that inherited the PID as the+ * detached job.** @param {string} controlDir - the job's spawnDetached control dir+ * @param {{executable: string, args?: string[]}|null} expectedProcess* @returns {Promise<boolean>}*/const readControlFile = (path) => readFile(path, 'utf8').catch((err) => {@@ -541,12 +550,31 @@ const readControlFile = (path) => readFile(path, 'utf8').catch((err) => {throw err;});-export async function isDetachedRunning(controlDir) {+const processMatches = async (pid, { executable, args }) => {+ const { stdout } = await execFileAsync(+ 'ps', ['-ww', '-p', String(pid), '-o', 'command='], safeChildProcessOptions({ timeout: 5000 })+ ).catch((err) => {+ // The process may exit between kill(pid, 0) and ps. That is a normal+ // not-running answer; every other probe failure must remain fail-closed.+ if (err?.code === 1) return { stdout: '' };+ throw err;+ });+ const command = stdout.trim();+ if (!command) return false;+ const actualExecutable = command.split(/\s+/, 1)[0];+ if (basename(actualExecutable) !== basename(executable)) return false;+ if (!Array.isArray(args)) return true;+ const actualArgs = command.slice(actualExecutable.length).trim();+ return actualArgs === args.map(String).join(' ');+};++export async function isDetachedRunning(controlDir, expectedProcess = null) {const pidRaw = await readControlFile(join(controlDir, 'pid'));const pid = Number.parseInt(pidRaw, 10);if (!Number.isFinite(pid) || pid <= 0) return false;const exitWritten = (await readControlFile(join(controlDir, 'exit'))).length > 0;- return !exitWritten && isAlive(pid);+ if (exitWritten || !isAlive(pid)) return false;+ return expectedProcess ? processMatches(pid, expectedProcess) : true;}/**diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.jsindex 0e835842ea..067f0021e8 100644--- a/server/lib/detachedSpawn.test.js+++ b/server/lib/detachedSpawn.test.js@@ -1,7 +1,7 @@import { describe, it, expect, afterEach, vi } from 'vitest';import { mkdir, mkdtemp, rm, stat, writeFile } from 'fs/promises';import { tmpdir } from 'os';-import { join } from 'path';+import { basename, join } from 'path';import { ChildProcess, execFile } from './childProcess.js';import { promisify } from 'util';import { pinPlatform } from './testHelper.js';@@ -488,6 +488,21 @@ describe('isDetachedRunning', () => {await onClose(handle);});+ it.runIf(IS_POSIX)('is true when the live process matches the expected executable', async () => {+ const controlDir = await tmpControlDir();+ await writeFile(join(controlDir, 'pid'), String(process.pid));+ expect(await isDetachedRunning(controlDir, { executable: basename(process.execPath) })).toBe(true);+ });++ it.runIf(IS_POSIX)('is false when a recycled live PID belongs to another process', async () => {+ const controlDir = await tmpControlDir();+ await writeFile(join(controlDir, 'pid'), String(process.pid));+ expect(await isDetachedRunning(controlDir, {+ executable: 'bash',+ args: ['/example/update.sh']+ })).toBe(false);+ });+it('is false once the job recorded its exit', async () => {const controlDir = await tmpControlDir();const handle = await spawnDetached('sh', ['-c', 'exit 0'], { controlDir, pollMs: 25 });diff --git a/server/services/updateExecutor.js b/server/services/updateExecutor.jsindex 1a98eea64e..4f9bae0c37 100644--- a/server/services/updateExecutor.js+++ b/server/services/updateExecutor.js@@ -76,7 +76,7 @@ export async function executeUpdate(tag, emit, { forceCleanWorkspaces } = {}) {// triggers, and its supervisor's late `exit` write into a truncated control// dir would prematurely close the new handle with the OLD script's status).// A still-running script also means a second update is wrong regardless.- if (!isWindows && await isDetachedRunning(controlDir)) {+ if (!isWindows && await isDetachedRunning(controlDir, { executable: cmd, args })) {const errorMessage = 'A previous update script is still running — wait for it to finish before starting another update';await recordUpdateResult({version: tag.replace(/^v/, ''),diff --git a/server/services/updateExecutor.test.js b/server/services/updateExecutor.test.jsindex 73f8979806..6cbf2e49df 100644--- a/server/services/updateExecutor.test.js+++ b/server/services/updateExecutor.test.js@@ -109,6 +109,13 @@ describe('executeUpdate', () => {await promise;expect(spawn).not.toHaveBeenCalled();+ expect(isDetachedRunning).toHaveBeenCalledWith(+ expect.stringContaining('update-detached'),+ {+ executable: 'bash',+ args: [expect.stringContaining('update.sh')]+ }+ );expect(spawnDetached).toHaveBeenCalledWith('bash',[expect.stringContaining('update.sh')],@@ -119,6 +126,19 @@ describe('executeUpdate', () => {);});+ it('continues when a stale control PID does not match the update process', async () => {+ isDetachedRunning.mockResolvedValue(false);+ const child = createMockChild();+ spawnDetached.mockResolvedValue(child);++ const { promise } = await startUpdate('v1.0.0', () => {});+ child.emit('close', 0);+ const result = await promise;++ expect(result.success).toBe(true);+ expect(spawnDetached).toHaveBeenCalledOnce();+ });+// Reusing the fixed control dir while the prior update script is still// alive would let the old supervisor's late `exit` write prematurely close// the new handle with the old script's status — so a still-running script