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

feat: lean isolated mode + system-prompt split for Ollama-backed Claude agents

Adam Eivydcfa65c71221
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index af3a25f1bd..b9cfbb55a7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## CoS Agents
+
+- **Local-model Claude agents now launch in a lean, isolated mode.** CoS agents on the Ollama-backed Claude providers (`claude-ollama`, `claude-ollama-tui`) previously inherited your full personal Claude Code environment — hooks, plugins, MCP servers, global CLAUDE.md — which reliably derailed small local models (a live eval showed qwen3.6:35b answering a session-start hook instead of its task). These sessions now spawn with `--bare --strict-mcp-config` (no hooks, no plugins, no MCP tool schemas, no CLAUDE.md auto-discovery), mirror their Ollama auth token into `ANTHROPIC_API_KEY` (bare mode's only accepted auth source), and get the same plain-`git`/`gh` completion workflow OpenCode agents use instead of slashdo commands bare mode can't load. The PortOS operating contract (worktree coordinates, completion sentinel protocol) also moves out of the pasted prompt into a real system prompt via `--append-system-prompt-file` — saved beside the agent's `prompt.txt` as `system-prompt.md` — so weak models weight it as instructions rather than conversation. Standard Claude/Codex/OpenCode providers are unchanged.
+
## Creative Writing Quality Engine
- **[issue-2165] Editorial review now catches recognizable "AI slop" writing tells automatically.** Four new deterministic editorial checks join the existing 68: a tiered banned-word scan (hard-bans like "delve"/"myriad"/"utilize"; suspicious words like "robust"/"seamless" only flagged when 3+ cluster in one paragraph), fiction-specific AI-tell idioms ("a sense of dread", "couldn't help but", "eyes widened", "a wave of relief washed over him"), rhetorical structural tics ("not just X, but Y", runs of "did not [verb]", punchy three-sentence-in-a-row bursts like "Fast. Precise. Deadly."), and structural burstiness (em-dash overuse, essay-style transition-word openers, mechanically uniform paragraph lengths). Each surfaces as an editorial finding with the exact offending quote, same as the existing prose checks — configurable thresholds and house-style allowlists included.
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 3284410037..bfd5de65f2 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -203,6 +203,80 @@ export function hasModelFlag(args) {
return false;
}
+/**
+ * True when a provider command points at the Claude Code binary — the bare
+ * `claude` on PATH, an absolute/relative path to it, or an optional Windows
+ * `.exe` suffix (same matching rules as `isOpencodeCommand`). An empty/null
+ * command also counts as Claude: `buildCliSpawnConfig`'s default branch and
+ * the TUI `inferTuiCommand` fallback both resolve a blank command to `claude`.
+ * @param {string|null|undefined} command
+ * @returns {boolean}
+ */
+export function isClaudeCommand(command) {
+ if (command == null || command === '') return true;
+ if (typeof command !== 'string') return false;
+ const base = command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');
+ return base === 'claude';
+}
+
+/**
+ * True for an Ollama-backed provider that launches the Claude Code binary
+ * (`claude-ollama` / `claude-ollama-tui`). These sessions run a small local
+ * model that drowns in Claude Code's full personal environment — hooks,
+ * plugins, MCP servers, global CLAUDE.md — so the spawners put them in lean
+ * mode (see `applyLeanClaudeArgs`). Keyed on the `ollamaBacked` marker + the
+ * launch command, not provider ids, so renamed/custom local providers get the
+ * same treatment.
+ * @param {{command?:string, ollamaBacked?:boolean}|null|undefined} provider
+ * @param {string} [command] - resolved launch command when it differs from
+ * `provider.command` (the TUI path may infer it from the provider id)
+ * @returns {boolean}
+ */
+export function isOllamaClaudeProvider(provider, command = provider?.command) {
+ return provider?.ollamaBacked === true && isClaudeCommand(command);
+}
+
+/**
+ * Lean-context flags for local-model Claude Code sessions:
+ * - `--bare` — skip hooks, plugin sync, auto-memory, and CLAUDE.md
+ * auto-discovery (the user's personal environment derails small models).
+ * - `--strict-mcp-config` — with no `--mcp-config` given, load zero MCP
+ * servers (their tool schemas alone can blow a small Ollama context).
+ */
+export const LEAN_CLAUDE_ARGS = ['--bare', '--strict-mcp-config'];
+
+/**
+ * Append the lean-context flags for Ollama-backed Claude providers. No-op for
+ * every other provider, and idempotent when the user already baked either
+ * flag into `provider.args`.
+ * @param {{command?:string, ollamaBacked?:boolean, args?:string[]}} provider
+ * @param {string[]} args - argv built so far
+ * @param {string} [command] - resolved launch command (see isOllamaClaudeProvider)
+ * @returns {string[]}
+ */
+export function applyLeanClaudeArgs(provider, args, command = provider?.command) {
+ if (!isOllamaClaudeProvider(provider, command)) return args;
+ return [...args, ...LEAN_CLAUDE_ARGS.filter(flag => !args.includes(flag))];
+}
+
+/**
+ * `--bare` reads Anthropic auth strictly from `ANTHROPIC_API_KEY` (or an
+ * apiKeyHelper) — OAuth and keychain are never consulted. The Ollama-backed
+ * Claude providers authenticate with `ANTHROPIC_AUTH_TOKEN=ollama` instead,
+ * so mirror that value into `ANTHROPIC_API_KEY` (Ollama ignores the key
+ * contents) unless the provider already sets one. Spread the result BEFORE
+ * `provider.envVars` so an explicit user-configured key always wins.
+ * @param {{command?:string, ollamaBacked?:boolean, envVars?:Object}} provider
+ * @param {string} [command]
+ * @returns {Object} `{ ANTHROPIC_API_KEY }` or `{}`
+ */
+export function leanClaudeAuthEnv(provider, command = provider?.command) {
+ if (!isOllamaClaudeProvider(provider, command)) return {};
+ const envVars = provider?.envVars || {};
+ if (envVars.ANTHROPIC_API_KEY) return {};
+ return { ANTHROPIC_API_KEY: envVars.ANTHROPIC_AUTH_TOKEN || 'ollama' };
+}
+
/**
* Extract the pinned model id from provider.args when a model flag is baked
* in. Supports separated form (`--model X` / `-m X`) and joined form
diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.js
index 453fd70a11..01508a981f 100644
--- a/server/lib/providerModels.test.js
+++ b/server/lib/providerModels.test.js
@@ -12,7 +12,12 @@ import {
toBedrockModelId,
resolveBedrockCliModel,
prefixOpencodeModel,
- isOpencodeCommand
+ isOpencodeCommand,
+ isClaudeCommand,
+ isOllamaClaudeProvider,
+ applyLeanClaudeArgs,
+ leanClaudeAuthEnv,
+ LEAN_CLAUDE_ARGS
} from './providerModels.js';
describe('providerModels', () => {
@@ -355,4 +360,76 @@ describe('providerModels', () => {
spy.mockRestore();
});
});
+
+ describe('isClaudeCommand', () => {
+ it('matches bare, pathed, and Windows forms of the claude binary', () => {
+ expect(isClaudeCommand('claude')).toBe(true);
+ expect(isClaudeCommand('/opt/homebrew/bin/claude')).toBe(true);
+ expect(isClaudeCommand('C:\\tools\\Claude.EXE')).toBe(true);
+ });
+
+ it('treats an empty/null command as claude (the spawners default to it)', () => {
+ expect(isClaudeCommand('')).toBe(true);
+ expect(isClaudeCommand(null)).toBe(true);
+ expect(isClaudeCommand(undefined)).toBe(true);
+ });
+
+ it('rejects other binaries and non-strings', () => {
+ expect(isClaudeCommand('opencode')).toBe(false);
+ expect(isClaudeCommand('codex')).toBe(false);
+ expect(isClaudeCommand('/usr/bin/claudette')).toBe(false);
+ expect(isClaudeCommand(42)).toBe(false);
+ });
+ });
+
+ describe('isOllamaClaudeProvider', () => {
+ it('requires BOTH the ollamaBacked marker and a claude command', () => {
+ expect(isOllamaClaudeProvider({ ollamaBacked: true, command: 'claude' })).toBe(true);
+ expect(isOllamaClaudeProvider({ ollamaBacked: true, command: 'opencode' })).toBe(false);
+ expect(isOllamaClaudeProvider({ command: 'claude' })).toBe(false);
+ expect(isOllamaClaudeProvider(null)).toBe(false);
+ });
+
+ it('honors an explicitly resolved command over provider.command', () => {
+ expect(isOllamaClaudeProvider({ ollamaBacked: true, command: '' }, 'claude')).toBe(true);
+ expect(isOllamaClaudeProvider({ ollamaBacked: true, command: '' }, 'codex')).toBe(false);
+ });
+ });
+
+ describe('applyLeanClaudeArgs', () => {
+ const ollamaClaude = { ollamaBacked: true, command: 'claude' };
+
+ it('appends --bare and --strict-mcp-config for Ollama-backed claude providers', () => {
+ expect(applyLeanClaudeArgs(ollamaClaude, ['--dangerously-skip-permissions']))
+ .toEqual(['--dangerously-skip-permissions', ...LEAN_CLAUDE_ARGS]);
+ });
+
+ it('is idempotent against user-baked lean flags', () => {
+ expect(applyLeanClaudeArgs(ollamaClaude, ['--bare'])).toEqual(['--bare', '--strict-mcp-config']);
+ expect(applyLeanClaudeArgs(ollamaClaude, [...LEAN_CLAUDE_ARGS])).toEqual([...LEAN_CLAUDE_ARGS]);
+ });
+
+ it('is a no-op for non-Ollama or non-claude providers', () => {
+ const args = ['--dangerously-skip-permissions'];
+ expect(applyLeanClaudeArgs({ command: 'claude' }, args)).toBe(args);
+ expect(applyLeanClaudeArgs({ ollamaBacked: true, command: 'opencode' }, args)).toBe(args);
+ });
+ });
+
+ describe('leanClaudeAuthEnv', () => {
+ it('mirrors ANTHROPIC_AUTH_TOKEN into ANTHROPIC_API_KEY for bare mode', () => {
+ expect(leanClaudeAuthEnv({ ollamaBacked: true, command: 'claude', envVars: { ANTHROPIC_AUTH_TOKEN: 'ollama' } }))
+ .toEqual({ ANTHROPIC_API_KEY: 'ollama' });
+ });
+
+ it('falls back to the literal "ollama" when no auth token is configured', () => {
+ expect(leanClaudeAuthEnv({ ollamaBacked: true, command: 'claude' }))
+ .toEqual({ ANTHROPIC_API_KEY: 'ollama' });
+ });
+
+ it('yields nothing when the provider already sets ANTHROPIC_API_KEY or is not lean', () => {
+ expect(leanClaudeAuthEnv({ ollamaBacked: true, command: 'claude', envVars: { ANTHROPIC_API_KEY: 'real' } })).toEqual({});
+ expect(leanClaudeAuthEnv({ command: 'claude' })).toEqual({});
+ });
+ });
});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 17e2545936..15f61fb0f2 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -26,7 +26,7 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
-import { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand } from '../lib/providerModels.js';
+import { resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, leanClaudeAuthEnv } from '../lib/providerModels.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
const AGENTS_DIR = PATHS.cosAgents;
@@ -241,7 +241,7 @@ export function createStreamJsonParser() {
* merge) — without it, a settings-only Bedrock box would map against an env
* missing the flag and still emit a bare, Bedrock-invalid `--model`.
*/
-export function buildCliSpawnConfig(provider, model, settingsEnv = {}) {
+export function buildCliSpawnConfig(provider, model, settingsEnv = {}, { systemPromptFile = null } = {}) {
const providerId = provider?.id || 'claude-code';
const effectiveModel = providerId === 'codex' && model === 'codex-configured-default' ? null : model;
@@ -301,15 +301,21 @@ export function buildCliSpawnConfig(provider, model, settingsEnv = {}) {
};
}
- // Default: Claude Code CLI
- const args = [
+ // Default: Claude Code CLI. applyLeanClaudeArgs adds `--bare
+ // --strict-mcp-config` for Ollama-backed claude sessions (no-op otherwise,
+ // idempotent against user-baked flags); the system-prompt contract file
+ // rides via --append-system-prompt-file.
+ const args = applyLeanClaudeArgs(provider, [
'--dangerously-skip-permissions', // Unrestricted mode
'--print', // Print output and exit
'--output-format', 'stream-json', // Stream JSON events for live output
'--verbose', // Required for stream-json
'--include-partial-messages', // Include incremental text deltas
...(provider?.args || []), // User-configured provider args
- ];
+ ], provider?.command || 'claude');
+ if (systemPromptFile) {
+ args.push('--append-system-prompt-file', systemPromptFile);
+ }
if (effectiveModel) {
// Bedrock box: map a bare Claude id to its region-prefixed Bedrock form
// just-in-time (no-op off Bedrock / for already-prefixed or non-Claude ids).
@@ -418,7 +424,10 @@ export async function spawnDirectly({
// The pm2 shim must be prepended onto the FINAL PATH (after any
// provider.envVars override) so a `--dangerously-skip-permissions` agent
// can't `pm2 kill` the shared daemon.
- env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })()
+ // leanClaudeAuthEnv: `--bare` reads auth strictly from ANTHROPIC_API_KEY, so
+ // Ollama-backed claude sessions get one mirrored from their auth token
+ // (before provider.envVars so an explicit user-configured key wins).
+ env: (() => { const e = { ...process.env, ...claudeSettingsEnv, ...leanClaudeAuthEnv(provider), ...provider.envVars }; delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })()
});
registerSpawnedAgent(claudeProcess.pid, {
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index aa22bac495..9400e38117 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -215,6 +215,29 @@ describe('buildCliSpawnConfig', () => {
expect(config.args).toEqual(['run', '-m', 'ollama/custom']);
});
+ it('adds lean-mode flags and the system-prompt file for an Ollama-backed claude CLI', () => {
+ const config = buildCliSpawnConfig(
+ { id: 'claude-ollama', command: 'claude', ollamaBacked: true },
+ 'qwen3.6:35b',
+ {},
+ { systemPromptFile: '/data/cos/agents/agent-1/system-prompt.md' },
+ );
+
+ expect(config.args).toContain('--bare');
+ expect(config.args).toContain('--strict-mcp-config');
+ const idx = config.args.indexOf('--append-system-prompt-file');
+ expect(config.args[idx + 1]).toBe('/data/cos/agents/agent-1/system-prompt.md');
+ // Lean flags must not disturb the model injection.
+ expect(config.args[config.args.indexOf('--model') + 1]).toBe('qwen3.6:35b');
+ });
+
+ it('does NOT add lean flags to the standard claude CLI provider', () => {
+ const config = buildCliSpawnConfig({ id: 'claude-code', command: 'claude' }, 'claude-opus-4-8');
+ expect(config.args).not.toContain('--bare');
+ expect(config.args).not.toContain('--strict-mcp-config');
+ expect(config.args).not.toContain('--append-system-prompt-file');
+ });
+
describe('Bedrock model-id mapping', () => {
// buildCliSpawnConfig reads process.env for the Bedrock signal; isolate the
// tests from whatever the host/CI environment happens to set.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index e814f7a0b2..0a60163185 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -22,6 +22,7 @@ import { determineLane, acquire, release } from './executionLanes.js';
import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';
import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';
+import { isOllamaClaudeProvider, isClaudeCommand, leanClaudeAuthEnv } from '../lib/providerModels.js';
import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
@@ -331,13 +332,28 @@ export async function spawnAgentForTask(task) {
const isTui = isTuiProvider(provider);
+ // Lean mode: an Ollama-backed Claude session gets `--bare --strict-mcp-config`
+ // (see applyLeanClaudeArgs) so the user's personal environment — hooks,
+ // plugins, MCP servers, global CLAUDE.md — doesn't drown the small local
+ // model. Lean sessions also split the prompt: the PortOS operating contract
+ // rides in a system-prompt file (`--append-system-prompt-file`) while the
+ // pasted/stdin prompt carries only the task itself. Split stays gated on
+ // lean mode until `--append-system-prompt-file` is validated on the
+ // standard interactive claude providers.
+ const leanMode = isOllamaClaudeProvider(provider);
+ const splitSystemPrompt = leanMode && isClaudeCommand(provider.command);
+
// Build the agent prompt. `provider.type` drives the light-vs-full split
// inside buildAgentPrompt — see its doc comment.
- const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {
+ const promptResult = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {
providerType: provider.type,
providerId: provider.id,
- providerCommand: provider.command
+ providerCommand: provider.command,
+ leanMode,
+ split: splitSystemPrompt
});
+ const prompt = typeof promptResult === 'string' ? promptResult : promptResult.userPrompt;
+ const systemPrompt = typeof promptResult === 'string' ? null : promptResult.systemPrompt;
// Create agent directory
const agentDir = join(AGENTS_DIR, agentId);
@@ -347,6 +363,11 @@ export async function spawnAgentForTask(task) {
// Save prompt to file
await writeFile(join(agentDir, 'prompt.txt'), prompt);
+ let systemPromptFile = null;
+ if (systemPrompt) {
+ systemPromptFile = join(agentDir, 'system-prompt.md');
+ await writeFile(systemPromptFile, systemPrompt);
+ }
// Create run entry for usage tracking
const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);
@@ -444,8 +465,8 @@ export async function spawnAgentForTask(task) {
// the spawn helper's own getClaudeSettingsEnv() call is effectively free.
const cliSettingsEnv = isClaudeCliProvider(provider) ? await getClaudeSettingsEnv() : {};
const cliConfig = isTui
- ? buildTuiSpawnConfig(provider, selectedModel)
- : buildCliSpawnConfig(provider, selectedModel, cliSettingsEnv);
+ ? buildTuiSpawnConfig(provider, selectedModel, { systemPromptFile })
+ : buildCliSpawnConfig(provider, selectedModel, cliSettingsEnv, { systemPromptFile });
emitLog('success', `Spawning agent for task ${task.id}`, {
agentId,
@@ -608,7 +629,10 @@ export async function spawnViaRunner(agentId, task, opts) {
prompt,
workspacePath,
model,
- envVars: { ...claudeSettingsEnv, ...provider.envVars },
+ // leanClaudeAuthEnv: `--bare` (lean-mode Ollama claude) reads auth strictly
+ // from ANTHROPIC_API_KEY — mirror the auth token in before provider.envVars
+ // so an explicit user-configured key wins.
+ envVars: { ...claudeSettingsEnv, ...leanClaudeAuthEnv(provider), ...provider.envVars },
cliCommand: cliConfig.command,
cliArgs: cliConfig.args
});
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index fc18a826e7..102a6df635 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -457,6 +457,13 @@ export function buildCompletionGuidelineBullet({
* @param {string} [options.providerCommand] - Provider launch command (e.g. `'opencode'`).
* Used to detect a slashdo-free TUI (OpenCode): such a TUI can't run `/do:pr` / `/do:push`,
* so its completion workflow falls back to plain `git`/`gh` commands.
+ * @param {boolean} [options.leanMode] - Ollama-backed Claude session launched with
+ * `--bare` (see `applyLeanClaudeArgs`): the completion workflow drops slashdo
+ * commands (bare mode skips command discovery) in favor of plain `git`/`gh`.
+ * @param {boolean} [options.split] - Light path only: return
+ * `{ userPrompt, systemPrompt }` (see `buildLightContextPromptParts`) instead
+ * of a single string, for providers spawned with `--append-system-prompt-file`.
+ * Ignored on the full/api path, which always returns a string.
*/
export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo = null, isTruthyMetaFn = (v) => v === true || v === 'true', options = {}) {
const providerType = options.providerType || PROVIDER_TYPES.API;
@@ -465,7 +472,10 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
const isTui = providerType === PROVIDER_TYPES.TUI;
if (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {
- return buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui, providerId, providerCommand });
+ const lightOptions = { isTui, providerId, providerCommand, leanMode: options.leanMode === true };
+ return options.split === true
+ ? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions)
+ : buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, lightOptions);
}
// Full path: API providers don't read CLAUDE.md natively, so always include it.
@@ -747,7 +757,33 @@ Begin working on the task now.`;
* Falls back gracefully when worktree/jira/pipeline metadata is absent — only
* the present sections render.
*/
-export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null } = {}) {
+export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options = {}) {
+ const { taskSections, contractSections } = buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options);
+ return [...taskSections, ...contractSections, BEGIN_WORKING_LINE].join('\n\n') + '\n';
+}
+
+/**
+ * Split variant of `buildLightContextPrompt` for providers with a real system
+ * channel (Claude Code's `--append-system-prompt-file`): the task-specific
+ * content (description, context, screenshots, attachments) becomes the user
+ * prompt, and the PortOS operating contract (worktree/pipeline/JIRA
+ * coordinates + completion workflow) rides in the system prompt where models
+ * weight it as instructions rather than conversation. Section content is
+ * byte-identical to the combined prompt — only the placement differs.
+ *
+ * @returns {{ userPrompt: string, systemPrompt: string|null }}
+ */
+export function buildLightContextPromptParts(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options = {}) {
+ const { taskSections, contractSections } = buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, options);
+ return {
+ userPrompt: [...taskSections, BEGIN_WORKING_LINE].join('\n\n') + '\n',
+ systemPrompt: contractSections.length ? contractSections.join('\n\n') + '\n' : null,
+ };
+}
+
+const BEGIN_WORKING_LINE = 'Begin working on the task now.';
+
+function buildLightContextSections(task, workspaceDir, worktreeInfo, isTruthyMetaFn, { isTui = true, providerId = null, providerCommand = null, leanMode = false } = {}) {
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);
const simplifyEnabled = isTruthyMetaFn(task.metadata?.simplify);
@@ -764,13 +800,21 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut
// Other CLI providers (codex, antigravity) can't — they get the legacy
// commit-only block where PortOS handles push+PR on exit.
const hasSlashdo = !isTui && (providerId === 'claude-code' || providerId === 'claude-code-bedrock');
- // A TUI that does NOT load Claude Code slash commands (OpenCode) can't run
- // `/do:pr` / `/do:push`, so its completion workflow uses plain git/gh instead.
- // Keyed on the launch command (not the id) so a path-configured or renamed
- // OpenCode provider is still recognised — mirrors the arg-builder gate.
- const tuiSlashdoFree = isTui && isOpencodeCommand(providerCommand);
-
- const sections = [];
+ // A TUI that does NOT load Claude Code slash commands can't run `/do:pr` /
+ // `/do:push`, so its completion workflow uses plain git/gh instead. Two ways
+ // to land here: an OpenCode TUI (keyed on the launch command, not the id, so
+ // a path-configured or renamed OpenCode provider is still recognised —
+ // mirrors the arg-builder gate), or a lean-mode Claude session (`--bare`
+ // skips project command discovery, and the small local models lean mode
+ // targets fumble multi-step slashdo flows anyway).
+ const tuiSlashdoFree = isTui && (isOpencodeCommand(providerCommand) || leanMode);
+
+ const taskSections = [];
+ const contractSections = [];
+ // Alias preserving the original single-list flow below: task-block pushes go
+ // to `taskSections`, then `sections` is repointed at `contractSections` for
+ // the operating-contract blocks.
+ let sections = taskSections;
// --- Task block --------------------------------------------------------
// cwd is set by the spawner and the agent knows its own id from the
@@ -790,6 +834,11 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut
if (taskBlock.screenshots) sections.push(taskBlock.screenshots);
if (taskBlock.attachments) sections.push(taskBlock.attachments);
+ // Everything below is the PortOS operating contract (not task content) —
+ // route it to `contractSections` so the split path can lift it into the
+ // system prompt.
+ sections = contractSections;
+
// --- Worktree ----------------------------------------------------------
if (worktreeInfo) {
sections.push([
@@ -844,8 +893,7 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut
sections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo, simplifyEnabled, reviewers: lightReviewers, reviewStopMode: lightReviewStopMode, reviewerApplies: lightReviewerApplies }));
}
- sections.push('Begin working on the task now.');
- return sections.join('\n\n') + '\n';
+ return { taskSections, contractSections };
}
/**
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index f9eed4bfbf..228acb9a44 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -602,6 +602,54 @@ describe('buildAgentPrompt — provider type routing', () => {
expect(prompt).toMatch(/^## Completion$/m);
});
+ describe('split system/user prompt (lean Ollama claude)', () => {
+ const wt = { branchName: 'cos/t/a', worktreePath: '/tmp/wt', baseBranch: 'main' };
+ const splitTask = () => makeTask({ metadata: { context: 'Some context', openPR: false } });
+
+ it('returns { userPrompt, systemPrompt } with the task in user and the contract in system', async () => {
+ const parts = await buildAgentPrompt(
+ splitTask(), {}, '/r', wt, isTruthyMeta,
+ { providerType: 'tui', providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true, split: true });
+ expect(parts.userPrompt).toMatch(/Add a button to the dashboard/);
+ expect(parts.userPrompt).toMatch(/Some context/);
+ expect(parts.userPrompt).toMatch(/Begin working on the task now\./);
+ expect(parts.userPrompt).not.toMatch(/## Completion Workflow/);
+ expect(parts.systemPrompt).toMatch(/## Git Worktree/);
+ expect(parts.systemPrompt).toMatch(/## Completion Workflow/);
+ expect(parts.systemPrompt).not.toMatch(/Add a button to the dashboard/);
+ });
+
+ it('split parts carry exactly the combined prompt sections (no drift)', async () => {
+ const opts = { providerType: 'tui', providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true };
+ const combined = await buildAgentPrompt(splitTask(), {}, '/r', wt, isTruthyMeta, opts);
+ const parts = await buildAgentPrompt(splitTask(), {}, '/r', wt, isTruthyMeta, { ...opts, split: true });
+ // Combined = task sections + contract sections + Begin line; the split
+ // moves the contract out and keeps the Begin line with the user prompt.
+ const reassembled = parts.userPrompt.replace(
+ /\n\nBegin working on the task now\.\n$/,
+ '\n\n' + parts.systemPrompt.replace(/\n$/, '') + '\n\nBegin working on the task now.\n'
+ );
+ expect(reassembled).toBe(combined);
+ });
+
+ it('leanMode routes a claude TUI to the slashdo-free completion workflow', async () => {
+ const prompt = await buildAgentPrompt(
+ splitTask(), {}, '/r', wt, isTruthyMeta,
+ { providerType: 'tui', providerId: 'claude-ollama-tui', providerCommand: 'claude', leanMode: true });
+ expect(prompt).not.toMatch(/`\/do:push`/);
+ expect(prompt).not.toMatch(/`\/do:pr`/);
+ // Same sentinel handshake as the OpenCode slashdo-free path.
+ expect(prompt).toMatch(/\.agent-done/);
+ });
+
+ it('without leanMode a claude TUI still gets the slashdo workflow', async () => {
+ const prompt = await buildAgentPrompt(
+ splitTask(), {}, '/r', wt, isTruthyMeta,
+ { providerType: 'tui', providerId: 'claude-code-tui', providerCommand: 'claude' });
+ expect(prompt).toMatch(/\/do:push/);
+ });
+ });
+
it('full-context (api) review-loop follow-up emits merge command WITHOUT --auto and includes MERGED verification', async () => {
// Regression for Copilot feedback on PR #260: the merge-without-auto +
// MERGED-state verification instructions live in BOTH the light and full
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 17736d3ede..02f77792f7 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -18,7 +18,7 @@ import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { shellQuote } from '../lib/shellQuote.js';
-import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand } from '../lib/providerModels.js';
+import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, leanClaudeAuthEnv } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { isAntigravityCommand } from '../lib/antigravity.js';
@@ -141,10 +141,13 @@ export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onDat
// claude's input-readiness only after this so the readiness probe's own
// shell activity can't prematurely open the paste gate.
onInitialCommandSent,
+ // leanClaudeAuthEnv: `--bare` reads auth strictly from ANTHROPIC_API_KEY,
+ // so Ollama-backed claude sessions get one mirrored from their auth token
+ // (spread FIRST so explicit provider envVars win).
// agentGuardEnv() prepends the pm2 shim to the agent session's PATH (and
// points it at the real pm2). Spread LAST so it wins over any provider PATH.
// Only AI agent sessions get this — the user's own Shell page does not.
- env: { ...(provider.envVars || {}), ...agentGuardEnv() },
+ env: { ...leanClaudeAuthEnv(provider), ...(provider.envVars || {}), ...agentGuardEnv() },
onData,
onExit,
});
@@ -197,10 +200,17 @@ function appendModelArgs(args, model, command, provider) {
return [...args, '--model', injectedModel];
}
-export function buildTuiSpawnConfig(provider, model) {
+export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null } = {}) {
const command = provider?.command || inferTuiCommand(provider?.id);
const baseArgs = applyCommandDefaults(command, [...(provider?.args || [])]);
- const args = appendModelArgs(baseArgs, model, command, provider);
+ let args = appendModelArgs(baseArgs, model, command, provider);
+ // Lean mode for Ollama-backed claude sessions (no-op otherwise) — must come
+ // before the system-prompt flag so `--bare` is present when the contract
+ // file rides along.
+ args = applyLeanClaudeArgs(provider, args, command);
+ if (systemPromptFile && isClaudeCommand(command)) {
+ args = [...args, '--append-system-prompt-file', systemPromptFile];
+ }
return {
command,
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 1f6b23d728..83de19ae40 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -97,7 +97,11 @@ tryReadFile: vi.fn().mockResolvedValue(null),
PATHS: { root: '/tmp/portos-root' }
}));
-vi.mock('../lib/providerModels.js', () => ({
+vi.mock('../lib/providerModels.js', async (importOriginal) => ({
+ // Pull the real module first so pure helpers added later (isClaudeCommand,
+ // applyLeanClaudeArgs, leanClaudeAuthEnv, …) don't silently vanish from the
+ // mock — only the fns below are stubbed/spied.
+ ...(await importOriginal()),
// Mirror the real behaviour: pass through the model string, return null for
// the codex-configured-default sentinel or null/undefined input.
resolveCliModel: vi.fn((m) => (m === 'codex-configured-default' || !m) ? null : m),
@@ -255,6 +259,34 @@ describe('agent TUI spawning', () => {
expect(config.args).toEqual(['--dangerously-bypass-approvals-and-sandbox']);
expect(config.commandLine).toBe('codex --dangerously-bypass-approvals-and-sandbox');
});
+
+ it('adds lean-mode flags and the system-prompt file for an Ollama-backed claude TUI', () => {
+ const config = buildTuiSpawnConfig({
+ id: 'claude-ollama-tui', type: 'tui', command: 'claude', ollamaBacked: true,
+ args: ['--dangerously-skip-permissions'],
+ }, 'qwen3.6:35b', { systemPromptFile: '/data/cos/agents/agent-1/system-prompt.md' });
+ expect(config.args).toEqual([
+ '--dangerously-skip-permissions',
+ '--model', 'qwen3.6:35b',
+ '--bare', '--strict-mcp-config',
+ '--append-system-prompt-file', '/data/cos/agents/agent-1/system-prompt.md',
+ ]);
+ });
+
+ it('does NOT add lean flags to the standard claude TUI, and skips the system-prompt flag for non-claude commands', () => {
+ const standard = buildTuiSpawnConfig({
+ id: 'claude-code-tui', type: 'tui', command: 'claude', args: ['--dangerously-skip-permissions'],
+ }, 'claude-opus-4-8', { systemPromptFile: '/tmp/sys.md' });
+ expect(standard.args).not.toContain('--bare');
+ // Claude command still honors an explicitly provided system-prompt file.
+ expect(standard.args).toContain('--append-system-prompt-file');
+
+ const opencode = buildTuiSpawnConfig({
+ id: 'opencode-ollama-tui', type: 'tui', command: 'opencode', args: [], ollamaBacked: true,
+ }, 'qwen3.6:35b', { systemPromptFile: '/tmp/sys.md' });
+ expect(opencode.args).not.toContain('--append-system-prompt-file');
+ expect(opencode.args).not.toContain('--bare');
+ });
});
// ─── spawnTuiAgent runtime tests ─────────────────────────────────────────────