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

Say what operator logs actually observed

[._.]/ Adam Eivyd7e2e0aceaf2
diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.js
index 15c1c808e9..f1c6acb32e 100644
--- a/server/lib/agentSentinel.js
+++ b/server/lib/agentSentinel.js
@@ -92,6 +92,25 @@ export function doneSentinelAgentId(name) {
*
* Pure: callers do their own `existsSync` / read.
*/
+const STARTUP_SENTINEL_REASONS = new Set(['paste-not-rendered', 'tui-not-ready']);
+
+/**
+ * The operator line for a TUI that ended without its completion sentinel.
+ *
+ * A startup failure never received the prompt, so the missing file is a
+ * consequence, not a second fault. Naming it as "finalized with no sentinel"
+ * reads as an agent that finished the task and skipped the done-signal.
+ */
+export function missingSentinelLogMessage({ agentId, reason, sentinelPath, mergeGateReprompted = false }) {
+ if (STARTUP_SENTINEL_REASONS.has(reason)) {
+ return `${agentId} startup failed (${reason}) before a completion sentinel could be written`;
+ }
+ if (mergeGateReprompted) {
+ return `${agentId} finalized (${reason}) without re-writing its sentinel after the merge-gate nudge — expected ${sentinelPath}`;
+ }
+ return `${agentId} finalized (${reason}) with no completion sentinel — expected ${sentinelPath}`;
+}
+
export function doneSentinelPath(workspacePath, agentId) {
if (!workspacePath || typeof workspacePath !== 'string') return null;
return join(workspacePath, doneSentinelName(agentId));
diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.js
index 52476f31df..70ea037739 100644
--- a/server/lib/agentSentinel.test.js
+++ b/server/lib/agentSentinel.test.js
@@ -1,6 +1,26 @@
import { describe, it, expect } from 'vitest';
import { join } from 'path';
-import { DONE_SENTINEL_NAME, doneSentinelAgentId, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';
+import { DONE_SENTINEL_NAME, doneSentinelAgentId, doneSentinelName, doneSentinelPath, extractSentinelPayloadFromTranscript, missingSentinelLogMessage, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';
+
+describe('missingSentinelLogMessage', () => {
+ it('names a startup failure as the reason the sentinel was never written', () => {
+ const message = missingSentinelLogMessage({
+ agentId: 'agent-1',
+ reason: 'paste-not-rendered',
+ sentinelPath: '/work/.agent-done-agent-1',
+ });
+ expect(message).toContain('startup failed (paste-not-rendered)');
+ expect(message).not.toContain('finalized');
+ });
+
+ it('keeps the expected path when a run that was working exits without the sentinel', () => {
+ expect(missingSentinelLogMessage({
+ agentId: 'agent-1',
+ reason: 'idle-timeout',
+ sentinelPath: '/work/.agent-done-agent-1',
+ })).toContain('expected /work/.agent-done-agent-1');
+ });
+});
describe('agentSentinel', () => {
it('exposes the sentinel filename', () => {
diff --git a/server/lib/goalFidelity.js b/server/lib/goalFidelity.js
index f4f743d75b..097fceeb4c 100644
--- a/server/lib/goalFidelity.js
+++ b/server/lib/goalFidelity.js
@@ -208,6 +208,17 @@ export function goalFidelityHoldsRun(review) {
return review?.verdict === GOAL_FIDELITY_HOLD_VERDICT;
}
+/**
+ * Marker for the one-line verdict log. A checkmark is only for `ship`.
+ * `fix-first` still records the run as a success, but it found something
+ * missing — logging it with the same mark as a clean ship reads as "all good".
+ */
+export function goalFidelityLogMarker(review) {
+ if (goalFidelityHoldsRun(review)) return '🎯';
+ if (review?.verdict === 'ship') return '✅';
+ return '🧩';
+}
+
/**
* One-line human summary of a verdict, for a log line, an agent card, or the
* Review Hub alert. Counts rather than the items themselves — the items are
diff --git a/server/lib/goalFidelity.test.js b/server/lib/goalFidelity.test.js
index 4834cfbc22..1103e1cb2b 100644
--- a/server/lib/goalFidelity.test.js
+++ b/server/lib/goalFidelity.test.js
@@ -4,6 +4,7 @@ import {
MAX_OBJECTIVE_CHARS,
formatGoalFidelitySummary,
goalFidelityHoldsRun,
+ goalFidelityLogMarker,
mergeOutcomeObjective,
mergeOutcomeReview,
normalizeGoalFidelityVerdict,
@@ -103,6 +104,14 @@ describe('goalFidelityHoldsRun', () => {
});
});
+describe('goalFidelityLogMarker', () => {
+ it('reserves the checkmark for a clean ship', () => {
+ expect(goalFidelityLogMarker({ verdict: 'ship' })).toBe('✅');
+ expect(goalFidelityLogMarker({ verdict: 'fix-first', missing: ['a'] })).toBe('🧩');
+ expect(goalFidelityLogMarker({ verdict: 'rethink', missing: ['a'] })).toBe('🎯');
+ });
+});
+
describe('formatGoalFidelitySummary', () => {
it('reports counts rather than the untrusted item text', () => {
expect(formatGoalFidelitySummary({ verdict: 'rethink', missing: ['a', 'b'], unrequested: ['c'] }))
diff --git a/server/lib/goalFidelityFollowUp.js b/server/lib/goalFidelityFollowUp.js
index 765857aaac..beb3905930 100644
--- a/server/lib/goalFidelityFollowUp.js
+++ b/server/lib/goalFidelityFollowUp.js
@@ -213,6 +213,33 @@ function reviewedChange(context) {
return `## Reviewed change\nBase commit: \`${context.base}\`\nHead commit: \`${context.head}\`\nReproduce the reviewed change in this repository with \`git diff ${context.base}..${context.head}\`. Find the associated PR/MR and inspect its discussion, checks, and merge state; forge operations and audit results may live outside the diff.`;
}
+/**
+ * Why a finding must not be copied onto the project's tracker, or `null` when
+ * the publication record matches that tracker and repository.
+ *
+ * A local task's objective is the operator's own prose. Filing it would publish
+ * that prose. A fetched issue may return only to the tracker and repository it
+ * was read from. The sentences name which of those gates closed, because
+ * "no verified provenance" does not tell an operator whether the refusal was
+ * the normal local-task case or a repository mismatch.
+ */
+export function explainGoalFidelityPublicationRefusal({ publication, tracker, target } = {}) {
+ if (publication?.source !== 'tracker-issue') {
+ return 'the objective was not a fetched tracker issue, so nothing was published';
+ }
+ if (publication.tracker !== tracker) {
+ const from = publication.tracker || 'another tracker';
+ const onto = tracker || 'the configured';
+ return `the objective was fetched from ${from}, not this project's ${onto} tracker, so nothing was published`;
+ }
+ const sameHost = publication.webHost && publication.webHost === target?.webHost;
+ const sameRepo = publication.fullName && publication.fullName === target?.fullName;
+ if (!sameHost || !sameRepo) {
+ return 'the objective was fetched from a different repository than this project tracks, so nothing was published';
+ }
+ return null;
+}
+
/**
* Public investigation projection: objective, compared commits, and allegation.
* Only an objective fetched from the target tracker can cross this boundary:
diff --git a/server/lib/goalFidelityFollowUp.test.js b/server/lib/goalFidelityFollowUp.test.js
index 2b92dc78cb..8deab7c13d 100644
--- a/server/lib/goalFidelityFollowUp.test.js
+++ b/server/lib/goalFidelityFollowUp.test.js
@@ -4,6 +4,7 @@ import {
GOAL_FIDELITY_FOLLOW_UP_TRIGGERS,
buildGoalFidelityFollowUpTask,
buildGoalFidelityIssue,
+ explainGoalFidelityPublicationRefusal,
formatGoalFidelityFollowUpSummary,
goalFidelityFingerprint,
goalFidelityFollowUpApplies,
@@ -22,6 +23,36 @@ const review = (over = {}) => ({
...over,
});
+describe('explainGoalFidelityPublicationRefusal', () => {
+ const target = { webHost: 'github.com', fullName: 'acme/comics' };
+
+ it('names a local objective instead of a generic provenance failure', () => {
+ expect(explainGoalFidelityPublicationRefusal({ publication: null, tracker: 'github', target }))
+ .toMatch(/not a fetched tracker issue/);
+ });
+
+ it('names a tracker mismatch separately from a repository mismatch', () => {
+ expect(explainGoalFidelityPublicationRefusal({
+ publication: { source: 'tracker-issue', tracker: 'gitlab', webHost: 'github.com', fullName: 'acme/comics' },
+ tracker: 'github',
+ target,
+ })).toMatch(/fetched from gitlab/);
+ expect(explainGoalFidelityPublicationRefusal({
+ publication: { source: 'tracker-issue', tracker: 'github', webHost: 'github.com', fullName: 'other/repo' },
+ tracker: 'github',
+ target,
+ })).toMatch(/different repository/);
+ });
+
+ it('allows a publication that matches the destination', () => {
+ expect(explainGoalFidelityPublicationRefusal({
+ publication: { source: 'tracker-issue', tracker: 'github', webHost: 'github.com', fullName: 'acme/comics' },
+ tracker: 'github',
+ target,
+ })).toBeNull();
+ });
+});
+
describe('resolveGoalFidelityFollowUp', () => {
it('is null when neither action is configured, so a disabled install pays nothing', () => {
expect(resolveGoalFidelityFollowUp(null)).toBeNull();
diff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.js
index 20d32236ab..fef0ea331b 100644
--- a/server/lib/primaryCheckoutGuard.js
+++ b/server/lib/primaryCheckoutGuard.js
@@ -606,7 +606,12 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
// run's movement, and the prose ("16 new commits") badly overstates what moved.
// Say so instead of quoting a number that no longer means what it says.
const baselineRewritten = !(await isAncestorOrSame(baseline.path, baseline.head, current.head));
- const message = formatDriftMessage({ baseline, current, commitCount, baselineRewritten });
+ const driftFacts = { baseline, current, commitCount, baselineRewritten };
+ const message = formatDriftMessage(driftFacts);
+ const unattributedMessage = async () => withCommitSubject(
+ formatDriftMessage({ ...driftFacts, attributed: false }),
+ await commitSubject(baseline.path, current.head),
+ );
// Second gate (#3703): stranded commits are only a failure if THIS agent could
// have produced them. Attribution runs whenever there is (or should be) a
@@ -639,7 +644,7 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
// being off `main` still matters — the next spawn baselines against it) but never
// a failure, per the fail-open asymmetry in the module header.
if (strandedCount === 0 && current.branch !== agentBranch) {
- return { drifted: false, unattributed: true, baseline, current, commitCount, unpushedCount, message };
+ return { drifted: false, unattributed: true, baseline, current, commitCount, unpushedCount, message: await unattributedMessage() };
}
if (strandedCount === null || strandedCount > 0) {
const attributed = await isDriftAttributableToAgent(baseline.path, {
@@ -651,7 +656,7 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
baselineRewritten,
});
if (!attributed) {
- return { drifted: false, unattributed: true, baseline, current, commitCount, unpushedCount, message };
+ return { drifted: false, unattributed: true, baseline, current, commitCount, unpushedCount, message: await unattributedMessage() };
}
}
@@ -683,8 +688,14 @@ export async function detectPrimaryCheckoutDrift(baseline, { agentBranch = null
};
}
-/** Human-readable "what moved". Pure. */
-export function formatDriftMessage({ baseline, current, commitCount, baselineRewritten = false }) {
+/**
+ * Human-readable "what moved". Pure.
+ *
+ * `attributed: false` is the unattributed outcome: the checkout moved, and this
+ * run's branch does not contain the new commits. The lead must not accuse the
+ * worktree agent — the caller is about to say the movement was someone else's.
+ */
+export function formatDriftMessage({ baseline, current, commitCount, baselineRewritten = false, attributed = true }) {
const branchPart = current.branch === baseline.branch
? `branch ${current.branch}`
: `branch ${baseline.branch} → ${current.branch}`;
@@ -696,7 +707,28 @@ export function formatDriftMessage({ baseline, current, commitCount, baselineRew
// rather than passing it off as "N new commits".
? `baseline rewritten by a rebase; ${commitCount} commit${commitCount === 1 ? '' : 's'} since the abandoned baseline`
: `${commitCount} new commit${commitCount === 1 ? '' : 's'}`;
- return `Worktree agent mutated the primary checkout ${baseline.path}: ${branchPart}, HEAD ${short(baseline.head)} → ${short(current.head)} (${countPart})`;
+ const lead = attributed
+ ? `Worktree agent mutated the primary checkout ${baseline.path}`
+ : `Primary checkout ${baseline.path} moved during a worktree run`;
+ return `${lead}: ${branchPart}, HEAD ${short(baseline.head)} → ${short(current.head)} (${countPart})`;
+}
+
+/** One-line subject of `sha`, or '' when git cannot name it. Never throws. */
+async function commitSubject(repoPath, sha) {
+ if (!repoPath || !sha) return '';
+ const result = await execGit(
+ ['log', '-1', '--format=%s', sha],
+ repoPath,
+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },
+ ).catch(() => null);
+ const subject = firstLine(result);
+ if (!subject) return '';
+ const oneLine = subject.replace(/[\r\n"]/g, ' ').replace(/\s+/g, ' ').trim();
+ return oneLine.length > 80 ? `${oneLine.slice(0, 77)}…` : oneLine;
+}
+
+function withCommitSubject(message, subject) {
+ return subject ? `${message} — "${subject}"` : message;
}
/**
diff --git a/server/lib/primaryCheckoutGuard.test.js b/server/lib/primaryCheckoutGuard.test.js
index 59750075f2..9ebc6dfcec 100644
--- a/server/lib/primaryCheckoutGuard.test.js
+++ b/server/lib/primaryCheckoutGuard.test.js
@@ -147,6 +147,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('detectPrimaryCheckoutDrift', () => {
expect(verdict.category).toBe(PRIMARY_CHECKOUT_MUTATED_CATEGORY);
expect(verdict.commitCount).toBe(2);
// The message names the drifted branch and the commit count...
+ expect(verdict.message).toContain('Worktree agent mutated');
expect(verdict.message).toContain('main');
expect(verdict.message).toContain('2 new commits');
// ...and the fix names the agent branch plus the exact recovery command.
@@ -170,7 +171,9 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('detectPrimaryCheckoutDrift', () => {
expect(verdict.drifted).toBe(false);
expect(verdict.unattributed).toBe(true);
expect(verdict.unpushedCount).toBe(1);
- expect(verdict.message).toContain('main');
+ expect(verdict.message).toContain('moved during a worktree run');
+ expect(verdict.message).not.toContain('Worktree agent mutated');
+ expect(verdict.message).toContain('someone else\'s commit');
expect(verdict.suggestedFix).toBeUndefined();
});
@@ -738,10 +741,17 @@ describe('prose helpers', () => {
const current = { path: '/example/repo', branch: 'main', head: 'b'.repeat(40) };
it('singularizes a one-commit drift', () => {
+ expect(formatDriftMessage({ baseline, current, commitCount: 1 })).toContain('Worktree agent mutated');
expect(formatDriftMessage({ baseline, current, commitCount: 1 })).toContain('(1 new commit)');
expect(formatDriftRecovery({ current, commitCount: 1, agentBranch: null })).toContain('1 commit ');
});
+ it('does not accuse the worktree agent when the movement is unattributed', () => {
+ const message = formatDriftMessage({ baseline, current, commitCount: 1, attributed: false });
+ expect(message).toContain('moved during a worktree run');
+ expect(message).not.toContain('Worktree agent mutated');
+ });
+
it('falls back to origin/<branch> only when no upstream was resolved', () => {
expect(formatDriftRecovery({ current, commitCount: 1, agentBranch: null }))
.toContain('reset --hard origin/main');
diff --git a/server/lib/spawnCwd.js b/server/lib/spawnCwd.js
index 1f86a50ea8..5953001206 100644
--- a/server/lib/spawnCwd.js
+++ b/server/lib/spawnCwd.js
@@ -83,10 +83,14 @@ export function resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId
* @param {string|undefined|null} workspacePath - caller-supplied workspace (app repoPath)
* @param {string} fallbackRoot - directory to use when no workspace was supplied
* @param {string} [label] - short run/agent identifier used in the log line
+ * @param {{ log?: boolean }} [options] - `log: false` when the caller logs the
+ * final directory itself. An agent prep resolves the source repo here and
+ * then may replace it with a worktree; logging the source as "cwd" reads as
+ * if the agent were about to edit the primary checkout.
* @returns {string} the directory to hand to `spawn`/`pty.spawn` as `cwd`
* @throws {Error} when `workspacePath` was supplied but is not an existing directory
*/
-export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run') {
+export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run', { log = true } = {}) {
// "Nothing was supplied" and "something blank was supplied" are different
// answers and must not collapse. `repoPath` is validated only as
// `z.string().min(1)`, so an app can hold " " — that is a MISCONFIGURED
@@ -96,7 +100,7 @@ export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run') {
// the schema still lets through.
const supplied = typeof workspacePath === 'string' && workspacePath.length > 0;
if (!supplied) {
- console.log(`📂 ${label} cwd: ${fallbackRoot} (no workspace selected)`);
+ if (log) console.log(`📂 ${label} cwd: ${fallbackRoot} (no workspace selected)`);
return fallbackRoot;
}
@@ -128,7 +132,7 @@ export function resolveSpawnCwd(workspacePath, fallbackRoot, label = 'run') {
);
}
- console.log(`📂 ${label} cwd: ${requested}`);
+ if (log) console.log(`📂 ${label} cwd: ${requested}`);
return requested;
}
diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.js
index dbe6840f1f..616a7f9da9 100644
--- a/server/lib/spawnCwd.test.js
+++ b/server/lib/spawnCwd.test.js
@@ -52,6 +52,12 @@ describe('resolveSpawnCwd', () => {
expect(logSpy.mock.calls.flat().join('\n')).toContain('no workspace selected');
});
+ it('can validate without logging when the caller reports the final directory', () => {
+ logSpy.mockClear();
+ expect(resolveSpawnCwd(dir, '/fallback', 'Task sys-1', { log: false })).toBe(dir);
+ expect(logSpy).not.toHaveBeenCalled();
+ });
+
// The #3180 regression: a workspace was requested but does not exist. The old
// behavior spawned in the PortOS root anyway, so the agent's relative file
// writes landed in the wrong repo with no error anywhere.
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 55bcc933d4..e699b5a820 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -47,6 +47,7 @@ import {
MAX_OBJECTIVE_CHARS,
formatGoalFidelitySummary,
goalFidelityHoldsRun,
+ goalFidelityLogMarker,
isDependencyAuditSummaryDiff,
mergeOutcomeObjective,
mergeOutcomeReview,
@@ -1201,7 +1202,7 @@ export async function finalizeAgent({
return { drifted: false };
});
if (drift.drifted) {
- emitLog('warn', `⚠️ ${drift.message} — reported by ${agentId}; PortOS will not repair it automatically`, {
+ emitLog('warn', `${drift.message} — reported by ${agentId}; PortOS will not repair it automatically`, {
agentId, taskId: task?.id, category: drift.category
});
} else if (drift.unattributed) {
@@ -1210,7 +1211,7 @@ export async function finalizeAgent({
// human's terminal, `update.sh`'s pull) moved it. Unreviewed commits on the
// primary are still worth surfacing, but this run did not cause them, so it is
// warn-logged WITHOUT downgrading an otherwise-successful run to a failure.
- emitLog('warn', `⚠️ ${drift.message} — not attributable to ${agentId}; surfacing without failing the run`, {
+ emitLog('warn', `${drift.message} — not attributable to ${agentId}; this run stays successful`, {
agentId, taskId: task?.id
});
} else if (drift.fastForwarded) {
@@ -1279,17 +1280,17 @@ export async function finalizeAgent({
const fidelity = verdict.success && !isPrivateSecurityTask(task)
? await evaluateGoalFidelity({ task, workspacePath, startedAt: runStartedAt })
.catch(err => {
- emitLog('warn', `⚠️ Goal-fidelity review failed for ${agentId}: ${err.message}`, { agentId });
+ emitLog('warn', `Goal-fidelity review failed for ${agentId}: ${err.message}`, { agentId });
return { verdict: null, review: null, error: err.message };
})
: { verdict: null, review: null, error: null };
const fidelityDowngrade = goalFidelityHoldsRun(fidelity.review);
if (fidelity.review) {
- emitLog(fidelityDowngrade ? 'warn' : 'info', `${fidelityDowngrade ? '🎯' : '✅'} ${formatGoalFidelitySummary(fidelity.review)} for ${agentId}`, {
+ emitLog(fidelityDowngrade ? 'warn' : 'info', `${goalFidelityLogMarker(fidelity.review)} ${formatGoalFidelitySummary(fidelity.review)} for ${agentId}`, {
agentId, taskId: task?.id, verdict: fidelity.verdict
});
} else if (fidelity.error) {
- emitLog('warn', `⚠️ Goal-fidelity review returned no verdict for ${agentId}: ${fidelity.error}`, { agentId, taskId: task?.id });
+ emitLog('warn', `Goal-fidelity review returned no verdict for ${agentId}: ${fidelity.error}`, { agentId, taskId: task?.id });
}
if (fidelityDowngrade) {
const analysis = goalFidelityAnalysis(fidelity.review);
@@ -1317,7 +1318,7 @@ export async function finalizeAgent({
const followUp = await import('./goalFidelityFollowUp.js')
.then(({ runGoalFidelityFollowUp }) => runGoalFidelityFollowUp({ agentId, task, review: fidelity.review, context: fidelity.context }))
.catch(err => {
- emitLog('warn', `⚠️ Goal-fidelity follow-up failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id });
+ emitLog('warn', `Goal-fidelity follow-up failed for ${agentId}: ${err.message}`, { agentId, taskId: task?.id });
return null;
});
if (followUp?.ran) {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 58f3c513c7..e0e4a69549 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -131,7 +131,7 @@ export async function spawnAgentForTask(task) {
return null;
}
if (outcome === SPAWN_DEDUP_SKIP) {
- console.log(`⚠️ Task ${task.id} already being spawned, skipping duplicate`);
+ console.warn(`⚠️ Task ${task.id} is already being spawned — ignoring this dequeue`);
return null;
}
return outcome;
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index c252ea9a68..6ee337d6cd 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -309,7 +309,7 @@ export async function verifyAgentRepoState({ agentId, task, agentState, success,
emitLog('info', `🔎 Repo state only partly readable for ${agentId} (${branchName}) — could not check: ${observed.unreadable.join(', ')}`, { agentId, branchName });
return { verified: false, skipReason: REPO_STATE_SKIPS.PROBE_INCOMPLETE, issues: [], observed, recoveryTaskId: null };
}
- emitLog('info', `🔎 Repo state verified clean for ${agentId} (${branchName})`, { agentId, branchName });
+ emitLog('info', `🔎 Agent branch ${branchName} verified clean for ${agentId}`, { agentId, branchName });
return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };
}
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index e619034fae..a56a83ec27 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -32,7 +32,7 @@
import { readFile } from 'fs/promises';
import { emitLog } from '../cosEvents.js';
import { HOST_SHUTDOWN_REASON } from '../../lib/hostShutdown.js';
-import { parseSentinelPayload } from '../../lib/agentSentinel.js';
+import { missingSentinelLogMessage, parseSentinelPayload } from '../../lib/agentSentinel.js';
import { SENTINEL_COMPLETION_MARKER } from '../../lib/agentOutputMarkers.js';
import { prClaimWasVerified } from '../../lib/prDisposition.js';
import { resolveMergeGateVerdict, buildMergeGateReprompt } from '../../lib/mergeGateContract.js';
@@ -939,9 +939,12 @@ export function createTuiSessionController({
// "never wrote one" would be a false reading of that path — and the
// remedy it points at is the opposite one (the nudge never landed).
if (sentinel.path && !terminatedByUser && !wroteSentinel) {
- emitLog('warn', mergeGateReprompted
- ? `⚠️ ${agentId} finalized (${reason}) without re-writing its sentinel after the merge-gate nudge — expected ${sentinel.path}`
- : `⚠️ ${agentId} finalized (${reason}) with no completion sentinel — expected ${sentinel.path}`, { agentId });
+ emitLog('warn', missingSentinelLogMessage({
+ agentId,
+ reason,
+ sentinelPath: sentinel.path,
+ mergeGateReprompted,
+ }), { agentId });
}
// output.txt has already been incrementally appended via the spooler;
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 32b451abf0..dd4fe18c5b 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -355,7 +355,10 @@ export async function prepareAgentWorkspace({ agentId, task }) {
// Reusing it is what keeps the two validation sites from drifting — an
// inline existsSync here did both of those wrong.
try {
- workspacePath = resolveSpawnCwd(workspacePath, ROOT_DIR, `Task ${task.id}`);
+ // The source repo is validated here and logged later, after a worktree (if
+ // any) replaces it. Logging it as the task cwd made every isolated run look
+ // like it was about to edit the primary checkout.
+ workspacePath = resolveSpawnCwd(workspacePath, ROOT_DIR, `Task ${task.id}`, { log: false });
} catch (err) {
const reason = `${err.message} (Task blocked before the agent started, so it could not write into the PortOS directory by mistake.)`;
emitLog('error', `❌ ${reason}`, { taskId: task.id, workspace: workspacePath });
diff --git a/server/services/cos.js b/server/services/cos.js
index e73036f1a9..df65b9a6bb 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1276,7 +1276,12 @@ export async function dequeueNextTask({ ignoreTaskId = null } = {}) {
await spawnDequeuePriority3IdleReview(ctx);
if (capacity.spawned > 0) {
- emitLog('info', `⚡ Dequeued ${capacity.spawned} task(s)`, { spawned: capacity.spawned, availableSlots });
+ const ids = capacity.spawnedTaskIds.join(', ');
+ emitLog('info', `⚡ Dequeued ${capacity.spawned} task(s): ${ids}`, {
+ spawned: capacity.spawned,
+ taskIds: capacity.spawnedTaskIds,
+ availableSlots,
+ });
}
}
diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.js
index be7c912b38..8ecdbd583a 100644
--- a/server/services/cosDequeue.js
+++ b/server/services/cosDequeue.js
@@ -78,6 +78,7 @@ export function createDequeueCapacity(state, {
const spawnProjectCounts = { ...agentsByProject };
const spawnLocalEndpointCounts = { ...localEndpointCounts };
+ const spawnedTaskIds = [];
let spawned = 0;
const admit = (task, ceiling, gateLocalEndpoint) => {
@@ -106,6 +107,7 @@ export function createDequeueCapacity(state, {
spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
const endpoint = resolveLocalEndpoint(task);
if (endpoint) spawnLocalEndpointCounts[endpoint] = (spawnLocalEndpointCounts[endpoint] || 0) + 1;
+ spawnedTaskIds.push(typeof task?.id === 'string' && task.id ? task.id : 'unknown-task');
spawned++;
};
@@ -121,6 +123,7 @@ export function createDequeueCapacity(state, {
// Live read of the running spawn count — a getter so callers always see the
// current total after trackSpawn mutations rather than a stale snapshot.
get spawned() { return spawned; },
+ get spawnedTaskIds() { return spawnedTaskIds; },
};
}
diff --git a/server/services/goalFidelityFollowUp.js b/server/services/goalFidelityFollowUp.js
index 5e0e3e418f..8c58c93ccc 100644
--- a/server/services/goalFidelityFollowUp.js
+++ b/server/services/goalFidelityFollowUp.js
@@ -72,6 +72,7 @@ import {
GOAL_FIDELITY_ISSUE_LABEL_SPEC,
buildGoalFidelityFollowUpTask,
buildGoalFidelityIssue,
+ explainGoalFidelityPublicationRefusal,
goalFidelityFingerprint,
goalFidelityFollowUpApplies,
goalFidelityIssueMarker,
@@ -287,13 +288,10 @@ async function fileFollowUpIssue({ task, review, fingerprint, context }) {
// Scrubbing token/email shapes cannot authorize publishing that content.
// Finalization grants this provenance only to a complete fetched claim
// objective, and it may return only to that same tracker and repository.
- const publication = context?.publication;
- if (publication?.source !== 'tracker-issue'
- || publication.tracker !== tracker
- || !publication.webHost || publication.webHost !== target?.webHost
- || !publication.fullName || publication.fullName !== target?.fullName) {
- return { issue: null, error: 'the reviewed objective has no verified provenance for this tracker; nothing was filed' };
- }
+ const publicationRefusal = explainGoalFidelityPublicationRefusal({
+ publication: context?.publication, tracker, target,
+ });
+ if (publicationRefusal) return { issue: null, error: publicationRefusal };
const exec = tracker === 'jira' ? null : await resolveForgeContext(app, tracker);
// The reachability probe runs before anything is read or created: on an
diff --git a/server/services/goalFidelityFollowUp.test.js b/server/services/goalFidelityFollowUp.test.js
index e3c87ef1b7..b1a5dcd314 100644
--- a/server/services/goalFidelityFollowUp.test.js
+++ b/server/services/goalFidelityFollowUp.test.js
@@ -363,7 +363,7 @@ describe('runGoalFidelityFollowUp — JIRA', () => {
settings({ fileIssue: true, queueTask: true });
const result = await run();
expect(result.issue).toBeNull();
- expect(result.issueError).toMatch(/verified provenance/);
+ expect(result.issueError).toMatch(/nothing was published/);
expect(searchIssues).not.toHaveBeenCalled();
expect(createTicket).not.toHaveBeenCalled();
expect(result.task).toMatchObject({ id: 'cos-9' });
@@ -486,7 +486,7 @@ describe('runGoalFidelityFollowUp — the queued task', () => {
const result = await runGoalFidelityFollowUp({ agentId: 'agent-1', task: { ...TASK, description: objective },
review: REVIEW, context: { base: CONTEXT.base, head: CONTEXT.head, objective } });
expect(result.issue).toBeNull();
- expect(result.issueError).toMatch(/verified provenance/);
+ expect(result.issueError).toMatch(/nothing was published/);
expect(execGh).not.toHaveBeenCalled();
expect(execGlab).not.toHaveBeenCalled();
expect(createTicket).not.toHaveBeenCalled();
@@ -503,7 +503,7 @@ describe('runGoalFidelityFollowUp — the queued task', () => {
const result = await runGoalFidelityFollowUp({ agentId: 'agent-1', task: TASK, review: REVIEW,
context: { ...CONTEXT, publication: { ...CONTEXT.publication, ...changed } } });
expect(result.issue).toBeNull();
- expect(result.issueError).toMatch(/verified provenance/);
+ expect(result.issueError).toMatch(/nothing was published/);
expect(execGh).not.toHaveBeenCalled();
expect(result.task).toMatchObject({ id: 'cos-9' });
});
diff --git a/server/services/instances.js b/server/services/instances.js
index a95ad37542..6f8f219949 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -211,6 +211,31 @@ function validName(name, fallback) {
return name.trim();
}
+// "NaN" and "undefined" are what a missing number or a missing value stringify
+// to. They are not peer names. The string "null" is left alone: a hostname can
+// actually be "null", and addPeer accepts it.
+const UNUSABLE_PEER_LABEL = /^(nan|undefined)$/i;
+
+/**
+ * The name to print for a peer in a server log.
+ *
+ * A missing name must not stringify as "NaN". Fall through host, address, then
+ * a short instance id so two peers in one sync line stay distinguishable.
+ */
+export function peerLogLabel(peer) {
+ const text = (value) => (typeof value === 'string' ? value.trim() : '');
+ const usable = (value) => Boolean(value) && !UNUSABLE_PEER_LABEL.test(value);
+ const name = text(peer?.name);
+ if (usable(name)) return name;
+ const host = text(peer?.host);
+ if (usable(host)) return host;
+ const address = text(peer?.address);
+ if (usable(address)) return address;
+ const id = text(peer?.instanceId);
+ if (usable(id)) return id.length > 12 ? `${id.slice(0, 8)}…` : id;
+ return 'unnamed peer';
+}
+
function isIPAddress(str) {
return net.isIP(str) !== 0;
}
diff --git a/server/services/instances.test.js b/server/services/instances.test.js
index 9d38d22a0a..03aa4d2606 100644
--- a/server/services/instances.test.js
+++ b/server/services/instances.test.js
@@ -64,6 +64,7 @@ import {
getPeers,
getAssignableInstances,
addPeer,
+ peerLogLabel,
removePeer,
updatePeer,
probePeer,
@@ -173,6 +174,20 @@ describe('instances.js', () => {
});
});
+ describe('peerLogLabel', () => {
+ it('does not stringify a missing name as NaN', () => {
+ expect(peerLogLabel({ name: 'NaN', host: 'peer-b.example', instanceId: 'abc123def456' })).toBe('peer-b.example');
+ expect(peerLogLabel({ name: NaN, address: '192.0.2.20' })).toBe('192.0.2.20');
+ expect(peerLogLabel({ instanceId: 'abc123def4567890' })).toBe('abc123de…');
+ expect(peerLogLabel({})).toBe('unnamed peer');
+ });
+
+ it('keeps a real name, including the hostname "null"', () => {
+ expect(peerLogLabel({ name: 'null', address: '192.0.2.10' })).toBe('null');
+ expect(peerLogLabel({ name: 'studio', instanceId: 'abc' })).toBe('studio');
+ });
+ });
+
describe('addPeer', () => {
it('persists the tailcat protocol without changing classic peer records', async () => {
readJSONFile.mockResolvedValue({ self: null, peers: [] });
diff --git a/server/services/shell.js b/server/services/shell.js
index b3f7957856..9bd5c79dff 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -825,7 +825,7 @@ export function resizeSession(sessionId, cols, rows) {
export function killSession(sessionId) {
const session = shellSessions.get(sessionId);
if (session) {
- console.log(`🐚 Killing shell session ${sessionId.slice(0, 8)}`);
+ console.log(`🐚 Killing shell session ${sessionId}`);
session.pty.kill();
shellSessions.delete(sessionId);
runHook('onExit', session, session.onExit, { exitCode: null, killed: true });
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index ae3e1f5b73..a3e19a5ad8 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -769,6 +769,15 @@ describe('killSession', () => {
it('returns false for an unknown session id', () => {
expect(shell.killSession('nope')).toBe(false);
});
+
+ it('logs the full session id', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const id = shell.createShellSession(makeSocket('owner'));
+ log.mockClear();
+ expect(shell.killSession(id)).toBe(true);
+ expect(log.mock.calls.flat().join('\n')).toContain(`Killing shell session ${id}`);
+ log.mockRestore();
+ });
});
describe('detachSocketSessions', () => {
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index b586e99ee6..33bae794fe 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -12,7 +12,7 @@ import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite, writeFileGuarded
import { createMutex } from '../lib/asyncMutex.js';
import { logFailureWithStack } from '../lib/failureLogging.js';
import { instanceEvents } from './instanceEvents.js';
-import { getPeers, resolveEffectiveCategories, updatePeer } from './instances.js';
+import { getPeers, peerLogLabel, resolveEffectiveCategories, updatePeer } from './instances.js';
import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instanceIdentity.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
import { peerFetch } from '../lib/peerHttpClient.js';
@@ -784,7 +784,7 @@ export async function syncWithPeer(peer) {
const categories = getEffectiveCategories(peer);
const enabledNames = Object.entries(categories).filter(([, on]) => on).map(([k]) => k);
- console.log(`🔄 Sync starting with ${peer.name || peerId}: categories=${enabledNames.join(',') || 'none'}`);
+ console.log(`🔄 Sync starting with ${peerLogLabel(peer)}: categories=${enabledNames.join(',') || 'none'}`);
emitSyncProgress({ phase: 'start', peerId });
// Read cursor snapshot outside lock so network I/O doesn't block other peers
@@ -851,7 +851,7 @@ export async function syncWithPeer(peer) {
enabledDataCats.map(cat =>
syncDataCategoryFromPeer(peer, peerId, cat, cachedChecksums, scopedInstanceId)
.catch(err => {
- logFailureWithStack(`⚠️ ${cat} sync with ${peer.name} failed`, err);
+ logFailureWithStack(`⚠️ ${cat} sync with ${peerLogLabel(peer)} failed`, err);
recordCategoryFailure(cat, err);
return { totalApplied: 0, checksum: null };
})
@@ -905,7 +905,7 @@ export async function syncWithPeer(peer) {
if (result.totalApplied > 0) parts.push(`${result.totalApplied} ${cat}`);
}
if (parts.length > 0) {
- console.log(`🔄 Synced with ${peer.name}: ${parts.join(', ')} changes`);
+ console.log(`🔄 Synced with ${peerLogLabel(peer)}: ${parts.join(', ')} changes`);
}
const totalApplied = brainResult.totalApplied + memoryResult.totalApplied
@@ -996,7 +996,7 @@ export async function syncAllPeers() {
const online = peers.filter(p => p.enabled && hasAnySyncEnabled(p) && p.status === 'online' && p.instanceId);
if (online.length > 0) {
- const names = online.map(p => p.name || p.instanceId).join(', ');
+ const names = online.map(p => peerLogLabel(p)).join(', ');
console.log(`🔄 Sync cycle: ${online.length} peer${online.length === 1 ? '' : 's'} online (${names})`);
}
@@ -1059,7 +1059,7 @@ export function initSyncOrchestrator() {
peerOnlineHandler = (peer) => {
if (!hasAnySyncEnabled(peer)) return;
syncWithPeer(peer).catch(err => {
- logFailureWithStack(`❌ Sync with ${peer.name} failed`, err);
+ logFailureWithStack(`❌ Sync with ${peerLogLabel(peer)} failed`, err);
});
};
instanceEvents.on('peer:online', peerOnlineHandler);
diff --git a/server/services/voice/proactiveSpeech.js b/server/services/voice/proactiveSpeech.js
index a0ee3965bf..913e4af921 100644
--- a/server/services/voice/proactiveSpeech.js
+++ b/server/services/voice/proactiveSpeech.js
@@ -108,7 +108,12 @@ export const speakProactive = async ({ io, text, priority = 'normal', source = '
: 0;
const decision = shouldSpeak(cfg, nowMinutes, { solicited });
if (!decision.ok) {
- console.log(`🔕 voice: proactive suppressed (${decision.reason}) "${trimmed.slice(0, 60)}"`);
+ // Voice off, or proactive speech off, is the install's steady configuration.
+ // Logging it on every task dequeue drowns the server log in lines that
+ // describe a choice already made. Quiet hours and oversized text are events.
+ if (decision.reason !== 'voice-disabled' && decision.reason !== 'proactive-disabled') {
+ console.log(`🔕 voice: proactive suppressed (${decision.reason}) "${trimmed.slice(0, 60)}"`);
+ }
return decision;
}
diff --git a/server/services/voice/proactiveSpeech.test.js b/server/services/voice/proactiveSpeech.test.js
index cc1698733e..5afcf15a53 100644
--- a/server/services/voice/proactiveSpeech.test.js
+++ b/server/services/voice/proactiveSpeech.test.js
@@ -230,6 +230,46 @@ describe('speakProactive', () => {
}
});
+ it('stays quiet when voice or proactive speech is configured off', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { getVoiceConfig } = await import('./config.js');
+ try {
+ getVoiceConfig.mockResolvedValueOnce({ enabled: false });
+ const { io } = makeIo();
+ await speakProactive({ io, text: 'A new task is ready' });
+ expect(log.mock.calls.flat().join('\n')).not.toContain('voice:');
+
+ log.mockClear();
+ getVoiceConfig.mockResolvedValueOnce({
+ enabled: true,
+ llm: { proactive: { enabled: false } },
+ });
+ await speakProactive({ io, text: 'A new task is ready' });
+ expect(log.mock.calls.flat().join('\n')).not.toContain('voice:');
+ } finally {
+ log.mockRestore();
+ }
+ });
+
+ it('still logs a quiet-hours suppression', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ const { getVoiceConfig } = await import('./config.js');
+ const { getLocalParts } = await import('../../lib/timezone.js');
+ try {
+ getVoiceConfig.mockResolvedValueOnce({
+ enabled: true,
+ llm: { proactive: { enabled: true, quietHours: { enabled: true, start: '22:00', end: '07:00' } } },
+ });
+ getLocalParts.mockReturnValueOnce({ hour: 23, minute: 30 });
+ const { io } = makeIo();
+ const r = await speakProactive({ io, text: 'late night ping' });
+ expect(r.reason).toBe('quiet-hours');
+ expect(log.mock.calls.flat().join('\n')).toContain('quiet-hours');
+ } finally {
+ log.mockRestore();
+ }
+ });
+
it('suppresses when proactive disabled', async () => {
const { getVoiceConfig } = await import('./config.js');
getVoiceConfig.mockResolvedValueOnce({
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index b4bf8cdd86..5388a8024d 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -957,7 +957,16 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
console.log(`🌳 Preserving branch ${branchName} — merge evidence into ${target} was not established, kept so a retry can resume from it`);
warnings.push(`Branch ${branchName} preserved — merge evidence was not established; kept for a retry`);
} else {
- console.log(`🌳 Branch ${branchName} is already merged into ${target} — safe to delete`);
+ // An ancestor of the target includes a branch that never received a commit
+ // of its own. Calling that "already merged" reads as if the agent's work
+ // landed, which is how a startup failure's empty branch looks like churn.
+ const ahead = parseInt((await execGit(
+ ['rev-list', '--count', `${target}..${branchName}`],
+ sourceWorkspace,
+ ).catch(() => ({ stdout: '' }))).stdout.trim(), 10);
+ console.log(ahead === 0
+ ? `🌳 Branch ${branchName} has no commits beyond ${target} — deleting it`
+ : `🌳 Branch ${branchName} is already merged into ${target} — safe to delete`);
}
}
if (hasUnmergedCommits) {
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index e2c5d6fec1..6fd7beb070 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -1009,6 +1009,32 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {
expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);
});
+ it('calls an empty branch unused instead of already merged', async () => {
+ hasBranchMergeEvidenceMock.mockResolvedValue(true);
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ execGitMock.mockImplementation((args) => {
+ if (args[0] === 'rev-list') return Promise.resolve({ stdout: '0\n', stderr: '', exitCode: 0 });
+ if (args[0] === 'rev-parse' && args[1] === '--show-toplevel') {
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ }
+ if (args[0] === 'status') return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ if (args[0] === 'rev-parse' && args[1] === '--verify') {
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 1 });
+ }
+ return Promise.resolve({ stdout: '', stderr: '', exitCode: 0 });
+ });
+
+ await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', {
+ merge: false, preserveBranchWithCommits: true,
+ });
+
+ const lines = log.mock.calls.flat().join('\n');
+ expect(lines).toContain('has no commits beyond');
+ expect(lines).not.toContain('already merged');
+ expect(calledWith(['branch', '-D', 'cos/task-1/agent-x'])).toBe(true);
+ log.mockRestore();
+ });
+
it('fails CLOSED — keeps the branch when the merged check cannot be determined', async () => {
hasBranchMergeEvidenceMock.mockRejectedValue(new Error('unknown revision'));