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

Stop reporting designed skips, holds and fallbacks as stderr faults (#12850)

[._.]/ Adam Eivy518e5edc382e
diff --git a/server/logLevelConventions.test.js b/server/logLevelConventions.test.js
index 32aacaf480..6a85c5f41f 100644
--- a/server/logLevelConventions.test.js
+++ b/server/logLevelConventions.test.js
@@ -413,10 +413,10 @@ describe('the failure-log recognizer', () => {
expect(findMislabeledEmitLogs(`emitLog('info', 'started', {}, '${NO_ENTRY}');`)).toEqual([]);
});
- it('would flag a restored quiet emitLog in cosTaskGenerator.js', () => {
- const src = readFileSync(join(SERVER_ROOT, 'services/cosTaskGenerator.js'), 'utf8');
+ it('would flag a restored quiet emitLog in agentCompletionCleanup.js', () => {
+ const src = readFileSync(join(SERVER_ROOT, 'services/agentCompletionCleanup.js'), 'utf8');
expect(findMislabeledEmitLogs(src)).toEqual([]);
- const quiet = "emitLog('warn', `" + NO_ENTRY + ' Skipping install-wide';
+ const quiet = "emitLog('warn', `" + NO_ENTRY + ' Pipeline';
const regressed = src.replace(quiet, quiet.replace("'warn'", "'info'"));
expect(regressed).not.toBe(src);
expect(findMislabeledEmitLogs(regressed)).toHaveLength(1);
diff --git a/server/services/agentChurn.js b/server/services/agentChurn.js
index 8441253c24..4d0767d32c 100644
--- a/server/services/agentChurn.js
+++ b/server/services/agentChurn.js
@@ -139,10 +139,15 @@ export async function observeAgentChurn(agent, task, {
const analysisType = scheduledTypeOf(task);
const appId = appIdOf(task);
- console.warn(`⚠️ CoS churn: ${taskType} ${churn.reason} (${churn.windowCompleted} runs in ${formatWindow(churn.windowMs)})`);
+ // A coordinator looping fast enough to be parked is a workflow fault; a burst
+ // of quick user tasks is just a busy hour and nothing acts on it.
+ const looping = NON_COMMITTING_COORDINATOR_TASK_TYPES.has(analysisType);
+ const summary = `CoS churn: ${taskType} ${churn.reason} (${churn.windowCompleted} runs in ${formatWindow(churn.windowMs)})`;
+ if (looping) console.warn(`⚠️ ${summary}`);
+ else console.log(`🔁 ${summary}`);
let parked = false;
- if (NON_COMMITTING_COORDINATOR_TASK_TYPES.has(analysisType)) {
+ if (looping) {
const parkFn = park || (async (...args) => {
const { parkPerpetual } = await import('./taskSchedule.js');
return parkPerpetual(...args);
diff --git a/server/services/agentChurn.test.js b/server/services/agentChurn.test.js
index 49373b1bb1..d17001e86f 100644
--- a/server/services/agentChurn.test.js
+++ b/server/services/agentChurn.test.js
@@ -102,6 +102,8 @@ describe('observeAgentChurn', () => {
it('parks a looping coordinator and keeps the signal local for Layered Intelligence', async () => {
const park = vi.fn(async () => ({}));
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const out = await observeAgentChurn(
{ result: { duration: 80_000 } },
{ metadata: { analysisType: 'branch-reconcile', app: 'app-1' } },
@@ -119,10 +121,16 @@ describe('observeAgentChurn', () => {
reason: 'churn-detected',
actionableCount: 20
});
+ // A coordinator the loop had to park is a workflow fault: stderr.
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('CoS churn: self-improve:branch-reconcile short-lived-burst'));
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('CoS churn: parked branch-reconcile'));
+ expect(log).not.toHaveBeenCalled();
});
it('keeps a non-coordinator churn signal local without parking or filing', async () => {
const park = vi.fn();
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
const out = await observeAgentChurn(
{ result: { duration: 40_000 } },
{ metadata: { analysisType: 'claim-issue', app: 'app-1' } },
@@ -137,5 +145,8 @@ describe('observeAgentChurn', () => {
expect(out.reason).toBe('local-metric');
expect(out.parked).toBe(false);
expect(park).not.toHaveBeenCalled();
+ // Nothing acts on this signal, so it is an observation, not a fault: stdout.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('CoS churn: self-improve:claim-issue short-lived-burst'));
+ expect(warn).not.toHaveBeenCalled();
});
});
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 84e4b3c53e..34acdfb2ad 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -784,7 +784,7 @@ export async function spawnDirectly({
if (finalizeOutcome.outcome === 'abandoned') {
outputBatcher.push('🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.');
- emitLog('warn', `Agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });
+ emitLog('info', `Agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });
await Promise.all([
outputBatcher.flush().catch(() => {}),
updateAgent(agentId, { metadata: { phase: 'interrupted', interruptedBy: HOST_SHUTDOWN_REASON } })
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index bf48fca239..2607a42e8d 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -150,6 +150,7 @@ import { isOllamaBackedProvider } from './providers.js';
// Real module — the flag is a plain process-local boolean, so driving it
// directly exercises the same code path production does.
import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';
+import { emitLog } from './cosEvents.js';
import { existsSync } from 'fs';
import { spawn } from '../lib/childProcess.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
@@ -1659,6 +1660,9 @@ describe('stream error containment', () => {
), { interval: 5 });
expect(releaseAgentLane).not.toHaveBeenCalled();
expect(finalizeAgent).not.toHaveBeenCalled();
+ // A restart the operator caused, preserved for resume, is the normal path: info, never warn.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('interrupted by a PortOS host restart'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('interrupted by a PortOS host restart'), expect.anything());
});
});
diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.js
index 0933c88161..f8aa6ea828 100644
--- a/server/services/agentCompletionCleanup.js
+++ b/server/services/agentCompletionCleanup.js
@@ -139,7 +139,7 @@ export async function handlePipelineProgression(task, agentId, success) {
await updateTask(task.id, {
metadata: { ...task.metadata, pipeline: { ...pipeline, status: 'failed', stageResults: updatedResults } }
}, task.taskType);
- emitLog('warn', `⏭️ Pipeline ${pipeline.id} stage ${nextStageIndex} precondition failed: ${check.reason}`, { pipelineId: pipeline.id });
+ emitLog('info', `⏭️ Pipeline ${pipeline.id} stage ${nextStageIndex} precondition failed: ${check.reason}`, { pipelineId: pipeline.id });
return;
}
}
@@ -232,7 +232,7 @@ export async function handlePipelineProgression(task, agentId, success) {
emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex} by reviving blocked task ${persisted.id}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });
return;
}
- emitLog('warn', `⚠️ Pipeline ${pipeline.id} stage ${nextStageIndex} already queued as ${persisted.id} (${persisted.status}) — skipping duplicate advance`, { pipelineId: pipeline.id, agentId });
+ emitLog('info', `⏭️ Pipeline ${pipeline.id} stage ${nextStageIndex} already queued as ${persisted.id} (${persisted.status}) — skipping duplicate advance`, { pipelineId: pipeline.id, agentId });
return;
}
emitLog('info', `🔗 Pipeline ${pipeline.id} advancing to stage ${nextStageIndex}: ${nextStage.name}`, { pipelineId: pipeline.id, agentId });
diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.js
index b96b8f13ac..ab4b37419c 100644
--- a/server/services/agentCompletionCleanup.test.js
+++ b/server/services/agentCompletionCleanup.test.js
@@ -40,7 +40,7 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ handleCreativeDirectorC
vi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));
import { handlePipelineProgression, runAgentCompletionCleanup, runSpawnerCompletionCleanup, removeCompletionSentinel } from './agentCompletionCleanup.js';
-import { updateTask, addTask, reviveBlockedTask, getAgent } from './cos.js';
+import { updateTask, addTask, reviveBlockedTask, getAgent, checkStagePrecondition } from './cos.js';
import { emitLog } from './cosEvents.js';
import { cleanupAgentWorktree, releaseRetryHold, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';
import { resolveReviewLoopOptions } from './codeReview.js';
@@ -126,6 +126,27 @@ describe('handlePipelineProgression', () => {
expect(nextTask.metadata.pipeline.previousStageAgentId).toBe('agent-1');
});
+ // Both are the pipeline working as designed, so they log at info: stderr is for faults.
+ it('reports a failed stage precondition at info after marking the pipeline failed', async () => {
+ checkStagePrecondition.mockReturnValueOnce({ passed: false, reason: 'REVIEW.md already exists' });
+ const stages = [{ name: 'stage-0' }, { name: 'stage-1', precondition: { fileNotExists: 'REVIEW.md' } }];
+ const task = { id: 't', taskType: 'user', metadata: { repoPath: '/example/repo', pipeline: runningPipeline({ stages }) } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(updateTask.mock.calls[0][1].metadata.pipeline.status).toBe('failed');
+ expect(addTask).not.toHaveBeenCalled();
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('precondition failed: REVIEW.md already exists'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('precondition failed'), expect.anything());
+ });
+
+ it('reports a duplicate stage advance at info and does not enqueue it again', async () => {
+ addTask.mockResolvedValueOnce({ id: 'queued-stage', duplicate: true, status: 'pending' });
+ const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline() } };
+ await handlePipelineProgression(task, 'agent-1', true);
+ expect(reviveBlockedTask).not.toHaveBeenCalled();
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('already queued as queued-stage (pending) — skipping duplicate advance'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('skipping duplicate advance'), expect.anything());
+ });
+
it('propagates the next stage provider/model/effort pins into the enqueued task', async () => {
const stages = [{ name: 'stage-0' }, { name: 'stage-1', providerId: 'codex', model: 'gpt-5', effort: 'xhigh' }];
const task = { id: 't', taskType: 'user', metadata: { pipeline: runningPipeline({ stages }) } };
diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.js
index eb03bf8018..3265e88a40 100644
--- a/server/services/agentFinalization.goalFidelity.test.js
+++ b/server/services/agentFinalization.goalFidelity.test.js
@@ -357,7 +357,8 @@ describe('finalizeAgent — goal-fidelity gate', () => {
30_000, { cwd: '/example/worktree', env: { GH_TOKEN: 'synthetic-token' } },
]));
expect(runLocalGoalFidelityReviewMock).not.toHaveBeenCalled();
- expect(emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('not judgeable from a diff'), expect.any(Object));
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('not judgeable from a diff'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('not judgeable from a diff'), expect.anything());
expect(cosEvents.emit).not.toHaveBeenCalledWith(GOAL_FIDELITY_HOLD_EVENT, expect.anything());
expect(runGoalFidelityFollowUpMock).not.toHaveBeenCalled();
expect(updateTaskMock).toHaveBeenCalledWith(task.id, { status: 'completed' }, 'internal');
@@ -498,6 +499,9 @@ describe('finalizeAgent — goal-fidelity gate', () => {
expect(runLocalGoalFidelityReviewMock).not.toHaveBeenCalled();
expect(runWindowDiffMock).not.toHaveBeenCalled();
if (reason === 'credentials unavailable') expect(execGh).not.toHaveBeenCalled();
+ // A claim flow is not a code objective: the designed skip belongs on stdout, not stderr.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('Goal-fidelity review skipped'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('returned no verdict'), expect.anything());
}
);
@@ -605,6 +609,15 @@ describe('finalizeAgent — goal-fidelity gate', () => {
}
});
+ it('warns when the reviewer itself fails to answer, unlike a deliberate decline', async () => {
+ runLocalGoalFidelityReviewMock.mockResolvedValue({ ok: false, error: 'ollama is not reachable' });
+
+ await finalize();
+
+ expect(emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('returned no verdict'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('info', expect.stringContaining('Goal-fidelity review skipped'), expect.anything());
+ });
+
// The follow-up is what carries a finding past this run's record — but the
// filer reaches the network, so a failure there must never change the run's
// own verdict.
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index d12c3da39b..753961dd39 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -777,6 +777,13 @@ ${JSON.stringify({ title: issue.title, body })}`;
/** The gate's no-verdict sentinel: nothing judged this run, so leave it alone. */
const noFidelityVerdict = (error = null) => ({ verdict: null, review: null, error });
+/**
+ * A run the gate declines to grade because a diff cannot answer its objective.
+ * That is the designed outcome, not a reviewer fault, so `skipped` keeps it off
+ * the stderr path a bare `error` takes.
+ */
+const fidelityNotJudged = (reason) => ({ verdict: null, review: null, error: reason, skipped: true });
+
/**
* The goal-fidelity answer for a run whose objective is to LAND a change
* request (`mergeOutcomeObjective`), established from forge state instead of
@@ -856,7 +863,8 @@ async function hasEmptyDependencyInventories(workspacePath) {
* no gate: it would convert an ollama restart into a queue of runs marked
* needs-attention.
*
- * @returns {Promise<{verdict: string|null, review: Object|null, error: string|null}>}
+ * @returns {Promise<{verdict: string|null, review: Object|null, error: string|null, skipped?: boolean}>}
+ * `skipped` marks a deliberate decline (see `fidelityNotJudged`); a bare `error` is a fault.
*/
async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {
if (!workspacePath || !task?.id) return noFidelityVerdict();
@@ -902,7 +910,9 @@ async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {
}
}
}
- if (!objective) return noFidelityVerdict(claimFlow ? 'Claimed issue requirements unavailable; claim workflow is not a code objective.' : null);
+ if (!objective) return claimFlow
+ ? fidelityNotJudged('Claimed issue requirements unavailable; claim workflow is not a code objective.')
+ : noFidelityVerdict();
// Retain the actual compared commits for an investigator on another checkout.
// Pin before reading the diff so a moving HEAD cannot misattribute the review.
@@ -925,11 +935,11 @@ async function evaluateGoalFidelity({ task, workspacePath, startedAt }) {
if (!claimFlow && resolveTaskHookType(task) === 'dependency-updates'
&& isDependencyAuditSummaryDiff({ diff, truncated })
&& await hasEmptyDependencyInventories(workspacePath).catch(() => false)) {
- return noFidelityVerdict('Dependency audit summary is not judgeable from a diff: independent forge queries found no open alerts or PRs, but the diff cannot verify the audit execution or scanner coverage.');
+ return fidelityNotJudged('Dependency audit summary is not judgeable from a diff: independent forge queries found no open alerts or PRs, but the diff cannot verify the audit execution or scanner coverage.');
}
if (!claimFlow && isForgeRemediationTestFixDiff({ analysisType: resolveTaskHookType(task), diff })) {
- return noFidelityVerdict('PR remediation is not judgeable from a diff: its objective is forge state (CI, merges), and the run window holds only a test-file CI repair.');
+ return fidelityNotJudged('PR remediation is not judgeable from a diff: its objective is forge state (CI, merges), and the run window holds only a test-file CI repair.');
}
const result = await runLocalGoalFidelityReview({
@@ -1764,6 +1774,8 @@ export async function finalizeAgent({
emitLog(fidelityDowngrade ? 'warn' : 'info', `${goalFidelityLogMarker(fidelity.review)} ${formatGoalFidelitySummary(fidelity.review)} for ${agentId}`, {
agentId, taskId: task?.id, verdict: fidelity.verdict
});
+ } else if (fidelity.skipped) {
+ emitLog('info', `⏭️ Goal-fidelity review skipped for ${agentId}: ${fidelity.error}`, { agentId, taskId: task?.id });
} else if (fidelity.error) {
emitLog('warn', `Goal-fidelity review returned no verdict for ${agentId}: ${fidelity.error}`, { agentId, taskId: task?.id });
}
diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.js
index 1d2f8bc91c..0e62a48937 100644
--- a/server/services/agentProviderResolution.js
+++ b/server/services/agentProviderResolution.js
@@ -348,7 +348,8 @@ async function resolveOrdinaryProviderAndModel(task) {
if (isUserPin && providerSwapped && !(provider.models || []).includes(selectedModel)) {
// Handled here rather than left to the list check below, which can't fire at
// all for a fallback provider that enumerates no `models`.
- emitLog('warn', `Dropping model "${selectedModel}" pinned for provider "${pinnedProviderId}" — running on fallback "${provider.id}" with its default model`, {
+ // The same handled fallback as the sidelined-provider notice above: not a fault.
+ emitLog('info', `Dropping model "${selectedModel}" pinned for provider "${pinnedProviderId}" — running on fallback "${provider.id}" with its default model`, {
taskId: task.id,
requestedModel: selectedModel,
pinnedProviderId,
diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.js
index 3d4c15aa2e..00414e2a52 100644
--- a/server/services/agentProviderResolution.test.js
+++ b/server/services/agentProviderResolution.test.js
@@ -378,6 +378,9 @@ describe('resolveAgentProviderAndModel', () => {
expect(r.ok).toBe(true);
expect(r.provider).toBe(fallback);
expect(r.selectedModel).toBe('claude-sonnet-5'); // NOT the antigravity pin
+ // Dropping the pin is part of the handled fallback, not a fault: info, never warn.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('Dropping model "gemini-3.6-flash"'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('Dropping model'), expect.anything());
});
it('drops a swap-invalidated pin even when the fallback provider enumerates no models', async () => {
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index 579c812508..a2e3dada9e 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -476,7 +476,8 @@ async function verifyAgentBranchState({ agentId, task, agentState, success, prEx
.catch(() => ({ reason: 'retirement-review-unavailable' }));
if (!prepared.retirement) {
await domain('blocked', prepared.reason);
- emitLog('warn', `Repo-state retirement retained ${branchName}: ${prepared.reason}`, { agentId, branchName });
+ // The retirement gate declining is its designed outcome; the reason is recorded on the domain above.
+ emitLog('info', `⏸️ Repo-state retirement retained ${branchName}: ${prepared.reason}`, { agentId, branchName });
return { verified: false, skipReason: prepared.reason, issues, observed, recoveryTaskId: null };
}
retirement = prepared.retirement;
@@ -518,7 +519,8 @@ async function verifyAgentBranchState({ agentId, task, agentState, success, prEx
await domain('blocked', reason);
return { verified: false, skipReason: reason, issues, observed, recoveryTaskId: null };
}
- emitLog('warn', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });
+ // The recovery task filed below is the investigation, so this line only records the divergence; filing failures still warn.
+ emitLog('info', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });
const recoveryTaskId = await fileRepoStateRecoveryTask({
agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId, retirement, claimRun: isTruthyMeta(metadata.claimPicksOwnBranch),
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index 3b5af12281..32b4f2db65 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -89,6 +89,7 @@ import { findPullRequestForBranch, execGh, getPullRequestState } from './github.
import { findMergeRequestForBranch } from './gitlab.js';
import { getAppById } from './apps.js';
import { addNotification, exists as notificationExists } from './notifications.js';
+import { emitLog } from './cosEvents.js';
import { readPendingMergePrs } from './prWatcher.js';
import { execGit } from '../lib/execGit.js';
import { existsSync } from 'fs';
@@ -301,8 +302,14 @@ describe('verifyAgentRepoState — divergent runs', () => {
expect(await run()).toMatchObject({ verified: false, skipReason: 'active-agent-owner', recoveryTaskId: null });
expect(addTask).not.toHaveBeenCalled();
expect(recordBranchReconcileOutcome).toHaveBeenCalledWith('demo-app', expect.objectContaining({ reason: 'active-agent-owner' }));
+ // The gate declining to retire is its designed outcome: reported at info, never warn.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('Repo-state retirement retained'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('Repo-state retirement retained'), expect.anything());
prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { ...review(), digest: 'b'.repeat(64) } });
expect(await run()).toMatchObject({ verified: false, recoveryTaskId: 'task-recovery-1' });
+ // The recovery task is the investigation, so the divergence itself is logged at info.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('Repo state diverged'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('Repo state diverged'), expect.anything());
expect(prepareInventoriedCheckoutRetirement).toHaveBeenCalledTimes(2);
});
diff --git a/server/services/agentSpawnPreparation.js b/server/services/agentSpawnPreparation.js
index 4b3987af16..6e7bb2676c 100644
--- a/server/services/agentSpawnPreparation.js
+++ b/server/services/agentSpawnPreparation.js
@@ -96,7 +96,7 @@ export async function prepareAgentSpawn(task, context = createAgentSpawnContext(
// after that lock and the presentation-only spawn grace window end.
const state = await loadState();
if (hasActiveTaskOwner(task.id, state.agents)) {
- console.warn(`⚠️ Task ${task.id} already has an active owner — skipping duplicate dispatch`);
+ console.log(`⏭️ Task ${task.id} already has an active owner — skipping duplicate dispatch`);
return null;
}
diff --git a/server/services/agentSpawnPreparation.test.js b/server/services/agentSpawnPreparation.test.js
new file mode 100644
index 0000000000..66bb0b9745
--- /dev/null
+++ b/server/services/agentSpawnPreparation.test.js
@@ -0,0 +1,32 @@
+import { describe, it, expect, vi } from 'vitest';
+
+const loadState = vi.hoisted(() => vi.fn());
+const hasActiveTaskOwner = vi.hoisted(() => vi.fn());
+
+vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn(), on: vi.fn() }, emitLog: vi.fn() }));
+vi.mock('./cosState.js', () => ({ loadState }));
+vi.mock('./agentState.js', () => ({ hasActiveTaskOwner }));
+vi.mock('./cos.js', () => ({ getTaskById: vi.fn(), updateTask: vi.fn() }));
+vi.mock('./toolStateMachine.js', () => ({
+ createToolExecution: vi.fn(), startExecution: vi.fn(), completeExecution: vi.fn(), errorExecution: vi.fn(),
+}));
+vi.mock('./executionLanes.js', () => ({ determineLane: vi.fn(), acquire: vi.fn(), release: vi.fn() }));
+vi.mock('./agentPromptBuilder.js', () => ({ getAppWorkspace: vi.fn() }));
+vi.mock('./instanceIdentity.js', () => ({ ensureInstanceId: vi.fn() }));
+vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn() }));
+
+import { prepareAgentSpawn } from './agentSpawnPreparation.js';
+
+describe('prepareAgentSpawn — duplicate dispatch', () => {
+ it('skips a task another run already owns and reports the skip on stdout, not stderr', async () => {
+ loadState.mockResolvedValue({ agents: {} });
+ hasActiveTaskOwner.mockReturnValue(true);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ expect(await prepareAgentSpawn({ id: 'task-1', taskType: 'user' })).toBeNull();
+
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Task task-1 already has an active owner'));
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index de2989b436..8812414f22 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -284,6 +284,7 @@ import {
// Real module, not a mock: the flag is a plain process-local boolean, so driving
// it directly exercises the same code path production does.
import { markHostShuttingDown, resetHostShutdownFlagForTests } from '../lib/hostShutdown.js';
+import { emitLog } from './cosEvents.js';
describe('agent TUI spawning', () => {
// `buildTuiSpawnConfig` → `appendModelArgs` → the REAL `resolveInjectedTuiModel`,
@@ -3940,6 +3941,9 @@ describe('spawnTuiAgent runtime', () => {
)).toBe(true);
expect(agentLifecycle.releaseAgentLane).not.toHaveBeenCalled();
expect(agentLifecycle.finalizeAgent).not.toHaveBeenCalled();
+ // A restart the operator caused, preserved for resume, is the normal path: info, never warn.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('interrupted by a PortOS host restart'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('interrupted by a PortOS host restart'), expect.anything());
});
});
});
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index e1b5009895..effe9848b2 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -1267,7 +1267,7 @@ export function createTuiSessionController({
stopRunMachinery();
appendLine(LIFECYCLE_LINES.hostRestarted());
- emitLog('warn', `TUI agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });
+ emitLog('info', `TUI agent ${agentId} interrupted by a PortOS host restart — preserved for resume`, { agentId, phase: 'interrupted' });
// Concurrent, not sequential: nothing awaits this function (it runs off the
// PTY-exit handler, racing the shutdown handler's own process.exit), so the
// shorter the critical path the more of the transcript actually lands. The
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 1554d8405d..664c29205f 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -328,7 +328,13 @@ async function prepareRequestedWorktree({
return null;
});
}
- if (worktreeError) {
+ // A branch still checked out in another worktree is a transient the timed
+ // `worktree-busy` pause below retries (and reports at info). Only a failure
+ // nothing retries is a fault worth stderr.
+ const retriesBusyBranch = Boolean(worktreeError) && !allowSharedWorkspaceFallback
+ && worktreeError.code !== PINNED_HEAD_MOVED
+ && isBranchCheckedOutElsewhereError(worktreeError.message) && attempt <= WORKTREE_BUSY_MAX_ATTEMPTS;
+ if (worktreeError && !retriesBusyBranch) {
emitLog('warn', `🌳 Worktree creation failed for task ${task.id}: ${worktreeError.message}`, { taskId: task.id });
}
@@ -362,7 +368,7 @@ async function prepareRequestedWorktree({
return { outcome: 'ready', workspacePath, worktreeInfo: null };
}
- if (isBranchCheckedOutElsewhereError(worktreeError?.message) && attempt <= WORKTREE_BUSY_MAX_ATTEMPTS) {
+ if (retriesBusyBranch) {
// The branch is checked out in ANOTHER worktree. Routinely that other
// worktree is the previous agent's, still being torn down by the very
// cleanup that spawned this task, so waiting it out lands the pull
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 7888fb322c..4a947faeac 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -84,6 +84,7 @@ vi.mock('./deepAudit.js', () => ({ getDeepAuditSourceRevision: vi.fn().mockResol
import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';
import { claimContinuationWorkspace } from '../lib/claimContinuation.js';
import { updateTask, addTask, getAgents } from './cos.js';
+import { emitLog } from './cosEvents.js';
import { ensureLatest, isRepo, fetchOrigin } from './git.js';
import { execGit } from '../lib/execGit.js';
import { detectConflicts } from './taskConflict.js';
@@ -1011,6 +1012,9 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
// The cooldown stamp is what the sweeper in cosTaskGenerator revives on.
expect(new Date(patch.metadata.cooldownUntil).getTime()).toBeGreaterThan(Date.now());
expect(patch.metadata.worktreeBusyAttempts).toBe(1);
+ // A retried busy branch is handled, not a fault: the pause reports at info and stderr stays quiet.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('retrying after a short cooldown'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('Worktree creation failed'), expect.anything());
});
it('counts up from the attempts already recorded on the task', async () => {
@@ -1032,6 +1036,8 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
// The git error rides along — "worktree creation failed" alone said nothing
// about which branch was held, or by what.
expect(patch.metadata.blockedReason).toContain('already used by worktree');
+ // Once the retry budget is spent nothing retries it, so the failure is a fault again.
+ expect(emitLog).toHaveBeenCalledWith('warn', expect.stringContaining('Worktree creation failed for task'), expect.any(Object));
});
// A terminal session's own worktree holds the branch for good: nothing PortOS
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index a01b064f06..4c9ef38065 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -615,7 +615,8 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc
// observes the surviving worktree and files the recovery that retries removal
// and drives the PR). The PR itself is untouched: it stays open/merged as it was.
function deferFollowUpWhileBranchHeld({ agentId, worktreeBranch, worktreePath, warnings }, prUrl) {
- emitLog('warn', `🌳 Deferring follow-up for ${prUrl} — worktree ${agentId} still holds ${worktreeBranch}`, { agentId, prUrl, branchName: worktreeBranch });
+ // The failed removal that left the branch held reported itself; this line only records the deferral.
+ emitLog('info', `🌳 Deferring follow-up for ${prUrl} — worktree ${agentId} still holds ${worktreeBranch}`, { agentId, prUrl, branchName: worktreeBranch });
warnings.push(`PR follow-up for ${prUrl} deferred — worktree ${worktreePath || agentId} still holds branch ${worktreeBranch}; retry the worktree cleanup, then re-dispatch the follow-up`);
}
diff --git a/server/services/backupScheduler.js b/server/services/backupScheduler.js
index fdd674742f..40c2e082c7 100644
--- a/server/services/backupScheduler.js
+++ b/server/services/backupScheduler.js
@@ -69,11 +69,11 @@ async function runScheduledBackup(logReason) {
if (corrupt) throw new Error('Backup settings unreadable — scheduled run was not started');
const effective = resolveBackupConfig(fresh.backup);
if (!effective.enabled) {
- console.warn('💾 Backup scheduler: disabled since registration — skipping run');
+ console.log('💾 Backup scheduler: disabled since registration — skipping run');
return { skipped: true, reason: 'disabled since registration' };
}
if (!effective.destPath) {
- console.warn('💾 Backup scheduler: destPath cleared since registration — skipping run');
+ console.log('💾 Backup scheduler: destPath cleared since registration — skipping run');
return { skipped: true, reason: 'destination cleared since registration' };
}
const excludePaths = fresh.backup?.excludePaths || [];
@@ -81,7 +81,7 @@ async function runScheduledBackup(logReason) {
console.log(`💾 Backup scheduler: running ${logReason} backup`);
const result = await runBackup(effective.destPath, null, { excludePaths, disabledDefaultExcludes, retentionCount: effective.retentionCount });
if (result?.skipped) {
- console.warn(`⚠️ Backup scheduler: ${logReason} backup skipped — a backup is already running`);
+ console.log(`⏭️ Backup scheduler: ${logReason} backup skipped — a backup is already running`);
return { skipped: true, reason: 'already running' };
}
}
diff --git a/server/services/backupScheduler.test.js b/server/services/backupScheduler.test.js
index a42e020133..ae623b06ed 100644
--- a/server/services/backupScheduler.test.js
+++ b/server/services/backupScheduler.test.js
@@ -170,6 +170,7 @@ describe('startBackupScheduler', () => {
it('reports a backup refused by the already-running latch as a skipped slot, not a success (#12023)', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
try {
const settings = { backup: { enabled: true, destPath: '/example-backups' } };
getSettings.mockResolvedValueOnce(settings);
@@ -179,17 +180,22 @@ describe('startBackupScheduler', () => {
runBackup.mockResolvedValueOnce({ skipped: true });
await expect(handler()).resolves.toEqual({ skipped: true, reason: 'already running' });
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('already running'));
+ // The latch refusing a duplicate run is a deliberate skip: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('already running'));
+ expect(warn).not.toHaveBeenCalled();
getSettings.mockResolvedValueOnce(settings);
runBackup.mockResolvedValueOnce({ success: true });
await expect(handler()).resolves.toBeUndefined();
} finally {
warn.mockRestore();
+ log.mockRestore();
}
});
it('handler skips the run if backup was disabled since registration', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
getSettings.mockResolvedValueOnce({
backup: { enabled: true, destPath: '/dest', excludePaths: [], disabledDefaultExcludes: [] }
});
@@ -204,9 +210,14 @@ describe('startBackupScheduler', () => {
await handler();
expect(runBackup).not.toHaveBeenCalled();
+ // The settings guard declining a stale cron slot is a deliberate skip: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('disabled since registration — skipping run'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('skipping run'));
});
it('handler skips the run if destPath has been cleared since registration', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
getSettings.mockResolvedValueOnce({
backup: { enabled: true, destPath: '/dest', excludePaths: [], disabledDefaultExcludes: [] }
});
@@ -219,6 +230,8 @@ describe('startBackupScheduler', () => {
await handler();
expect(runBackup).not.toHaveBeenCalled();
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('destPath cleared since registration — skipping run'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('skipping run'));
});
});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 0109ab012a..2a9494d84b 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -1276,7 +1276,8 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>
// rest closed below — a handler mid-write loses its response only at the deadline.
timing.mark('requestDrain');
const { remaining } = await requestsDrained;
- if (remaining > 0) console.warn(`⚠️ ${remaining} request(s) still running after the ${HTTP_DRAIN_WINDOW_MS}ms drain — closing them`);
+ // The drain window is bounded on purpose, so closing what outlives it is the handling.
+ if (remaining > 0) console.log(`⏱️ ${remaining} request(s) still running after the ${HTTP_DRAIN_WINDOW_MS}ms drain — closing them`);
// Close BOTH servers explicitly. The drain already stopped both listeners
// (ERR_SERVER_NOT_RUNNING → treated as success by closeServer), and
// the bounded backstop in closeServer guarantees neither can hang shutdown even
diff --git a/server/services/bootstrap.shutdown.test.js b/server/services/bootstrap.shutdown.test.js
index 50e6d380d1..a1bf7afc99 100644
--- a/server/services/bootstrap.shutdown.test.js
+++ b/server/services/bootstrap.shutdown.test.js
@@ -100,6 +100,11 @@ describe('shutdown handler — request drain ordering (#8323)', () => {
expect(code.indexOf('closeAllConnections')).toBe(-1);
});
+ it('reports requests that outlive the drain window on stdout: closing them is the bounded handling', () => {
+ expect(code).toMatch(/remaining > 0\) console\.log\(`⏱️ /);
+ expect(code).not.toMatch(/remaining > 0\) console\.(warn|error)\(/);
+ });
+
it('fits the drain window and the close graces inside the shutdown ceiling', () => {
const constant = (name) => Number(SRC.match(new RegExp(`const ${name} = (\\d+);`))?.[1]);
const closeGrace = Number(SRC.match(/const closeServer = \(server, label, graceMs = (\d+)\)/)?.[1]);
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index a9ea411458..acb138b5db 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1106,7 +1106,7 @@ async function retainedClaimMarkers(repoPath, branch, { origin } = {}) {
const target = origin === undefined ? await getOriginInfo(repoPath).catch(() => null) : origin;
if (target && !githubRepoSpec(target)) return null;
const hold = { branch, issue: Number(issue), reason: 'claim-reservation-owner-unverified', markerState: 'unknown', ownerState: 'unknown' };
- console.warn(`🔒 branch-reconcile: issue #${issue} markers untouched; reservation owner/state unverified`);
+ console.log(`🔒 branch-reconcile: issue #${issue} markers untouched; reservation owner/state unverified`);
return hold;
}
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 282b390b3f..8b62f4c7b0 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -362,10 +362,15 @@ const mockOwnedClaim = () => execGh.mockImplementation(async (args) => {
describe('unverified issue reservations in reconcile', () => {
it('retires the local checkout while leaving possible same-account peer markers untouched before its first commit', async () => {
mockOwnedClaim();
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
getOriginInfo.mockResolvedValue({ hasOrigin: true, host: 'github.example.com', fullName: 'example/app' });
wt.reapMergedWorktrees.mockResolvedValue({ reaped: [{ branch: 'claim/issue-42', branchDeleted: true }], skipped: [] });
git.getBranches.mockResolvedValue([]);
const result = await reconcile('/repo', { forgeAccount: 'app-account' });
+ // Leaving unverified peer markers alone is the designed policy on every local retirement: stdout.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('issue #42 markers untouched'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('markers untouched'));
expect(result.cleaned).toEqual(['claim/issue-42']);
expect(result.claimMarkersHeld).toEqual([{ branch: 'claim/issue-42', issue: 42, reason: 'claim-reservation-owner-unverified', markerState: 'unknown', ownerState: 'unknown' }]);
expect(execGh.mock.calls.some(([args]) => args[0] === 'issue' || args[0] === 'api')).toBe(false);
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 48bfcb139f..9ea0494fe1 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -805,6 +805,8 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
};
it('keeps the PR published but does not dispatch the follow-up into the occupied branch', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
openPr();
removeWorktree.mockResolvedValue({
merged: false, removed: false, cleanupIncomplete: true, uncommittedSaved: false,
@@ -818,6 +820,9 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
expect(forceSpawnTask).not.toHaveBeenCalled();
expect(warnings.some(w => /cleanup incomplete/.test(w))).toBe(true);
expect(warnings.some(w => w.includes('PR follow-up for https://github.com/test/repo/pull/45 deferred'))).toBe(true);
+ // The deferral is the handling; the failed removal behind it reported itself, so stderr stays quiet here.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Deferring follow-up for https://github.com/test/repo/pull/45'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('Deferring follow-up'));
});
it('treats a thrown removal as an unreleased branch too', async () => {
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index 3998ab5ac6..cada1d837a 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -1113,7 +1113,7 @@ async function runReviewerCompletion({ backend, model: pinnedModel, messages, us
let attempt = await sendChatCompletion(baseUrl, { model, messages, timeoutMs }, resolvedEffort)
if (!attempt.ok && attempt.status === 400 && resolvedEffort && /does not support thinking/i.test(attempt.text || '')) {
- console.warn(`⚠️ ${backend} model ${model} ignores reasoning_effort — retried without it`)
+ console.log(`⏭️ ${backend} model ${model} ignores reasoning_effort — retried without it`)
thinkingUnsupportedModels.set(thinkingCacheKey(backend, model), true)
resolvedEffort = null
effortUnsupported = true
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index 83a628a2bc..845af3ab7e 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -2372,12 +2372,17 @@ describe('codeReview helpers', () => {
.mockResolvedValueOnce(mockTextResponse(thinkingRejectedBody, { ok: false, status: 400 }))
.mockResolvedValueOnce(mockJsonResponse({ choices: [{ message: { content: 'No findings.' } }] }))
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const r = await runLocalCodeReview({ backend: 'ollama', model: 'nonthinking-model', diff: 'd', effort: 'low' })
expect(global.fetch).toHaveBeenCalledTimes(2)
const secondBody = JSON.parse(global.fetch.mock.calls[1][1].body)
expect('reasoning_effort' in secondBody).toBe(false)
expect(r).toMatchObject({ ok: true, effort: null, effortUnsupported: true, findings: 'No findings.' })
+ // A model without a thinking mode is a capability the call adapts to, not a fault: stdout.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('nonthinking-model ignores reasoning_effort'))
+ expect(warn).not.toHaveBeenCalled()
})
it('does not retry a 400 that is unrelated to thinking', async () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index 9142311b5e..d6b492cec4 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -348,7 +348,7 @@ export function start() {
async function runStart() {
if (isDaemonRunning()) {
- emitLog('warn', 'CoS already running');
+ emitLog('info', '⏭️ CoS already running');
return { success: false, error: 'Already running' };
}
diff --git a/server/services/cos.startStop.test.js b/server/services/cos.startStop.test.js
index 818c86ac62..6bd12d3dc0 100644
--- a/server/services/cos.startStop.test.js
+++ b/server/services/cos.startStop.test.js
@@ -149,6 +149,20 @@ describe('CoS daemon start/stop lifecycle (#11860)', () => {
expect(statuses.at(-1)).toEqual({ running: false });
});
+ it('a second start() while the daemon runs is refused at info, not reported as a fault', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const starting = start();
+ await waitFor(() => typeof releaseRecovery === 'function');
+ releaseRecovery();
+ await starting;
+
+ await expect(start()).resolves.toEqual({ success: false, error: 'Already running' });
+
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('CoS already running'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('CoS already running'));
+ });
+
it('the handoff follow-up poll shares the pending-merge gate and is cancelled on stop', async () => {
persisted = { ...persisted, paused: false, config: { ...persisted.config, domainAutonomy: { cos: 'execute' } } };
const starting = start();
diff --git a/server/services/cosClaimOwnership.js b/server/services/cosClaimOwnership.js
index 1a5c2f4d32..ac837d998e 100644
--- a/server/services/cosClaimOwnership.js
+++ b/server/services/cosClaimOwnership.js
@@ -45,6 +45,8 @@ async function ownershipTransaction(operation, done, work) {
const finishPhase = () => { timings[phase] = elapsed(phaseStartedAt); };
const enter = name => { finishPhase(); phase = name; phaseStartedAt = performance.now(); };
const report = status => {
+ // A queue-timeout or pending report means the lock was held past its budget, which only happens
+ // during the event-loop stalls #12852 reopens on — an anomaly, so it stays on stderr; settled is routine.
const log = status === 'failed' ? console.error : status === 'settled' ? console.log : console.warn;
log(`🔒 Claim ownership operation=${operation} status=${status} phase=${phase} phaseMs=${elapsed(phaseStartedAt)} totalMs=${elapsed(queuedAt)} ownershipQueueMs=${timings.ownershipQueue} stateQueueMs=${timings.stateQueue} ownerReadMs=${timings.ownerRead} ownershipCheckMs=${timings.ownershipCheck} persistenceMs=${timings.persistence}`);
};
diff --git a/server/services/cosForgeSpawnGate.js b/server/services/cosForgeSpawnGate.js
index 8df76a6c1d..c6cdc99a21 100644
--- a/server/services/cosForgeSpawnGate.js
+++ b/server/services/cosForgeSpawnGate.js
@@ -169,7 +169,8 @@ export async function forgeSpawnHoldReason(task, { now = Date.now() } = {}) {
// line naming the host rather than one per task.
if (!state.warned) {
const detail = health.detail ? ` — ${String(health.detail).split('\n')[0].slice(0, 120)}` : '';
- emitLog('warn', `⏸️ Holding forge-dependent tasks: ${host} is unreachable${detail}`, { taskId: task.id });
+ // The hold is the handling; the one-hour escalation above is what warns.
+ emitLog('info', `⏸️ Holding forge-dependent tasks: ${host} is unreachable${detail}`, { taskId: task.id });
}
heldHosts.set(host, { ...state, warned: true });
scheduleForgeRecheck();
diff --git a/server/services/cosForgeSpawnGate.test.js b/server/services/cosForgeSpawnGate.test.js
index c60d588e4a..6f2f9f7362 100644
--- a/server/services/cosForgeSpawnGate.test.js
+++ b/server/services/cosForgeSpawnGate.test.js
@@ -233,16 +233,18 @@ describe('forgeSpawnHoldReason', () => {
});
describe('logging', () => {
- it('warns once per outage naming the host, not once per held task', async () => {
+ it('reports the hold once per outage naming the host, not once per held task', async () => {
probe('unreachable', 'error connecting to forge.example.com');
await forgeSpawnHoldReason(prTask());
await forgeSpawnHoldReason({ id: 'task-2', metadata: { openPR: true } });
await forgeSpawnHoldReason({ id: 'task-3', metadata: { openPR: true } });
- const warnings = emitLog.mock.calls.filter(([level]) => level === 'warn');
- expect(warnings).toHaveLength(1);
- expect(warnings[0][1]).toContain('forge.example.com is unreachable');
+ const holds = emitLog.mock.calls.filter(([level]) => level === 'info');
+ expect(holds).toHaveLength(1);
+ expect(holds[0][1]).toContain('forge.example.com is unreachable');
+ // Holding is the designed handling, so stderr stays quiet until the outage outlasts the hour.
+ expect(emitLog.mock.calls.filter(([level]) => level === 'warn')).toHaveLength(0);
});
it('warns once when it gives up on a host, so the expiry is not silent', async () => {
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index f90663509d..c93aa40e66 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -82,6 +82,8 @@ async function transaction(work, operation) {
const report = (status) => {
const summary = status === 'pending' ? span.snapshot() : span.end();
if (status === 'settled' && summary.totalMs < SLOW_ADMISSION_MS) return;
+ // Same contract as claim ownership: a queue-timeout or pending report only appears during the
+ // event-loop stalls #12852 reopens on, so it stays on stderr; a slow settle is telemetry.
const log = status === 'failed' ? console.error : status === 'settled' ? console.log : console.warn;
const phases = REPORTED_PHASES.map((name) => `${name}Ms=${phaseGroup(summary, name).ms}`);
const stages = REPORTED_STAGES.map(([name, stage]) => `${stage}Ms=${summary.phases[`${name}.${stage}`]?.ms ?? 0}`);
diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.js
index 5872f3f718..6d9286e53c 100644
--- a/server/services/cosMergeHandoff.test.js
+++ b/server/services/cosMergeHandoff.test.js
@@ -650,7 +650,9 @@ describe('handoff follow-up poll', () => {
await minutes(prWatcher.HANDOFF_FOLLOW_UP_CAP_MS / 60000);
expect(vi.getTimerCount()).toBe(0);
expect(pending()).toEqual([expect.objectContaining({ ticks: 0 })]);
- expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('the timer sweep owns 1 entry'));
+ // Handing back to the timer sweep at the cap is the designed bounded wait, not a fault: stdout.
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('the timer sweep owns 1 entry'));
+ expect(console.warn).not.toHaveBeenCalled();
const finalReads = forgeViews();
await minutes(60);
expect(forgeViews()).toBe(finalReads);
@@ -662,12 +664,13 @@ describe('handoff follow-up poll', () => {
gate.mockResolvedValue('daemon paused');
await minutes(prWatcher.HANDOFF_FOLLOW_UP_INTERVAL_MS / 60000);
expect(forgeViews()).toBe(reads);
- expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('skipped: daemon paused'));
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('skipped: daemon paused'));
+ expect(console.warn).not.toHaveBeenCalled();
expect(vi.getTimerCount()).toBe(1);
});
it('stops when the daemon stops', async () => {
- await handOffPending();
+ const armed = await handOffPending();
const reads = forgeViews();
prWatcher.cancelHandoffFollowUps();
expect(vi.getTimerCount()).toBe(0);
@@ -677,6 +680,11 @@ describe('handoff follow-up poll', () => {
// A receipt while the daemon is stopped leaves the entry to the timer sweep.
await handOffPending();
expect(vi.getTimerCount()).toBe(0);
+ // Declining to arm is the designed handoff to the timer sweep: stdout, not stderr.
+ await prWatcher.followUpHandoffReceipt('app1', armed.receipt.id);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('not armed: CoS daemon is stopped'));
+ expect(console.warn).not.toHaveBeenCalled();
});
it('owns a throwing poll and keeps polling', async () => {
@@ -693,4 +701,24 @@ describe('handoff follow-up poll', () => {
expect(mergePrMock).toHaveBeenCalledTimes(1);
expect(vi.getTimerCount()).toBe(0);
});
+
+ // Both ends of the bounded wait hand the entry to the timer sweep: designed, so stdout.
+ it('drops the poll without a fault when the gate reports the daemon stopped', async () => {
+ await handOffPending();
+ gate.mockResolvedValue('daemon-stopped');
+ await minutes(prWatcher.HANDOFF_FOLLOW_UP_INTERVAL_MS / 60000);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('stopped: CoS daemon is stopped'));
+ expect(console.warn).not.toHaveBeenCalled();
+ });
+
+ it('hands a poll that keeps throwing back to the timer sweep at the cap, logging each throw as an error', async () => {
+ await handOffPending();
+ f.apps.get = () => { throw new Error('apps store unreadable'); };
+ await minutes(prWatcher.HANDOFF_FOLLOW_UP_CAP_MS / 60000 + prWatcher.HANDOFF_FOLLOW_UP_BACKOFF_MS / 60000);
+ expect(vi.getTimerCount()).toBe(0);
+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('apps store unreadable'));
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('reached its cap; the timer sweep owns its entries'));
+ expect(console.warn).not.toHaveBeenCalled();
+ });
});
diff --git a/server/services/cosTaskGenerator.cronQueue.test.js b/server/services/cosTaskGenerator.cronQueue.test.js
index 29cc7dfa2a..68032d33c8 100644
--- a/server/services/cosTaskGenerator.cronQueue.test.js
+++ b/server/services/cosTaskGenerator.cronQueue.test.js
@@ -15,7 +15,7 @@ import { queueEligibleImprovementTasks } from './cosTaskGenerator.js';
import { getDueTasks, recordExecution } from './taskSchedule.js';
import { loadAppActivity } from './appActivity.js';
import { getActiveApps } from './apps.js';
-import { cosEvents } from './cosEvents.js';
+import { cosEvents, emitLog } from './cosEvents.js';
const state = { config: { improvementEnabled: true, appReviewCooldownMs: 60_000 } };
const dueCron = taskType => ({ taskType, reason: 'cron-due', interval: { type: 'cron' } });
@@ -67,6 +67,11 @@ describe('scheduled managed-app queue admission', () => {
await run([queuedTask('do-release', status)]);
expect(prepareTask.mock.calls.map(([type]) => type)).toEqual(['pr-watcher']);
expect(recordExecution).toHaveBeenCalledExactlyOnceWith('task:pr-watcher', 'example-app');
+ if (status === 'blocked') {
+ // A blocked task holding its slot is the dedupe working: info, never warn.
+ expect(emitLog).toHaveBeenCalledWith('info', expect.stringContaining('Skipping do-release for Example App: blocked task'), expect.any(Object));
+ expect(emitLog).not.toHaveBeenCalledWith('warn', expect.stringContaining('Skipping do-release'), expect.anything());
+ }
});
it('does not consume cadence for generator declines or disk-level duplicate races', async () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index b2bdb116f3..fdd56a112e 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1218,7 +1218,7 @@ export async function queueDueInstallWideImprovementTasks({
const taskKey = taskType;
if (existingTaskTypes.has(taskKey)) {
if (blockedTaskTypes.has(taskKey)) {
- emitLog('warn', `⛔ Skipping install-wide ${taskType}: blocked task ${blockedTaskTypes.get(taskKey)} already exists — resolve or delete it to resume`, { analysisType: taskType });
+ emitLog('info', `⏸️ Skipping install-wide ${taskType}: blocked task ${blockedTaskTypes.get(taskKey)} already exists — resolve or delete it to resume`, { analysisType: taskType });
} else {
emitLog('debug', `Install-wide improvement task ${taskType} already queued`);
}
@@ -1374,7 +1374,7 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, {
const taskKey = `app:${app.id}:${nextType}`;
if (existingTaskTypes.has(taskKey)) {
if (blockedTaskTypes.has(taskKey)) {
- emitLog('warn', `⛔ Skipping ${nextType} for ${app.name}: blocked task ${blockedTaskTypes.get(taskKey)} of this type already exists — resolve or delete it to resume`, { appId: app.id });
+ emitLog('info', `⏸️ Skipping ${nextType} for ${app.name}: blocked task ${blockedTaskTypes.get(taskKey)} of this type already exists — resolve or delete it to resume`, { appId: app.id });
} else {
emitLog('debug', `Improvement task ${nextType} for ${app.name} already queued`);
}
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 5dc74c0429..7809657665 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -1422,6 +1422,8 @@ describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy thei
const wake = vi.fn();
const existingTaskTypes = new Set(['repo-sync']);
const blockedTaskTypes = new Map([['repo-sync', 'blocked-repo-sync']]);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const queued = await queueDueInstallWideImprovementTasks({
dueTasks: [
@@ -1442,6 +1444,9 @@ describe('buildImprovementDedupSets (#2614 — failure-blocked tasks occupy thei
});
expect(queued).toBe(0);
+ // A blocked task occupying the slot is the dedupe working, re-announced each cycle: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Skipping install-wide repo-sync: blocked task blocked-repo-sync'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('Skipping install-wide'));
expect(generateTask).toHaveBeenCalledTimes(1);
expect(generateTask).toHaveBeenCalledWith('user-action-review', { config: {} });
expect(persistTask).not.toHaveBeenCalled();
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 3447c587b6..ebce65004f 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -572,7 +572,7 @@ const pendingTransitions = new Map();
// rather than stranding a finished job half-terminated.
const COMPLETION_ADMISSION_MS = 60 * 60 * 1000;
const admitCompletion = (state, commit) => (state === 'completed'
- ? withBackupAssetPublication(commit, { timeoutMs: COMPLETION_ADMISSION_MS, onWait: () => console.warn('⏸️ media-job completion waiting for the backup to finish') })
+ ? withBackupAssetPublication(commit, { timeoutMs: COMPLETION_ADMISSION_MS, onWait: () => console.log('⏸️ media-job completion waiting for the backup to finish') })
: commit());
function stageTerminalTransition(job, apply, acknowledge) {
job.terminating = true;
@@ -705,7 +705,7 @@ function recordQuotaCooldown(job, errorText) {
// shorter remaining wait, and taking it would release the queue early.
if (deferral.resumeAt <= existing) return;
quotaCooldowns.set(mode, deferral.resumeAt);
- console.warn(`⏳ media-job: ${mode} quota exhausted — holding queued ${mode} renders for ${formatDeferral(deferral.resetsInMs)}`);
+ console.log(`⏳ media-job: ${mode} quota exhausted — holding queued ${mode} renders for ${formatDeferral(deferral.resetsInMs)}`);
}
// Derived from the ABSOLUTE reset so the message is constant for the whole
@@ -1998,7 +1998,8 @@ async function runJobLifecycle(job, markDispatched, permit, finalizeLane) {
*/
export function assertMediaQueueRoom(count = 1) {
if (queue.length + count <= MAX_PENDING_MEDIA_JOBS) return;
- console.warn(`⚠️ media queue full — refused ${count} job(s) with ${queue.length} waiting (limit ${MAX_PENDING_MEDIA_JOBS})`);
+ // The caller gets the 4xx; this is the queue's backpressure answering, not a fault.
+ console.log(`🚫 media queue full — refused ${count} job(s) with ${queue.length} waiting (limit ${MAX_PENDING_MEDIA_JOBS})`);
throw mediaQueueFullError({ pending: queue.length, requested: count });
}
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index eea633e05c..f57a2ee82b 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -3700,6 +3700,8 @@ describe('pending-job ceiling', () => {
it('admits exactly the ceiling under concurrent submission and refuses the next without touching state', async () => {
const { MAX_PENDING_MEDIA_JOBS } = mediaJobQueue;
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
// A running job holds the only GPU slot, so everything below waits.
const blocker = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'running' } });
await waitFor(() => mediaJobQueue.getJob(blocker.jobId)?.status === 'running');
@@ -3710,6 +3712,9 @@ describe('pending-job ceiling', () => {
(_, i) => mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: `wait-${i}` } })));
expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(MAX_PENDING_MEDIA_JOBS);
expect(results.filter((r) => r.status === 'rejected').map((r) => r.reason)).toEqual([expect.objectContaining(queueFull)]);
+ // The refused submission is backpressure answering the caller (429), not a fault: stdout, never stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('media queue full'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('media queue full'));
expect(waiting()).toBe(MAX_PENDING_MEDIA_JOBS);
await flush();
@@ -3966,6 +3971,29 @@ describe('backup snapshot admission for media completion', () => {
expect(capture(jobId)).toEqual({ files: [`${jobId}.mp4`], queueStatus: 'completed', rows: new Map([[jobId, `${jobId}.mp4`]]) });
});
+ it('says why a finished render waits while the backup cut holds admission, without alarming stderr', async () => {
+ vi.useFakeTimers();
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ let release;
+ try {
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'synthetic' } });
+ await vi.waitFor(() => expect(stubs.generateVideo).toHaveBeenCalledTimes(1));
+ await flush();
+ release = await boundary.acquireBackupSnapshotCut();
+ renderFinishes(jobId);
+ // One notice interval: the hold repeats its reason every minute while the cut is open.
+ await vi.advanceTimersByTimeAsync(61_000);
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('media-job completion waiting for the backup to finish'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('waiting for the backup'));
+ } finally {
+ release?.();
+ await flush();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
it('releases a finished provider lane after admission times out and recovers its pending result', async () => {
vi.useFakeTimers();
const completed = vi.fn();
@@ -4304,6 +4332,8 @@ describe('provider quota cooldowns', () => {
// empty. Re-importing here would reset modules mid-setup.
it('holds a later render for the same backend instead of dispatching it into the same 429', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
const first = await mediaJobQueue.enqueueJob({ kind: 'image', params: { mode: 'codex', prompt: 'page 1' } });
await waitFor(() => stubs.generateImageCodex.mock.calls.length === 1);
@@ -4318,6 +4348,9 @@ describe('provider quota cooldowns', () => {
expect(mediaJobQueue.getJob(second.jobId).status).toBe('queued');
expect(stubs.generateImageCodex).toHaveBeenCalledTimes(1);
expect(mediaJobQueue.getJob(second.jobId).statusMsg).toMatch(/resumes at /);
+ // Holding for the provider's quota window is the designed handling: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('codex quota exhausted — holding queued codex renders'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('quota exhausted'));
});
it('keeps one hold message for the window, then promotes the job without it once the reset passes', async () => {
diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.js
index b4dc85ba0b..75fdc062f3 100644
--- a/server/services/memoryEmbeddings.js
+++ b/server/services/memoryEmbeddings.js
@@ -298,7 +298,7 @@ export async function generateEmbedding(text) {
if (result.ok) return result.data.data?.[0]?.embedding || null;
if (result.overflow && maxChars > 500) {
maxChars = Math.floor(maxChars / 2); // undershoot — shrink and retry
- console.warn(`⚠️ Embedding input over context; retrying at ${maxChars} chars`);
+ console.log(`🔁 Embedding input over context; retrying at ${maxChars} chars`);
continue;
}
console.error(`❌ Embedding generation failed: ${result.error}`);
@@ -339,7 +339,7 @@ export async function generateBatchEmbeddings(texts) {
if (result.overflow) {
// One member still overflowed — re-embed each individually so the rest
// aren't lost to a single oversized input.
- console.warn('⚠️ Batch embedding over context; falling back to per-item embedding');
+ console.log('🔁 Batch embedding over context; falling back to per-item embedding');
const out = [];
for (const t of texts) out.push(await generateEmbedding(t));
return out;
diff --git a/server/services/memoryEmbeddings.test.js b/server/services/memoryEmbeddings.test.js
index 5c51174ab2..86ec73bcac 100644
--- a/server/services/memoryEmbeddings.test.js
+++ b/server/services/memoryEmbeddings.test.js
@@ -183,8 +183,13 @@ describe('memoryEmbeddings — context-budget truncation + overflow retry', () =
it('shrinks and retries when the backend still reports a context overflow', async () => {
wireFetch([contextOverflow, embedOk]);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const emb = await embeddings.generateEmbedding('x'.repeat(50000));
+ // The shrink-and-retry is the designed handling of an over-long input: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Embedding input over context; retrying at'));
+ expect(warn).not.toHaveBeenCalled();
expect(emb).toEqual([0.1, 0.2, 0.3]);
const calls = embedCalls();
@@ -220,8 +225,12 @@ describe('memoryEmbeddings — context-budget truncation + overflow retry', () =
it('batch: falls back to per-item embedding when the batch overflows', async () => {
// Batch POST overflows; then each of the 2 items embeds individually.
wireFetch([contextOverflow, embedOk, embedOk]);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const out = await embeddings.generateBatchEmbeddings(['a', 'b']);
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('falling back to per-item embedding'));
+ expect(warn).not.toHaveBeenCalled();
expect(out).toEqual([[0.1, 0.2, 0.3], [0.1, 0.2, 0.3]]);
expect(embedCalls().length).toBe(3);
diff --git a/server/services/musicVideo/autonomousSuno.js b/server/services/musicVideo/autonomousSuno.js
index 6f4190a34f..1e8f0fc828 100644
--- a/server/services/musicVideo/autonomousSuno.js
+++ b/server/services/musicVideo/autonomousSuno.js
@@ -86,7 +86,7 @@ async function sunoRefusalSignals(page) {
}
// An older Suno UI may lack one of the Advanced options: skip it, but say so.
-const skipped = (control) => console.warn(`⚠️ ${LABEL}: ${control} not found — continuing without it`);
+const skipped = (control) => console.log(`⏭️ ${LABEL}: ${control} not found — continuing without it`);
/**
* The brief's optional Advanced-form controls (model version, exclude styles,
diff --git a/server/services/musicVideo/autonomousSuno.test.js b/server/services/musicVideo/autonomousSuno.test.js
index 69a66e223f..acc5ea1dc8 100644
--- a/server/services/musicVideo/autonomousSuno.test.js
+++ b/server/services/musicVideo/autonomousSuno.test.js
@@ -198,13 +198,16 @@ describe('submitSunoSong', () => {
expect(cleared.fills['input[placeholder="Exclude styles"]']).toBe('');
});
- it('warns and still creates the song when the version menu lacks the model or an older UI lacks the controls', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ it('notes the skip and still creates the song when the version menu lacks the model or an older UI lacks the controls', async () => {
+ // An older Suno UI lacking an optional control is a designed skip: stdout, never stderr.
+ const warn = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const stderr = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const page = fakePage({ options: { version: 'v5', menuItems: ['v4.5 Pro', 'v5 Pro'], expanded: true, gender: null } });
await submitSunoSong(page, { ...fields, model: 'v9', vocalGender: 'male' }, { sleep: noSleep });
expect(page.actions).toEqual(['open-version-menu', 'key:Escape', 'gender:male', 'create']);
expect(warn).toHaveBeenCalledWith(expect.stringMatching(/model v9 in the version menu/));
+ expect(stderr).not.toHaveBeenCalled();
warn.mockClear();
const older = fakePage();
@@ -214,8 +217,10 @@ describe('submitSunoSong', () => {
expect.stringMatching(/model version menu/), expect.stringMatching(/More Options/),
expect.stringMatching(/Exclude styles/), expect.stringMatching(/Vocal Gender row/), expect.stringMatching(/Max Mode row/),
]);
+ expect(stderr).not.toHaveBeenCalled();
} finally {
warn.mockRestore();
+ stderr.mockRestore();
}
});
diff --git a/server/services/ollamaAgentContext.js b/server/services/ollamaAgentContext.js
index 9df48677ce..ac7e91195c 100644
--- a/server/services/ollamaAgentContext.js
+++ b/server/services/ollamaAgentContext.js
@@ -142,6 +142,6 @@ export async function dropUnsupportedOllamaThinking(provider, model, effort = nu
if (!await ollamaModelRejectsThinking(provider, model)) return keep
const { effort: _requestedEffort, thinking: _requestedThinking, ...rest } = provider
- console.warn(`⚠️ ${model} does not support thinking — running without a reasoning effort`)
+ console.log(`⏭️ ${model} does not support thinking — running without a reasoning effort`)
return { provider: { ...rest, thinking: false }, effort: null, dropped: true }
}
diff --git a/server/services/ollamaAgentContext.test.js b/server/services/ollamaAgentContext.test.js
index 79d39d055d..bfc53cb05f 100644
--- a/server/services/ollamaAgentContext.test.js
+++ b/server/services/ollamaAgentContext.test.js
@@ -101,11 +101,15 @@ describe('dropUnsupportedOllamaThinking', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(console, 'warn').mockImplementation(() => {})
+ vi.spyOn(console, 'log').mockImplementation(() => {})
})
it('drops the effort when the model reports no thinking capability', async () => {
getModelCapabilities.mockResolvedValue(['completion', 'vision'])
const result = await dropUnsupportedOllamaThinking({ ...opencodeOllama, effort: 'medium' }, 'gemma3:27b', 'medium')
+ // The model lacking a capability is a designed fallback, not a fault: stdout.
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('gemma3:27b does not support thinking'))
+ expect(console.warn).not.toHaveBeenCalled()
expect(result.dropped).toBe(true)
expect(result.effort).toBeNull()
expect(result.provider.effort).toBeUndefined()
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 9869607a60..a1f08d209f 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -1483,7 +1483,7 @@ async function pullModel(modelId, onProgress) {
// the transient network class, and only while attempts remain.
if (attempt >= PULL_MAX_ATTEMPTS || !isTransientPullError(lastError)) break
const delayMs = PULL_RETRY_BASE_DELAY_MS * attempt
- console.warn(`🔁 Ollama pull ${modelId} hit transient error "${lastError}" (attempt ${attempt}/${PULL_MAX_ATTEMPTS}); retrying in ${delayMs}ms`)
+ console.log(`🔁 Ollama pull ${modelId} hit transient error "${lastError}" (attempt ${attempt}/${PULL_MAX_ATTEMPTS}); retrying in ${delayMs}ms`)
if (typeof onProgress === 'function') onProgress({ status: 'retrying after network error', percent: null, retrying: true })
await sleep(delayMs)
}
diff --git a/server/services/ollamaManager.test.js b/server/services/ollamaManager.test.js
index c2a278a1c4..afe3260759 100644
--- a/server/services/ollamaManager.test.js
+++ b/server/services/ollamaManager.test.js
@@ -219,6 +219,8 @@ describe('ollamaManager.pullModel transient-error retry', () => {
it('retries a mid-stream {"error":"EOF"} frame and succeeds on a later attempt', async () => {
const pullModel = await loadPullModel()
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const { pullUrls } = stubFetch([
makeStreamResponse([{ status: 'pulling manifest' }, { status: 'downloading', total: 100, completed: 40 }, { error: 'EOF' }]),
makeStreamResponse([{ status: 'downloading', total: 100, completed: 100 }, { status: 'success' }])
@@ -228,6 +230,9 @@ describe('ollamaManager.pullModel transient-error retry', () => {
expect(result).toEqual({ success: true, modelId: 'smollm:135m' })
expect(pullUrls).toHaveLength(2) // one retry
+ // The bounded retry is the designed handling of a dropped download: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Ollama pull smollm:135m hit transient error'))
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('hit transient error'))
})
it('retries a dropped-connection read rejection (undici "terminated")', async () => {
diff --git a/server/services/prWatcher.js b/server/services/prWatcher.js
index 8214c15e62..a24a8621fc 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -906,7 +906,7 @@ async function queuedReceiptIds(appId) {
async function armHandoffFollowUp(appId, receiptId) {
if (!receiptId || !(await queuedReceiptIds(appId)).has(receiptId)) return;
if (!handoffFollowUpGate) {
- console.warn(`⏸️ Handoff follow-up for app ${appId} not armed: CoS daemon is stopped; the timer sweep owns the entry`);
+ console.log(`⏸️ Handoff follow-up for app ${appId} not armed: CoS daemon is stopped; the timer sweep owns the entry`);
return;
}
const deadline = Date.now() + HANDOFF_FOLLOW_UP_CAP_MS;
@@ -932,7 +932,7 @@ function scheduleHandoffFollowUp(appId, poller) {
// Still bounded when every poll throws: the latest receipt's cap ends it.
if (Date.now() >= Math.max(...poller.receipts.values())) {
handoffFollowUps.delete(appId);
- console.warn(`⏸️ Handoff follow-up for app ${appId} reached its cap; the timer sweep owns its entries`);
+ console.log(`⏸️ Handoff follow-up for app ${appId} reached its cap; the timer sweep owns its entries`);
} else {
scheduleHandoffFollowUp(appId, poller);
}
@@ -947,11 +947,11 @@ async function pollHandoffFollowUp(appId, poller) {
if (handoffFollowUps.get(appId) !== poller) return;
if (blocked === 'daemon-stopped') {
handoffFollowUps.delete(appId);
- console.warn(`⏸️ Handoff follow-up for app ${appId} stopped: CoS daemon is stopped`);
+ console.log(`⏸️ Handoff follow-up for app ${appId} stopped: CoS daemon is stopped`);
return;
}
if (blocked) {
- console.warn(`⏸️ Handoff follow-up poll for app ${appId} skipped: ${blocked}`);
+ console.log(`⏸️ Handoff follow-up poll for app ${appId} skipped: ${blocked}`);
} else {
const result = await _sweepPendingMergeApp(appId);
// null: receiptSweep already logged the thrown failure.
@@ -971,7 +971,7 @@ async function pollHandoffFollowUp(appId, poller) {
if (poller.receipts.size === 0) {
handoffFollowUps.delete(appId);
if (expired) {
- console.warn(`⏸️ Handoff follow-up for app ${appId} reached its ${HANDOFF_FOLLOW_UP_CAP_MS / 60000}-minute cap; the timer sweep owns ${expired} entr${expired === 1 ? 'y' : 'ies'}`);
+ console.log(`⏸️ Handoff follow-up for app ${appId} reached its ${HANDOFF_FOLLOW_UP_CAP_MS / 60000}-minute cap; the timer sweep owns ${expired} entr${expired === 1 ? 'y' : 'ies'}`);
} else {
console.log(`✅ Handoff follow-up for app ${appId} done: every handed-off entry settled`);
}
diff --git a/server/services/privacySubjects.js b/server/services/privacySubjects.js
index e3e72c3e62..7b10d0e77e 100644
--- a/server/services/privacySubjects.js
+++ b/server/services/privacySubjects.js
@@ -295,7 +295,7 @@ export async function assertSubjectConsent(subjectId, { scope, action = 'this ac
assertKnownScope(scope);
const subject = await assertSubject(subjectId);
if (await hasActiveConsent(subject.id, scope)) return subject;
- console.warn(`⛔ Refused ${action} for privacy subject ${subject.id}: no active ${scope} consent`);
+ console.log(`🚫 Refused ${action} for privacy subject ${subject.id}: no active ${scope} consent`);
throw new ServerError(
`Privacy subject ${subject.id} has no active ${scope} consent — ${action} refused`,
{ status: 403, code: 'SUBJECT_CONSENT_REQUIRED', context: { scope } },
diff --git a/server/services/privacySubjects.test.js b/server/services/privacySubjects.test.js
index 985731106a..80be175e89 100644
--- a/server/services/privacySubjects.test.js
+++ b/server/services/privacySubjects.test.js
@@ -203,11 +203,16 @@ describe('consent gate — purpose-scoped (#8332)', () => {
it('a pii_vault-only subject is refused BOTH broker purposes', async () => {
useConsentRows([{ subjectId: 's2', scope: 'pii_vault' }]);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
await expect(assertSubjectConsent('s2', { scope: 'pii_vault' })).resolves.toMatchObject({ id: 's2' });
for (const scope of ['broker_scan', 'broker_optout']) {
await expect(assertSubjectConsent('s2', { scope, action: 'x' }))
.rejects.toMatchObject({ status: 403, code: 'SUBJECT_CONSENT_REQUIRED' });
}
+ // The guard refusing is its designed outcome (the 403 is the answer): stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Refused x for privacy subject s2: no active broker_scan consent'));
+ expect(warn).not.toHaveBeenCalled();
});
it('broker_scan unlocks the scan without unlocking submissions', async () => {
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 3545cd460b..2254f7c420 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -2480,13 +2480,25 @@ describe('peerSync', () => {
});
it('handles a network-level failure without throwing (returns pushed:false)', async () => {
- vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
- vi.mocked(peerFetch).mockRejectedValue(new Error('ECONNREFUSED'));
- const result = await pushRecordToPeer({
- id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
- });
- expect(result.pushed).toBe(false);
- expect(result.reason).toBe('network');
+ // The once-per-cause ledger would swallow the line if an earlier test already logged this cause.
+ __resetPushFailureLogForTests();
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockRejectedValue(new Error('ECONNREFUSED'));
+ const result = await pushRecordToPeer({
+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ });
+ expect(result.pushed).toBe(false);
+ expect(result.reason).toBe('network');
+ // An asleep or offline peer is routine: stdout, not stderr.
+ expect(logSpy.mock.calls.some(([line]) => /peerSync: push universe\/u1 .* unreachable/.test(line))).toBe(true);
+ expect(warnSpy).not.toHaveBeenCalled();
+ } finally {
+ logSpy.mockRestore();
+ warnSpy.mockRestore();
+ }
});
it('logs a rejected push once per peer and cause, then logs recovery', async () => {
@@ -5129,7 +5141,14 @@ describe('peerSync', () => {
const sub = await subscribePeer({
peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
}, { adoptedFromReverse: true });
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
const result = await pushRecordToPeer(sub);
+ // A peer that is merely behind is handled by the persisted block: stdout, not stderr.
+ expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("doesn't recognize the 'universe' record kind"));
+ expect(warnSpy).not.toHaveBeenCalled();
+ logSpy.mockRestore();
+ warnSpy.mockRestore();
expect(result.pushed).toBe(false);
expect(result.reason).toBe('peer-schema-behind');
expect(result.blockedBySchema).toBe(true);
diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.js
index 9a1f8065bb..359f39bbe9 100644
--- a/server/services/sharing/peerSyncPush.js
+++ b/server/services/sharing/peerSyncPush.js
@@ -181,7 +181,7 @@ function reportPushFailure(sub, peer, reason, detail) {
// An unreachable peer is routine (asleep, off the tailnet). Retryable
// failures schedule the bounded walk; a peer the probe has marked offline
// is left for `peer:online`. A peer that answered and refused is not retried.
- if (reason === 'network') console.warn(`⚠️ peerSync: push ${target} unreachable${suffix}`);
+ if (reason === 'network') console.log(`🔌 peerSync: push ${target} unreachable${suffix}`);
else console.error(`❌ peerSync: push ${target} rejected with ${reason}${suffix}`);
}
@@ -313,8 +313,9 @@ export async function pushRecordToPeer(sub, options = {}) {
// never explains. It clears on the next successful push once the peer
// upgrades (same recovery as the 409 path).
await persistSchemaVersionBlock(sub.id, { reason: 'peer-pre-feature' });
- console.warn(
- `⚠️ peerSync: ${peer.name || peer.instanceId} rejected push — its PortOS doesn't recognize the ` +
+ // Same class as a schema-version refusal: the peer is behind, the block is persisted, and re-tries pause.
+ console.log(
+ `⏸️ peerSync: ${peer.name || peer.instanceId} rejected push — its PortOS doesn't recognize the ` +
`'${sub.recordKind}' record kind yet. Re-tries pause until they upgrade.`,
);
return { pushed: false, reason: 'peer-schema-behind', blockedBySchema: true };
diff --git a/server/services/shell.js b/server/services/shell.js
index fe95a7defb..3783e36389 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -140,7 +140,7 @@ function refusedForSessionCap() {
if (!session.external) owned += 1;
}
if (owned < MAX_TOTAL_SESSIONS) return false;
- console.warn(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);
+ console.log(`🐚 Max total sessions reached (${MAX_TOTAL_SESSIONS})`);
return true;
}
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index af76e089f4..a3997d5283 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -111,6 +111,8 @@ describe('createShellSession', () => {
});
it('emits shell:error and returns null when max sessions reached', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
for (let i = 0; i < 20; i++) shell.createShellSession(makeSocket(`s${i}`));
const socket = makeSocket('over');
const id = shell.createShellSession(socket);
@@ -118,6 +120,9 @@ describe('createShellSession', () => {
expect(socket.emit).toHaveBeenCalledWith('shell:error', {
error: 'Max 20 shell sessions. Kill an existing session first.',
});
+ // The cap refusing a request is the answer the caller already got: stdout, not stderr.
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Max total sessions reached (20)'));
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('Max total sessions'));
});
it('does not throw when over-cap and socket is missing', () => {
diff --git a/server/services/updateChecker.js b/server/services/updateChecker.js
index e43a20fa35..907cbf4c6c 100644
--- a/server/services/updateChecker.js
+++ b/server/services/updateChecker.js
@@ -551,14 +551,14 @@ export function startUpdateScheduler() {
startupTimeout = setTimeout(() => {
startupTimeout = null;
checkForUpdate().catch(err => {
- console.warn(`⚠️ Update check failed: ${err.message}`);
+ console.log(`🔌 Update check failed: ${err.message}`);
});
}, STARTUP_DELAY_MS);
// Periodic checks
schedulerInterval = setInterval(() => {
checkForUpdate().catch(err => {
- console.warn(`⚠️ Update check failed: ${err.message}`);
+ console.log(`🔌 Update check failed: ${err.message}`);
});
}, CHECK_INTERVAL_MS);
diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.js
index e9addc7439..08742aae29 100644
--- a/server/services/updateChecker.test.js
+++ b/server/services/updateChecker.test.js
@@ -57,7 +57,8 @@ import {
updateEvents,
isUpdateInProgress,
setUpdateInProgress,
- recordUpdateResult
+ recordUpdateResult,
+ startUpdateScheduler
} from './updateChecker.js';
describe('compareSemver', () => {
@@ -987,3 +988,25 @@ describe('processUpdateMarker', () => {
expect(unlink).toHaveBeenCalledTimes(1);
});
});
+
+describe('startUpdateScheduler', () => {
+ it('reports a failed scheduled check on stdout: an unreachable GitHub is retried next interval, not a fault', async () => {
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ readJSONFile
+ .mockResolvedValueOnce({ lastCheck: null, latestRelease: null, ignoredVersions: [], updateInProgress: false, lastUpdateResult: null })
+ .mockResolvedValueOnce({ version: '1.26.0' });
+ execGh.mockRejectedValue(new Error('error connecting to api.github.com'));
+ try {
+ startUpdateScheduler();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Update check failed: error connecting to api.github.com'));
+ expect(warn).not.toHaveBeenCalled();
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/server/services/voice/bootstrap.js b/server/services/voice/bootstrap.js
index fbe9055ef4..819787d180 100644
--- a/server/services/voice/bootstrap.js
+++ b/server/services/voice/bootstrap.js
@@ -337,7 +337,7 @@ export const ensureToolCapableModel = async (cfg) => {
console.log(`🎙️ voice: fast tool-capable model ready — ${fastNew}`);
return { installed: fastNew };
}
- console.warn(`🎙️ voice: ${target} unavailable (${String(outcome?.reason || 'unknown').slice(0, 160)}) — trying next`);
+ console.log(`🎙️ voice: ${target} unavailable (${String(outcome?.reason || 'unknown').slice(0, 160)}) — trying next`);
}
console.warn(`🎙️ voice: exhausted ${backend.label} install chain ${chain.join(', ')} — set voice.llm.model explicitly in Settings`);
return { failed: chain };
diff --git a/server/services/voice/bootstrap.retirement.test.js b/server/services/voice/bootstrap.retirement.test.js
index c2858f5635..deca7d396e 100644
--- a/server/services/voice/bootstrap.retirement.test.js
+++ b/server/services/voice/bootstrap.retirement.test.js
@@ -107,6 +107,27 @@ it('stops at one message instead of walking the chain when the backend is unreac
warn.mockRestore();
});
+// A chain entry that will not install is the designed fallback to the next entry, not a fault.
+it('moves to the next chain entry on stdout when an install does not take', async () => {
+ vi.clearAllMocks();
+ const backend = fakeBackend({
+ listModels: vi.fn(async () => []),
+ install: vi.fn(async () => ({ ok: false, reason: 'registry refused' })),
+ });
+ getVoiceProvisioner.mockReturnValue(backend);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const outcome = await ensureToolCapableModel(toolsOn());
+
+ expect(outcome).toHaveProperty('failed');
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('unavailable (registry refused) — trying next'));
+ expect(warn.mock.calls.some(([line]) => line.includes('trying next'))).toBe(false);
+ // Exhausting the whole chain is a real failure and still reaches stderr.
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('exhausted'));
+ vi.restoreAllMocks();
+});
+
it('installs from the chain when the backend is reachable with nothing capable', async () => {
vi.clearAllMocks();
const backend = fakeBackend({
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 9a0f51390c..9c0db7695f 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -444,6 +444,9 @@ export async function forceRemoveWorktreeDir(repo, worktreePath, opts = {}) {
.catch(error => ({ removed: false, reason: error.message, warning: 'Checkout retained: repository reservation unavailable' }));
}
+// Hold reasons that mean the cleanup could not even decide, rather than a gate declining.
+const REMOVAL_FAULT_HOLDS = new Set(['worktree-ownership-unreadable', 'worktree-removal-refused']);
+
async function forceRemoveWorktreeDirAdmitted(repo, worktreePath, { label, log = 'remove', subject = worktreePath, verifyRemoval, beforeMutation = async () => {} } = {}) {
const logAll = label && log === 'all';
let lastFailure = null;
@@ -484,7 +487,13 @@ async function forceRemoveWorktreeDirAdmitted(repo, worktreePath, { label, log =
});
const outcome = removalOutcome(worktreePath, await probeWorktreeRemoval(repo, worktreePath), heldReason || lastFailure);
if (heldReason) outcome.reason = heldReason;
- if (!outcome.removed && label) console.warn(`⚠️ ${outcome.warning}`);
+ if (!outcome.removed && label) {
+ // A gate keeping the checkout is the cleanup working as designed (the warning
+ // says "retryable"); an unreadable registry or a removal Git refused is a fault.
+ const designedHold = heldReason && !REMOVAL_FAULT_HOLDS.has(heldReason);
+ if (designedHold) console.log(`⏸️ ${outcome.warning}`);
+ else console.warn(`⚠️ ${outcome.warning}`);
+ }
return outcome;
}
@@ -1794,7 +1803,8 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,
// deleting it would fail, and `removed: true` would tell the caller it may
// queue work onto a branch the old worktree still owns. Report the truth with
// a retryable warning; `merged` stays accurate for the publication outcome.
- console.warn(`⚠️ Worktree for ${agentId} was not removed — branch ${branchName} kept`);
+ // `forceRemoveWorktreeDir` above already reported why on the right stream.
+ console.log(`⏸️ Worktree for ${agentId} was not removed — branch ${branchName} kept`);
warnings.push(removal.warning);
return { merged, removed: false, cleanupIncomplete: true, uncommittedSaved: false, warnings };
}
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 1f9021f230..403b717778 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -132,6 +132,26 @@ describe('completed branch archival boundary', () => {
expect(beforeMutation).toHaveBeenCalledTimes(2);
expect(execGitMock.mock.calls.some(([args]) => args[0] === 'worktree' && args[1] === 'prune')).toBe(false);
});
+ it('reports a caller gate that keeps the checkout on stdout, since that cleanup is retryable by design', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(await forceRemoveWorktreeDir('/repo', '/checkout', { label: 'cleanup', verifyRemoval: async () => 'retirement-forge-unavailable' }))
+ .toMatchObject({ removed: false, reason: 'retirement-forge-unavailable' });
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Worktree cleanup incomplete'));
+ expect(warn).not.toHaveBeenCalled();
+ });
+ it('warns when Git itself refused to remove a checkout that survives', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ execGitMock.mockImplementation(async args => {
+ if (args[0] === 'worktree' && args[1] === 'remove') throw new Error('Permission denied');
+ return { stdout: '', exitCode: 0 };
+ });
+ expect(await forceRemoveWorktreeDir('/repo', '/checkout', { label: 'cleanup', verifyRemoval: async () => null }))
+ .toMatchObject({ removed: false, reason: 'worktree-removal-refused' });
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Worktree cleanup incomplete'));
+ expect(log).not.toHaveBeenCalledWith(expect.stringContaining('Worktree cleanup incomplete'));
+ });
it.each(['archive failure', 'archive verification failure'])('never sends the deletion when there is an %s', async failure => {
if (failure === 'archive failure') preserveBranchMock.mockRejectedValue(new Error('archive disk full'));
else preserveBranchMock.mockResolvedValue({ archiveDir: '/branch-archive', verify: async () => false });
@@ -939,6 +959,8 @@ describe('removeWorktree identity, dirt and branch preservation', () => {
afterEach(() => { rm.mockReset().mockResolvedValue(undefined); });
it('reports removed:false with a retryable warning, keeps the branch, and flags cleanupIncomplete', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
present();
failRemoval();
@@ -946,6 +968,10 @@ describe('removeWorktree identity, dirt and branch preservation', () => {
expect(result).toMatchObject({ merged: false, removed: false, cleanupIncomplete: true });
expect(result.warnings.join(' ')).toMatch(/cleanup incomplete.*directory still present.*retryable/);
+ // Git refusing the removal is a fault, so the cleanup warning reaches stderr; the "branch kept"
+ // consequence is already explained by it and follows on stdout.
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('Worktree cleanup incomplete'));
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Worktree for agent-x was not removed — branch cos/task-1/agent-x kept'));
expect(execGitMock.mock.calls.some(([args]) => args[0] === 'push' && args.includes(':refs/heads/cos/task-1/agent-x'))).toBe(false);
});