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 CoS churn telemetry local for Layered Intelligence
[._.]/ Adam Eivy323f26256fb6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2e04789809..6c345c9d3f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,6 @@## 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.+- 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 and keeps the per-run duration signal local for a future Layered Intelligence run to assess and, only when justified, turn into a concrete planned fix.- Git submodules are now managed per app instead of on one global Dev Tools page. Any managed app whose repo has a `.gitmodules` gets a Submodules tab showing each submodule against its remote, so PortOS's own bundled slashdo is maintained from the PortOS app page alongside its git, processes and update controls. Updating a submodule can now also commit the pointer bump for you: leave "Commit the pointer bump" on and the update stages just that submodule and commits it on the repo's default branch. It refuses to commit — and says why — when the repo is checked out on some other branch, so the bump can't land in the middle of unrelated work. The old `/devtools/submodules` link redirects to PortOS's own tab.- Quota Burn steps can now be marked **Run once**, so a burn plan can be a one-shot series instead of a rotation that repeats forever. A plan is walked lap after lap until a quota gate closes, which is right for a standing audit and wrong for work that only needs doing once — that work was simply re-done every lap for as long as the window had quota left. A step marked Run once records its dispatch, drops out of the rotation, and shows when it ran, with a ↺ Re-arm on the row (and Re-arm all on the plan) to put it back. Re-arming spends nothing; the next cycle still faces every gate. Existing plans are unaffected: steps repeat by default, exactly as before. A plan whose steps have all run also stops paying for the multi-second provider quota scrape every interval, and reports "every enabled job has already run once" rather than looking misconfigured.- The Usage page can now record what you pay each month for your AI subscriptions (Claude, Codex, Antigravity, Grok) and shows what those plans saved against the estimated API cost. Each plan's price is prorated across whatever report window is selected, so both sides of the comparison cover the same days, and every plan gets its own row: monthly price, cost for this window, the API-rate cost its usage ran up, and the difference. Usage no subscription covers — pay-as-you-go API providers and pre-breakdown legacy rows — is reported separately instead of being credited to a plan.diff --git a/server/services/agentChurn.js b/server/services/agentChurn.jsindex 76b0067c51..8441253c24 100644--- a/server/services/agentChurn.js+++ b/server/services/agentChurn.js@@ -3,23 +3,19 @@** 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.+ * identical findings, each a couple of minutes) is a local diagnostic signal.+ * This module watches every agent completion, decides from the task-type+ * recency ring whether the type is churning, and parks a looping coordinator+ * so it stops burning quota. The learning ring stays local; Layered+ * Intelligence can later decide whether the signal supports a concrete,+ * planned fix worth filing.** 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';-import { formatDurationShort } from './autonomousJobs/selfDiagnostics.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@@ -29,12 +25,6 @@ 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;@@ -113,70 +103,11 @@ export function computeChurn(recentOutcomes, opts = {}) {return { ...stats, flagged: reason !== null, reason };}-export function buildChurnIssueTitle(taskType) {- return `CoS churn: ${taskType} is looping on short-lived executions`;-}-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 (< ${formatDurationShort(SHORT_LIVED_MS)}):** ${churn?.shortLivedCount ?? 0}`- + (churn?.shortLivedSampleSize- ? ` of ${churn.shortLivedSampleSize} timed runs`- : ' (no per-run duration recorded — used completion spacing)'),- `**Median duration:** ${formatDurationShort(churn?.medianDurationMs)}`,- `**Median gap between completions:** ${formatDurationShort(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;}@@ -185,77 +116,16 @@ 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.+ * agent-completed boundary must stay up if 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+ park = null} = {}) {const taskType = extractTaskType(task);if (!taskType) return { flagged: false };@@ -282,48 +152,5 @@ export async function observeAgentChurn(agent, task, {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 };+ return { flagged: true, filed: false, parked, taskType, churn, reason: 'local-metric' };}diff --git a/server/services/agentChurn.test.js b/server/services/agentChurn.test.jsindex 3cc2da0a88..49373b1bb1 100644--- a/server/services/agentChurn.test.js+++ b/server/services/agentChurn.test.js@@ -1,20 +1,10 @@-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 { describe, it, expect, vi } from 'vitest';import {CHURN_WINDOW_MS,CHURN_MIN_RUNS,- CHURN_SLUG_PREFIX,summarizeRecentRuns,computeChurn,- buildChurnIssueTitle,- buildChurnIssueBody,- shouldFileChurnAlert,- findOpenChurnIssue,- fileChurnIssue,- observeAgentChurn,- alertsPath+ observeAgentChurn} from './agentChurn.js';const HOUR = 60 * 60 * 1000;@@ -90,288 +80,62 @@ describe('summarizeRecentRuns / computeChurn', () => {});});-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\//);- });-- // The durations are rendered by `formatDurationShort`, which agentChurn shares- // with selfDiagnostics. Pin the rendered strings here so a diagnostics-motivated- // tweak to that formatter can't silently reword the auto-filed churn issue.- it('renders the durations through the shared short-duration formatter', () => {- 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- },- generatedAt: '2026-08-12T08:00:00.000Z'- });- expect(body).toContain('**Short-lived (< 5m):** 24 of 24 timed runs');- expect(body).toContain('**Median duration:** 1m 30s');- expect(body).toContain('**Median gap between completions:** 8m');- });-- it('renders absent durations as the em-dash sentinel', () => {- const body = buildChurnIssueBody({- taskType: 'self-improve:branch-reconcile',- churn: {- reason: 'rapid-succession',- windowCompleted: 12,- windowMs: CHURN_WINDOW_MS,- shortLivedCount: 0,- shortLivedSampleSize: 0,- medianDurationMs: null,- medianGapMs: null- },- generatedAt: '2026-08-12T08:00:00.000Z'- });- expect(body).toContain('**Median duration:** —');- expect(body).toContain('**Median gap between completions:** —');- expect(body).toContain('(no per-run duration recorded — used completion spacing)');- });-});--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 })+ park});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 () => {+ it('parks a looping coordinator and keeps the signal local for Layered Intelligence', 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 })+ park});expect(out.flagged).toBe(true);- expect(out.filed).toBe(true);- expect(out.created).toBe(true);+ expect(out.filed).toBe(false);+ expect(out.reason).toBe('local-metric');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 () => {+ it('keeps a non-coordinator churn signal local without parking or filing', 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 })+ park});expect(out.flagged).toBe(true);- expect(out.filed).toBe(true);+ expect(out.filed).toBe(false);+ expect(out.reason).toBe('local-metric');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/autonomousJobs/selfDiagnostics.js b/server/services/autonomousJobs/selfDiagnostics.jsindex 86ea3f7bcf..039dbcfb98 100644--- a/server/services/autonomousJobs/selfDiagnostics.js+++ b/server/services/autonomousJobs/selfDiagnostics.js@@ -94,8 +94,6 @@ export function computeFailingCategories(byTaskType, { minCompleted = 1, now = D* Distinct from `fileUtils.formatDuration` (which floors to whole minutes and* renders sub-minute as "0m") and the client `formatDurationMs`: diagnostics* durations are often seconds, and absent must read as `—`, not a zero duration.- * SHARED — also renders the churn issue body in `services/agentChurn.js`- * (`buildChurnIssueBody`). Changing the output here changes both filed issues.*/export function formatDurationShort(ms) {if (!Number.isFinite(ms) || ms < 0) return '—'diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 6adcf5ca5a..c406cb08e5 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -53,6 +53,7 @@ import {computeDeliveryThrottle,formatDeliveryThrottleGuidance,renderCosMetricsSource,+ renderChurnSignals,COS_METRICS_MAX_CHARS,computeProposalExecutionAwareness,computeCrossReferenceAnalysis,@@ -1420,6 +1421,29 @@ describe('buildPrompt', () => {expect(withGuidance).not.toContain('### scopeGuidance');});+ it('frames PortOS churn metrics as local evidence that needs a concrete fix', () => {+ const source = 'Instance-local CoS churn signals\n- self-improve:branch-reconcile: signal=short-lived-burst';+ const portos = buildPrompt({+ app,+ isPortos: true,+ config: { allowedScopes: ['loop-meta'], rules: '' },+ sources: { churnSignals: source }+ });+ expect(portos).toContain('### liChurnSignals');+ expect(portos).toContain('not an automatic filing instruction');+ expect(portos).toContain('concrete fix');+ expect(portos).not.toContain('### churnSignals');++ const managed = buildPrompt({+ app,+ isPortos: false,+ config: { allowedScopes: ['app-improvement'], rules: '' },+ sources: { churnSignals: source }+ });+ expect(managed).not.toContain('### liChurnSignals');+ expect(managed).not.toContain(source);+ });+it('injects the per-proposal-domain execution block only when a report is passed (#2765)', () => {const base = { app, isPortos: true, config: { allowedScopes: ['loop-meta'], rules: '' } };expect(buildPrompt(base)).not.toContain('### liProposalExecution');@@ -3159,6 +3183,56 @@ describe('gatherSources cosMetrics windowed rate (issue #2460)', () => {expect(parsed['self-improve:branch-reconcile'].recent24hMedianDurationMs).toBe(80_000);});+ it('surfaces an active churn signal to PortOS LI as local evidence, not tracker work', async () => {+ const now = Date.now();+ await writeLearning({+ byTaskType: {+ 'self-improve:branch-reconcile': {+ completed: 12, succeeded: 12, failed: 0, successRate: 100, avgDurationMs: 80_000,+ recentOutcomes: Array.from({ length: 12 }, (_, i) => ({+ t: new Date(now - i * 10 * 60 * 1000).toISOString(),+ s: true,+ d: 80_000+ }))+ }+ }+ });+ const portos = await gatherSources(+ { repoPath: dir },+ { sources: { cosMetrics: true } },+ { cosPath: dir, isPortos: true }+ );+ const parsed = JSON.parse(portos.cosMetrics);+ expect(parsed['self-improve:branch-reconcile'].churn).toMatchObject({+ signal: 'short-lived-burst',+ windowCompleted: 12,+ shortLivedCount: 12,+ shortLivedSampleSize: 12+ });+ expect(portos.churnSignals).toContain('Instance-local CoS churn signals');+ expect(portos.churnSignals).toContain('concrete planned fix');++ const managed = await gatherSources(+ { repoPath: dir },+ { sources: { cosMetrics: true } },+ { cosPath: dir, isPortos: false }+ );+ expect(managed.churnSignals).toBeUndefined();+ expect(JSON.parse(managed.cosMetrics)['self-improve:branch-reconcile'].churn).toBeUndefined();+ });++ it('renders only active churn entries and caps the signal list', () => {+ const rendered = renderChurnSignals({+ calm: { lifetimeCompleted: 2 },+ noisy: { churn: { signal: 'short-lived-burst', windowCompleted: 8, windowMs: 1000, shortLivedCount: 8, shortLivedSampleSize: 8, medianDurationMs: 20, medianGapMs: 30 } },+ noisy2: { churn: { signal: 'rapid-succession', windowCompleted: 9, windowMs: 1000, shortLivedCount: 0, shortLivedSampleSize: 0, medianDurationMs: null, medianGapMs: 30 } }+ }, { maxItems: 1 });+ expect(rendered).toContain('noisy');+ expect(rendered).not.toContain('noisy2');+ expect(rendered).not.toContain('calm');+ expect(rendered).toContain('additional churn signal(s) omitted');+ });+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/prompt.js b/server/services/layeredIntelligence/prompt.jsindex a13e69fc89..46e7e050cd 100644--- a/server/services/layeredIntelligence/prompt.js+++ b/server/services/layeredIntelligence/prompt.js@@ -15,7 +15,7 @@ import { extractSlugFromBody } from './dedup.js';// Keeping them in one named set — rather than accreting `&& k !== 'x'` clauses on the// filter — documents WHY these keys are special and gives the next dedicated-block// signal a single edit point.-const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);+const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance', 'churnSignals']);/*** Build the JSON-only reasoning prompt for one app. Deterministic: given the@@ -115,6 +115,14 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? `\n### liScopeAwareness\n${sources.scopeGuidance.trim()}\n\nThese are per-task-type completion rates for THIS install — how reliably each KIND of work tends to get finished, not a per-proposal record (your proposals don't map 1:1 onto these types). Use it as directional context: a proposal whose implementation resembles a low-completion type deserves extra scrutiny or a narrower scope; high-completion kinds are safer bets. A low rate on self-improve:layered-intelligence is LI's OWN reasoning-run rate — a direct signal to propose conservatively. Where the liProposalExecution block below covers a domain, prefer it: it is a direct per-proposal record, whereas these buckets are only directional.\n`: '';+ // Churn awareness: these are instance-local measurements from PortOS's own+ // learning ring, not user-approved tracker work. Keep the signal visible to+ // the PortOS reasoner while making the filing decision explicit: investigate,+ // scope a concrete planned fix, and otherwise return proposal: null.+ const churnSignalsBlock = (isPortos && typeof sources.churnSignals === 'string' && sources.churnSignals.trim())+ ? `\n### liChurnSignals\n${sources.churnSignals.trim()}\n\nTreat these as evidence for investigation, not an automatic filing instruction. If you can establish a reproducible PortOS defect and describe a concrete fix that belongs in planned work, propose that fix; if the signal is transient, expected, already addressed, or not specific enough to scope, return proposal: null.\n`+ : '';+// Per-proposal-domain execution record (#2765): unlike liScopeAwareness above —// which borrows install-wide per-task-TYPE rates a proposal only loosely maps onto —// this keys on how LI's OWN proposals in each domain actually fared once handed off@@ -167,7 +175,7 @@ ${openList}Gathered sources:${sourceBlocks || (plannedWorkBlock ? '(no other sources available — you may propose an app-data-gap to add telemetry)' : '(no sources available — you may propose an app-data-gap to add telemetry)')}-${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${deliveryThrottleBlock}${scopeGuidanceBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}+${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${deliveryThrottleBlock}${scopeGuidanceBlock}${churnSignalsBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}Respond with JSON only (no markdown fences):{"analysis": "brief reasoning summary",diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.jsindex 420b0a49be..21f76d0ad4 100644--- a/server/services/layeredIntelligence/sources.js+++ b/server/services/layeredIntelligence/sources.js@@ -15,7 +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 { computeChurn, 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,@@ -230,6 +230,39 @@ export function renderCosMetricsSource({ metricsByType = {}, delivery = null } =return JSON.stringify(payload).slice(0, COS_METRICS_MAX_CHARS);}+const CHURN_SIGNAL_MAX_ITEMS = 8;+const CHURN_SIGNAL_MAX_CHARS = 4000;++/**+ * Render the active churn signals for the PortOS install. These are local+ * diagnostic measurements, not tracker work: the reasoner must investigate+ * them and decide whether a concrete planned fix is justified. Pure.+ */+export function renderChurnSignals(metricsByType, { maxItems = CHURN_SIGNAL_MAX_ITEMS } = {}) {+ const signals = Object.entries(metricsByType || {})+ .filter(([, metrics]) => metrics?.churn && typeof metrics.churn === 'object')+ .slice(0, Math.max(0, maxItems));+ if (!signals.length) return '';++ const lines = [+ 'Instance-local CoS churn signals (deterministic telemetry; not tracker issues):',+ 'These measurements describe this PortOS install only. Investigate whether each signal is a reproducible defect with a concrete planned fix; do not file a proposal merely because a signal exists. Return proposal: null when the evidence does not support actionable work.'+ ];+ for (const [type, metrics] of signals) {+ const churn = metrics.churn;+ const label = String(type).replace(/\s+/g, ' ').slice(0, 160);+ const timing = churn.shortLivedSampleSize > 0+ ? `${churn.shortLivedCount}/${churn.shortLivedSampleSize} timed runs under ${SHORT_LIVED_MS}ms`+ : 'completion spacing only (no per-run durations)';+ lines.push(`- ${label}: signal=${churn.signal}; completions=${churn.windowCompleted}; windowMs=${churn.windowMs}; ${timing}; medianDurationMs=${churn.medianDurationMs ?? 'unavailable'}; medianGapMs=${churn.medianGapMs ?? 'unavailable'}`);+ }+ const total = Object.values(metricsByType || {})+ .filter(metrics => metrics?.churn && typeof metrics.churn === 'object')+ .length;+ if (total > signals.length) lines.push(`- ${total - signals.length} additional churn signal(s) omitted from this prompt for brevity.`);+ return lines.join('\n').slice(0, CHURN_SIGNAL_MAX_CHARS);+}+/*** Gather the enabled Layer-1 sources for one app into a `{ key: string }` map.* Deterministic reads only (files + CoS metric JSON + tracker lists); NO LLM calls.@@ -302,11 +335,11 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustSheconst 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.+ // 24h burst stats (duration + count) plus the deterministic churn signal+ // below so a future PortOS LI run can judge whether the local evidence+ // supports a concrete planned fix.const burst = summarizeRecentRuns(m?.recentOutcomes, { windowMs: DAY_MS });- summary[type] = {+ const entry = {lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,lifetimeCompleted: m?.completed || 0,recentSuccessRate: windowed.windowedSuccessRate,@@ -317,6 +350,20 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustSherecent24hMedianDurationMs: burst.medianDurationMs,shortLivedMs: SHORT_LIVED_MS};+ const churn = isPortos ? computeChurn(m?.recentOutcomes) : null;+ if (churn?.flagged) {+ entry.churn = {+ signal: churn.reason,+ windowMs: churn.windowMs,+ windowCompleted: churn.windowCompleted,+ shortLivedCount: churn.shortLivedCount,+ shortLivedSampleSize: churn.shortLivedSampleSize,+ shortLivedRatio: churn.shortLivedRatio,+ medianDurationMs: churn.medianDurationMs,+ medianGapMs: churn.medianGapMs+ };+ }+ summary[type] = entry;}// No delivery block yet: the approval → delivery numbers come from the app's// outcome records, which the hook only has AFTER it has reconciled them against@@ -339,6 +386,8 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustSheif (isPortos) {const scopeGuidance = computeScopeAwareness({ metricsByType: summary });if (scopeGuidance) out.scopeGuidance = scopeGuidance;+ const churnSignals = renderChurnSignals(summary);+ if (churnSignals) out.churnSignals = churnSignals;}}for (const custom of src.custom || []) {diff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.jsindex 97f871db5f..a05baefbc3 100644--- a/server/services/taskLearning/lifecycle.js+++ b/server/services/taskLearning/lifecycle.js@@ -53,8 +53,9 @@ export function initTaskLearning() {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.+ // the SAME task type is a local diagnostic signal. A coordinator is parked+ // immediately; Layered Intelligence decides later whether it supports a+ // concrete planned fix.const { observeAgentChurn } = await import('../agentChurn.js');await observeAgentChurn(agent, task).catch(err => {console.error(`❌ 🔁 CoS churn: Failed to observe completion: ${err.message}`);diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 4f08cd6884..f5c8a6ebbd 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -1068,9 +1068,9 @@ const PARK_FIELDS = ['parkedUntil', 'parkReason', 'parkActionableCount', 'parkCo** `dispatchCount` therefore DEFAULTS to 0: a park ends the drain window by* definition, so zeroing the budget is the invariant, not an opt-in every caller- * has to remember. (The churn detector's park in agentChurn.js is exactly the- * caller that forgot, leaving the next window to cap early on a spend it never- * made.) Note `dispatchCount` is still deliberately NOT in `PARK_FIELDS`:+ * has to remember. The churn detector's park in agentChurn.js relies on this+ * default so a local signal ends the current drain window cleanly. Note+ * `dispatchCount` is still deliberately NOT in `PARK_FIELDS`:* `recordPerpetualDispatch` clears those fields mid-drain on every dispatch, and* zeroing the counter there would reset the budget before every dispatch, so the* cap could never fire.diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex d52fdf008d..d2f3284933 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -1736,10 +1736,10 @@ describe('taskSchedule', () => {expect(partial).toEqual([])})- // The churn detector (agentChurn.js) parks a coordinator and FILES a tracker- // issue off signatureRepeatCount, so a dispatch that leaves a stale count- // behind makes the next park increment it and over-report "same finding- // again". A dispatch only happens on a CHANGED set, so it resets to 1.+ // The churn detector (agentChurn.js) parks a coordinator when a local+ // signal fires. A dispatch that leaves a stale count behind makes the next+ // park over-report "same finding again". A dispatch only happens on a+ // CHANGED set, so it resets to 1.it('recordPerpetualDispatch resets signatureRepeatCount for the new signature', async () => {mockSchedule({tasks: { 'branch-reconcile': { type: 'perpetual', enabled: true } },