Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep TUI lifecycle telemetry out of generated PR descriptions
[._.]/ Adam Eivyfff1c2d48f4e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 588257d879..7a3648996e 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -16,6 +16,7 @@## Fixed+- **CoS agent PRs no longer open with TUI startup noise as their description.** A PR that PortOS opened for a Codex/Antigravity/OpenCode agent led with the session's own lifecycle log — `📟 TUI session started: … (codex …)`, `💡 Open the Shell tab…`, `📟 Prompt pasted…` — before getting to what the agent actually did. The PR description now starts at the agent's completion summary and drops PortOS's status lines, along with the trailing `## Branch` / `## PR` section that only repeats what the PR page already shows.- **Branch reconciler no longer hands long-lived shared branches to the coordinator agent.** `gh-pages` (the GitHub Pages publishing branch) is now protected alongside `main`/`master`/`dev`/`develop`/`release`, so the scheduled `branch-reconcile` task never tries to "open a PR" merging it into the default branch (which would break the published site). The reconciler now reuses the single canonical `PROTECTED_BRANCHES` set in `server/lib/gitArgs.js` instead of its own narrower list, so it also picks up `dev`/`develop` protection.## Changeddiff --git a/server/lib/README.md b/server/lib/README.mdindex eb166d92cc..a8d1af37f0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -24,6 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |+| `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 `RE_AGENT_LIFECYCLE_LINE`/`stripLifecycleLines(lines)`. 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). || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `quotaReset.js` | Normalizes provider quota reset timestamps and computes time remaining without treating unknown values as imminent resets. |@@ -164,7 +165,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. || `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). || `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — pure GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. |-| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. |+| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. || `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. || `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. || `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. Pinokio-launched PortOS exports `MallocStackLogging`/`MallocScribble`/etc. that flood Python subprocess stderr with `can't turn off malloc stack logging` lines; route every Node→Python spawn through this. No-op on Linux/Windows. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (Malloc-stripped env, 5s timeout) returning the absolute binary path or `null`; the shared discovery probe behind `findYtDlp`/`findFfmpeg`/`detectPython`/voice `which`. |diff --git a/server/lib/agentOutputMarkers.js b/server/lib/agentOutputMarkers.jsnew file mode 100644index 0000000000..b171cc182b--- /dev/null+++ b/server/lib/agentOutputMarkers.js@@ -0,0 +1,39 @@+/**+ * Status lines PortOS writes INTO an agent's output buffer.+ *+ * A TUI agent's `output.txt` is not a transcript — the live PTY stream goes to+ * `raw.txt` and the Shell tab. What lands in `output.txt` is a mix of two very+ * different things:+ * 1. lifecycle telemetry PortOS itself appends (`📟 TUI session started…`,+ * `💡 Open the Shell tab…`, `⚠️ Paste verification failed…`), and+ * 2. the agent's own `.agent-done` summary, ingested behind+ * `SENTINEL_COMPLETION_MARKER` when the run finalizes.+ *+ * 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.+ */++/** Line `ingestDoneSentinel` appends immediately before the sentinel summary. */+export const SENTINEL_COMPLETION_MARKER = '✅ Agent signaled completion';++/**+ * Matches a PortOS-authored lifecycle status line. These are all emitted via the+ * output spooler's `appendLine` with a leading emoji + space — a shape the agent's+ * own summary essentially never takes, since it writes markdown (a bullet leads+ * with `-`, a heading with `#`). Base codepoints with an optional VS16 (`️`),+ * because the emitters are inconsistent about the variation selector (`⚠️` carries+ * one, `⚡` does not) and a literal-only match would miss half of them.+ */+export const RE_AGENT_LIFECYCLE_LINE = /^\s*(?:📟|💡|⚡|⏳|⚠|❌|✅|🌳)️?\s/u;++/**+ * Drop PortOS lifecycle status lines from an array of output lines.+ * @param {string[]} lines+ * @returns {string[]}+ */+export function stripLifecycleLines(lines) {+ return lines.filter(line => !RE_AGENT_LIFECYCLE_LINE.test(line));+}diff --git a/server/lib/gitOutputParsers.js b/server/lib/gitOutputParsers.jsindex 28a7d8544e..0a06d71e5c 100644--- a/server/lib/gitOutputParsers.js+++ b/server/lib/gitOutputParsers.js@@ -2,6 +2,8 @@// access — these turn the text git prints into structured data. The// orchestration that actually runs git lives in server/services/git.js.+import { SENTINEL_COMPLETION_MARKER, stripLifecycleLines } from './agentOutputMarkers.js';+/*** Map a 2-char porcelain status code to a human-readable label.* Falls back to the trimmed code for unmapped combinations.@@ -80,34 +82,54 @@ export function parseSubmoduleStatusLine(line) {/*** Extract a meaningful implementation summary from raw agent output.- * Agents typically end their output with a summary of what was implemented.- * This function finds the last tool-call artifact in the tail of the output- * and returns everything after it, cleaned up.+ *+ * Two shapes reach this:+ * - A TUI agent's `output.txt`, which is lifecycle telemetry plus the+ * `.agent-done` sentinel summary ingested behind+ * `SENTINEL_COMPLETION_MARKER`. When that marker is present, everything+ * after it IS the agent's summary — nothing before it was ever the agent+ * talking, so the tool-line walk must not be allowed to reach back into it.+ * - A CLI agent's streamed output, which ends with a summary after the last+ * tool-call artifact. That's the fallback walk.+ *+ * Either way, PortOS-authored lifecycle status lines are dropped: they are+ * telemetry for the agent card, and a PR body that opens with+ * "📟 TUI session started: …" is noise the reviewer has to scroll past.+ ** @param {string} output - Raw agent output* @returns {string|null} Cleaned summary text, or null if nothing usable*/export function extractAgentSummary(output) {if (!output || output.length < 50) return null;- // Take the last ~4000 chars where the summary typically lives- const tail = output.slice(-4000);- const lines = tail.split('\n');-- // Find the last tool-call artifact line index.- // Everything after it is the agent's final summary.- let lastToolLine = -1;- for (let i = lines.length - 1; i >= 0; i--) {- const trimmed = lines[i].trimStart();- if (trimmed.startsWith('→') || trimmed.startsWith('🔧') || /^\s*\$ /.test(lines[i])) {- lastToolLine = i;- break;+ // Anchor on the completion marker when the agent wrote a sentinel; otherwise+ // fall back to the last ~4000 chars, where a streamed summary typically lives.+ // The marker is searched in the FULL output, not the tail — a long sentinel+ // summary can itself run past 4000 chars and push the marker out of the window.+ const markerIdx = output.lastIndexOf(SENTINEL_COMPLETION_MARKER);+ const region = markerIdx >= 0+ ? output.slice(markerIdx + SENTINEL_COMPLETION_MARKER.length)+ : output.slice(-4000);+ const lines = region.split('\n');++ let summaryLines;+ if (markerIdx >= 0) {+ summaryLines = lines;+ } else {+ // Find the last tool-call artifact line index.+ // Everything after it is the agent's final summary.+ let lastToolLine = -1;+ for (let i = lines.length - 1; i >= 0; i--) {+ const trimmed = lines[i].trimStart();+ if (trimmed.startsWith('→') || trimmed.startsWith('🔧') || /^\s*\$ /.test(lines[i])) {+ lastToolLine = i;+ break;+ }}+ summaryLines = lastToolLine >= 0 ? lines.slice(lastToolLine + 1) : lines;}- // Extract everything after the last tool line- const summaryLines = lastToolLine >= 0- ? lines.slice(lastToolLine + 1)- : lines;+ summaryLines = stripLifecycleLines(summaryLines);// Trim leading/trailing blank lineswhile (summaryLines.length && !summaryLines[0].trim()) summaryLines.shift();@@ -122,6 +144,16 @@ export function extractAgentSummary(output) {while (summaryLines.length && !summaryLines[0].trim()) summaryLines.shift();}+ // Drop a trailing "## Branch" / "## PR" section. The sentinel template asks for+ // one so a human reading the agent card knows where the work landed — but in a+ // PR description the forge already shows the head branch, and a "## PR" section+ // is a link to the very page you're reading.+ const tailIdx = summaryLines.findIndex(l => /^\s*(#{1,6}\s*)?(branch|pr)\s*:?\s*$/i.test(l));+ if (tailIdx >= 0) {+ summaryLines = summaryLines.slice(0, tailIdx);+ while (summaryLines.length && !summaryLines[summaryLines.length - 1].trim()) summaryLines.pop();+ }+const summary = summaryLines.join('\n').trim();// Must have meaningful content (at least a sentence)diff --git a/server/lib/gitOutputParsers.test.js b/server/lib/gitOutputParsers.test.jsindex 997255fb2c..e488d0877f 100644--- a/server/lib/gitOutputParsers.test.js+++ b/server/lib/gitOutputParsers.test.js@@ -139,4 +139,85 @@ describe('extractAgentSummary', () => {const summary = extractAgentSummary(output);expect(summary?.split('\n')[0]).toContain('Added a Run Backup Now button');});++ // Regression: PR #3191 shipped with "📟 TUI session started: … (codex …)" as the+ // first three lines of its description. A TUI agent's output.txt has no tool-call+ // artifacts at all, so the old backwards walk found no boundary and kept the whole+ // buffer — lifecycle telemetry included.+ it('drops TUI lifecycle telemetry and keeps only the sentinel summary', () => {+ const output = [+ '📟 TUI session started: 92356307 (codex --dangerously-bypass-approvals-and-sandbox --model gpt-5.6-terra)',+ '💡 Open the Shell tab for live TUI output — this panel only logs lifecycle events.',+ '📟 Prompt pasted into TUI session 92356307 (ready)',+ '✅ Agent signaled completion',+ '## Summary',+ 'Rendered malware scan reports inside PortOS.',+ '## Changes',+ '- Added a deep-linkable Brain scan-report page.',+ ].join('\n');++ const summary = extractAgentSummary(output);+ expect(summary).not.toContain('TUI session started');+ expect(summary).not.toContain('Open the Shell tab');+ expect(summary).not.toContain('Prompt pasted');+ expect(summary).not.toContain('Agent signaled completion');+ expect(summary?.split('\n')[0]).toBe('Rendered malware scan reports inside PortOS.');+ expect(summary).toContain('## Changes');+ });++ it('drops mid-run lifecycle warnings that land after the completion marker', () => {+ const output = [+ '📟 TUI session started: abc12345 (codex)',+ '⚠️ Paste verification failed — prompt text not found in buffer, retrying in 5000ms',+ '✅ Agent signaled completion',+ 'Fixed the scan-report route so deep links resolve to the SPA.',+ '⏳ Max runtime reached — asking the agent to wrap up',+ ].join('\n');++ const summary = extractAgentSummary(output);+ expect(summary).toBe('Fixed the scan-report route so deep links resolve to the SPA.');+ });++ it('finds the completion marker even when the sentinel summary runs past the 4000-char tail', () => {+ const filler = 'x'.repeat(5000);+ const output = [+ '📟 TUI session started: abc12345 (codex)',+ '✅ Agent signaled completion',+ 'Reworked the exporter so every frame lands in the atlas.',+ filler,+ ].join('\n');++ const summary = extractAgentSummary(output);+ expect(summary?.split('\n')[0]).toBe('Reworked the exporter so every frame lands in the atlas.');+ expect(summary).not.toContain('TUI session started');+ });++ it.each([+ ['## Branch', 'cos/task-example/agent-example'],+ ['## PR', 'https://example.com/org/repo/pull/1'],+ ])('drops the trailing "%s" section the sentinel template asks for', (heading, value) => {+ const output = [+ '✅ Agent signaled completion',+ '## Summary',+ 'Wrapped Brain Link tags so they no longer scroll horizontally on mobile.',+ heading,+ value,+ ].join('\n');++ const summary = extractAgentSummary(output);+ expect(summary).toBe('Wrapped Brain Link tags so they no longer scroll horizontally on mobile.');+ });++ it('leaves a non-TUI streamed summary on the tool-call walk', () => {+ const output = [+ '🔧 Using Edit tool',+ ' → /path/to/file.js',+ '',+ 'Reworked the retry backoff so a wedged provider is reaped instead of spun on.',+ ].join('\n');++ expect(extractAgentSummary(output)).toBe(+ 'Reworked the retry backoff so a wedged provider is reaped instead of spun on.'+ );+ });});diff --git a/server/lib/index.js b/server/lib/index.jsindex ae5ec98ccf..34f93ddcfa 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -142,6 +142,7 @@ export * from './zipWriter.js';// === Process execution ===export * from './agentGuard/index.js';+export * from './agentOutputMarkers.js';export * from './agentSentinel.js';export * from './bareUrl.js';export * from './bashResolver.js';diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 5ed415678c..45894a11fe 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -19,6 +19,7 @@ import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents, isFalsyMeta } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';+import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';import { resolvePrCompletion } from '../lib/prDisposition.js';import { canTypeSlashCommands } from '../lib/slashdoInvocation.js';import { normalizeReviewers } from '../lib/validation.js';@@ -393,7 +394,10 @@ export async function spawnTuiAgent({// parses back as its own text, so this is a no-op change for existing types.const { summary } = parseSentinelPayload(contents);if (!summary) return;- appendLine(`✅ Agent signaled completion`);+ // Shared constant, not a literal: `extractAgentSummary` anchors the PR-body+ // extraction on this exact line to tell the agent's summary apart from the+ // lifecycle telemetry above it. Reword it here only, and the noise returns.+ appendLine(SENTINEL_COMPLETION_MARKER);const truncated = summary.length > 4096 ? `${summary.slice(0, 4096)}\n…[truncated]` : summary;for (const line of truncated.split('\n')) appendLine(line);};