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: isolate Creative Director CLI cwd and drop dev prompt bloat (#4650)

Adam Eivyf83956c74bb5
diff --git a/server/lib/README.md b/server/lib/README.md
index 860f69be25..054d3fad1b 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). `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)` / `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.
| `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 5e571bb215..6b8454d782 100644
--- a/server/lib/spawnCwd.js
+++ b/server/lib/spawnCwd.js
@@ -25,9 +25,52 @@
* cwd it was actually spawned in (issue #3193).
*/
+import { join } from 'path';
+import { tmpdir } from 'os';
import { statSync } from 'fs';
import { expandHome } from './fileUtils.js';
+/**
+ * Creative Director treatment/plan/evaluate tasks are HTTP-PATCH deliverables
+ * (`noCodeOutput`) and never asked for a worktree. Spawning them with
+ * `cwd = PATHS.root` lets Claude Code / Codex natively discover the PortOS
+ * repo's CLAUDE.md files — the same dev-convention bloat the API path already
+ * skips via `skipClaudeMd`. A per-agent scratch dir with no CLAUDE.md in its
+ * tree is the provider-agnostic fix (#4650).
+ *
+ * `useWorktree: true` keeps the worktree: an explicit isolation request still
+ * wins. CD production tasks always set `useWorktree: false`.
+ */
+export function usesCreativeDirectorScratchCwd(task) {
+ if (!task?.metadata?.creativeDirector) return false;
+ const useWorktree = task.metadata.useWorktree;
+ return useWorktree !== true && useWorktree !== 'true';
+}
+
+/**
+ * Isolated cwd for a CD-marked CLI/TUI run. Lives under the OS temp dir — NOT
+ * under the PortOS checkout (`data/cos/agents` is still inside the git tree,
+ * so Claude Code / Codex walking parent directories would still find the repo
+ * CLAUDE.md). `agentId` is required — a missing id would collapse every CD run
+ * onto one shared folder.
+ */
+export function creativeDirectorScratchCwd(agentId) {
+ if (typeof agentId !== 'string' || !agentId) {
+ throw new Error('creativeDirectorScratchCwd requires a non-empty agentId');
+ }
+ return join(tmpdir(), 'portos-cd-cwd', agentId);
+}
+
+/**
+ * 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`);
+ * everyone else keeps the existing `workspacePath || fallbackRoot` rule.
+ */
+export function resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId } = {}) {
+ if (usesCreativeDirectorScratchCwd(task)) return creativeDirectorScratchCwd(agentId);
+ return workspacePath && typeof workspacePath === 'string' ? workspacePath : fallbackRoot;
+}
+
/**
* Resolve the working directory for a spawned run or agent.
*
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index 7dc5241b52..7e625c6f15 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -4,7 +4,8 @@ import { posixPath } from './testHelper.js';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir, homedir } from 'os';
import { join } from 'path';
-import { resolveSpawnCwd, withSpawnCwdEnv } from './spawnCwd.js';
+import { resolveSpawnCwd, withSpawnCwdEnv, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd, resolveAgentCliCwd } from './spawnCwd.js';
+import { PATHS } from './fileUtils.js';
import { collectServerSources, readServerSource } from './testHelper.js';
describe('resolveSpawnCwd', () => {
@@ -135,6 +136,59 @@ describe('resolveSpawnCwd — supplied-but-unusable never reaches the fallback',
});
});
+describe('Creative Director scratch cwd (#4650)', () => {
+ const cdTask = (extra = {}) => ({
+ metadata: { creativeDirector: { projectId: 'p', kind: 'plan' }, useWorktree: false, ...extra },
+ });
+
+ it('recognizes a CD no-worktree task and rejects a worktree-requested one', () => {
+ expect(usesCreativeDirectorScratchCwd(cdTask())).toBe(true);
+ expect(usesCreativeDirectorScratchCwd(cdTask({ useWorktree: 'false' }))).toBe(true);
+ expect(usesCreativeDirectorScratchCwd(cdTask({ useWorktree: true }))).toBe(false);
+ expect(usesCreativeDirectorScratchCwd(cdTask({ useWorktree: 'true' }))).toBe(false);
+ expect(usesCreativeDirectorScratchCwd({ metadata: {} })).toBe(false);
+ expect(usesCreativeDirectorScratchCwd(null)).toBe(false);
+ });
+
+ it('places the scratch dir under the OS temp dir, outside the PortOS checkout', () => {
+ const cwd = creativeDirectorScratchCwd('agent-cd-1');
+ expect(cwd).toBe(join(tmpdir(), 'portos-cd-cwd', 'agent-cd-1'));
+ expect(cwd).not.toBe(PATHS.root);
+ // Native CLAUDE.md discovery walks parents to the git root. A path under
+ // the checkout (including gitignored data/) would still leak repo CLAUDE.md.
+ expect(cwd.startsWith(`${PATHS.root}/`)).toBe(false);
+ expect(cwd.startsWith(PATHS.root + '\\')).toBe(false);
+ });
+
+ it('refuses a missing agentId so CD runs cannot collapse onto one folder', () => {
+ expect(() => creativeDirectorScratchCwd('')).toThrow(/agentId/);
+ expect(() => creativeDirectorScratchCwd(null)).toThrow(/agentId/);
+ });
+
+ it('resolveAgentCliCwd swaps PATHS.root for the scratch path on a CD task', () => {
+ const scratch = creativeDirectorScratchCwd('agent-cd-2');
+ expect(resolveAgentCliCwd({
+ workspacePath: PATHS.root,
+ fallbackRoot: PATHS.root,
+ task: cdTask(),
+ agentId: 'agent-cd-2',
+ })).toBe(scratch);
+ // Non-CD keeps the caller workspace, including the root fallback.
+ expect(resolveAgentCliCwd({
+ workspacePath: '/tmp',
+ fallbackRoot: PATHS.root,
+ task: { metadata: {} },
+ agentId: 'agent-cd-2',
+ })).toBe('/tmp');
+ expect(resolveAgentCliCwd({
+ workspacePath: null,
+ fallbackRoot: PATHS.root,
+ task: { metadata: {} },
+ agentId: 'agent-cd-2',
+ })).toBe(PATHS.root);
+ });
+});
+
describe('withSpawnCwdEnv', () => {
// The bug (#3193): spawn({ cwd }) changes the child's real working directory
// but leaves the inherited PWD naming wherever the SERVER was started. OpenCode
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 2debbdfd86..d93ec4a5d4 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -35,6 +35,7 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { buildVendorSpawnConfig } from '../lib/providerVendors.js';
import { resolveCliModel, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
import { resolveForgeTokenEnv } from './git.js';
+import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
import { buildCliChildEnv } from '../lib/cliChildEnv.js';
import { prClaimWasVerified, resolvePrCompletion, resolvePrCreation } from '../lib/prDisposition.js';
@@ -341,8 +342,10 @@ export async function spawnDirectly({
const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;
const ROOT_DIR = PATHS.root;
- // Ensure workspacePath is valid
- const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;
+ // CD no-worktree tasks get an isolated scratch cwd so native CLAUDE.md
+ // discovery cannot reach the PortOS repo tree (#4650). Everyone else keeps
+ // workspacePath, falling back to the repo root when it was omitted.
+ const cwd = resolveAgentCliCwd({ workspacePath, fallbackRoot: ROOT_DIR, task, agentId });
// Direct CLI agents bypass runner.js, so their Ollama-backed harnesses need
// the same daemon context preparation as runner and TUI launches. This is
@@ -410,7 +413,7 @@ export async function spawnDirectly({
agentId,
taskId: task.id,
model,
- workspacePath,
+ workspacePath: cwd,
prompt: (task.description || '').substring(0, 500)
});
@@ -671,7 +674,7 @@ export async function spawnDirectly({
if (terminatedByUser) userTerminatedAgents.delete(agentId);
// This run's own sentinel (see doneSentinelName) — a worktree-less agent
// shares its workspace and must not read a sibling's signal as its own.
- const sentinelPath = doneSentinelPath(workspacePath, agentId);
+ const sentinelPath = doneSentinelPath(cwd, agentId);
const completionSentinelPresent = !!sentinelPath && existsSync(sentinelPath);
const completedBeforeHostShutdown = isHostShuttingDown() && completionSentinelPresent;
@@ -830,7 +833,7 @@ export async function spawnDirectly({
isTruthyMetaFn,
error: finalError || undefined,
completionReason: terminatedByUser ? 'user-terminated' : undefined,
- workspacePath,
+ workspacePath: cwd,
prExpected: directPrClaimExpected,
// The run window the commit criterion is evaluated against (#3637).
startedAt: agentData?.startedAt ?? null,
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 2c02e013d8..6e763108ac 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -826,6 +826,29 @@ describe('stream error containment', () => {
await spawnPromise.catch(() => {});
});
+ it('spawns a Creative Director task in an isolated scratch cwd, not the PortOS root (#4650)', async () => {
+ const { creativeDirectorScratchCwd } = await import('../lib/spawnCwd.js');
+ const args = {
+ ...minimalArgs,
+ task: {
+ id: 'task-cd',
+ description: 'Evaluate scene',
+ metadata: { creativeDirector: { projectId: 'p', kind: 'evaluate' }, useWorktree: false },
+ },
+ workspacePath: '/tmp', // the previous default — must not win over the scratch path
+ };
+ const spawnPromise = spawnDirectly(args);
+ await new Promise((r) => setTimeout(r, 10));
+ const expectedCwd = creativeDirectorScratchCwd('agent-test');
+ expect(spawn).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.anything(),
+ expect.objectContaining({ cwd: expectedCwd }),
+ );
+ fakeProcess.emit('close', 0);
+ await spawnPromise.catch(() => {});
+ });
+
it('leaves the spawn env\'s ambient GH_TOKEN untouched when there is no owner match', async () => {
const { resolveForgeTokenEnv } = await import('./git.js');
vi.mocked(resolveForgeTokenEnv).mockResolvedValueOnce({});
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index dff3adf3bf..3eb8d3fae6 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -1645,23 +1645,31 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// Creative Director tasks (scene evaluation, treatment/plan run via API) judge
// generated content rather than writing PortOS code — shared below by both
- // `skipClaudeMd` (the repo's dev-oriented CLAUDE.md files are pure noise for
- // that prompt) and `noCodeOutput` (the deliverable is an HTTP PATCH, not a
- // commit).
+ // `skipDevContext` (the repo's CLAUDE.md files plus memory / digital-twin /
+ // onboard-tools are pure noise for that prompt) and `noCodeOutput` (the
+ // deliverable is an HTTP PATCH, not a commit).
const isCreativeDirectorTask = !!task.metadata?.creativeDirector;
// Full path: API providers don't read CLAUDE.md natively, so always include it —
- // except for Creative Director tasks, per above.
- const skipClaudeMd = isCreativeDirectorTask;
+ // except for Creative Director tasks, per above. Memory, digital-twin, and the
+ // onboard-tools catalog are the same category of dev-oriented noise for a
+ // vision/PATCH task (#4650) — CD evaluate uses native Read + HTTP PATCH, and
+ // CD plan already receives creative-tool specs via `getToolSpecs()` in its
+ // own prompt, not this section.
+ const skipDevContext = isCreativeDirectorTask;
// Fetch independent context sections in parallel
const [memorySection, claudeMdSection, digitalTwinSection] = await Promise.all([
- getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 })
- .catch(err => { console.log(`⚠️ Memory retrieval failed: ${err.message}`); return null; }),
- skipClaudeMd
+ skipDevContext
+ ? Promise.resolve(null)
+ : getMemorySection(task, { maxTokens: config.memory?.maxContextTokens || 2000 })
+ .catch(err => { console.log(`⚠️ Memory retrieval failed: ${err.message}`); return null; }),
+ skipDevContext
? Promise.resolve(null)
: getClaudeMdContext(workspaceDir)
.catch(err => { console.log(`⚠️ CLAUDE.md retrieval failed: ${err.message}`); return null; }),
- getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000, personaId: 'active' })
- .catch(err => { console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`); return null; })
+ skipDevContext
+ ? Promise.resolve(null)
+ : getDigitalTwinForPrompt({ maxTokens: config.digitalTwin?.maxContextTokens || config.soul?.maxContextTokens || 2000, personaId: 'active' })
+ .catch(err => { console.log(`⚠️ Digital twin context retrieval failed: ${err.message}`); return null; })
]);
// Build context compaction section if task is retrying after a context-limit failure
@@ -1875,10 +1883,12 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
const skillSection = await loadSkillTemplates(detectSkillTemplates(task));
// Build onboard tools section for agent awareness
- const toolsSection = await getToolsSummaryForPrompt().catch(err => {
- console.log(`⚠️ Tools summary retrieval failed: ${err.message}`);
- return '';
- });
+ const toolsSection = skipDevContext
+ ? ''
+ : await getToolsSummaryForPrompt().catch(err => {
+ console.log(`⚠️ Tools summary retrieval failed: ${err.message}`);
+ return '';
+ });
// Build .planning/ context section for GSD-enabled apps
let planningContextSection = '';
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index a3f4948263..aff030bd57 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -96,6 +96,9 @@ import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBull
import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured default
import { isTruthyMeta } from './agentState.js';
import { buildPrompt } from './promptService.js'; // mocked above — inspect call args
+import { getMemorySection } from './memoryRetriever.js';
+import { getDigitalTwinForPrompt } from './digital-twin.js';
+import { getToolsSummaryForPrompt } from './tools.js';
import { loadSlashdoFile, writeResolvedSlashdoBody } from '../lib/slashdoLoader.js'; // mocked above — control the inlined body
import { SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';
// The heading a task-type hook's prompt points at to locate the sentinel path.
@@ -2221,6 +2224,70 @@ describe('discardWorktree (reasoning-only) completion contract', () => {
expect(prompt).not.toMatch(/Example Global Instructions/);
});
+ it('a Creative Director task on the full (api) path also omits memory, digital-twin, and onboard-tools sections (#4650)', async () => {
+ // Distinctive sentinels so a skipped fetch cannot be confused with an
+ // empty-but-called fetch. Restored after so sibling tests keep the empty
+ // default (null/'') the rest of the file relies on.
+ vi.mocked(getMemorySection).mockClear().mockResolvedValue('## Memory Context\nCD_MEMORY_SENTINEL');
+ vi.mocked(getDigitalTwinForPrompt).mockClear().mockResolvedValue('## Digital Twin\nCD_TWIN_SENTINEL');
+ vi.mocked(getToolsSummaryForPrompt).mockClear().mockResolvedValue('## Available Tools\nCD_TOOLS_SENTINEL');
+ vi.mocked(buildPrompt).mockClear();
+ const cdTask = makeTask({
+ metadata: { creativeDirector: { projectId: 'p', kind: 'evaluate' }, useWorktree: false, openPR: false },
+ });
+ const prompt = await buildAgentPrompt(cdTask, {}, '/r', null, isTruthyMeta, { providerType: 'api' });
+ expect(getMemorySection).not.toHaveBeenCalled();
+ expect(getDigitalTwinForPrompt).not.toHaveBeenCalled();
+ expect(getToolsSummaryForPrompt).not.toHaveBeenCalled();
+ const [, context] = vi.mocked(buildPrompt).mock.calls.at(-1);
+ expect(context.memorySection).toBeNull();
+ expect(context.digitalTwinSection).toBeNull();
+ expect(context.toolsSection).toBe('');
+ expect(context.claudeMdSection).toBeNull();
+ expect(prompt).not.toContain('CD_MEMORY_SENTINEL');
+ expect(prompt).not.toContain('CD_TWIN_SENTINEL');
+ expect(prompt).not.toContain('CD_TOOLS_SENTINEL');
+ vi.mocked(getMemorySection).mockResolvedValue(null);
+ vi.mocked(getDigitalTwinForPrompt).mockResolvedValue(null);
+ vi.mocked(getToolsSummaryForPrompt).mockResolvedValue('');
+ });
+
+ it('a non-CD api task still loads memory, digital-twin, and onboard-tools sections', async () => {
+ vi.mocked(getMemorySection).mockClear().mockResolvedValue('## Memory Context\nNONCD_MEMORY_SENTINEL');
+ vi.mocked(getDigitalTwinForPrompt).mockClear().mockResolvedValue('## Digital Twin\nNONCD_TWIN_SENTINEL');
+ vi.mocked(getToolsSummaryForPrompt).mockClear().mockResolvedValue('## Available Tools\nNONCD_TOOLS_SENTINEL');
+ vi.mocked(buildPrompt).mockClear();
+ const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, isTruthyMeta, { providerType: 'api' });
+ expect(getMemorySection).toHaveBeenCalled();
+ expect(getDigitalTwinForPrompt).toHaveBeenCalled();
+ expect(getToolsSummaryForPrompt).toHaveBeenCalled();
+ const [, context] = vi.mocked(buildPrompt).mock.calls.at(-1);
+ expect(context.memorySection).toContain('NONCD_MEMORY_SENTINEL');
+ expect(context.digitalTwinSection).toContain('NONCD_TWIN_SENTINEL');
+ expect(context.toolsSection).toContain('NONCD_TOOLS_SENTINEL');
+ // Fallback template (buildPrompt is mocked null) still inlines memory + tools.
+ expect(prompt).toContain('NONCD_MEMORY_SENTINEL');
+ expect(prompt).toContain('NONCD_TOOLS_SENTINEL');
+ vi.mocked(getMemorySection).mockResolvedValue(null);
+ vi.mocked(getDigitalTwinForPrompt).mockResolvedValue(null);
+ vi.mocked(getToolsSummaryForPrompt).mockResolvedValue('');
+ });
+
+ it('a CD scratch cwd does not leak repo CLAUDE.md into getClaudeMdContext', async () => {
+ // Mirrors the fixture-pinning in this block: a dir with no CLAUDE.md
+ // (the CD scratch shape) must not surface content that lives in a sibling
+ // "repo" fixture. Global ~/.claude/CLAUDE.md still splices here because
+ // this describe points homedir at a live fixture — that is a different
+ // channel than native project discovery from cwd.
+ const repo = mkdtempSync(join(tmpdir(), 'portos-cd-repo-'));
+ writeFileSync(join(repo, 'CLAUDE.md'), 'REPO_CLAUDE_MD_LEAK_SENTINEL');
+ const scratch = mkdtempSync(join(tmpdir(), 'portos-cd-scratch-'));
+ expect(await getClaudeMdContext(repo)).toContain('REPO_CLAUDE_MD_LEAK_SENTINEL');
+ expect(await getClaudeMdContext(scratch)).not.toContain('REPO_CLAUDE_MD_LEAK_SENTINEL');
+ rmSync(repo, { recursive: true, force: true });
+ rmSync(scratch, { recursive: true, force: true });
+ });
+
it('light TUI path suppresses the merge instruction and never splices the global CLAUDE.md at all', () => {
// `openPR: true` on purpose: this is the shape where merge suppression has
// to do work — the task metadata asks for a PR, and discardWorktree must
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 7d2d3ab007..22550cdb72 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -17,6 +17,7 @@ import { resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';
import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';
import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';
import { PATHS, watchForFile } from '../lib/fileUtils.js';
+import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { doneSentinelName, doneSentinelPath as resolveDoneSentinelPath, parseSentinelPayload } from '../lib/agentSentinel.js';
import { shouldAbandonForHostShutdown, HOST_SHUTDOWN_REASON } from '../lib/hostShutdown.js';
import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';
@@ -538,7 +539,10 @@ export async function spawnTuiAgent({
// state writes must batch"), and `analyzeAgentFailure` reads the file on
// failure so it gets the full PTY stream regardless of run length.
const rawFile = join(agentDir, 'raw.txt');
- const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : PATHS.root;
+ // CD no-worktree tasks get an isolated scratch cwd so native CLAUDE.md
+ // discovery cannot reach the PortOS repo tree (#4650). Everyone else keeps
+ // workspacePath, falling back to the repo root when it was omitted.
+ const cwd = resolveAgentCliCwd({ workspacePath, fallbackRoot: PATHS.root, task, agentId });
// The agent writes `.agent-done` in its workspace to signal completion (see
// the sentinel watcher below) and then stops — it does NOT run `/quit` (that
// is a UI command the agent can't invoke). The file watcher is the primary
@@ -547,7 +551,7 @@ export async function spawnTuiAgent({
// up front so both the watcher AND finish() can read it (see ingestDoneSentinel).
// Resolved from the shared helper, so this is byte-identical to the path the
// prompt told the agent to write (see resolveSentinelPath).
- const doneSentinelPath = resolveDoneSentinelPath(workspacePath, agentId);
+ const doneSentinelPath = resolveDoneSentinelPath(cwd, agentId);
const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
const commandName = tuiConfig.command.split('/').pop();
let finalized = false;
@@ -869,7 +873,7 @@ export async function spawnTuiAgent({
isTruthyMetaFn,
error: finalError || undefined,
completionReason: reason,
- workspacePath,
+ workspacePath: cwd,
prExpected: prClaimExpected,
// The run window the commit criterion is evaluated against (#3637).
startedAt: agentData?.startedAt ?? null,
@@ -1266,7 +1270,7 @@ export async function spawnTuiAgent({
agentId,
taskId: task.id,
model,
- workspacePath,
+ workspacePath: cwd,
prompt: (task.description || '').substring(0, 500)
});
}
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 285f763627..11bc373b38 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -31,11 +31,11 @@ import { emitLog } from './cosEvents.js';
import { updateTask, addTask } from './cos.js';
import { getAppById } from './apps.js';
import { isTruthyMeta, isFalsyMeta, getActiveAgentIds } from './agentState.js';
-import { PATHS } from '../lib/fileUtils.js';
+import { PATHS, ensureDir } from '../lib/fileUtils.js';
import * as git from './git.js';
import { detectConflicts } from './taskConflict.js';
import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch, isBranchCheckedOutElsewhereError } from './worktreeManager.js';
-import { resolveSpawnCwd } from '../lib/spawnCwd.js';
+import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';
@@ -144,6 +144,27 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,
* @returns {Promise<object>} discriminated outcome (see module doc)
*/
export async function prepareAgentWorkspace({ agentId, task }) {
+ // Creative Director treatment/plan/evaluate tasks are HTTP-PATCH deliverables
+ // and never asked for a worktree. Pin them to an isolated scratch cwd BEFORE
+ // the PortOS-root resolution / git-pull / conflict scan, so a CLI/TUI provider
+ // cannot natively discover the repo CLAUDE.md tree (#4650).
+ if (usesCreativeDirectorScratchCwd(task)) {
+ const workspacePath = creativeDirectorScratchCwd(agentId);
+ await ensureDir(workspacePath);
+ emitLog('info', `📂 Agent workspace: ${workspacePath} (creative-director scratch)`, {
+ taskId: task.id, workspace: workspacePath,
+ });
+ return {
+ outcome: 'ready',
+ workspacePath,
+ resolvedAppName: null,
+ worktreeInfo: null,
+ jiraTicket: null,
+ jiraBranchName: null,
+ explicitWorktree: false,
+ };
+ }
+
// Determine workspace path and resolve app name
const isReadOnly = isTruthyMeta(task.metadata?.readOnly);
let workspacePath = task.metadata?.app
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 496500f686..893dfc16ff 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -43,6 +43,13 @@ vi.mock('./agentPromptBuilder.js', () => ({
getAppDataForTask: vi.fn().mockResolvedValue(null),
createJiraTicketForTask: vi.fn(),
}));
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ };
+});
import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';
import { updateTask, getAgents } from './cos.js';
@@ -50,9 +57,47 @@ import { ensureLatest } from './git.js';
import { detectConflicts } from './taskConflict.js';
import { getAppWorkspace } from './agentPromptBuilder.js';
import { createWorktree, adoptWorktree, findAdoptableWorktreeForBranch } from './worktreeManager.js';
+import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
beforeEach(() => { vi.clearAllMocks(); });
+describe('prepareAgentWorkspace — Creative Director scratch cwd (#4650)', () => {
+ it('pins a CD no-worktree task to an isolated scratch dir and skips the git pull', async () => {
+ const task = {
+ id: 't-cd',
+ taskType: 'internal',
+ metadata: { creativeDirector: { projectId: 'p', kind: 'plan' }, useWorktree: false },
+ };
+ const r = await prepareAgentWorkspace({ agentId: 'agent-cd', task });
+ expect(r.outcome).toBe('ready');
+ expect(r.workspacePath).toBe(creativeDirectorScratchCwd('agent-cd'));
+ expect(r.workspacePath).not.toBe(PATHS.root);
+ expect(r.worktreeInfo).toBeNull();
+ expect(ensureDir).toHaveBeenCalledWith(r.workspacePath);
+ expect(ensureLatest).not.toHaveBeenCalled();
+ expect(createWorktree).not.toHaveBeenCalled();
+ expect(detectConflicts).not.toHaveBeenCalled();
+ });
+
+ it('leaves a CD task that explicitly asked for a worktree on the normal path', async () => {
+ ensureLatest.mockResolvedValue({ success: true, upToDate: true });
+ createWorktree.mockResolvedValue({
+ worktreePath: '/mock/worktrees/agent-cd-wt', branchName: 'cos/t-cd/agent-cd-wt', baseBranch: 'main',
+ });
+ const task = {
+ id: 't-cd-wt',
+ taskType: 'internal',
+ metadata: { creativeDirector: { projectId: 'p', kind: 'plan' }, useWorktree: true },
+ };
+ const r = await prepareAgentWorkspace({ agentId: 'agent-cd-wt', task });
+ expect(r.outcome).toBe('ready');
+ expect(r.workspacePath).toBe('/mock/worktrees/agent-cd-wt');
+ expect(ensureLatest).toHaveBeenCalled();
+ expect(createWorktree).toHaveBeenCalled();
+ });
+});
+
describe('prepareAgentWorkspace', () => {
it('read-only task: returns ready with the shared workspace and skips the git pull', async () => {
const task = { id: 't-ro', taskType: 'user', metadata: { readOnly: true } };