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: TUI agents with zero file changes now fail instead of succeeding (#2191)
[._.]/ Adam Eivyc955d51b0779
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6be0359478..edd945d247 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@- **Swarm claim-issue runs now write the completion sentinel so the task actually finishes.** In `/do:next --swarm` mode the orchestrator ships every issue via a PR and never touches the working tree, so it was skipping the `.agent-done` completion sentinel — leaving the CoS task hanging with no summary as if the run never ended. Phase C of the swarm directive now explicitly instructs the orchestrator to write the sentinel (with a run summary of the issues claimed, their PRs, and merge outcomes) after the serialized merges, while still skipping the per-agent `/simplify`/push steps. (`server/services/cosTaskGenerator.js`)- **[issue-2190] OpenCode Ollama providers now accept any --model flag.** The static `OPENCODE_CONFIG_CONTENT` lacked a models map, so OpenCode rejected every model with "not valid" and the agent sat idle. The config is now built dynamically at spawn time with the effective model declared, fixing the TUI eval path for local Ollama models.+- **[issue-2191] TUI agents with zero file changes are now marked failed instead of silently succeeding.** A TUI agent that idled out after showing working indicators but made no uncommitted file changes was previously finalized as `success: idle-complete` — deleting the worktree and any evidence of what happened. Now the idle-complete path checks `git status` in the worktree: if the tree is clean, it finalizes as `failure: idle-no-changes` with the TUI buffer tail as error context. Any uncommitted diff is also captured to `worktree-diff.txt` in the agent archive dir before cleanup, so post-mortems can see what (if anything) was left behind.- **Scheduled improvement tasks with no configured model now follow the active provider's default instead of a stale hardcoded one.** When a self-improvement or managed-app improvement task had no explicit model in its schedule config, the generator pinned a hardcoded `claude-opus-4-5-20251101` into the task — a model that had since dropped out of the `claude-code-tui` provider config, so the scheduler spawned `claude --model claude-opus-4-5-20251101` even after the provider default moved to Opus 4.8. Since a per-task model pin is honored above the provider default (it's passed straight through to the CLI), that stale literal overrode the configured default on every scheduled run. The generator no longer pins a literal: with no configured model it leaves the task's model unset, so model selection resolves the active provider's tier/default model at spawn time and always uses a model the provider actually lists. An explicit per-task or per-schedule model pin still wins as before. (`server/services/cosTaskGenerator.js`)- **An explicit per-task model pin is now always honored — no more silent, expensive downgrades.** When you set a specific model on a CoS task, PortOS validated it against the provider's `models` list and, on any mismatch, *silently fell back to the provider's default (heaviest) model*. Because `claude-code-tui` lists the dated id `claude-haiku-4-5-20251001` while `claude-code` lists the undated `claude-haiku-4-5`, picking "haiku" on the TUI provider quietly ran **Opus** instead. Explicit user-specified models are now passed through to the CLI even when they're not in the convenience list (the CLIs accept any valid id; a genuine typo surfaces as a provider error rather than a costly silent substitution). Auto-selected models still fall back to the tier default as before.- **Worktree tasks now default to opening a PR instead of auto-merging to your default branch.** A CoS task run in an isolated worktree with "Open PR" off merges its commits straight back to the main development branch on completion — fine for trusted agents, dangerous for unreviewed local-model work. Creating a worktree task now defaults "Open PR" on (in the UI, enabling Worktree checks it; via the API, a worktree user-task without an explicit `openPR` defaults to `true`). You can still turn it off per-task for a quick auto-merge, and internal automation (autopilot, self-improvement) keeps its existing auto-merge behavior so nothing starts silently waiting on a human to merge a PR.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 602320ee45..d68bc3d11e 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -17,6 +17,7 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';+import * as git from './git.js';import { shellQuote } from '../lib/shellQuote.js';import { resolveCliModel, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs } from '../lib/providerModels.js';import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';@@ -102,6 +103,45 @@ async function readFileTail(path, maxBytes) {await fh.close().catch(() => {});}}+/**+ * Check if a worktree has any uncommitted changes. Returns true when the+ * working tree is dirty (staged or unstaged changes exist). Used to gate+ * idle-complete success — an agent that idled out with zero file changes+ * should fail, not succeed.+ */+async function worktreeHasChanges(workspacePath) {+ if (!workspacePath || typeof workspacePath !== 'string') return false;+ const status = await git.getStatus(workspacePath).catch(() => null);+ return status && !status.clean;+}++/**+ * Capture the git diff (staged + unstaged) from a worktree and save it to the+ * agent archive dir. Called before worktree cleanup so post-mortems can see+ * what changes existed even if the worktree is deleted. Non-throwing — a+ * failure to capture shouldn't block finalize.+ *+ * @returns {string|null} The captured diff, or null if none/error.+ */+async function captureWorktreeDiff(workspacePath, agentDir) {+ if (!workspacePath || typeof workspacePath !== 'string') return null;+ if (!agentDir || typeof agentDir !== 'string') return null;+ const [staged, unstaged] = await Promise.all([+ git.getDiff(workspacePath, true).catch(() => ''),+ git.getDiff(workspacePath, false).catch(() => ''),+ ]);+ const combined = [+ staged ? `### STAGED CHANGES ###\n${staged}` : '',+ unstaged ? `### UNSTAGED CHANGES ###\n${unstaged}` : '',+ ].filter(Boolean).join('\n\n');+ if (!combined.trim()) return null;+ const diffFile = join(agentDir, 'worktree-diff.txt');+ await writeFile(diffFile, combined).catch((err) => {+ console.error(`❌ Failed to capture worktree diff for agent: ${err.message}`);+ });+ return combined;+}+// Debounce window for batching parsed output to disk + state. A chatty TUI can// emit hundreds of lines/sec; without batching, each line triggers a full// state load+save (see appendAgentOutput) and a small appendFile, which slows@@ -978,8 +1018,19 @@ export async function spawnTuiAgent({// completion on those providers would falsely fail). So: downgrade to// failure only when the provider DOES render the counter and we never saw// it advance.+ //+ // Issue #2191 extension: even when workActivity.active is true, the model+ // may have "worked" (made tool calls, printed output) without actually+ // writing any files — e.g. rambled, made invalid tool calls, or hit an+ // error. Check the worktree for evidence of actual changes: if the+ // worktree is clean (no git status changes), mark as failed so the+ // orchestrator doesn't treat a no-op as done. Capture the diff into the+ // agent archive dir before cleanup so post-mortems can see what (if+ // anything) was left behind.const noWorkButCounterExpected = !workActivity.active && rendersWorkCounter(commandName);if (noWorkButCounterExpected) {+ // Capture any uncommitted changes for post-mortem analysis+ captureWorktreeDiff(cwd, agentDir).catch(() => {});finish({success: false,exitCode: 1,@@ -989,8 +1040,32 @@ export async function spawnTuiAgent({emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });});} else {- finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {- emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });+ // Gate idle-complete success on evidence of work in the worktree.+ // An agent that shows activity counters but makes no file changes+ // (rambled, invalid tool calls, hit an error) should fail, not succeed.+ (async () => {+ const hasChanges = await worktreeHasChanges(cwd);+ // Capture any uncommitted changes for post-mortem analysis regardless+ // of outcome — the diff is useful even on success for debugging.+ await captureWorktreeDiff(cwd, agentDir).catch(() => {});+ if (!hasChanges) {+ finish({+ success: false,+ exitCode: 1,+ error: 'TUI agent idled out with zero uncommitted file changes — the model may have processed but produced no work.',+ reason: 'idle-no-changes',+ }).catch(err => {+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });+ });+ } else {+ finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(err => {+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });+ });+ }+ })().catch(err => {+ emitLog('error', `TUI agent ${agentId} idle-complete check failed: ${err.message}`, { agentId });+ // Fall back to success if the check itself failed (don't block on git)+ finish({ success: true, exitCode: 0, reason: 'idle-complete' }).catch(() => {});});}}diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 83de19ae40..dcde170ef5 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -69,6 +69,13 @@ vi.mock('./agentState.js', () => ({pausedAgents: new Map()}));+vi.mock('./git.js', () => ({+ // Default: worktree has changes so idle-complete succeeds. Tests that want+ // to exercise the idle-no-changes failure path override via mockResolvedValueOnce.+ getStatus: vi.fn().mockResolvedValue({ clean: false, files: [{ path: 'file.txt', status: 'M' }] }),+ getDiff: vi.fn().mockResolvedValue('diff content here'),+}));+vi.mock('fs', () => ({// Default: no .agent-done sentinel on disk. The completion-sentinel test// overrides this to true. Re-set in beforeEach so it can't leak between tests.@@ -154,6 +161,7 @@ import * as shellService from './shell.js';import * as agentLifecycle from './agentLifecycle.js';import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgents from './cosAgents.js';+import * as gitService from './git.js';import { activeAgents, userTerminatedAgents } from './agentState.js';describe('agent TUI spawning', () => {@@ -383,6 +391,11 @@ describe('spawnTuiAgent runtime', () => {// implementation, so re-set explicitly to prevent cross-test leakage.vi.mocked(existsSync).mockReturnValue(false);vi.mocked(readFile).mockResolvedValue('');++ // Reset git mock: default is worktree has changes (idle-complete succeeds).+ // Tests that want to exercise the idle-no-changes failure path override this.+ vi.mocked(gitService.getStatus).mockResolvedValue({ clean: false, files: [{ path: 'file.txt', status: 'M' }] });+ vi.mocked(gitService.getDiff).mockResolvedValue('diff content here');});afterEach(() => {@@ -500,6 +513,56 @@ describe('spawnTuiAgent runtime', () => {);});+ // ── 1a-ter. Idle-out with work activity but zero file changes → failure (#2191) ─+ // Issue #2191: a TUI agent that shows the working counter (workActivity.active+ // becomes true) but produces NO file changes in the worktree should fail, not+ // succeed. Examples: the model rambled, made invalid tool calls, hit an error+ // ("Model is not valid"), or ended at an interactive prompt with zero edits.+ // The fix gates idle-complete success on evidence of work in the worktree+ // (non-empty git status) in addition to the work-counter signal.+ it('idle-no-changes: finalizes failure when work counter advanced but worktree is clean (zero file changes)', async () => {+ // Override the default git mock to report a clean worktree (no changes, no diff).+ vi.mocked(gitService.getStatus).mockResolvedValue({ clean: true, files: [] });+ vi.mocked(gitService.getDiff).mockResolvedValue('');++ let resolveComplete;+ const completeDone = new Promise((r) => { resolveComplete = r; });+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });++ runSpawn();+ await flushMicrotasks();++ await capturedOnData(Buffer.from('Codex booting...\n'));+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(2000);+ await flushMicrotasks();++ // Advance past PASTE_TO_ENTER_FALLBACK_MS so submit fires.+ await vi.advanceTimersByTimeAsync(3600);+ await flushMicrotasks();++ // Feed PTY chunks that PROVE the model was working — the elapsed working+ // counter ADVANCING through two distinct values. This sets workActivity.active+ // to true, but the worktree is still clean (no file changes).+ await capturedOnData(Buffer.from('(1s · thinking with high effort)\n'));+ await vi.advanceTimersByTimeAsync(800);+ await capturedOnData(Buffer.from('(2s · thinking with high effort)\n'));++ // Advance past DEFAULT_TUI_MIN_RUNTIME_MS + idleTimeoutMs.+ await vi.advanceTimersByTimeAsync(21000);++ vi.useRealTimers();+ await completeDone;++ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-1',+ success: false,+ completionReason: 'idle-no-changes',+ })+ );+ });+// ── 1b. Command exited before the prompt → don't paste into the bare shell ───// The TUI command (claude/codex/…) runs as a CHILD of the persistent PTY// shell, so if it exits at startup the PTY stays open and onExit never fires.@@ -1045,7 +1108,10 @@ describe('agentTuiSpawning — idle reap decision (#2074)', () => {const MERGE_QUEUE_IDLE_TIMEOUT_MS = 900000;const REVIEW_LOOP_IDLE_TIMEOUT_MS = 900000;- // Faithful copy of the idleTimer body's finalize-selection logic.+ // Faithful copy of the SYNCHRONOUS part of the idleTimer body's finalize-+ // selection logic. The real code has an async worktree-changes check (#2191)+ // that may downgrade `idle-complete` to `idle-no-changes` — that's tested via+ // the full fake-timer harness above, not this pure function.function decideIdleReap({ idle, baseIdleTimeoutMs, mergeQueueActive, reviewLoopActive, workActive, rendersCounter }) {const effectiveIdleTimeoutMs = mergeQueueActive? Math.max(baseIdleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)