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
feat: detect short-lived CoS task churn and file a fix issue
[._.]/ Adam Eivy7878fd7c16c5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 90cf5d8fee..fff7ec129a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,3 +1,7 @@+## Added++- CoS now notices when a scheduled task (the overnight branch-reconcile loop) finishes the same work over and over in short-lived agent runs. It parks a looping coordinator so it stops burning quota, files one GitHub issue to fix the drain, and records per-run duration so the burst is visible as a metric.+## Fixed- Tapping the notifications bell on a phone now opens a panel that stays on screen. It was anchored to the bell — which sits mid-screen in the sidebar — so the panel ran off the right edge, clipping notification titles and putting every per-item dismiss button and the mark-all/clear-all controls out of reach with nothing to scroll to them.diff --git a/server/services/agentChurn.js b/server/services/agentChurn.jsnew file mode 100644index 0000000000..1d26a4dfc0--- /dev/null+++ b/server/services/agentChurn.js@@ -0,0 +1,338 @@+/**+ * CoS agent-run churn detector.+ *+ * A scheduled / perpetual task that finishes the SAME work over and over in+ * short-lived agent runs (last night's branch-reconcile loop: dozens of+ * identical findings, each a couple of minutes) is a defect — not something+ * Layered Intelligence should have to notice by reading telemetry. This module+ * watches every agent completion, decides from the task-type recency ring+ * whether the type is churning, parks a looping coordinator so it stops+ * burning quota, and files ONE tracker issue so a human / coding agent can+ * fix the root cause.+ *+ * Detection is deterministic (counts + durations + inter-arrival gaps). No+ * LLM call — safe under the cold-bootstrap AI policy.+ */++import { join } from 'path';+import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import { extractTaskType, loadLearningData } from './taskLearning/store.js';+import { NON_COMMITTING_COORDINATOR_TASK_TYPES } from './taskTypeHooks.js';+import { runCli } from './layeredIntelligence/runCli.js';++// Tight window: the failure mode is a burst overnight, not a busy week of+// legitimate drain. Eight completions is already more than a healthy+// coordinator should need to re-state the same finding.+export const CHURN_WINDOW_MS = 6 * 60 * 60 * 1000;+export const SHORT_LIVED_MS = 5 * 60 * 1000;+export const CHURN_MIN_RUNS = 8;+export const CHURN_SHORT_LIVED_RATIO = 0.7;+export const RAPID_GAP_MS = 15 * 60 * 1000;+export const CHURN_ALERT_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000;+export const CHURN_SLUG_PREFIX = 'cos-churn';++export const alertsPath = (cosDir = PATHS.cos) => join(cosDir, 'churn-alerts.json');++const slugMarker = (taskType) => `<!-- lil-slug: ${CHURN_SLUG_PREFIX}:${taskType} -->`;++function median(values) {+ if (!values.length) return null;+ const sorted = [...values].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 === 1+ ? sorted[mid]+ : Math.round((sorted[mid - 1] + sorted[mid]) / 2);+}++/**+ * Window a recent-outcomes ring and summarize duration + spacing. Pure.+ * Samples without a parseable timestamp are dropped (they cannot contribute+ * to a recency burst). Duration stats are null when no sample carried `d`,+ * so pre-instrumentation history is distinguishable from "every run was instant".+ */+export function summarizeRecentRuns(recentOutcomes, {+ now = Date.now(),+ windowMs = CHURN_WINDOW_MS+} = {}) {+ const ring = Array.isArray(recentOutcomes) ? recentOutcomes : [];+ const cutoff = now - windowMs;+ const windowed = ring.filter((o) => {+ const t = Date.parse(o?.t);+ return Number.isFinite(t) && t >= cutoff;+ });+ const durations = windowed+ .map((o) => o?.d)+ .filter((d) => Number.isFinite(d) && d >= 0);+ const shortLivedCount = durations.filter((d) => d < SHORT_LIVED_MS).length;+ const times = windowed+ .map((o) => Date.parse(o?.t))+ .filter(Number.isFinite)+ .sort((a, b) => a - b);+ const gaps = [];+ for (let i = 1; i < times.length; i++) gaps.push(times[i] - times[i - 1]);+ return {+ windowCompleted: windowed.length,+ windowMs,+ shortLivedCount,+ shortLivedSampleSize: durations.length,+ shortLivedRatio: durations.length > 0 ? shortLivedCount / durations.length : null,+ averageDurationMs: durations.length+ ? Math.round(durations.reduce((sum, d) => sum + d, 0) / durations.length)+ : null,+ medianDurationMs: median(durations),+ medianGapMs: median(gaps)+ };+}++/**+ * Classify a task-type recency ring as churning or not. Pure.+ *+ * Two independent signals, either of which is enough once the run-count floor+ * is met:+ * - short-lived-burst — enough of the measured runs finished under+ * SHORT_LIVED_MS (the last-night shape: coordinator reports the same+ * finding and exits in a couple of minutes).+ * - rapid-succession — no duration data (pre-instrumentation ring) but the+ * completions are packed tighter than RAPID_GAP_MS. The timestamp cadence+ * is the only honest proxy when `d` was never recorded.+ *+ * A healthy drain of real work (a handful of long runs, or many long runs+ * spaced out) does not flag.+ */+export function computeChurn(recentOutcomes, opts = {}) {+ const stats = summarizeRecentRuns(recentOutcomes, opts);+ let reason = null;+ if (stats.windowCompleted >= CHURN_MIN_RUNS) {+ if (stats.shortLivedRatio !== null && stats.shortLivedRatio >= CHURN_SHORT_LIVED_RATIO) {+ reason = 'short-lived-burst';+ } else if (stats.shortLivedRatio === null && stats.medianGapMs !== null && stats.medianGapMs < RAPID_GAP_MS) {+ reason = 'rapid-succession';+ }+ }+ return { ...stats, flagged: reason !== null, reason };+}++export function buildChurnIssueTitle(taskType) {+ return `CoS churn: ${taskType} is looping on short-lived executions`;+}++function formatDuration(ms) {+ if (!Number.isFinite(ms) || ms < 0) return '—';+ if (ms < 1000) return `${Math.round(ms)}ms`;+ const sec = Math.round(ms / 1000);+ if (sec < 60) return `${sec}s`;+ const min = Math.floor(sec / 60);+ const rem = sec % 60;+ return rem ? `${min}m ${rem}s` : `${min}m`;+}++function formatWindow(ms) {+ const hours = Math.round((Number(ms) || 0) / 3600000);+ return hours <= 1 ? '1h' : `${hours}h`;+}++/**+ * Markdown body for the auto-filed churn issue. Pure. No hostnames, branch+ * names, paths, or other live-instance data — only the task-type slug and+ * the numeric burst.+ */+export function buildChurnIssueBody({ taskType, churn, signatureRepeatCount = null, generatedAt = new Date().toISOString() } = {}) {+ const windowLabel = formatWindow(churn?.windowMs);+ const lines = [+ `_Automated CoS churn alert — a scheduled task completed an excessive number of short-lived runs without making progress. Do not hand-edit the marker at the bottom._`,+ '',+ `**Task type:** \`${taskType || 'unknown'}\``,+ `**Signal:** ${churn?.reason || 'unknown'}`,+ `**Runs in last ${windowLabel}:** ${churn?.windowCompleted ?? 0}`,+ `**Short-lived (< ${formatDuration(SHORT_LIVED_MS)}):** ${churn?.shortLivedCount ?? 0}`+ + (churn?.shortLivedSampleSize+ ? ` of ${churn.shortLivedSampleSize} timed runs`+ : ' (no per-run duration recorded — used completion spacing)'),+ `**Median duration:** ${formatDuration(churn?.medianDurationMs)}`,+ `**Median gap between completions:** ${formatDuration(churn?.medianGapMs)}`+ ];+ if (Number.isFinite(signatureRepeatCount) && signatureRepeatCount > 1) {+ lines.push(`**Same-finding park count:** ${signatureRepeatCount} (the actionable set did not change)`);+ }+ lines.push('');+ lines.push('This is the failure mode where a perpetual coordinator (for example branch-reconcile) re-reports the same finding over and over instead of parking or advancing. Fix the drain so an unchanged finding parks for the recheck cadence and does not spawn another short-lived agent.');+ lines.push('');+ lines.push(`_Detected: ${generatedAt}_`);+ lines.push('');+ lines.push(slugMarker(taskType));+ return lines.join('\n');+}++export function shouldFileChurnAlert(alerts, taskType, { now = Date.now(), cooldownMs = CHURN_ALERT_COOLDOWN_MS } = {}) {+ const rec = alerts?.byTaskType?.[taskType];+ if (!rec?.filedAt) return true;+ const filedAt = Date.parse(rec.filedAt);+ if (!Number.isFinite(filedAt)) return true;+ return (now - filedAt) >= cooldownMs;+}++async function readAlerts(cosDir) {+ const parsed = await readJSONFile(alertsPath(cosDir), null);+ const byTaskType = (parsed?.byTaskType && typeof parsed.byTaskType === 'object' && !Array.isArray(parsed.byTaskType))+ ? parsed.byTaskType+ : {};+ return { byTaskType };+}++async function writeAlert(cosDir, taskType, rec) {+ const current = await readAlerts(cosDir);+ current.byTaskType[taskType] = rec;+ await atomicWrite(alertsPath(cosDir), current);+ return current;+}++function scheduledTypeOf(task) {+ return task?.metadata?.analysisType || task?.metadata?.taskAnalysisType || null;+}++function appIdOf(task) {+ return task?.metadata?.app || task?.metadata?.taskApp || null;+}++/**+ * Locate an already-open churn issue for this task type (slug marker in the+ * body, falling back to the stable title). `ok: false` means the list FAILED+ * — do not then create, or a gh blip duplicates the issue.+ */+export async function findOpenChurnIssue(taskType, { cwd = PATHS.root, exec = runCli } = {}) {+ const { code, stdout } = await exec('gh',+ ['issue', 'list', '--state', 'open', '--limit', '50', '--search', `${buildChurnIssueTitle(taskType)} in:title`, '--json', 'number,title,body,url'],+ { cwd });+ if (code !== 0) return { ok: false, issue: null };+ if (!stdout.trim()) return { ok: true, issue: null };+ let parsed;+ try { parsed = JSON.parse(stdout); } catch { return { ok: false, issue: null }; }+ if (!Array.isArray(parsed)) return { ok: false, issue: null };+ const marker = slugMarker(taskType);+ const title = buildChurnIssueTitle(taskType);+ const ours = parsed.find((i) => (i.body || '').includes(marker))+ || parsed.find((i) => i.title === title)+ || null;+ return {+ ok: true,+ issue: ours+ ? { number: ours.number ?? null, title: ours.title || '', url: ours.url || null }+ : null+ };+}++/**+ * File or refresh the churn issue. Injectable exec/cwd for tests.+ */+export async function fileChurnIssue({ taskType, churn, signatureRepeatCount = null, cwd = PATHS.root, exec = runCli, now = () => new Date().toISOString() } = {}) {+ const title = buildChurnIssueTitle(taskType);+ const body = buildChurnIssueBody({ taskType, churn, signatureRepeatCount, generatedAt: now() });+ const found = await findOpenChurnIssue(taskType, { cwd, exec });+ if (!found.ok) return { ok: false, issue: null, reason: 'list-failed' };+ if (found.issue?.number) {+ const { code, stderr } = await exec('gh',+ ['issue', 'edit', String(found.issue.number), '--body', body],+ { cwd });+ if (code !== 0) {+ console.warn(`⚠️ CoS churn: failed to update issue #${found.issue.number}: ${(stderr || '').trim()}`);+ return { ok: false, issue: found.issue, reason: 'edit-failed' };+ }+ return { ok: true, issue: found.issue, created: false };+ }+ const { code, stdout, stderr } = await exec('gh',+ ['issue', 'create', '--title', title, '--body', body],+ { cwd });+ if (code !== 0) {+ console.warn(`⚠️ CoS churn: failed to create issue: ${(stderr || '').trim()}`);+ return { ok: false, issue: null, reason: 'create-failed' };+ }+ const url = ((stdout || '').trim().match(/(https?:\/\/\S+)/) || [])[1] || (stdout || '').trim();+ const number = Number((url.match(/(\d+)\s*$/) || [])[1]) || null;+ return { ok: true, issue: { number, url, title }, created: true };+}++/**+ * Watch one completed agent run. Call AFTER `recordTaskCompletion` so this+ * run is already on the recency ring. Never throws — callers at the+ * agent-completed boundary must stay up if filing or parking fails.+ */+export async function observeAgentChurn(agent, task, {+ loadLearning = loadLearningData,+ now = Date.now,+ exec = runCli,+ cwd = PATHS.root,+ cosDir = PATHS.cos,+ park = null,+ readPark = null,+ forgeGate = null+} = {}) {+ const taskType = extractTaskType(task);+ if (!taskType) return { flagged: false };+ const clock = typeof now === 'function' ? now() : now;+ const nowMs = typeof clock === 'number' ? clock : Date.parse(clock);+ const effectiveNow = Number.isFinite(nowMs) ? nowMs : Date.now();++ const data = await loadLearning();+ const churn = computeChurn(data?.byTaskType?.[taskType]?.recentOutcomes, { now: effectiveNow });+ if (!churn.flagged) return { flagged: false, taskType, churn };++ const analysisType = scheduledTypeOf(task);+ const appId = appIdOf(task);+ console.warn(`⚠️ CoS churn: ${taskType} ${churn.reason} (${churn.windowCompleted} runs in ${formatWindow(churn.windowMs)})`);++ let parked = false;+ if (NON_COMMITTING_COORDINATOR_TASK_TYPES.has(analysisType)) {+ const parkFn = park || (async (...args) => {+ const { parkPerpetual } = await import('./taskSchedule.js');+ return parkPerpetual(...args);+ });+ await parkFn(analysisType, appId, { reason: 'churn-detected', actionableCount: churn.windowCompleted });+ parked = true;+ console.warn(`⚠️ CoS churn: parked ${analysisType} so the loop stops burning quota`);+ }++ let signatureRepeatCount = null;+ if (analysisType && appId) {+ const read = readPark || (async (type, id) => {+ const { getPerpetualParkInfo } = await import('./taskSchedule.js');+ return getPerpetualParkInfo(type, id);+ });+ const parkInfo = await read(analysisType, appId).catch(() => null);+ if (Number.isFinite(parkInfo?.signatureRepeatCount)) signatureRepeatCount = parkInfo.signatureRepeatCount;+ }++ const alerts = await readAlerts(cosDir);+ if (!shouldFileChurnAlert(alerts, taskType, { now: effectiveNow })) {+ return { flagged: true, filed: false, parked, taskType, churn, reason: 'cooldown' };+ }++ const gate = forgeGate || (async () => {+ const { ensureForgeReachable } = await import('./github.js');+ return ensureForgeReachable('cos-churn');+ });+ const forge = await gate();+ if (!forge?.ok) {+ return { flagged: true, filed: false, parked, taskType, churn, reason: 'forge-unavailable' };+ }++ const isoNow = () => new Date(effectiveNow).toISOString();+ const filed = await fileChurnIssue({+ taskType,+ churn,+ signatureRepeatCount,+ cwd,+ exec,+ now: isoNow+ });+ if (filed.ok) {+ await writeAlert(cosDir, taskType, {+ filedAt: isoNow(),+ issueNumber: filed.issue?.number ?? null,+ url: filed.issue?.url ?? null,+ reason: churn.reason,+ windowCompleted: churn.windowCompleted+ });+ console.log(`🔁 CoS churn: ${filed.created ? 'filed' : 'updated'} issue ${filed.issue?.url || `#${filed.issue?.number}`} for ${taskType}`);+ }+ return { flagged: true, filed: !!filed.ok, created: !!filed.created, parked, taskType, churn, issue: filed.issue || null };+}diff --git a/server/services/agentChurn.test.js b/server/services/agentChurn.test.jsnew file mode 100644index 0000000000..8cf9a28ff0--- /dev/null+++ b/server/services/agentChurn.test.js@@ -0,0 +1,336 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, readFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import {+ CHURN_WINDOW_MS,+ CHURN_MIN_RUNS,+ CHURN_SLUG_PREFIX,+ summarizeRecentRuns,+ computeChurn,+ buildChurnIssueTitle,+ buildChurnIssueBody,+ shouldFileChurnAlert,+ findOpenChurnIssue,+ fileChurnIssue,+ observeAgentChurn,+ alertsPath+} from './agentChurn.js';++const HOUR = 60 * 60 * 1000;+const MIN = 60 * 1000;++function ring({ n, now, durationMs = 90_000, gapMs = 10 * MIN, withDuration = true }) {+ return Array.from({ length: n }, (_, i) => {+ const sample = {+ t: new Date(now - (n - 1 - i) * gapMs).toISOString(),+ s: true+ };+ if (withDuration) sample.d = durationMs;+ return sample;+ });+}++describe('summarizeRecentRuns / computeChurn', () => {+ const now = Date.parse('2026-08-12T08:00:00.000Z');++ it('flags the last-night shape: many short-lived completions of the same task', () => {+ const recentOutcomes = ring({ n: 24, now, durationMs: 90_000, gapMs: 8 * MIN });+ const churn = computeChurn(recentOutcomes, { now });+ expect(churn.flagged).toBe(true);+ expect(churn.reason).toBe('short-lived-burst');+ expect(churn.windowCompleted).toBe(24);+ expect(churn.shortLivedCount).toBe(24);+ expect(churn.medianDurationMs).toBe(90_000);+ });++ it('flags a pre-instrumentation burst from completion spacing alone', () => {+ const recentOutcomes = ring({ n: 12, now, withDuration: false, gapMs: 10 * MIN });+ const churn = computeChurn(recentOutcomes, { now });+ expect(churn.flagged).toBe(true);+ expect(churn.reason).toBe('rapid-succession');+ expect(churn.shortLivedRatio).toBeNull();+ expect(churn.medianGapMs).toBe(10 * MIN);+ });++ it('does not flag a healthy drain of a few long runs', () => {+ const recentOutcomes = ring({ n: 3, now, durationMs: 25 * MIN, gapMs: 40 * MIN });+ expect(computeChurn(recentOutcomes, { now }).flagged).toBe(false);+ });++ it('does not flag many long runs (real work finishing, just busy)', () => {+ const recentOutcomes = ring({ n: 10, now, durationMs: 20 * MIN, gapMs: 30 * MIN });+ const churn = computeChurn(recentOutcomes, { now });+ expect(churn.flagged).toBe(false);+ expect(churn.windowCompleted).toBe(10);+ expect(churn.shortLivedRatio).toBe(0);+ });++ it('does not flag a thin window below the run-count floor', () => {+ const recentOutcomes = ring({ n: CHURN_MIN_RUNS - 1, now, durationMs: 30_000, gapMs: 5 * MIN });+ expect(computeChurn(recentOutcomes, { now }).flagged).toBe(false);+ });++ it('drops samples outside the burst window', () => {+ const recentOutcomes = [+ ...ring({ n: 20, now: now - CHURN_WINDOW_MS - HOUR, durationMs: 30_000, gapMs: 5 * MIN }),+ ...ring({ n: 2, now, durationMs: 30_000, gapMs: 5 * MIN })+ ];+ const stats = summarizeRecentRuns(recentOutcomes, { now });+ expect(stats.windowCompleted).toBe(2);+ expect(computeChurn(recentOutcomes, { now }).flagged).toBe(false);+ });++ it('treats an empty / missing ring as not-churning, with null duration sentinels', () => {+ const empty = computeChurn([], { now });+ expect(empty.flagged).toBe(false);+ expect(empty.medianDurationMs).toBeNull();+ expect(empty.shortLivedRatio).toBeNull();+ expect(computeChurn(undefined, { now }).flagged).toBe(false);+ });+});++describe('churn issue copy', () => {+ it('uses a stable title keyed on the task type', () => {+ expect(buildChurnIssueTitle('self-improve:branch-reconcile'))+ .toBe('CoS churn: self-improve:branch-reconcile is looping on short-lived executions');+ });++ it('embeds the slug marker and no live-instance data', () => {+ const body = buildChurnIssueBody({+ taskType: 'self-improve:branch-reconcile',+ churn: {+ reason: 'short-lived-burst',+ windowCompleted: 24,+ windowMs: CHURN_WINDOW_MS,+ shortLivedCount: 24,+ shortLivedSampleSize: 24,+ medianDurationMs: 90_000,+ medianGapMs: 8 * MIN+ },+ signatureRepeatCount: 4,+ generatedAt: '2026-08-12T08:00:00.000Z'+ });+ expect(body).toContain(`<!-- lil-slug: ${CHURN_SLUG_PREFIX}:self-improve:branch-reconcile -->`);+ expect(body).toContain('short-lived-burst');+ expect(body).toContain('24');+ expect(body).toContain('**Same-finding park count:** 4');+ expect(body).not.toMatch(/\/Users\//);+ expect(body).not.toMatch(/origin\//);+ });+});++describe('shouldFileChurnAlert', () => {+ const now = Date.parse('2026-08-12T08:00:00.000Z');++ it('files when nothing has been recorded for the type', () => {+ expect(shouldFileChurnAlert({ byTaskType: {} }, 'self-improve:branch-reconcile', { now })).toBe(true);+ });++ it('suppresses a re-file inside the cooldown', () => {+ expect(shouldFileChurnAlert({+ byTaskType: { 'self-improve:branch-reconcile': { filedAt: '2026-08-11T08:00:00.000Z' } }+ }, 'self-improve:branch-reconcile', { now })).toBe(false);+ });++ it('re-files after the cooldown elapses', () => {+ expect(shouldFileChurnAlert({+ byTaskType: { 'self-improve:branch-reconcile': { filedAt: '2026-08-01T08:00:00.000Z' } }+ }, 'self-improve:branch-reconcile', { now })).toBe(true);+ });+});++describe('fileChurnIssue', () => {+ it('creates when no open issue exists', async () => {+ const exec = vi.fn()+ .mockResolvedValueOnce({ code: 0, stdout: '[]' })+ .mockResolvedValueOnce({ code: 0, stdout: 'https://github.com/example/PortOS/issues/42\n', stderr: '' });+ const result = await fileChurnIssue({+ taskType: 'self-improve:branch-reconcile',+ churn: { reason: 'short-lived-burst', windowCompleted: 12, windowMs: CHURN_WINDOW_MS, shortLivedCount: 12, shortLivedSampleSize: 12 },+ exec,+ now: () => '2026-08-12T08:00:00.000Z'+ });+ expect(result.ok).toBe(true);+ expect(result.created).toBe(true);+ expect(result.issue.number).toBe(42);+ expect(exec.mock.calls[1][0]).toBe('gh');+ expect(exec.mock.calls[1][1][0]).toBe('issue');+ expect(exec.mock.calls[1][1][1]).toBe('create');+ });++ it('edits an existing open issue instead of creating a duplicate', async () => {+ const existing = [{+ number: 7,+ title: buildChurnIssueTitle('self-improve:branch-reconcile'),+ body: `old\n<!-- lil-slug: ${CHURN_SLUG_PREFIX}:self-improve:branch-reconcile -->`,+ url: 'https://github.com/example/PortOS/issues/7'+ }];+ const exec = vi.fn()+ .mockResolvedValueOnce({ code: 0, stdout: JSON.stringify(existing) })+ .mockResolvedValueOnce({ code: 0, stdout: '', stderr: '' });+ const result = await fileChurnIssue({+ taskType: 'self-improve:branch-reconcile',+ churn: { reason: 'short-lived-burst', windowCompleted: 20, windowMs: CHURN_WINDOW_MS, shortLivedCount: 18, shortLivedSampleSize: 20 },+ exec+ });+ expect(result.ok).toBe(true);+ expect(result.created).toBe(false);+ expect(result.issue.number).toBe(7);+ expect(exec.mock.calls[1][1]).toEqual(['issue', 'edit', '7', '--body', expect.any(String)]);+ });++ it('refuses to create when the open-issue list fails', async () => {+ const exec = vi.fn().mockResolvedValue({ code: 1, stdout: '', stderr: 'gh: auth' });+ const result = await fileChurnIssue({+ taskType: 'self-improve:branch-reconcile',+ churn: { reason: 'short-lived-burst', windowCompleted: 12, windowMs: CHURN_WINDOW_MS },+ exec+ });+ expect(result).toEqual({ ok: false, issue: null, reason: 'list-failed' });+ expect(exec).toHaveBeenCalledTimes(1);+ });+});++describe('findOpenChurnIssue', () => {+ it('returns ok:false when gh fails so a caller will not create a duplicate', async () => {+ const exec = vi.fn().mockResolvedValue({ code: 1, stdout: '' });+ await expect(findOpenChurnIssue('self-improve:branch-reconcile', { exec }))+ .resolves.toEqual({ ok: false, issue: null });+ });+});++describe('observeAgentChurn', () => {+ let dir;+ const now = Date.parse('2026-08-12T08:00:00.000Z');++ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'cos-churn-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ const burstRing = ring({ n: 20, now, durationMs: 80_000, gapMs: 8 * MIN });++ it('no-ops when the type is not churning', async () => {+ const park = vi.fn();+ const exec = vi.fn();+ const out = await observeAgentChurn(+ { result: { duration: 20 * MIN } },+ { metadata: { analysisType: 'branch-reconcile', app: 'app-1' } },+ {+ loadLearning: async () => ({ byTaskType: { 'self-improve:branch-reconcile': { recentOutcomes: ring({ n: 2, now, durationMs: 20 * MIN }) } } }),+ now: () => now,+ park,+ exec,+ cosDir: dir,+ forgeGate: async () => ({ ok: true })+ }+ );+ expect(out.flagged).toBe(false);+ expect(park).not.toHaveBeenCalled();+ expect(exec).not.toHaveBeenCalled();+ });++ it('parks a looping coordinator and files one issue (the last-night branch-reconcile case)', async () => {+ const park = vi.fn(async () => ({}));+ const exec = vi.fn()+ .mockResolvedValueOnce({ code: 0, stdout: '[]' })+ .mockResolvedValueOnce({ code: 0, stdout: 'https://github.com/example/PortOS/issues/99\n', stderr: '' });+ const out = await observeAgentChurn(+ { result: { duration: 80_000 } },+ { metadata: { analysisType: 'branch-reconcile', app: 'app-1' } },+ {+ loadLearning: async () => ({ byTaskType: { 'self-improve:branch-reconcile': { recentOutcomes: burstRing } } }),+ now: () => now,+ park,+ exec,+ cosDir: dir,+ cwd: dir,+ forgeGate: async () => ({ ok: true }),+ readPark: async () => ({ signatureRepeatCount: 6 })+ }+ );+ expect(out.flagged).toBe(true);+ expect(out.filed).toBe(true);+ expect(out.created).toBe(true);+ expect(out.parked).toBe(true);+ expect(park).toHaveBeenCalledWith('branch-reconcile', 'app-1', {+ reason: 'churn-detected',+ actionableCount: 20+ });+ const createBody = exec.mock.calls[1][1][exec.mock.calls[1][1].indexOf('--body') + 1];+ expect(createBody).toContain('**Same-finding park count:** 6');+ const saved = JSON.parse(await readFile(alertsPath(dir), 'utf8'));+ expect(saved.byTaskType['self-improve:branch-reconcile'].issueNumber).toBe(99);+ });++ it('files but does not park a non-coordinator task type', async () => {+ const park = vi.fn();+ const exec = vi.fn()+ .mockResolvedValueOnce({ code: 0, stdout: '[]' })+ .mockResolvedValueOnce({ code: 0, stdout: 'https://github.com/example/PortOS/issues/3\n', stderr: '' });+ const out = await observeAgentChurn(+ { result: { duration: 40_000 } },+ { metadata: { analysisType: 'claim-issue', app: 'app-1' } },+ {+ loadLearning: async () => ({ byTaskType: { 'self-improve:claim-issue': { recentOutcomes: burstRing } } }),+ now: () => now,+ park,+ exec,+ cosDir: dir,+ cwd: dir,+ forgeGate: async () => ({ ok: true })+ }+ );+ expect(out.flagged).toBe(true);+ expect(out.filed).toBe(true);+ expect(out.parked).toBe(false);+ expect(park).not.toHaveBeenCalled();+ });++ it('does not re-file inside the cooldown, but still parks a coordinator', async () => {+ const { writeFile, mkdir } = await import('fs/promises');+ await mkdir(dir, { recursive: true });+ await writeFile(alertsPath(dir), JSON.stringify({+ byTaskType: { 'self-improve:branch-reconcile': { filedAt: new Date(now - HOUR).toISOString(), issueNumber: 1 } }+ }));+ const park = vi.fn(async () => ({}));+ const exec = vi.fn();+ const out = await observeAgentChurn(+ { result: { duration: 80_000 } },+ { metadata: { taskAnalysisType: 'branch-reconcile', taskApp: 'app-1' } },+ {+ loadLearning: async () => ({ byTaskType: { 'self-improve:branch-reconcile': { recentOutcomes: burstRing } } }),+ now: () => now,+ park,+ exec,+ cosDir: dir,+ forgeGate: async () => ({ ok: true })+ }+ );+ expect(out.flagged).toBe(true);+ expect(out.filed).toBe(false);+ expect(out.reason).toBe('cooldown');+ expect(out.parked).toBe(true);+ expect(exec).not.toHaveBeenCalled();+ });++ it('skips filing when the forge is unreachable', async () => {+ const park = vi.fn(async () => ({}));+ const exec = vi.fn();+ const out = await observeAgentChurn(+ { result: { duration: 80_000 } },+ { metadata: { analysisType: 'branch-reconcile', app: 'app-1' } },+ {+ loadLearning: async () => ({ byTaskType: { 'self-improve:branch-reconcile': { recentOutcomes: burstRing } } }),+ now: () => now,+ park,+ exec,+ cosDir: dir,+ forgeGate: async () => ({ ok: false, status: 'error' })+ }+ );+ expect(out.filed).toBe(false);+ expect(out.reason).toBe('forge-unavailable');+ expect(out.parked).toBe(true);+ expect(exec).not.toHaveBeenCalled();+ });+});diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex f81a2bfeb6..6adcf5ca5a 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -3138,6 +3138,27 @@ describe('gatherSources cosMetrics windowed rate (issue #2460)', () => {expect(out.cosMetrics).toBeUndefined();});+ it('harvests 24h short-lived run counts next to the lifetime duration', async () => {+ const now = Date.now();+ await writeLearning({+ byTaskType: {+ 'self-improve:branch-reconcile': {+ completed: 24, succeeded: 24, failed: 0, successRate: 100, avgDurationMs: 90_000,+ recentOutcomes: Array.from({ length: 12 }, (_, i) => ({+ t: new Date(now - i * 10 * 60 * 1000).toISOString(),+ s: true,+ d: 80_000+ }))+ }+ }+ });+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: true } }, { cosPath: dir });+ const parsed = JSON.parse(out.cosMetrics);+ expect(parsed['self-improve:branch-reconcile'].recent24hCompleted).toBe(12);+ expect(parsed['self-improve:branch-reconcile'].recent24hShortLived).toBe(12);+ expect(parsed['self-improve:branch-reconcile'].recent24hMedianDurationMs).toBe(80_000);+ });+it('does not emit scopeGuidance when cosMetrics is off (#2760)', async () => {await writeLearning({byTaskType: { 'accessibility': { completed: 4, succeeded: 0, failed: 4, successRate: 0, recentOutcomes: [] } }diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.jsindex e53c9e1bc4..420b0a49be 100644--- a/server/services/layeredIntelligence/sources.js+++ b/server/services/layeredIntelligence/sources.js@@ -15,6 +15,7 @@ import { fetchPublicText } from '../../lib/safeUrlFetch.js';import { validateCommand } from '../../lib/commandSecurity.js';import { getSettings } from '../settings.js';import { computeWindowedStats } from '../taskLearning/store.js';+import { summarizeRecentRuns, SHORT_LIVED_MS } from '../agentChurn.js';import {PLANNED_WORK_LABEL, PLANNED_WORK_NONE, PLANNED_WORK_UNAVAILABLE_PREFIX,PLANNED_WORK_MAX_ITEMS, PLANNED_WORK_MAX_CHARS, LI_TASK_TYPE,@@ -298,14 +299,23 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShe// still have approved-but-undelivered proposals worth surfacing. When both halves// are empty renderCosMetricsSource returns '' and the source is omitted as before.const summary = {};+ const DAY_MS = 24 * 60 * 60 * 1000;for (const [type, m] of Object.entries(learning?.byTaskType || {})) {const windowed = computeWindowedStats(m?.recentOutcomes);+ // 24h burst stats (duration + count) so the PortOS reasoner can see a+ // short-lived loop as numbers even though detection/filing is now+ // programmatic at agent completion, not an LI judgment call.+ const burst = summarizeRecentRuns(m?.recentOutcomes, { windowMs: DAY_MS });summary[type] = {lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,lifetimeCompleted: m?.completed || 0,recentSuccessRate: windowed.windowedSuccessRate,recentCompleted: windowed.windowedCompleted,- avgDurationMs: m?.avgDurationMs || 0+ avgDurationMs: m?.avgDurationMs || 0,+ recent24hCompleted: burst.windowCompleted,+ recent24hShortLived: burst.shortLivedCount,+ recent24hMedianDurationMs: burst.medianDurationMs,+ shortLivedMs: SHORT_LIVED_MS};}// No delivery block yet: the approval → delivery numbers come from the app'sdiff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.jsindex ba7f80bc6a..97f871db5f 100644--- a/server/services/taskLearning/lifecycle.js+++ b/server/services/taskLearning/lifecycle.js@@ -52,6 +52,13 @@ export function initTaskLearning() {await recordTaskCompletion(agent, task).catch(err => {console.error(`❌ 📚 TaskLearning: Failed to record completion: ${err.message}`);});+ // After the ring includes this run: a burst of short-lived completions of+ // the SAME task type is a looping coordinator, not something LI should+ // have to notice. Park + file happen inside observeAgentChurn.+ const { observeAgentChurn } = await import('../agentChurn.js');+ await observeAgentChurn(agent, task).catch(err => {+ console.error(`❌ 🔁 CoS churn: Failed to observe completion: ${err.message}`);+ });});// Self-heal model tier metrics on startupdiff --git a/server/services/taskLearning/lifecycle.test.js b/server/services/taskLearning/lifecycle.test.jsindex fd0ab508f8..9df3d7df9b 100644--- a/server/services/taskLearning/lifecycle.test.js+++ b/server/services/taskLearning/lifecycle.test.js@@ -17,10 +17,14 @@ vi.mock('./store.js', () => ({emitLog: vi.fn(),}));vi.mock('../cos.js', () => ({ getAgents: vi.fn(async () => agentsStore.list) }));+vi.mock('../agentChurn.js', () => ({+ observeAgentChurn: vi.fn(async () => ({ flagged: false })),+}));import { backfillFromHistory, initTaskLearning } from './lifecycle.js';import { recordTaskCompletion } from './metrics.js';import { cosEvents } from './store.js';+import { observeAgentChurn } from '../agentChurn.js';const completed = (taskId, analysisType, validationPassed) => ({status: 'completed',@@ -136,5 +140,15 @@ describe('agent:completed listener — a resumed record is a continuation, not ametadata: { taskType: 'user', taskDescription: 'Half-finished work' },});expect(recordTaskCompletion).toHaveBeenCalledTimes(1);+ expect(observeAgentChurn).toHaveBeenCalledTimes(1);+ });++ it('does not observe churn for a resume continuation', async () => {+ await emitCompleted({+ status: 'completed', taskId: 't1',+ result: { success: false, resumed: true, resumedTaskId: 't1' },+ metadata: { taskType: 'user', taskDescription: 'Half-finished work' },+ });+ expect(observeAgentChurn).not.toHaveBeenCalled();});});diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.jsindex 30a0d8353b..f7428ececc 100644--- a/server/services/taskLearning/metrics.js+++ b/server/services/taskLearning/metrics.js@@ -490,7 +490,17 @@ export async function recordTaskCompletion(agent, task) {// counters above never decay; the ring lets LI read a recency-windowed rate so// a since-resolved failure burst ages out of the "is work needed" signal// instead of depressing it forever. Stamped with the same `lastCompleted` time.- appendRecentOutcome(typeMetrics, { success: outcomeSuccess, at: typeMetrics.lastCompleted });+ // Prefer the runner's measured duration; fall back to the wall split so a+ // coordinator that never stamped `result.duration` still contributes to the+ // short-lived-burst detector. Absent both → omit `d` (not 0).+ const durationMs = Number.isFinite(agent.result?.duration)+ ? agent.result.duration+ : telemetry.latency?.executionMs;+ appendRecentOutcome(typeMetrics, {+ success: outcomeSuccess,+ at: typeMetrics.lastCompleted,+ durationMs: Number.isFinite(durationMs) ? durationMs : null+ });// Update model tier metricsconst tierMetrics = data.byModelTier[modelTier];diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.jsindex dd56213862..5b14e4ee76 100644--- a/server/services/taskLearning/store.js+++ b/server/services/taskLearning/store.js@@ -67,14 +67,21 @@ export const DEFAULT_WINDOW_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days/*** Append a recent outcome to a task-type metrics bucket's bounded ring (issue* #2460). Mutates `metrics` in place and returns it for chaining. Stores the compact `{ t, s }`- * shape (ISO timestamp + success bool). Tolerates a bucket that predates the ring- * (older learning.json before migration 188) by initializing it. Enforces- * `RECENT_OUTCOMES_CAP`, dropping the oldest sample first.+ * shape (ISO timestamp + success bool), plus `d` (duration ms) when a finite+ * duration was measured — omitted when unknown so a pre-duration sample and a+ * duration-less new sample stay the same shape (absent ≠ 0). Tolerates a bucket+ * that predates the ring (older learning.json before migration 188) by+ * initializing it. Enforces `RECENT_OUTCOMES_CAP`, dropping the oldest sample first.*/-export function appendRecentOutcome(metrics, { success, at } = {}) {+export function appendRecentOutcome(metrics, { success, at, durationMs } = {}) {if (!metrics || typeof metrics !== 'object') return metrics;if (!Array.isArray(metrics.recentOutcomes)) metrics.recentOutcomes = [];- metrics.recentOutcomes.push({ t: at || new Date().toISOString(), s: !!success });+ const sample = { t: at || new Date().toISOString(), s: !!success };+ // Only a finite, non-negative duration is a measurement. `|| 0` would collapse+ // "not recorded" into "instant", which is exactly the sentinel the churn+ // detector must not trip on for pre-instrumentation history.+ if (Number.isFinite(durationMs) && durationMs >= 0) sample.d = durationMs;+ metrics.recentOutcomes.push(sample);if (metrics.recentOutcomes.length > RECENT_OUTCOMES_CAP) {metrics.recentOutcomes = metrics.recentOutcomes.slice(-RECENT_OUTCOMES_CAP);}diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.jsindex 71d023657a..03a34f514e 100644--- a/server/services/taskLearning/store.test.js+++ b/server/services/taskLearning/store.test.js@@ -420,6 +420,19 @@ describe('store.appendRecentOutcome', () => {it('is a no-op on a non-object metrics bucket', () => {expect(appendRecentOutcome(null, { success: true })).toBeNull();});++ it('stores a finite duration as d and omits the key when duration is unknown', () => {+ const metrics = {};+ appendRecentOutcome(metrics, { success: true, at: '2026-07-10T00:00:00.000Z', durationMs: 90_000 });+ expect(metrics.recentOutcomes[0]).toEqual({ t: '2026-07-10T00:00:00.000Z', s: true, d: 90_000 });+ appendRecentOutcome(metrics, { success: false, at: '2026-07-10T00:01:00.000Z' });+ expect(metrics.recentOutcomes[1]).toEqual({ t: '2026-07-10T00:01:00.000Z', s: false });+ appendRecentOutcome(metrics, { success: true, at: '2026-07-10T00:02:00.000Z', durationMs: null });+ expect(metrics.recentOutcomes[2]).not.toHaveProperty('d');+ // A measured 0 is a real instant run, not "unknown".+ appendRecentOutcome(metrics, { success: true, at: '2026-07-10T00:03:00.000Z', durationMs: 0 });+ expect(metrics.recentOutcomes[3].d).toBe(0);+ });});describe('store.computeWindowedStats', () => {diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 98fdfa11ff..41e63c0489 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -1047,9 +1047,20 @@ export async function parkPerpetual(taskType, appId = null, { reason = null, act// next recheck can tell "same stuck set" (park again) from "the set changed"// (resume). `null` clears it (an idle park with nothing actionable); `undefined`// (the default) leaves any prior signature untouched.+ //+ // `signatureRepeatCount` is the harvested "same finding again" metric the+ // CoS churn detector reports: increment when this park restates the same+ // signature, reset when the set changes, clear when idle.if (signature !== undefined) {- if (signature === null) delete record.lastActionableSignature;- else record.lastActionableSignature = signature;+ if (signature === null) {+ delete record.lastActionableSignature;+ delete record.signatureRepeatCount;+ } else if (signature === record.lastActionableSignature) {+ record.signatureRepeatCount = (Number(record.signatureRepeatCount) || 1) + 1;+ } else {+ record.lastActionableSignature = signature;+ record.signatureRepeatCount = 1;+ }}await saveSchedule(schedule);emitLog('info', `Perpetual ${taskType} parked until ${parkedUntil} (${reason || 'idle'})`, { taskType, appId, parkedUntil }, '📅 TaskSchedule');@@ -1072,7 +1083,8 @@ export async function getPerpetualParkInfo(taskType, appId = null) {parkReason: record.parkReason ?? null,parkActionableCount: record.parkActionableCount ?? null,parkCounts: record.parkCounts ?? null,- parkedAt: record.parkedAt ?? null+ parkedAt: record.parkedAt ?? null,+ signatureRepeatCount: Number.isFinite(record.signatureRepeatCount) ? record.signatureRepeatCount : null};}@@ -1125,7 +1137,7 @@ export async function resetPerpetualForManualRun(taskType, appId = null) {const record = resolveExecutionRecord(schedule, taskType, appId);if (!record) return false;let changed = false;- for (const field of [...PARK_FIELDS, 'lastActionableSignature']) {+ for (const field of [...PARK_FIELDS, 'lastActionableSignature', 'signatureRepeatCount']) {if (record[field] !== undefined) { delete record[field]; changed = true; }}if (changed) await saveSchedule(schedule);diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 8943ed3b33..8797ff2efe 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -1660,6 +1660,28 @@ describe('taskSchedule', () => {const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBeUndefined()})++ it('parkPerpetual increments signatureRepeatCount when the same finding is parked again', async () => {+ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'a:NEEDS_PR:none' } } } }+ })+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 1, signature: 'a:NEEDS_PR:none' })+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].signatureRepeatCount).toBe(2)+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('a:NEEDS_PR:none')+ })++ it('parkPerpetual resets signatureRepeatCount when the finding changes', async () => {+ mockSchedule({+ tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true, recheckIntervalMs: 3600000 } },+ executions: { 'task:branch-reconcile': { lastRun: null, count: 0, perApp: { 'app-1': { lastRun: null, count: 0, lastActionableSignature: 'old', signatureRepeatCount: 6 } } } }+ })+ await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-progress', actionableCount: 1, signature: 'new' })+ const saved = JSON.parse(writeFile.mock.calls.at(-1)[1])+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].lastActionableSignature).toBe('new')+ expect(saved.executions['task:branch-reconcile'].perApp['app-1'].signatureRepeatCount).toBe(1)+ })})describe('type-level failure ledger (#2616)', () => {