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: prevent CoS swarm agents being reaped mid-merge-queue (#2074)
Adam Eivy4a22556b4101
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 08f0a5e257..b850f14d02 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -50,3 +50,4 @@- Audited the cross-domain insights engine against the no-cold-bootstrap LLM policy and documented the trigger contract at the two generation entry points (#2037). Verified the only functions that call an AI provider — `generateThemeAnalysis` (INS-02) and `refreshCrossDomainNarrative` (INS-04) — are reached solely from user-triggered POST endpoints (`/api/insights/themes/refresh`, `/api/insights/narrative/refresh`, both fired by an explicit "Refresh" click); the page-mount and cached-read paths (`getThemeAnalysis`/`getCrossDomainNarrative`) are disk-only, boot (`server/index.js`) mounts the router without generating, and no scheduler references insights. No violation found — added a contract comment block plus a regression test asserting the read paths never call a provider.- Single-sourced the Tribe care-cadence rules so the page, the Care dashboard widget, and the proactive alert can no longer drift (#2060). The Tribe page's `contactStatus` (client) and the server's `personCadenceStatus`/`getCareSummary` (added in #2032) previously carried two hand-mirrored copies of the same "external-excluded / missing-vs-overdue / <=7d soon" state machine. The rules now live in one authoritative pure module, `server/lib/tribeCadence.js` (`cadenceStatus`, `daysSinceDate`), mirrored to `client/src/lib/tribeCadence.js`; `personCadenceStatus` re-exports it and the client `contactStatus` is now a thin presentation wrapper that only attaches label/tone. A cross-boundary contract test imports both copies and fails CI if they ever diverge. Semantics are unchanged — the Tribe page header counts, the widget, and the alert all compute identically to before.- Refreshed GOALS.md status to reflect shipped Apple Health integration (#2039). The Health & Longevity status-table row said "Apple Health integration planned," but the integration shipped: `server/routes/appleHealth.js` (ingest/metrics/correlation/XML+clinical import) is wired through `apiHealth.js` into the MeatSpace Alcohol/Health/Nicotine tabs. The row now marks it shipped, and the stale "Apple Health Integration" bullet was removed from Secondary Goals. Documentation only; other status rows spot-checked against code (Sketch & Annotation Canvas confirmed genuinely unshipped, left as planned).+- Prevented CoS `/do:next --swarm` orchestrators from being reaped mid-merge as `idle-complete`, which left PRs opened-but-unmerged or merged-but-uncleaned while `state.json` recorded `status: completed` (#2074). The swarm Phase C serialized merge queue merges PRs one at a time, and each subsequent PR must rebase onto the new `main` and re-run required CI — several minutes of *silent* TUI output per PR that routinely blew past the 3-minute idle default, so the runner reaped the still-working orchestrator. The TUI idle detector (`agentTuiSpawning.js`) now latches a merge-queue flag (`createMergeQueueTracker`/`isMergeQueueSignal` in `tuiHandshake.js`) the first time it sees Phase C chrome (`gh pr merge`, `gh pr checks`, `--delete-branch`, "serialized merge queue", "Phase C") and, while latched, extends the idle grace to `MERGE_QUEUE_IDLE_TIMEOUT_MS` (15min) — comfortably covering one CI run's silent gap while still bounding a genuinely-dead orchestrator's reap. Detection is deliberately conservative (a false positive only extends the window; a false negative preserves prior behavior). As a blast-radius safety net, if the *extended* window still elapses the agent is finalized as a needs-manual-finish failure with reason `merge-queue-idle-timeout` (pointing at open/uncleaned PRs) instead of the silent `idle-complete` success that hid the half-done queue.diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.jsindex e161b16530..dd3007f4c2 100644--- a/server/lib/tuiHandshake.js+++ b/server/lib/tuiHandshake.js@@ -313,6 +313,71 @@ export function scheduleSubmitEnters(write, isFinalized) {export const DEFAULT_TUI_PROMPT_DELAY_MS = 2500;export const DEFAULT_TUI_IDLE_TIMEOUT_MS = 180000;+// Extended idle threshold applied ONLY while a `/do:next --swarm` orchestrator+// is in its Phase C serialized merge queue (issue #2074). Merging PRs one at a+// time makes each subsequent PR rebase onto the new `main` and re-run required+// CI — several minutes of *silent* TUI output per PR (`gh pr checks --watch`+// shows a static "pending" screen with no repaint). That quiet window routinely+// blows past the 3-minute default and the runner reaps the still-working+// orchestrator as `idle-complete`, leaving PRs merged-but-uncleaned or unmerged+// while `state.json` records `status: completed`. 15 minutes comfortably covers+// one CI run's silent gap while still bounding a genuinely-dead orchestrator's+// reap (see MERGE_QUEUE_IDLE_TIMEOUT reap path in agentTuiSpawning.js).+export const MERGE_QUEUE_IDLE_TIMEOUT_MS = 900000;++// Distinctive markers the swarm orchestrator's TUI prints once it enters the+// Phase C merge queue. Detection is deliberately conservative: a false POSITIVE+// only *extends* the idle window (bounded, low-cost), and a false NEGATIVE just+// preserves the pre-#2074 behavior (no regression) — so this is nothing like the+// fragile completion-detection regexes we avoid for FINALIZING a run. Matched+// against ANSI-stripped output. Kept lower-cased for case-insensitive testing.+const MERGE_QUEUE_MARKERS = [+ 'merge queue',+ 'serialized merge',+ 'phase c',+ 'gh pr merge',+ 'gh pr checks',+ '--delete-branch',+];++/**+ * True when a chunk of ANSI-stripped TUI output shows the swarm orchestrator has+ * entered its Phase C serialized merge queue. Callers MUST pass stripped output.+ * Non-string / empty input yields false.+ *+ * @param {string} strippedText — ANSI-stripped output (a chunk or accumulator).+ * @returns {boolean}+ */+export function isMergeQueueSignal(strippedText) {+ if (typeof strippedText !== 'string' || !strippedText) return false;+ const lower = strippedText.toLowerCase();+ return MERGE_QUEUE_MARKERS.some((marker) => lower.includes(marker));+}++/**+ * Latching tracker for "this agent is in a serialized merge queue" (issue+ * #2074). Feed it each ANSI-stripped post-submit chunk via `observe(text)`; it+ * becomes `active` the first time a merge-queue marker appears and STAYS active+ * thereafter. Latching (not a sliding window) is deliberate: the whole failure+ * mode is a *silent* CI wait — no markers print during the quiet gap — so a+ * recency window would age the flag out exactly when the extended idle grace is+ * needed. Once latched, the idle reaper uses MERGE_QUEUE_IDLE_TIMEOUT_MS instead+ * of the 3-minute default. Lives here so the detection logic is unit-testable.+ *+ * @returns {{ observe: (strippedText: string) => boolean, readonly active: boolean }}+ */+export function createMergeQueueTracker() {+ let active = false;+ return {+ observe(strippedText) {+ if (active) return true;+ if (isMergeQueueSignal(strippedText)) active = true;+ return active;+ },+ get active() { return active; },+ };+}+// ─── Buffer caps (defensive RAM bounds) ───────────────────────────────────//// RAW caps stay small — the raw PTY stream is only used for paste-markerdiff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.jsindex b6ac084521..93ec80ea7a 100644--- a/server/lib/tuiHandshake.test.js+++ b/server/lib/tuiHandshake.test.js@@ -12,6 +12,9 @@ import {MIN_WORK_COUNTER_SPAN_MS,extractWorkCounterSeconds,createWorkActivityTracker,+ MERGE_QUEUE_IDLE_TIMEOUT_MS,+ isMergeQueueSignal,+ createMergeQueueTracker,rendersWorkCounter,PASTE_TO_ENTER_MIN_DELAY_MS,PASTE_TO_ENTER_FALLBACK_MS,@@ -247,6 +250,46 @@ describe('tuiHandshake — paste timing constants', () => {});});+// Issue #2074 — a swarm orchestrator in its Phase C serialized merge queue goes+// silent for minutes per PR (each rebases + re-runs CI). Detection latches so the+// idle reaper can extend its grace and not reap a still-working orchestrator.+describe('tuiHandshake — merge-queue idle suppression (#2074)', () => {+ it('extends the idle timeout well past the default 3-minute window', () => {+ expect(MERGE_QUEUE_IDLE_TIMEOUT_MS).toBe(900000);+ expect(MERGE_QUEUE_IDLE_TIMEOUT_MS).toBeGreaterThan(DEFAULT_TUI_IDLE_TIMEOUT_MS);+ });++ it('isMergeQueueSignal matches Phase C merge-queue chrome (case-insensitive)', () => {+ expect(isMergeQueueSignal('### Swarm Phase C — Serialized merge queue')).toBe(true);+ expect(isMergeQueueSignal('Running: gh pr checks 2071 --required --watch --fail-fast')).toBe(true);+ expect(isMergeQueueSignal('gh pr merge 2071 --merge --delete-branch')).toBe(true);+ expect(isMergeQueueSignal('PHASE C: serialized MERGE QUEUE begins')).toBe(true);+ });++ it('isMergeQueueSignal ignores ordinary implementation/output chrome', () => {+ expect(isMergeQueueSignal('Editing server/services/agentTuiSpawning.js')).toBe(false);+ expect(isMergeQueueSignal('● high · (12s · running tests)')).toBe(false);+ expect(isMergeQueueSignal('')).toBe(false);+ expect(isMergeQueueSignal(null)).toBe(false);+ expect(isMergeQueueSignal(undefined)).toBe(false);+ });++ it('createMergeQueueTracker latches on first signal and stays active through silence', () => {+ const tracker = createMergeQueueTracker();+ expect(tracker.active).toBe(false);+ tracker.observe('implementing the fix, running the suite');+ expect(tracker.active).toBe(false);+ // Enters Phase C — latches.+ expect(tracker.observe('gh pr merge 2071 --merge --delete-branch')).toBe(true);+ expect(tracker.active).toBe(true);+ // Subsequent quiet CI-wait chunks (no marker) must NOT un-latch it — the+ // whole point is that the silent gap is when the grace is needed.+ tracker.observe('waiting...');+ tracker.observe('');+ expect(tracker.active).toBe(true);+ });+});+describe('tuiHandshake.inferTuiCommand', () => {// Catch-all default also returns claude; the claude rows just confirm// an explicit match isn't accidentally tagged codex/antigravity/gemini.diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex b6e0ef3bf6..8adef08168 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -25,11 +25,13 @@ import { isAntigravityCommand } from '../lib/antigravity.js';import {DEFAULT_TUI_PROMPT_DELAY_MS,DEFAULT_TUI_IDLE_TIMEOUT_MS,+ MERGE_QUEUE_IDLE_TIMEOUT_MS,READY_POLL_INTERVAL_MS,READY_IDLE_THRESHOLD_MS,PASTE_MARKER_POLL_MS,countPasteMarkers,createWorkActivityTracker,+ createMergeQueueTracker,createInputReadyTracker,rendersWorkCounter,PASTE_TO_ENTER_MIN_DELAY_MS,@@ -276,6 +278,11 @@ export async function spawnTuiAgent({// fallback idle-complete path from finalizing a never-submitted prompt as// success (issue #1229).const workActivity = createWorkActivityTracker();+ // Latches once the agent enters a `/do:next --swarm` Phase C serialized merge+ // queue, whose per-PR CI re-runs produce minutes of silent output. While+ // latched, the idle reaper uses the extended MERGE_QUEUE_IDLE_TIMEOUT_MS so a+ // still-working orchestrator isn't reaped mid-merge (issue #2074).+ const mergeQueue = createMergeQueueTracker();// Tracks claude's interactive input-readiness (footer chrome) and its first-run// folder-trust gate. Gates the prompt paste for the claude TUI so we never// paste into a startup banner, a trust menu, or a returned shell prompt.@@ -625,6 +632,13 @@ export async function spawnTuiAgent({// across wall-clock time confirms real work (a static echo's counters all// arrive together and fail the time-span). Gates idle-complete (#1229).if (promptSubmittedAt && stripped && !workActivity.active) workActivity.observe(stripped, now);+ // Detect entry into the swarm Phase C merge queue so the idle reaper can+ // extend its grace window across the silent per-PR CI waits (issue #2074).+ // Latches once — observe only until active, then announce the transition.+ if (promptSubmittedAt && stripped && !mergeQueue.active && mergeQueue.observe(stripped)) {+ emitLog('info', `TUI agent ${agentId} entered merge queue — idle reaper extended to ${Math.round(MERGE_QUEUE_IDLE_TIMEOUT_MS / 60000)}min`, { agentId, phase: 'merge-queue' });+ await updateAgent(agentId, { metadata: { phase: 'merge-queue' } });+ }lastOutputAt = now;if (firstOutputAt === null) firstOutputAt = lastOutputAt;@@ -881,7 +895,29 @@ export async function spawnTuiAgent({// counts because per-line PTY capture is intentionally disabled for TUI// agents — see handleData.if (lastOutputAt <= promptSentAt) return;- if (idle >= tuiConfig.idleTimeoutMs) {+ // While the agent is in a swarm Phase C serialized merge queue, per-PR CI+ // re-runs go silent for minutes at a time; extend the idle grace so a+ // still-working orchestrator isn't reaped mid-merge (issue #2074). The+ // extended window still bounds a genuinely-dead orchestrator's reap.+ const effectiveIdleTimeoutMs = mergeQueue.active+ ? Math.max(tuiConfig.idleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)+ : tuiConfig.idleTimeoutMs;+ if (idle >= effectiveIdleTimeoutMs) {+ // Reaped AFTER the extended merge-queue grace elapsed: the orchestrator+ // almost certainly died mid-merge with PRs opened/merged-but-uncleaned.+ // Surface it as a needs-manual-finish FAILURE rather than the silent+ // `status: completed` that hid the half-done merge queue (issue #2074).+ if (mergeQueue.active) {+ finish({+ success: false,+ exitCode: 1,+ error: `TUI agent idled out after ${Math.round(effectiveIdleTimeoutMs / 60000)}min in the merge queue — it likely died mid-merge; check for open or merged-but-uncleaned PRs and finish them manually.`,+ reason: 'merge-queue-idle-timeout',+ }).catch(err => {+ emitLog('error', `Failed to finalize TUI agent ${agentId}: ${err.message}`, { agentId });+ });+ return;+ }// Distinguish a real (sentinel-less) completion from a never-submitted// prompt that just idled out. `lastOutputAt > promptSentAt` only proves// the TUI repainted SOMETHING — banner/status chrome churns even with thediff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 77c4b82a17..0e022144d4 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -1001,3 +1001,65 @@ describe('spawnTuiAgent runtime', () => {expect(outputTxtWrites).toContain('https://example.com/pr/42');});});++// Issue #2074 — the idle reaper must extend its grace while a swarm orchestrator+// is in its Phase C merge queue, and, if the EXTENDED window still blows, surface+// a needs-manual-finish failure instead of a silent `status: completed`. This is+// the exact decision the `idleTimer` interval makes; mirror it as a pure function+// (the inline-copy pattern from subAgentSpawner.test.js) so the branch matrix is+// tested without standing up the full fake-timer PTY harness.+describe('agentTuiSpawning — idle reap decision (#2074)', () => {+ const MERGE_QUEUE_IDLE_TIMEOUT_MS = 900000;++ // Faithful copy of the idleTimer body's finalize-selection logic.+ function decideIdleReap({ idle, baseIdleTimeoutMs, mergeQueueActive, workActive, rendersCounter }) {+ const effectiveIdleTimeoutMs = mergeQueueActive+ ? Math.max(baseIdleTimeoutMs, MERGE_QUEUE_IDLE_TIMEOUT_MS)+ : baseIdleTimeoutMs;+ if (idle < effectiveIdleTimeoutMs) return { action: 'wait', effectiveIdleTimeoutMs };+ if (mergeQueueActive) {+ return { action: 'reap', success: false, reason: 'merge-queue-idle-timeout', effectiveIdleTimeoutMs };+ }+ const noWorkButCounterExpected = !workActive && rendersCounter;+ if (noWorkButCounterExpected) {+ return { action: 'reap', success: false, reason: 'idle-no-activity', effectiveIdleTimeoutMs };+ }+ return { action: 'reap', success: true, reason: 'idle-complete', effectiveIdleTimeoutMs };+ }++ const BASE = 180000;++ it('does NOT reap at the 3-min default while in a merge queue — grace extends to 15min', () => {+ const r = decideIdleReap({ idle: BASE + 5000, baseIdleTimeoutMs: BASE, mergeQueueActive: true, workActive: true, rendersCounter: true });+ expect(r.action).toBe('wait');+ expect(r.effectiveIdleTimeoutMs).toBe(MERGE_QUEUE_IDLE_TIMEOUT_MS);+ });++ it('reaps a merge-queue agent as needs-manual-finish once the EXTENDED window blows', () => {+ const r = decideIdleReap({ idle: MERGE_QUEUE_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: true, workActive: true, rendersCounter: true });+ expect(r.action).toBe('reap');+ expect(r.success).toBe(false);+ expect(r.reason).toBe('merge-queue-idle-timeout');+ });++ it('leaves the pre-#2074 idle-complete path untouched when NOT in a merge queue', () => {+ const r = decideIdleReap({ idle: BASE + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: false, workActive: true, rendersCounter: true });+ expect(r.action).toBe('reap');+ expect(r.success).toBe(true);+ expect(r.reason).toBe('idle-complete');+ });++ it('leaves the #1229 no-activity failure path untouched when NOT in a merge queue', () => {+ const r = decideIdleReap({ idle: BASE + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: false, workActive: false, rendersCounter: true });+ expect(r.action).toBe('reap');+ expect(r.success).toBe(false);+ expect(r.reason).toBe('idle-no-activity');+ });++ it('a merge-queue reap takes precedence over the no-activity downgrade', () => {+ // Even with no work counter seen, a latched merge queue means real work was+ // happening — surface it as needs-manual-finish, not a never-submitted prompt.+ const r = decideIdleReap({ idle: MERGE_QUEUE_IDLE_TIMEOUT_MS + 1, baseIdleTimeoutMs: BASE, mergeQueueActive: true, workActive: false, rendersCounter: true });+ expect(r.reason).toBe('merge-queue-idle-timeout');+ });+});