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

fix: git-init CD scratch cwd and remove it on finalize (#4650)

Adam Eivy53d21996821e
diff --git a/server/lib/README.md b/server/lib/README.md
index 054d3fad1b..5e48990dbd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -206,7 +206,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |
| `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. |
| `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)` / `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 CLAUDE.md discovery cannot walk up into the repo (#4650). `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.
+| `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 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. |
| `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. |
diff --git a/server/lib/spawnCwd.js b/server/lib/spawnCwd.js
index 6b8454d782..13c91fb92d 100644
--- a/server/lib/spawnCwd.js
+++ b/server/lib/spawnCwd.js
@@ -28,6 +28,7 @@
import { join } from 'path';
import { tmpdir } from 'os';
import { statSync } from 'fs';
+import { rm } from 'fs/promises';
import { expandHome } from './fileUtils.js';
/**
@@ -61,6 +62,11 @@ export function creativeDirectorScratchCwd(agentId) {
return join(tmpdir(), 'portos-cd-cwd', agentId);
}
+/** Best-effort: missing dirs are a no-op (`force: true`). */
+export async function removeCreativeDirectorScratchCwd(agentId) {
+ await rm(creativeDirectorScratchCwd(agentId), { recursive: true, force: true });
+}
+
/**
* Spawn-site cwd for a CoS agent. CD scratch tasks always resolve to the
* per-agent scratch path (even if the caller still handed `PATHS.root`);
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 7e625c6f15..6e935ad801 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -1,10 +1,10 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { posixPath } from './testHelper.js';
-import { mkdtempSync, rmSync, writeFileSync } from 'fs';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from 'fs';
import { tmpdir, homedir } from 'os';
import { join } from 'path';
-import { resolveSpawnCwd, withSpawnCwdEnv, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd, resolveAgentCliCwd } from './spawnCwd.js';
+import { resolveSpawnCwd, withSpawnCwdEnv, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd, resolveAgentCliCwd, removeCreativeDirectorScratchCwd } from './spawnCwd.js';
import { PATHS } from './fileUtils.js';
import { collectServerSources, readServerSource } from './testHelper.js';
@@ -187,6 +187,16 @@ describe('Creative Director scratch cwd (#4650)', () => {
agentId: 'agent-cd-2',
})).toBe(PATHS.root);
});
+
+ it('removeCreativeDirectorScratchCwd deletes the scratch dir and is a no-op when missing', async () => {
+ const dir = creativeDirectorScratchCwd('agent-cd-rm');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'leftover.txt'), 'x');
+ expect(existsSync(dir)).toBe(true);
+ await removeCreativeDirectorScratchCwd('agent-cd-rm');
+ expect(existsSync(dir)).toBe(false);
+ await expect(removeCreativeDirectorScratchCwd('agent-cd-rm')).resolves.toBeUndefined();
+ });
});
describe('withSpawnCwdEnv', () => {
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 9378f98fb9..9b27c447ee 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -40,6 +40,7 @@ import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMAR
import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion } from './taskTypeHooks.js';
import { processAgentCompletion } from './agentCompletion.js';
import { extractSimplifySummaries } from './agentSummaryExtraction.js';
+import { usesCreativeDirectorScratchCwd, removeCreativeDirectorScratchCwd } from '../lib/spawnCwd.js';
/**
* Release the execution lane and complete tool-execution tracking for a
@@ -921,6 +922,12 @@ export async function finalizeAgent({
await processAgentCompletion(agentId, task, success, outputBuffer);
+ if (usesCreativeDirectorScratchCwd(task)) {
+ await removeCreativeDirectorScratchCwd(agentId).catch((err) => {
+ emitLog('warn', `⚠️ CD scratch cleanup failed for ${agentId}: ${err.message}`, { agentId });
+ });
+ }
+
// Hand the CORRECTED verdict back so the caller's worktree cleanup runs on the
// same answer this function just persisted (#3358). Without it, a run
// downgraded to `pr-missing` would still be cleaned up as a success — worktree
diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.js
index 88ce239edd..5aa011b973 100644
--- a/server/services/agentFinalization.providerBench.test.js
+++ b/server/services/agentFinalization.providerBench.test.js
@@ -290,3 +290,34 @@ describe('finalizeAgent provider sidelining', () => {
expect(markProviderUnavailableMock).not.toHaveBeenCalled();
});
});
+
+describe('finalizeAgent — Creative Director scratch cleanup (#4650)', () => {
+ it('removes the per-agent scratch cwd when the CD run finishes', async () => {
+ const { mkdirSync, writeFileSync, existsSync } = await import('fs');
+ const { join } = await import('path');
+ const { creativeDirectorScratchCwd } = await import('../lib/spawnCwd.js');
+ const dir = creativeDirectorScratchCwd('agent-cd-fin');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'leftover.txt'), 'x');
+ await finalizeAgent({
+ agentId: 'agent-cd-fin',
+ task: {
+ id: 'task-cd',
+ taskType: 'internal',
+ description: 'CD plan',
+ metadata: { creativeDirector: { projectId: 'p', kind: 'plan' }, useWorktree: false },
+ },
+ runId: 'run-cd',
+ providerId: 'codex',
+ success: true,
+ exitCode: 0,
+ duration: 1000,
+ outputBuffer: '',
+ terminatedByUser: false,
+ isTruthyMetaFn: () => false,
+ workspacePath: dir,
+ prExpected: false,
+ });
+ expect(existsSync(dir)).toBe(false);
+ });
+});
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 11bc373b38..15373fcbef 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -151,6 +151,15 @@ export async function prepareAgentWorkspace({ agentId, task }) {
if (usesCreativeDirectorScratchCwd(task)) {
const workspacePath = creativeDirectorScratchCwd(agentId);
await ensureDir(workspacePath);
+ // Codex (and any CLI that refuses a non-git cwd) needs a repo root here.
+ // Initializing INSIDE the scratch makes the scratch itself the git root, so
+ // native CLAUDE.md discovery cannot walk up into the PortOS checkout —
+ // `--skip-git-repo-check` would only cover Codex's exec path, not TUI.
+ await execGit(['init'], workspacePath).catch((err) => {
+ emitLog('warn', `⚠️ CD scratch git init failed for ${agentId}: ${err.message}`, {
+ taskId: task.id, workspace: workspacePath,
+ });
+ });
emitLog('info', `📂 Agent workspace: ${workspacePath} (creative-director scratch)`, {
taskId: task.id, workspace: workspacePath,
});
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 893dfc16ff..2576bb3e36 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -12,7 +12,9 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
-vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));
+vi.mock('../lib/execGit.js', () => ({
+ execGit: vi.fn().mockResolvedValue({ stdout: '', stderr: '', exitCode: 0 }),
+}));
vi.mock('./cos.js', () => ({
updateTask: vi.fn().mockResolvedValue({}),
addTask: vi.fn().mockResolvedValue({}),
@@ -54,6 +56,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {
import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';
import { updateTask, getAgents } from './cos.js';
import { ensureLatest } from './git.js';
+import { execGit } from '../lib/execGit.js';
import { detectConflicts } from './taskConflict.js';
import { getAppWorkspace } from './agentPromptBuilder.js';
import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch } from './worktreeManager.js';
@@ -75,6 +78,7 @@ describe('prepareAgentWorkspace — Creative Director scratch cwd (#4650)', () =
expect(r.workspacePath).not.toBe(PATHS.root);
expect(r.worktreeInfo).toBeNull();
expect(ensureDir).toHaveBeenCalledWith(r.workspacePath);
+ expect(execGit).toHaveBeenCalledWith(['init'], r.workspacePath);
expect(ensureLatest).not.toHaveBeenCalled();
expect(createWorktree).not.toHaveBeenCalled();
expect(detectConflicts).not.toHaveBeenCalled();