Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep every TUI lifecycle line out of PR bodies by declaring each line once

Adam Eivyddb8d7f9935d
diff --git a/server/lib/README.md b/server/lib/README.md
index 7a48623908..7128662485 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -66,7 +66,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentOutcome.js` | Is a completed CoS agent record an OUTCOME, or a HANDOFF to its own continuation? `isAgentHandoff(agent)` — `result.resumed === true`, what `resumeAgent`/`relaunchAgent` stamps when it retires a record and requeues the SAME task, typically because the user swapped providers after a usage limit. Every consumer that read `result.success` as the verdict booked a phantom failure per swap — a red history card, a failed task in the daily report and weekly digest, a dented success rate, a quota-burn denial recorded against "Relaunched by user", a feature agent flipped to `error` — so the rule task-learning already applied lives here once. Reads only `result`, so `completeAgent`'s stats writer can ask it before the record exists. Keyed on a field `resumeAgent` has always written, so archived relaunches reclassify retroactively with no migration. Also carries `agentHandoffReason(agent)` — `metadata.pauseReason` when a continuation was queued, else `result.error`, so an abandoned run is not captioned as a deliberate provider swap — and `isQueuedContinuation(agent)`, the narrower check for a caller about to SKIP its own completion handling because it expects a continuation run to fire it instead: `isAgentHandoff` alone is not proof a continuation exists (a stranded pause retirement also stamps `resumed: true` with nothing requeued), so use this one there. `client/src/lib/agentOutcome.js` re-exports this file rather than copying it. |
| `cosAgentCompletionOrder.js` | Wire format + projection rule for the CoS archive completion-order sidecar (`data/cos/agents/index.order.json`). `projectArchivedAgent` reduces an archived record to its completion timestamp plus a completed / still-needs-feedback bitfield; `encodeCompletionOrder` / `decodeCompletionOrder` round-trip the versioned document, decoding anything unrecognized as empty so the readers repair it by re-reading the day. Shared by the runtime index and the one-shot backfill migration so the two cannot drift. |
| `cosAgentFeedback.js` | Pure shared eligibility, rating, update-target, and archive-locator predicates for durable CoS feedback actions; mirrored to the client so the queue and Agents tab use the server contract. |
-| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
+| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary), `LIFECYCLE_LINES` (every TUI lifecycle line, declared once as a tagged template — the emitter writes `LIFECYCLE_LINES.<id>(values)` and the reader's pattern derives from the same text), plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitters (`services/agentTuiSpawning.js` and its `agentTuiSpawning/` modules) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |
| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
| `agentRegistrationRecord.js` | The `registerAgent` payload one spawn writes, projected from its task — `buildAgentRegistration({ task, provider, … })` plus `resolveExecutionMode({ spawnHeadless, useRunner })` (`direct` / `runner` / `tui` / `runner-tui`, replacing a nested ternary chain). `agent.metadata` is a HAND-PICKED projection of `task.metadata`, never a spread: every downstream reader (run cards, `perpetualRefillPlan`, `declaresNoCommitCriterion`, the quota-burn continuation, `featureAgents`) sees the agent record alone, so an unlisted field does not survive the spawn — which is how `quotaBurnStepId` shipped persisted but unprojected (#6406) while this list was maintained inline in a 900-line orchestrator. Pure and synchronous: `primaryCheckoutBaseline` and `providerEndpoint` arrive as VALUES (both were `await`/service calls inline) keeping this leaf out of the agent-state and local-endpoint graphs. |
diff --git a/server/lib/agentOutputMarkers.js b/server/lib/agentOutputMarkers.js
index 0ee415ca07..c514b07170 100644
--- a/server/lib/agentOutputMarkers.js
+++ b/server/lib/agentOutputMarkers.js
@@ -11,40 +11,120 @@
*
* Downstream consumers that present the agent's words to a human — most
* importantly the generated PR description — must keep (2) and drop (1).
- * Both live here, pure and dependency-free, so the emitter
- * (`services/agentTuiSpawning.js`) and the readers can't drift apart: a marker
- * reworded on one side but not the other silently reverts the noise.
+ *
+ * Every lifecycle line is declared ONCE, in `LIFECYCLE_LINES` below: the emitter
+ * (`services/agentTuiSpawning.js` and its `agentTuiSpawning/` modules) writes
+ * `LIFECYCLE_LINES.<id>(values)`, and the reader's pattern is derived from that
+ * same template. There is no second list to keep in sync — the hand-kept regex
+ * list this replaced was written against nine messages and silently missed every
+ * one added after it (merge-gate, stall, OOM and permission nudges, host restart,
+ * provider-signal holds), so those leaked into PR bodies again.
+ * `agentOutputMarkers.test.js` fails on a literal `appendLine('…')` in an
+ * emitter, so a new line can only be added here.
*/
+import { escapeRegExp } from './textUtils.js';
+
/** Line `ingestDoneSentinel` appends immediately before the sentinel summary. */
export const SENTINEL_COMPLETION_MARKER = '✅ Agent signaled completion';
+// Fill a template's named slots. A missing value renders empty rather than
+// throwing: these run inside PTY/timer callbacks, where a throw is a crash.
+const formatter = (strings, keys) => (values = {}) => strings.reduce(
+ (line, text, i) => line + text + (i < keys.length ? String(values[keys[i]] ?? '') : ''),
+ '',
+);
+
/**
- * The PortOS-authored lifecycle status lines, matched on their actual message
- * shapes — deliberately NOT "any line starting with an emoji."
+ * Declare a lifecycle line as a tagged template whose interpolations NAME its
+ * per-run values: lifecycleLine`📟 TUI session started: ${'session'} (${'commandLine'})`.
*
+ * The reader matches on ALL of the template's fixed text, in order — the
+ * message's actual shape, deliberately NOT "any line starting with an emoji."
* The agent's own summary is markdown, but nothing stops it from writing a
* checklist line like `✅ Tests passed` or `⚠️ Known limitation: …` with no
* leading `-`. A bare emoji-prefix test would classify those as telemetry and
* silently delete them from the PR description — and a summary made mostly of
* such lines could shrink under `extractAgentSummary`'s minimum length and fall
- * all the way back to commit messages. Anchoring on the message text means only
- * lines PortOS actually emits can match.
- *
- * Kept in sync with `appendLine` in `services/agentTuiSpawning.js`. Not listed:
- * the generic `❌ <summary>` from `finishStartupFailure`, whose text comes from
- * its caller and so has no fixed shape to anchor on — it only fires on a startup
- * failure, which finalizes the agent unsuccessfully and never opens a PR.
+ * all the way back to commit messages. So a template with too little fixed text
+ * to tell it apart from an agent's line is refused at load.
+ */
+function lifecycleLine(strings, ...keys) {
+ const fixedText = strings.join('');
+ if ((fixedText.match(/\p{L}/gu) || []).length < 8) {
+ throw new Error(`Lifecycle line "${fixedText}" has too little fixed text to anchor on — declare it with emitOnlyLine`);
+ }
+ const format = formatter(strings, keys);
+ format.pattern = new RegExp(`^\\s*${strings.map(escapeRegExp).join('.*?')}`, 'u');
+ return Object.freeze(format);
+}
+
+/**
+ * A line whose text is entirely caller-supplied, so there is nothing fixed to
+ * anchor on: the reader leaves it alone rather than risk eating an agent's own
+ * `❌ …` line. Reserved for failures that finalize the run unsuccessfully,
+ * which never opens a PR.
*/
+function emitOnlyLine(strings, ...keys) {
+ const format = formatter(strings, keys);
+ format.pattern = null;
+ return Object.freeze(format);
+}
+
+/**
+ * Every status line PortOS writes into a TUI agent's output buffer, keyed by
+ * what it reports. Each entry is `(values) => line`, with `.pattern` the
+ * anchor the readers strip it by.
+ */
+export const LIFECYCLE_LINES = Object.freeze({
+ // Session start (services/agentTuiSpawning.js)
+ sessionStarted: lifecycleLine`📟 TUI session started: ${'session'} (${'commandLine'})`,
+ shellTabHint: lifecycleLine`💡 Open the Shell tab for live TUI output — this panel only logs lifecycle events.`,
+ spawnAdopted: lifecycleLine`🔁 Spawn acknowledgement lost (${'reason'}) — re-attached to the live runner PTY`,
+ startFailed: lifecycleLine`❌ Failed to start ${'provider'} TUI: ${'message'}`,
+ ollamaContextApplied: lifecycleLine`🪟 Reloaded Ollama at a ${'contextLength'}-token context window`,
+ // Ollama context warnings (lib/ollamaContext.js, services/ollamaAgentContext.js)
+ ollamaContextTooSmall: lifecycleLine`⚠️ ${'who'} is running on an Ollama window of ${'runtime'} — below the ${'minimum'} an agent harness usually needs. Set "Local num_ctx" in AI Providers to reload Ollama at a larger window (VRAM permitting), or the run will fail partway through.`,
+ ollamaReloadFailed: lifecycleLine`⚠️ Could not reload Ollama at a ${'contextLength'}-token window (${'error'}) — ${'who'} continues on the current window.`,
+ // Prompt delivery (services/agentTuiSpawning/sessionController.js)
+ promptPasted: lifecycleLine`📟 Prompt pasted into TUI session ${'session'} (${'reason'})${'attemptSuffix'}`,
+ pasteRetrying: lifecycleLine`⚠️ Paste verification failed — prompt text not found in buffer, retrying in ${'delayMs'}ms${'bootNote'}`,
+ pasteNeverLandedMcpBoot: lifecycleLine`❌ Paste never landed after ${'seconds'}s of waiting for MCP servers to boot — prompt never rendered`,
+ pasteNeverRendered: lifecycleLine`❌ Paste verification failed after ${'attempts'} attempts — prompt never rendered`,
+ startupDialogAnswered: lifecycleLine`📟 ${'message'} for session ${'session'}`,
+ handshakeResubmitted: lifecycleLine`🔁 Provider handshake still open — re-submitted the prompt (attempt ${'attempt'})`,
+ // Provider signals
+ providerFallbackSignal: lifecycleLine`⚡ Provider fallback signal: ${'message'}`,
+ providerSignalHolding: lifecycleLine`⏳ Provider signal (self-clearing): ${'message'} — holding the session up to ${'seconds'}s for it to clear`,
+ providerSignalCleared: lifecycleLine`✅ Provider signal cleared — ${'command'} is generating again; continuing the run`,
+ claudeSessionLimit: lifecycleLine`⏳ Claude Code session limit reached — sent /low-priority from the provider opt-in`,
+ claudeLowPriorityResubmitted: lifecycleLine`🔁 Re-submitted the task after enabling Claude low-priority mode`,
+ permissionDeclined: lifecycleLine`🚫 Declined ${'command'} permission prompt for ${'toolCall'} — an unattended run never widens its scope (${'count'}/${'max'})`,
+ // Continuation nudges
+ agyResumedNudged: lifecycleLine`🔁 agy resumed its conversation — nudged it to continue`,
+ agyRelaunched: lifecycleLine`🔁 agy exited to the shell — relaunched it on conversation ${'conversation'} (attempt ${'attempt'}/${'max'})`,
+ permissionDeclineNudged: lifecycleLine`🔁 Nudged the session to continue after declined permission prompt ${'declined'}`,
+ localOomPending: lifecycleLine`⏳ Local runtime out of GPU memory — will nudge the session to continue if it goes quiet`,
+ localOomNudged: lifecycleLine`🔁 Local runtime OOM — nudged the session to continue (attempt ${'attempt'}/${'max'})`,
+ truncationPending: lifecycleLine`⏳ Response was truncated before completion — will nudge the session to continue if it goes quiet`,
+ truncationNudged: lifecycleLine`🔁 Response was truncated before completion — nudged the session to continue (attempt ${'attempt'}/${'max'})`,
+ stallNudged: lifecycleLine`🔁 Session idle with the task unfinished — nudged it to continue (attempt ${'attempt'}/${'max'}, ${'sent'}/${'total'} this run)`,
+ stallGaveUp: lifecycleLine`🛑 Session still idle after ${'nudges'} nudges — it is not finishing; open the Shell tab to take it over`,
+ // Completion and interruption
+ mergeGateReprompted: lifecycleLine`🔁 Merge Gate not finished (PR still OPEN, no blocker stated) — re-prompted the session (1 nudge only)`,
+ hostRestarted: lifecycleLine`🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.`,
+ failure: emitOnlyLine`❌ ${'summary'}`,
+});
+
+// Lines an older PortOS wrote and this one no longer does. A buffer from such a
+// run can still be read after an upgrade, so its telemetry keeps being stripped.
+const RETIRED_LIFECYCLE_LINE_PATTERNS = [
+ /^\s*⏳ Max runtime reached — /u, // the max-runtime stop, removed in 2c594832a
+];
+
const LIFECYCLE_LINE_PATTERNS = [
- /^\s*📟 TUI session started: /u,
- /^\s*📟 Prompt pasted into TUI session /u,
- /^\s*📟 Auto-confirmed .+ folder-trust prompt for session /u,
- /^\s*💡 Open the Shell tab /u,
- /^\s*⚡ Provider fallback signal: /u,
- /^\s*⏳ Max runtime reached — /u,
- /^\s*⚠️?\s*Paste verification failed /u,
- /^\s*❌ Paste (?:never landed|verification failed) /u,
+ ...Object.values(LIFECYCLE_LINES).map(line => line.pattern).filter(Boolean),
+ ...RETIRED_LIFECYCLE_LINE_PATTERNS,
];
/**
diff --git a/server/lib/agentOutputMarkers.test.js b/server/lib/agentOutputMarkers.test.js
new file mode 100644
index 0000000000..926210c677
--- /dev/null
+++ b/server/lib/agentOutputMarkers.test.js
@@ -0,0 +1,38 @@
+import { describe, it, expect } from 'vitest';
+import { readdirSync, readFileSync } from 'fs';
+import { join, dirname, relative } from 'path';
+import { fileURLToPath } from 'url';
+
+const SERVER_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+
+// The TUI spawner and its extracted modules: everything that holds the output
+// spooler's `appendLine`.
+const EMITTER_FILES = [
+ join(SERVER_ROOT, 'services/agentTuiSpawning.js'),
+ ...readdirSync(join(SERVER_ROOT, 'services/agentTuiSpawning'))
+ .filter(name => name.endsWith('.js') && !name.endsWith('.test.js'))
+ .map(name => join(SERVER_ROOT, 'services/agentTuiSpawning', name)),
+];
+
+// `appendLine('…')`, `appendLine(`…`)`, or a ternary of literals.
+const LITERAL_APPEND = /appendLine\(\s*(?:[\w.?]+\s*\?\s*)?['"`][^\n]*/g;
+
+describe('lifecycle line catalog', () => {
+ // The hand-kept pattern list this catalog replaced matched nine messages and
+ // missed every one added after it, so the readers let them into PR bodies. A
+ // line written as a literal at the emitter is that drift starting again: it
+ // has no pattern, so nothing strips it.
+ it('every TUI lifecycle line is written through LIFECYCLE_LINES', () => {
+ const literals = [];
+ let catalogCalls = 0;
+ for (const file of EMITTER_FILES) {
+ const source = readFileSync(file, 'utf8');
+ catalogCalls += source.split('appendLine(LIFECYCLE_LINES.').length - 1;
+ for (const [call] of source.matchAll(LITERAL_APPEND)) {
+ literals.push(`${relative(SERVER_ROOT, file)}: ${call.trim().slice(0, 100)}`);
+ }
+ }
+ expect(catalogCalls, 'scan found no catalog writes — EMITTER_FILES is stale').toBeGreaterThan(20);
+ expect(literals, 'declare the line in LIFECYCLE_LINES (lib/agentOutputMarkers.js) and write it from there').toEqual([]);
+ });
+});
diff --git a/server/lib/gitOutputParsers.js b/server/lib/gitOutputParsers.js
index 5db5df7dc5..18ecbffb73 100644
--- a/server/lib/gitOutputParsers.js
+++ b/server/lib/gitOutputParsers.js
@@ -114,12 +114,12 @@ export function extractAgentSummary(output) {
let summaryLines;
if (markerIdx >= 0) {
- // Everything past the marker is the sentinel, appended verbatim and
- // contiguously by `ingestDoneSentinel` at the top of finalize — no other
- // `appendLine` runs after it. So take it as-is: filtering here could only
- // ever delete the agent's own words (a summary is free to contain a line
- // like "✅ Tests passed").
- summaryLines = lines;
+ // Past the marker is the sentinel summary — but not only that: a Merge Gate
+ // re-prompt (#5876) appends its own line after it and reopens the run, so a
+ // run that never writes a second sentinel ends with that line and any
+ // nudges after it. The strip matches PortOS's own message shapes only, so
+ // an agent's "✅ Tests passed" survives it.
+ summaryLines = stripLifecycleLines(lines);
} else {
// Find the last tool-call artifact line index.
// Everything after it is the agent's final summary.
diff --git a/server/lib/gitOutputParsers.test.js b/server/lib/gitOutputParsers.test.js
index 7faf0b1746..c20caa0d2e 100644
--- a/server/lib/gitOutputParsers.test.js
+++ b/server/lib/gitOutputParsers.test.js
@@ -8,6 +8,7 @@ import {
extractAgentSummary,
isBenignConcurrentFetchRefRace
} from './gitOutputParsers.js';
+import { LIFECYCLE_LINES } from './agentOutputMarkers.js';
describe('parseStatus', () => {
it('maps known porcelain codes to labels', () => {
@@ -179,8 +180,7 @@ describe('extractAgentSummary', () => {
expect(summary).toBe('Fixed the scan-report route so deep links resolve to the SPA.');
});
- // The sentinel is appended verbatim and nothing else writes after it, so a
- // summary is free to use emoji-led checklist lines of its own — stripping any
+ // A summary is free to use emoji-led checklist lines of its own — stripping any
// emoji-prefixed line would delete the agent's actual words, and a summary made
// mostly of them could fall under the minimum length and lose the body entirely.
it('keeps the agent\'s own emoji checklist lines inside the sentinel summary', () => {
@@ -229,6 +229,37 @@ describe('extractAgentSummary', () => {
);
});
+ // An idle-complete TUI run's output.txt is nothing but PortOS telemetry, so the
+ // PR body must fall back to commit messages rather than open with a nudge log.
+ // Built from the catalog the emitters write through, so a shape whose derived
+ // pattern misses its own output fails here.
+ it('strips every line the TUI emitters can write, leaving no summary', () => {
+ const lines = Object.entries(LIFECYCLE_LINES)
+ .filter(([, line]) => line.pattern)
+ .map(([id, line]) => line(new Proxy({}, { get: (_, key) => `${id}-${String(key)} (1/3)` })));
+ expect(lines.length).toBeGreaterThan(20);
+ expect(extractAgentSummary(lines.join('\n'))).toBeNull();
+ });
+
+ // A Merge Gate re-prompt appends its line AFTER the completion marker and
+ // reopens the run; one that then stalls without a second sentinel ends the
+ // buffer with nudges, which used to be carried into the summary verbatim.
+ it('drops the merge-gate and stall telemetry appended after the completion marker', () => {
+ const output = [
+ '📟 TUI session started: abc12345 (claude)',
+ '✅ Agent signaled completion',
+ 'Moved the lifecycle lines into one catalog so the PR body reader cannot drift.',
+ '✅ Tests passed',
+ '🔁 Merge Gate not finished (PR still OPEN, no blocker stated) — re-prompted the session (1 nudge only)',
+ '🔁 Session idle with the task unfinished — nudged it to continue (attempt 1/3, 1/6 this run)',
+ '🛑 Session still idle after 6 nudges — it is not finishing; open the Shell tab to take it over',
+ ].join('\n');
+
+ expect(extractAgentSummary(output)).toBe(
+ 'Moved the lifecycle lines into one catalog so the PR body reader cannot drift.\n✅ Tests passed'
+ );
+ });
+
it('finds the completion marker even when the sentinel summary runs past the 4000-char tail', () => {
const filler = 'x'.repeat(5000);
const output = [
diff --git a/server/lib/ollamaContext.js b/server/lib/ollamaContext.js
index 639b4585bb..b7d2ee0f5f 100644
--- a/server/lib/ollamaContext.js
+++ b/server/lib/ollamaContext.js
@@ -25,6 +25,7 @@
// and the dispatch gate, both inside the server suite's import budget. The leaf
// imports nothing.
import { isOllamaBackedProvider, ollamaBaseFromProvider, withRuntimeContextWindow } from './aiToolkit/internal/ollamaBacked.js'
+import { LIFECYCLE_LINES } from './agentOutputMarkers.js'
/**
* Smallest runtime window an Ollama-backed *agent harness* can realistically
@@ -249,8 +250,11 @@ export function describeOllamaContextOverflow(overflow, { model = null, provider
* @returns {string}
*/
export function describeOllamaContextTooSmall(runtimeContext, { providerName = null } = {}) {
- const who = providerName ? `${providerName}` : 'This provider'
- return `⚠️ ${who} is running on an Ollama window of ${tokenLabel(runtimeContext)} — below the ` +
- `${tokenLabel(OLLAMA_AGENT_MIN_CONTEXT)} an agent harness usually needs. Set "Local num_ctx" in AI Providers ` +
- `to reload Ollama at a larger window (VRAM permitting), or the run will fail partway through.`
+ // A pre-spawn warning that lands in the agent's output buffer, so its text is
+ // the lifecycle line the PR-body reader knows to strip.
+ return LIFECYCLE_LINES.ollamaContextTooSmall({
+ who: providerName || 'This provider',
+ runtime: tokenLabel(runtimeContext),
+ minimum: tokenLabel(OLLAMA_AGENT_MIN_CONTEXT),
+ })
}
diff --git a/server/services/agentSummaryExtraction.test.js b/server/services/agentSummaryExtraction.test.js
index bd1a379912..42f2955087 100644
--- a/server/services/agentSummaryExtraction.test.js
+++ b/server/services/agentSummaryExtraction.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';
+import { LIFECYCLE_LINES } from '../lib/agentOutputMarkers.js';
describe('sentinel summary precedence', () => {
it.each(['Thinking: I will now run /simplify.', 'tokens used\n123\nEarlier assistant reply.'])(
@@ -11,7 +12,7 @@ describe('sentinel summary precedence', () => {
transcript,
'✅ Agent signaled completion',
summary,
- '💡 Open the Shell tab to view the session',
+ LIFECYCLE_LINES.shellTabHint(),
].join('\n');
expect(extractFinalSummary(output)).toBe(summary);
expect(extractSimplifySummaries(output)).toEqual({ taskSummary: summary, simplifySummary: null });
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index c8059f2cce..3907adb567 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -40,6 +40,7 @@ import { resolveAgentCliCwd } from '../lib/spawnCwd.js';
import { doneSentinelPath as resolveDoneSentinelPath } from '../lib/agentSentinel.js';
import { createAgentSentinelAccess } from './agentSentinelWatcher.js';
import { PTY_UNAVAILABLE_PREFIX } from '../lib/ptySpawnDiagnostics.js';
+import { LIFECYCLE_LINES } from '../lib/agentOutputMarkers.js';
import { finalizeAgentRunCommon, shouldAbandonAgentRun } from './agentRunFinalize.js';
import { leavesPrForHuman } from '../lib/prDisposition.js';
import { resolvePrOwnership, PR_OPENED_BY } from '../lib/slashdoInvocation.js';
@@ -443,7 +444,7 @@ export async function spawnTuiAgent({
? await ensureOllamaAgentContext(provider, { model })
: null;
if (ollamaContext?.warning) appendLine(ollamaContext.warning);
- if (ollamaContext?.applied) appendLine(`🪟 Reloaded Ollama at a ${ollamaContext.contextLength}-token context window`);
+ if (ollamaContext?.applied) appendLine(LIFECYCLE_LINES.ollamaContextApplied({ contextLength: ollamaContext.contextLength }));
// A spawn failure here (a runner 400 for a command missing from its allowlist,
// an unreachable runner, a PTY that won't open) used to propagate raw out of
@@ -489,7 +490,7 @@ export async function spawnTuiAgent({
session.ptyProcess?.onExit?.(() => { maintenanceExited = true; settleMaintenance(); });
} catch (err) {
const message = err?.message || String(err);
- appendLine(`❌ Failed to start ${provider.name || provider.id} TUI: ${message}`);
+ appendLine(LIFECYCLE_LINES.startFailed({ provider: provider.name || provider.id, message }));
// The durable runner probes the configured executable before it opens a
// PTY. Distinguish that deterministic configuration failure from a runner
// outage/refusal so it is blocked with the existing actionable
@@ -573,7 +574,7 @@ export async function spawnTuiAgent({
},
});
if (session.adopted) {
- appendLine(`🔁 Spawn acknowledgement lost (${session.adoptedReason}) — re-attached to the live runner PTY`);
+ appendLine(LIFECYCLE_LINES.spawnAdopted({ reason: session.adoptedReason }));
emitLog('warn', `TUI agent ${agentId} spawn acknowledgement was lost; adopted the live runner PTY`, { agentId, taskId: task.id });
}
}
@@ -640,7 +641,7 @@ export async function spawnTuiAgent({
}
});
- appendLine(`📟 TUI session started: ${sessionId.slice(0, 8)} (${tuiConfig.commandLine})`);
- appendLine(`💡 Open the Shell tab for live TUI output — this panel only logs lifecycle events.`);
+ appendLine(LIFECYCLE_LINES.sessionStarted({ session: sessionId.slice(0, 8), commandLine: tuiConfig.commandLine }));
+ appendLine(LIFECYCLE_LINES.shellTabHint());
return agentId;
}
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index ecf25e2a2f..154904e2d3 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -34,7 +34,7 @@ import { readFile } from 'fs/promises';
import { emitLog } from '../cosEvents.js';
import { HOST_SHUTDOWN_REASON } from '../../lib/hostShutdown.js';
import { missingSentinelLogMessage, parseSentinelPayload } from '../../lib/agentSentinel.js';
-import { SENTINEL_COMPLETION_MARKER } from '../../lib/agentOutputMarkers.js';
+import { LIFECYCLE_LINES, SENTINEL_COMPLETION_MARKER } from '../../lib/agentOutputMarkers.js';
import { resolveMergeGateVerdict, buildMergeGateReprompt } from '../../lib/mergeGateContract.js';
import { createStreamingAnsiStripper, stripAnsi } from '../../lib/ansiStrip.js';
import { createClaudeSessionLimitBannerDetector, createImmediateFallbackSignalDetector, createLocalRuntimeOomDetector, createTruncatedResponseDetector } from '../../lib/aiToolkit/errorDetection.js';
@@ -282,7 +282,7 @@ function createPasteRetryController({
armAttempt();
write(`\x1b[200~${prompt}\x1b[201~`);
const attemptSuffix = attemptNum > 1 ? ` [attempt ${attemptNum}/${PASTE_RETRY_MAX_ATTEMPTS}]` : '';
- appendLine(`📟 Prompt pasted into TUI session ${sessionLabel} (${reason})${attemptSuffix}`);
+ appendLine(LIFECYCLE_LINES.promptPasted({ session: sessionLabel, reason, attemptSuffix }));
// Confirms the TUI actually received the paste before we submit. The
// paste-commit marker is authoritative — Claude Code and OpenCode can
@@ -314,7 +314,7 @@ function createPasteRetryController({
const bootNote = bootActive
? ` (waiting for ${tuiConfig.command} MCP servers to finish booting)`
: '';
- appendLine(`⚠️ Paste verification failed — prompt text not found in buffer, retrying in ${retryDelayMs}ms${bootNote}`);
+ appendLine(LIFECYCLE_LINES.pasteRetrying({ delayMs: retryDelayMs, bootNote }));
// The failed attempt's buffer stays live during the backoff (see
// enterBackoff). A busy TUI can paint its authoritative paste marker
// only after the verification window closes; dropping output in this
@@ -339,11 +339,9 @@ function createPasteRetryController({
const summary = bootActive
? `${tuiConfig.command} did not finish booting its MCP servers within ${bootSecs}s, so the prompt was never delivered. A slow or hung MCP server in your ~/.codex config (e.g. playwright via npx, or a node_repl) blocks codex from accepting input — disable or fix it, or remove it for headless runs.`
: `${tuiConfig.command} was still initializing and the paste was silently swallowed. The prompt never appeared in the TUI buffer after ${PASTE_RETRY_MAX_ATTEMPTS} attempts.`;
- appendLine(
- bootActive
- ? `❌ Paste never landed after ${bootSecs}s of waiting for MCP servers to boot — prompt never rendered`
- : `❌ Paste verification failed after ${PASTE_RETRY_MAX_ATTEMPTS} attempts — prompt never rendered`,
- );
+ appendLine(bootActive
+ ? LIFECYCLE_LINES.pasteNeverLandedMcpBoot({ seconds: bootSecs })
+ : LIFECYCLE_LINES.pasteNeverRendered({ attempts: PASTE_RETRY_MAX_ATTEMPTS }));
finishStartupFailure('paste-not-rendered', summary)
.catch(err => emitLog('error', `TUI agent ${agentId} finishStartupFailure(paste-not-rendered) failed: ${err?.message || err}`, { agentId }));
};
@@ -833,7 +831,7 @@ export function createTuiSessionController({
sentinelIngested = false;
await sentinel.remove();
doneSentinelWatcher = armSentinelWatcher();
- appendLine(`🔁 Merge Gate not finished (PR still OPEN, no blocker stated) — re-prompted the session (1 nudge only)`);
+ appendLine(LIFECYCLE_LINES.mergeGateReprompted());
emitLog('warn', `🔁 Merge-gate contract nudge sent for ${agentId} — PR still OPEN with no stated blocker`, { agentId });
return true;
};
@@ -1189,7 +1187,7 @@ export function createTuiSessionController({
sessionPhase = 'abandoned';
stopRunMachinery();
- appendLine('🛑 PortOS restarted while this agent was running — the run was interrupted, not completed. Its worktree is preserved and the task will resume.');
+ appendLine(LIFECYCLE_LINES.hostRestarted());
emitLog('warn', `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
@@ -1218,7 +1216,7 @@ export function createTuiSessionController({
// would tag a run that went on to RECOVER with the banner as its error.
const failOverToFallback = (analysis) => {
immediateFallbackAnalysis = analysis;
- appendLine(`⚡ Provider fallback signal: ${analysis.message}`);
+ appendLine(LIFECYCLE_LINES.providerFallbackSignal({ message: analysis.message }));
return finish({
success: false,
exitCode: 1,
@@ -1254,7 +1252,7 @@ export function createTuiSessionController({
// the session is already gone, and a transcript line saying otherwise would
// send a post-mortem looking for a paste the provider never received.
if (pasteController?.resubmit()) {
- appendLine(`🔁 Provider handshake still open — re-submitted the prompt (attempt ${attempt})`);
+ appendLine(LIFECYCLE_LINES.handshakeResubmitted({ attempt }));
}
};
@@ -1344,7 +1342,7 @@ export function createTuiSessionController({
emitLog('warn', `TUI agent ${agentId} could not send Claude low-priority command: ${err?.message || err}`, { agentId });
}
if (submitted) {
- appendLine('⏳ Claude Code session limit reached — sent /low-priority from the provider opt-in');
+ appendLine(LIFECYCLE_LINES.claudeSessionLimit());
claudeLowPriorityResubmitTimer = setTimeout(() => {
claudeLowPriorityResubmitTimer = null;
if (sessionPhase !== 'running') return;
@@ -1356,7 +1354,7 @@ export function createTuiSessionController({
}
if (promptResubmitted) {
claudeLowPriorityPromptResubmitted = true;
- appendLine('🔁 Re-submitted the task after enabling Claude low-priority mode');
+ appendLine(LIFECYCLE_LINES.claudeLowPriorityResubmitted());
return;
}
failOverToFallback({
@@ -1393,7 +1391,7 @@ export function createTuiSessionController({
// is load-bearing — it lets the gate discount the echo of a prompt IT just
// re-pasted (see SELF_CLEARING_RESUBMIT_ECHO_MS).
if (selfClearingGate.observe(stripped, now)) {
- appendLine(`✅ Provider signal cleared — ${tuiConfig.command} is generating again; continuing the run`);
+ appendLine(LIFECYCLE_LINES.providerSignalCleared({ command: tuiConfig.command }));
}
const fallbackSignal = detectImmediateFallbackSignal(stripped);
@@ -1405,7 +1403,7 @@ export function createTuiSessionController({
// when one is already open or the provider already recovered).
if (fallbackSignal?.graceMs > 0) {
if (selfClearingGate.arm(fallbackSignal, now)) {
- appendLine(`⏳ Provider signal (self-clearing): ${fallbackSignal.message} — holding the session up to ${Math.round(fallbackSignal.graceMs / 1000)}s for it to clear`);
+ appendLine(LIFECYCLE_LINES.providerSignalHolding({ message: fallbackSignal.message, seconds: Math.round(fallbackSignal.graceMs / 1000) }));
}
} else if (fallbackSignal) {
await failOverToFallback(fallbackSignal);
@@ -1425,7 +1423,7 @@ export function createTuiSessionController({
if (agyResumeAwaitingComposer && AGY_INPUT_READY_PATTERN.test(stripped)) {
agyResumeAwaitingComposer = false;
if (pasteController?.resubmit({ text: STALL_NUDGE_TEXT, label: 'agy resume nudge' })) {
- appendLine('🔁 agy resumed its conversation — nudged it to continue');
+ appendLine(LIFECYCLE_LINES.agyResumedNudged());
}
}
}
@@ -1433,7 +1431,7 @@ export function createTuiSessionController({
if (oomSignal) {
const armed = oomNudgeGate.arm(oomSignal, now);
if (armed === 'armed') {
- appendLine('⏳ Local runtime out of GPU memory — will nudge the session to continue if it goes quiet');
+ appendLine(LIFECYCLE_LINES.localOomPending());
} else if (armed === 'exhausted') {
// Nudged its way through OOM_NUDGE_MAX_ATTEMPTS and it came back
// again: the conversation no longer fits this device, and it only
@@ -1452,7 +1450,7 @@ export function createTuiSessionController({
if (truncationSignal) {
const armed = truncationNudgeGate.arm(truncationSignal, now);
if (armed === 'armed') {
- appendLine('⏳ Response was truncated before completion — will nudge the session to continue if it goes quiet');
+ appendLine(LIFECYCLE_LINES.truncationPending());
} else if (armed === 'exhausted') {
// The truncations outlasted every nudge: this provider is not going
// to finish this response, so hand the task to a fallback provider.
@@ -1488,7 +1486,7 @@ export function createTuiSessionController({
// then Enter — lands under both of Ink's selection models, whereas a bare
// digit is immediate-select in some builds and ignored in others.
session.write(sessionId, `${'\x1b[B'.repeat(Math.max(0, permissionDialog.noOption - 1))}${SUBMIT_KEY}`);
- appendLine(`🚫 Declined ${tuiConfig.command} permission prompt for ${permissionDialog.toolCall || 'a tool call'} — an unattended run never widens its scope (${permissionDialog.count}/${TOOL_PERMISSION_DECLINE_MAX})`);
+ appendLine(LIFECYCLE_LINES.permissionDeclined({ command: tuiConfig.command, toolCall: permissionDialog.toolCall || 'a tool call', count: permissionDialog.count, max: TOOL_PERMISSION_DECLINE_MAX }));
}
if (!promptSentAt) {
@@ -1563,7 +1561,7 @@ export function createTuiSessionController({
const tail = raw
? stripAnsi(raw).split('\n').map((s) => s.trimEnd()).filter(Boolean).slice(-12).join('\n')
: '';
- appendLine(`❌ ${summary}`);
+ appendLine(LIFECYCLE_LINES.failure({ summary }));
await finish({
success: false,
exitCode: 1,
@@ -1689,7 +1687,7 @@ export function createTuiSessionController({
if (answeredBeforeComposer) {
lastOutputAt = now;
firstOutputAt = null;
- appendLine(`📟 ${answeredBeforeComposer.message} for session ${sessionLabel}`);
+ appendLine(LIFECYCLE_LINES.startupDialogAnswered({ message: answeredBeforeComposer.message, session: sessionLabel }));
return;
}
@@ -1725,7 +1723,7 @@ export function createTuiSessionController({
write: writeToTuiSession,
});
if (answeredAtComposer) {
- appendLine(`📟 ${answeredAtComposer.message} for session ${sessionLabel}`);
+ appendLine(LIFECYCLE_LINES.startupDialogAnswered({ message: answeredAtComposer.message, session: sessionLabel }));
return;
}
if (inputReady.ready && elapsed >= tuiConfig.promptDelayMs) {
@@ -1782,7 +1780,7 @@ export function createTuiSessionController({
: null;
if (modelRejection && !sentinelPresent()) {
immediateFallbackAnalysis = { ...modelRejection, affectedModel: model, configuredModel: model };
- appendLine(`❌ ${modelRejection.message}`);
+ appendLine(LIFECYCLE_LINES.failure({ summary: modelRejection.message }));
finish({ success: false, exitCode: 1, error: modelRejection.message, reason: 'model-access-rejected' })
.catch(err => emitLog('error', `TUI agent ${agentId} model-access finish failed: ${err?.message || err}`, { agentId }));
return;
@@ -1812,7 +1810,7 @@ export function createTuiSessionController({
if (wrote === false) return;
agyResumeGate.recordRelaunch();
agyResumeAwaitingComposer = true;
- appendLine(`🔁 agy exited to the shell — relaunched it on conversation ${resumeId.slice(0, 8)} (attempt ${agyResumeGate.attempts}/${AGY_RESUME_MAX_ATTEMPTS})`);
+ appendLine(LIFECYCLE_LINES.agyRelaunched({ conversation: resumeId.slice(0, 8), attempt: agyResumeGate.attempts, max: AGY_RESUME_MAX_ATTEMPTS }));
}).catch((err) => emitLog('error', `TUI agent ${agentId} agy resume failed: ${err?.message || err}`, { agentId }));
return;
}
@@ -1827,7 +1825,7 @@ export function createTuiSessionController({
const declined = toolPermissionGate.takeNudge(now, lastOutputAt);
if (declined) {
if (pasteController?.resubmit({ text: TOOL_PERMISSION_NUDGE_TEXT, label: 'declined-permission nudge' })) {
- appendLine(`🔁 Nudged the session to continue after declined permission prompt ${declined}`);
+ appendLine(LIFECYCLE_LINES.permissionDeclineNudged({ declined }));
}
return;
}
@@ -1837,7 +1835,7 @@ export function createTuiSessionController({
const nudge = oomNudgeGate.takeNudge(now, lastOutputAt);
if (nudge) {
if (pasteController?.resubmit({ text: OOM_NUDGE_TEXT, label: 'local-runtime OOM nudge' })) {
- appendLine(`🔁 Local runtime OOM — nudged the session to continue (attempt ${nudge}/${OOM_NUDGE_MAX_ATTEMPTS})`);
+ appendLine(LIFECYCLE_LINES.localOomNudged({ attempt: nudge, max: OOM_NUDGE_MAX_ATTEMPTS }));
}
return;
}
@@ -1846,7 +1844,7 @@ export function createTuiSessionController({
const truncationNudge = truncationNudgeGate.takeNudge(now, lastOutputAt);
if (truncationNudge) {
if (pasteController?.resubmit({ text: TRUNCATION_NUDGE_TEXT, label: 'truncated-response nudge' })) {
- appendLine(`🔁 Response was truncated before completion — nudged the session to continue (attempt ${truncationNudge}/${TRUNCATION_NUDGE_MAX_ATTEMPTS})`);
+ appendLine(LIFECYCLE_LINES.truncationNudged({ attempt: truncationNudge, max: TRUNCATION_NUDGE_MAX_ATTEMPTS }));
}
return;
}
@@ -1872,7 +1870,7 @@ export function createTuiSessionController({
// (a model looping on "continue"). Either way more nudges won't help. There is no ceiling left to reap it, so say
// so loudly and badge the card — an agent nobody can see is stuck is the
// condition this gate exists to end, and only a human can end this one.
- appendLine(`🛑 Session still idle after ${stallNudgeGate.nudgesSent} nudges — it is not finishing; open the Shell tab to take it over`);
+ appendLine(LIFECYCLE_LINES.stallGaveUp({ nudges: stallNudgeGate.nudgesSent }));
emitLog('warn', `🛑 TUI agent ${agentId} is wedged — still idle after ${stallNudgeGate.nudgesSent} stall nudges`, { agentId });
persistence.updateAgent(agentId, { metadata: { phase: 'stalled' } }).catch((err) =>
emitLog('error', `TUI agent ${agentId} stalled-phase update failed: ${err?.message || err}`, { agentId }));
@@ -1883,7 +1881,7 @@ export function createTuiSessionController({
return;
}
if (pasteController?.resubmit({ text: STALL_NUDGE_TEXT, label: 'stalled-session nudge' })) {
- appendLine(`🔁 Session idle with the task unfinished — nudged it to continue (attempt ${stalled}/${STALL_NUDGE_MAX_ATTEMPTS}, ${stallNudgeGate.nudgesSent}/${STALL_NUDGE_MAX_TOTAL} this run)`);
+ appendLine(LIFECYCLE_LINES.stallNudged({ attempt: stalled, max: STALL_NUDGE_MAX_ATTEMPTS, sent: stallNudgeGate.nudgesSent, total: STALL_NUDGE_MAX_TOTAL }));
}
}, PROVIDER_SIGNAL_POLL_MS);
diff --git a/server/services/ollamaAgentContext.js b/server/services/ollamaAgentContext.js
index 9029c77d35..9df48677ce 100644
--- a/server/services/ollamaAgentContext.js
+++ b/server/services/ollamaAgentContext.js
@@ -33,6 +33,7 @@ import {
resolveOllamaContextLength
} from '../lib/ollamaContext.js'
import { ensureContextWindow, getBaseUrl, getModelCapabilities, getRuntimeContextLength } from './ollamaManager.js'
+import { LIFECYCLE_LINES } from '../lib/agentOutputMarkers.js'
/**
* Prepare the Ollama daemon for an agent harness run.
@@ -78,7 +79,7 @@ export async function ensureOllamaAgentContext(provider, { env = process.env, mo
applied: false, reason: 'error', error: err.message
}))
const warning = result.error
- ? `⚠️ Could not reload Ollama at a ${contextLength}-token window (${result.error}) — ${providerName || 'the run'} continues on the current window.`
+ ? LIFECYCLE_LINES.ollamaReloadFailed({ contextLength, error: result.error, who: providerName || 'the run' })
: null
if (warning) console.warn(warning)
return { skipped: false, contextLength, applied: !!result.applied, warning }