Skip to content

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

feat: daily self-diagnostics job surfacing CoS self-healing failures (#2464)

Adam Eivye3104264b9a3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1aa9ec313d..209246fb7b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -67,3 +67,5 @@
- **Audio → MIDI transcription now installs its runtime automatically on first use.** Clicking *Transcribe MIDI* (Rounds reference audio) or *MIDI* (Music Video source track) used to dead-end on a toast telling you to run `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` in a terminal. Now, when the MuScriptor venv isn't provisioned yet, PortOS opens an in-app installer that streams the setup line-by-line — the same experience as the image and video model runtimes — and, on completion, automatically runs the transcription you originally asked for. A new `GET /api/midi-runtime/install` endpoint reuses the shared `RuntimeInstallModal`/SSE-install path (in-flight singleton, detached process group so a cancel kills pip/git children, post-install venv re-probe); `useMidiTranscription` catches the `503 MIDI_RUNTIME_MISSING` kickoff, gates the modal, and retries once installed (with a loop guard so a genuinely-failed install surfaces its error instead of relooping).
- **PortOS now installs a service worker for offline app-shell loading and low-bandwidth caching** — the modern replacement for the long-deprecated AppCache manifest. After the first online visit, the built app shell (`index.html`) and the content-hashed JS/CSS chunks are cached, so the UI loads instantly on repeat visits, keeps rendering when the server is briefly unreachable (flaky Tailnet links), and stops re-pulling megabytes of vendor JS on every navigation over a slow connection. Google Fonts and static public assets (icons, textures, manifest) are cached too. Real-time and large/dynamic routes — `/api/*`, `/socket.io/*`, and `/data/*` media — are **never** cached, so live data and streamed assets always hit the network (HTTP Range preserved for `/data`). Navigations stay network-first so a fresh build is always picked up when online, and the existing build-id / stale-chunk-reload machinery still handles "the server rebuilt while a tab was open." The worker registers only in a production **secure context** (HTTPS, or `localhost`) — it is a progressive enhancement that silently no-ops over a plain-HTTP Tailnet hostname and in the Vite dev server (where it also tears down any stale worker). Implemented as a hand-rolled worker (`client/public/sw.js`) with no new dependency; registration lives in `client/src/lib/registerServiceWorker.js`. The PWA manifest gained explicit `id`/`scope` for a deterministic installed-app identity.
+
+- **A daily self-diagnostics job now surfaces CoS self-healing failures into a single GitHub monitoring issue (#2464).** The Layered Intelligence loop can only improve if failures are actually observed, but a category quietly stuck failing (e.g. `self-improve:claim-issue`'s claim-work at a ~30% failure rate, or `layered-intelligence` failing its first run) had no automated pulse — the numbers lived only in the Learning tab. A new deterministic `type: 'script'` autonomous job (`job-self-diagnostics`, `scriptHandler: 'self-diagnostics'`, daily at 05:00, disabled by default) reads the task-learning per-category metrics (`data/cos/learning.json` `byTaskType`), and for every category with recorded failures records a structured single-line log entry (slug, failed/total, success rate, `lastCompleted`, avg/max duration) and aggregates them — ordered by impact (most failures first, then lowest success rate) — into ONE persistent GitHub summary issue. It reuses an existing open issue marked `monitoring` (matched by an embedded dedup slug marker) rather than filing a fresh duplicate each cycle, refreshes its body in place, and toggles a `needs attention` label on while failures exist / off once the categories recover. The issue read distinguishes a failed `gh` call (skip, don't file) from an empty list (`ok:true`), so a transient CLI blip can't defeat dedup. No LLM calls — a pure metrics-read + `gh` write, cold-bootstrap-safe and a sanctioned scheduled automation. The new default job self-installs on existing installs via the additive `mergeWithDefaults` boot merge (no migration needed).
diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.js
index d783ed3d15..f4a565fba1 100644
--- a/server/services/autonomousJobs/defaults.js
+++ b/server/services/autonomousJobs/defaults.js
@@ -255,6 +255,23 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-self-diagnostics',
+ name: 'Self-Diagnostics',
+ description: 'Daily scan of CoS task-learning metrics. Surfaces any self-healing category with recorded failures (claim-work, layered-intelligence, etc.) into a single reusable GitHub summary issue marked `monitoring`, ordered by impact. Deterministic — no AI calls.',
+ category: 'self-diagnostics',
+ interval: 'daily',
+ intervalMs: DAY,
+ scheduledTime: '05:00',
+ enabled: false,
+ priority: 'LOW',
+ type: 'script',
+ scriptHandler: 'self-diagnostics',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
// 'job-layered-intelligence' removed (#2322): Layered Intelligence is now a
// per-app HANDLER-BACKED scheduled task (CoS → Schedule) rather than a global
// autonomous-job sweep. Migration 184 tombstones the persisted job record and
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index 08ae5db332..c63a25d289 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -16,6 +16,7 @@ import { checkAndPrompt as autobiographyCheckAndPrompt } from '../autobiography.
import { runGoalCheckIn } from '../goalCheckIn.js'
import { cleanupOrphanedWorktrees, reapMergedWorktrees } from '../worktreeManager.js'
import { getActiveAgentIds } from '../agentState.js'
+import { runSelfDiagnostics } from './selfDiagnostics.js'
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
@@ -139,7 +140,11 @@ const SCRIPT_HANDLERS = {
'autobiography-prompt': autobiographyCheckAndPrompt,
'moltworld-exploration': runMoltworldExploration,
'agent-data-cleanup': agentDataCleanup,
- 'goal-check-in': runGoalCheckIn
+ 'goal-check-in': runGoalCheckIn,
+ // Daily self-diagnostics (#2464): reads task-learning per-category metrics and
+ // files a single `monitoring`-labeled GitHub summary of failing self-healing
+ // categories. Deterministic — no LLM calls (cold-bootstrap-safe).
+ 'self-diagnostics': runSelfDiagnostics
// 'layered-intelligence' retired here (#2322): LI is now a per-app scheduled
// task, not a global autonomous-job sweep. It runs as a normal reasoning agent
// with programmatic-I/O hooks — see taskTypeHooks.js +
diff --git a/server/services/autonomousJobs/selfDiagnostics.js b/server/services/autonomousJobs/selfDiagnostics.js
new file mode 100644
index 0000000000..547e41bdeb
--- /dev/null
+++ b/server/services/autonomousJobs/selfDiagnostics.js
@@ -0,0 +1,266 @@
+/**
+ * Autonomous Jobs — self-diagnostics script handler (#2464).
+ *
+ * A deterministic `type: 'script'` job that surfaces CoS self-healing failures
+ * (claim-work / layered-intelligence / any task category) so operators get an
+ * automated pulse on system health. On each run it:
+ * 1. Reads the task-learning per-category metrics (`byTaskType`) — the same
+ * completion data the Learning tab renders.
+ * 2. For every category with `failed > 0`, records a structured single-line log
+ * entry (slug, total/failed counts, lastCompleted, avg/max duration).
+ * 3. Aggregates the failing categories, ordered by impact, into ONE persistent
+ * GitHub summary issue — reusing an existing issue marked `monitoring` so the
+ * loop never files a fresh duplicate each cycle.
+ * 4. Applies a `needs attention` label while failures exist (and removes it once
+ * the categories recover) so the same summary isn't re-reported as stale.
+ *
+ * NO LLM calls — this is a pure metrics-read + `gh` issue write, safe to run on a
+ * schedule under the cold-bootstrap AI policy. The pure helpers (compute/sort,
+ * title/body/log builders) are side-effect-free and unit-tested; the I/O handler
+ * takes injectable deps so tests drive it without a live `gh` or filesystem.
+ */
+
+import { spawn } from 'child_process'
+import { PATHS, safeJSONParse } from '../../lib/fileUtils.js'
+import { loadLearningData } from '../taskLearning/store.js'
+
+// The label that marks the ONE persistent summary issue to reuse across runs, and
+// the attention label the loop toggles so a still-open summary isn't re-filed.
+export const MONITORING_LABEL = 'monitoring'
+export const NEEDS_ATTENTION_LABEL = 'needs attention'
+
+// Stable dedup marker embedded in the summary issue body. Lets a run recognize
+// its own prior summary even if the `monitoring` label was hand-applied to an
+// unrelated issue, and lets a human/label read find it.
+export const DIAGNOSTICS_SLUG = 'cos-self-diagnostics'
+const SLUG_MARKER = `<!-- lil-slug: ${DIAGNOSTICS_SLUG} -->`
+
+const STABLE_TITLE = 'CoS self-diagnostics: self-healing failures'
+
+/**
+ * Reduce the learning `byTaskType` map to the categories that have at least one
+ * failure, projected onto the fields the summary + logs need, ordered by impact.
+ * Pure. Impact order: most failures first, then lowest success rate, then most
+ * total runs (a big-sample low-rate category outranks a one-off flake).
+ *
+ * @param {Record<string, object>} byTaskType
+ * @param {{ minCompleted?: number }} [opts] - ignore thin categories below this
+ * completion count (default 1 — any category with a recorded failure qualifies).
+ * @returns {Array<{ slug, total, failed, succeeded, successRate, lastCompleted, avgDurationMs, maxDurationMs }>}
+ */
+export function computeFailingCategories(byTaskType, { minCompleted = 1 } = {}) {
+ if (!byTaskType || typeof byTaskType !== 'object') return []
+ return Object.entries(byTaskType)
+ .map(([slug, m]) => ({
+ slug,
+ total: m?.completed ?? 0,
+ failed: m?.failed ?? 0,
+ succeeded: m?.succeeded ?? 0,
+ // Prefer the stored rate; fall back to a derived one so an older record
+ // without `successRate` still sorts/renders correctly.
+ successRate: Number.isFinite(m?.successRate)
+ ? m.successRate
+ : (m?.completed > 0 ? Math.round(((m.succeeded ?? 0) / m.completed) * 100) : 0),
+ lastCompleted: m?.lastCompleted ?? null,
+ avgDurationMs: m?.avgDurationMs ?? null,
+ maxDurationMs: m?.maxDurationMs ?? null
+ }))
+ .filter(c => c.failed > 0 && c.total >= minCompleted)
+ .sort((a, b) =>
+ b.failed - a.failed ||
+ a.successRate - b.successRate ||
+ b.total - a.total
+ )
+}
+
+/**
+ * Human-friendly ms → minutes/seconds. Pure. Null-safe (`—` when absent).
+ * 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.
+ */
+export function formatDurationShort(ms) {
+ if (!Number.isFinite(ms) || ms < 0) return '—'
+ if (ms < 1000) return `${Math.round(ms)}ms`
+ const totalSec = Math.round(ms / 1000)
+ if (totalSec < 60) return `${totalSec}s`
+ const min = Math.floor(totalSec / 60)
+ const sec = totalSec % 60
+ return sec ? `${min}m ${sec}s` : `${min}m`
+}
+
+/**
+ * Structured single-line log entry for one failing category. Pure — the handler
+ * emits it via console so logs stay single-line + emoji-prefixed (CLAUDE.md).
+ */
+export function formatCategoryLogLine(c) {
+ return `🩺 ${c.slug}: ${c.failed}/${c.total} failed (${c.successRate}% success) · ` +
+ `last ${c.lastCompleted || 'n/a'} · avg ${formatDurationShort(c.avgDurationMs)} · max ${formatDurationShort(c.maxDurationMs)}`
+}
+
+/** Stable summary-issue title. Pure. */
+export function buildDiagnosticsIssueTitle() {
+ return STABLE_TITLE
+}
+
+/**
+ * Markdown body for the summary issue. Pure. Lists failing categories in impact
+ * order as a table, embeds the dedup slug marker, and stamps the run time so a
+ * reused issue shows freshness. `failing:[]` renders an explicit all-clear.
+ */
+export function buildDiagnosticsIssueBody(failing, { generatedAt = new Date().toISOString() } = {}) {
+ const lines = []
+ lines.push('_Automated CoS self-diagnostics — regenerated each run. Do not hand-edit; edits are overwritten._')
+ lines.push('')
+ if (!failing || failing.length === 0) {
+ lines.push('✅ **All self-healing categories are passing** — no categories with recorded failures.')
+ } else {
+ lines.push(`Found **${failing.length}** self-healing categor${failing.length === 1 ? 'y' : 'ies'} with recorded failures, ordered by impact:`)
+ lines.push('')
+ lines.push('| Category | Failed / Total | Success rate | Last completed | Avg duration | Max duration |')
+ lines.push('| --- | --- | --- | --- | --- | --- |')
+ for (const c of failing) {
+ lines.push(`| \`${c.slug}\` | ${c.failed} / ${c.total} | ${c.successRate}% | ${c.lastCompleted || '—'} | ${formatDurationShort(c.avgDurationMs)} | ${formatDurationShort(c.maxDurationMs)} |`)
+ }
+ lines.push('')
+ lines.push('These are candidates for human diagnosis (model routing, tooling, or pipeline issues). Investigate the highest-impact rows first.')
+ }
+ lines.push('')
+ lines.push(`_Last run: ${generatedAt}_`)
+ lines.push('')
+ lines.push(SLUG_MARKER)
+ return lines.join('\n')
+}
+
+// ---------------------------------------------------------------------------
+// I/O layer — `gh` shell + the handler. Injectable deps keep them testable.
+// ---------------------------------------------------------------------------
+
+/** Run a CLI, resolving `{ code, stdout, stderr }` (never rejects). Pure I/O. */
+function runCli(cmd, args, options = {}) {
+ return new Promise((resolve) => {
+ const child = spawn(cmd, args, { shell: false, windowsHide: true, ...options })
+ let stdout = ''
+ let stderr = ''
+ child.stdout?.on('data', d => { stdout += d.toString() })
+ child.stderr?.on('data', d => { stderr += d.toString() })
+ child.on('close', code => resolve({ code, stdout, stderr }))
+ child.on('error', err => resolve({ code: -1, stdout: '', stderr: err.message }))
+ })
+}
+
+/**
+ * Locate the persistent summary issue to reuse. Prefers an open `monitoring`
+ * issue carrying our slug marker; falls back to the first open `monitoring`
+ * issue. Returns `{ ok, issue }` — `ok:false` means the read FAILED (do NOT then
+ * create a new one, or a transient `gh` blip files a duplicate; sentinel rule).
+ */
+export async function findMonitoringIssue({ cwd = PATHS.root, exec = runCli } = {}) {
+ const { code, stdout } = await exec('gh',
+ ['issue', 'list', '--label', MONITORING_LABEL, '--state', 'open', '--limit', '20', '--json', 'number,title,body,labels,url'],
+ { cwd })
+ if (code !== 0) return { ok: false, issue: null }
+ if (!stdout.trim()) return { ok: true, issue: null }
+ const parsed = safeJSONParse(stdout, null, { logError: false })
+ if (!Array.isArray(parsed)) return { ok: false, issue: null }
+ const norm = parsed.map(i => ({
+ number: i.number ?? null,
+ title: i.title || '',
+ body: i.body || '',
+ url: i.url || null,
+ labels: (i.labels || []).map(l => (typeof l === 'string' ? l : l?.name)).filter(Boolean)
+ }))
+ const bySlug = norm.find(i => i.body.includes(SLUG_MARKER))
+ return { ok: true, issue: bySlug || norm[0] || null }
+}
+
+/**
+ * Ensure the labels exist before the first `issue create` (gh fails creating an
+ * issue with a non-existent label). Idempotent — `--force` is a no-op when the
+ * label already exists.
+ */
+export async function ensureDiagnosticsLabels({ cwd = PATHS.root, exec = runCli } = {}) {
+ const labels = [
+ { name: MONITORING_LABEL, color: '0e8a16', desc: 'Persistent monitoring / self-diagnostics summary issue' },
+ { name: NEEDS_ATTENTION_LABEL, color: 'd93f0b', desc: 'Flagged by CoS self-diagnostics — needs human diagnosis' }
+ ]
+ for (const l of labels) {
+ await exec('gh', ['label', 'create', l.name, '--color', l.color, '--description', l.desc, '--force'], { cwd })
+ }
+}
+
+/**
+ * Self-diagnostics handler (SCRIPT_HANDLERS['self-diagnostics']).
+ *
+ * @param {object} [deps]
+ * @param {() => Promise<object>} [deps.loadLearning] - learning-data loader
+ * @param {(cmd,args,opts)=>Promise<{code,stdout,stderr}>} [deps.exec] - CLI runner
+ * @param {string} [deps.cwd] - repo root for `gh`
+ * @param {() => string} [deps.now] - ISO clock (test seam)
+ * @returns {Promise<{ failingCount, categories, issue }>}
+ */
+export async function runSelfDiagnostics({
+ loadLearning = loadLearningData,
+ exec = runCli,
+ cwd = PATHS.root,
+ now = () => new Date().toISOString()
+} = {}) {
+ const data = await loadLearning()
+ const failing = computeFailingCategories(data?.byTaskType)
+
+ if (failing.length === 0) {
+ console.log('🩺 Self-diagnostics: no self-healing categories with recorded failures — all clear')
+ } else {
+ console.log(`🩺 Self-diagnostics: ${failing.length} failing categor${failing.length === 1 ? 'y' : 'ies'} (top: ${failing[0].slug} ${failing[0].failed}/${failing[0].total})`)
+ for (const c of failing) console.log(formatCategoryLogLine(c))
+ }
+
+ const generatedAt = now()
+ const title = buildDiagnosticsIssueTitle()
+ const body = buildDiagnosticsIssueBody(failing, { generatedAt })
+
+ const found = await findMonitoringIssue({ cwd, exec })
+ if (!found.ok) {
+ // Read failed — refuse to file, or a transient gh blip duplicates the summary.
+ console.warn('⚠️ Self-diagnostics: could not read monitoring issues (gh unavailable?) — skipping issue update')
+ return { failingCount: failing.length, categories: failing, issue: null }
+ }
+
+ const hasFailures = failing.length > 0
+ await ensureDiagnosticsLabels({ cwd, exec })
+
+ if (found.issue) {
+ // Reuse the existing monitoring issue: refresh the body, and toggle the
+ // attention label to match the current state (add on failures, clear on all-green).
+ const editArgs = ['issue', 'edit', String(found.issue.number), '--body', body]
+ if (hasFailures && !found.issue.labels.includes(NEEDS_ATTENTION_LABEL)) {
+ editArgs.push('--add-label', NEEDS_ATTENTION_LABEL)
+ } else if (!hasFailures && found.issue.labels.includes(NEEDS_ATTENTION_LABEL)) {
+ editArgs.push('--remove-label', NEEDS_ATTENTION_LABEL)
+ }
+ const { code, stderr } = await exec('gh', editArgs, { cwd })
+ if (code !== 0) {
+ console.warn(`⚠️ Self-diagnostics: failed to update issue #${found.issue.number}: ${stderr.trim()}`)
+ return { failingCount: failing.length, categories: failing, issue: null }
+ }
+ console.log(`🩺 Self-diagnostics: updated monitoring issue #${found.issue.number} (${failing.length} failing)`)
+ return { failingCount: failing.length, categories: failing, issue: { number: found.issue.number, url: found.issue.url, created: false } }
+ }
+
+ if (!hasFailures) {
+ // Nothing failing and no existing summary — don't create noise.
+ console.log('🩺 Self-diagnostics: no failures and no existing summary issue — nothing to file')
+ return { failingCount: 0, categories: [], issue: null }
+ }
+
+ const createArgs = ['issue', 'create', '--title', title, '--body', body, '--label', MONITORING_LABEL, '--label', NEEDS_ATTENTION_LABEL]
+ const { code, stdout, stderr } = await exec('gh', createArgs, { cwd })
+ if (code !== 0) {
+ console.warn(`⚠️ Self-diagnostics: failed to create monitoring issue: ${stderr.trim()}`)
+ return { failingCount: failing.length, categories: failing, issue: null }
+ }
+ const url = (stdout.trim().match(/(https?:\/\/\S+)/) || [])[1] || stdout.trim()
+ const number = Number((url.match(/(\d+)\s*$/) || [])[1]) || null
+ console.log(`🩺 Self-diagnostics: filed monitoring issue ${url} (${failing.length} failing)`)
+ return { failingCount: failing.length, categories: failing, issue: { number, url, created: true } }
+}
diff --git a/server/services/autonomousJobs/selfDiagnostics.test.js b/server/services/autonomousJobs/selfDiagnostics.test.js
new file mode 100644
index 0000000000..4eff6b0887
--- /dev/null
+++ b/server/services/autonomousJobs/selfDiagnostics.test.js
@@ -0,0 +1,215 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ computeFailingCategories,
+ formatDurationShort,
+ formatCategoryLogLine,
+ buildDiagnosticsIssueTitle,
+ buildDiagnosticsIssueBody,
+ findMonitoringIssue,
+ runSelfDiagnostics,
+ MONITORING_LABEL,
+ NEEDS_ATTENTION_LABEL,
+ DIAGNOSTICS_SLUG
+} from './selfDiagnostics.js'
+
+// A sample byTaskType map mirroring the learning.json shape.
+const sampleMetrics = {
+ 'self-improve:claim-issue': { completed: 192, succeeded: 137, failed: 55, successRate: 71, lastCompleted: '2026-07-01T00:00:00.000Z', avgDurationMs: 160000, maxDurationMs: 900000 },
+ 'self-improve:console': { completed: 3, succeeded: 1, failed: 2, successRate: 33, lastCompleted: '2026-06-01T00:00:00.000Z', avgDurationMs: 40000, maxDurationMs: 60000 },
+ 'user-task': { completed: 1177, succeeded: 1002, failed: 175, successRate: 85, lastCompleted: '2026-07-02T00:00:00.000Z', avgDurationMs: 120000, maxDurationMs: 500000 },
+ 'self-improve:update': { completed: 7, succeeded: 7, failed: 0, successRate: 100, lastCompleted: '2026-02-04T00:00:00.000Z', avgDurationMs: 160000, maxDurationMs: 200000 }
+}
+
+describe('computeFailingCategories', () => {
+ it('returns only categories with failures, ordered by impact (failed desc, then successRate asc)', () => {
+ const out = computeFailingCategories(sampleMetrics)
+ expect(out.map(c => c.slug)).toEqual([
+ 'user-task', // 175 failures — most
+ 'self-improve:claim-issue', // 55 failures
+ 'self-improve:console' // 2 failures
+ ])
+ // The passing category is excluded entirely.
+ expect(out.find(c => c.slug === 'self-improve:update')).toBeUndefined()
+ })
+
+ it('projects the required fields (slug, total, failed, successRate, lastCompleted, avg/max duration)', () => {
+ const [top] = computeFailingCategories(sampleMetrics)
+ expect(top).toMatchObject({
+ slug: 'user-task',
+ total: 1177,
+ failed: 175,
+ succeeded: 1002,
+ successRate: 85,
+ lastCompleted: '2026-07-02T00:00:00.000Z',
+ avgDurationMs: 120000,
+ maxDurationMs: 500000
+ })
+ })
+
+ it('derives successRate when the stored value is missing', () => {
+ const [c] = computeFailingCategories({ x: { completed: 4, succeeded: 1, failed: 3 } })
+ expect(c.successRate).toBe(25)
+ })
+
+ it('honors minCompleted to drop thin categories', () => {
+ const out = computeFailingCategories(sampleMetrics, { minCompleted: 10 })
+ expect(out.map(c => c.slug)).not.toContain('self-improve:console') // only 3 completions
+ })
+
+ it('is null-safe', () => {
+ expect(computeFailingCategories(null)).toEqual([])
+ expect(computeFailingCategories(undefined)).toEqual([])
+ expect(computeFailingCategories({})).toEqual([])
+ })
+})
+
+describe('formatDurationShort', () => {
+ it('renders seconds, minutes, and absent sentinel distinctly', () => {
+ expect(formatDurationShort(40000)).toBe('40s')
+ expect(formatDurationShort(160000)).toBe('2m 40s')
+ expect(formatDurationShort(120000)).toBe('2m')
+ expect(formatDurationShort(500)).toBe('500ms')
+ expect(formatDurationShort(null)).toBe('—')
+ expect(formatDurationShort(undefined)).toBe('—')
+ // A genuine zero is NOT the same as absent.
+ expect(formatDurationShort(0)).toBe('0ms')
+ })
+})
+
+describe('formatCategoryLogLine', () => {
+ it('is a single line with the required fields', () => {
+ const line = formatCategoryLogLine(computeFailingCategories(sampleMetrics)[1])
+ expect(line).not.toContain('\n')
+ expect(line).toContain('self-improve:claim-issue')
+ expect(line).toContain('55/192 failed')
+ expect(line).toContain('71% success')
+ })
+})
+
+describe('buildDiagnosticsIssueBody', () => {
+ it('lists failing categories as a table and embeds the dedup slug marker', () => {
+ const body = buildDiagnosticsIssueBody(computeFailingCategories(sampleMetrics), { generatedAt: '2026-07-12T00:00:00.000Z' })
+ expect(body).toContain(`lil-slug: ${DIAGNOSTICS_SLUG}`)
+ expect(body).toContain('| `user-task` | 175 / 1177 |')
+ expect(body).toContain('Last run: 2026-07-12T00:00:00.000Z')
+ // Table order matches impact order.
+ expect(body.indexOf('user-task')).toBeLessThan(body.indexOf('self-improve:claim-issue'))
+ })
+
+ it('renders an explicit all-clear when there are no failures', () => {
+ const body = buildDiagnosticsIssueBody([], { generatedAt: '2026-07-12T00:00:00.000Z' })
+ expect(body).toContain('All self-healing categories are passing')
+ expect(body).toContain(`lil-slug: ${DIAGNOSTICS_SLUG}`)
+ })
+})
+
+// A scripted `gh` runner: matches on args and returns { code, stdout, stderr }.
+function makeExec(routes) {
+ return vi.fn(async (cmd, args) => {
+ for (const r of routes) {
+ if (r.match(args)) return r.result
+ }
+ return { code: 0, stdout: '', stderr: '' }
+ })
+}
+
+const argsHave = (...needles) => (args) => needles.every(n => args.includes(n))
+
+describe('findMonitoringIssue', () => {
+ it('prefers the issue carrying the diagnostics slug marker', async () => {
+ const exec = makeExec([{
+ match: argsHave('issue', 'list'),
+ result: {
+ code: 0,
+ stdout: JSON.stringify([
+ { number: 10, title: 'Unrelated monitoring', body: 'no marker', labels: [{ name: 'monitoring' }] },
+ { number: 42, title: 'CoS self-diagnostics', body: `x\n<!-- lil-slug: ${DIAGNOSTICS_SLUG} -->`, labels: [{ name: 'monitoring' }, { name: 'needs attention' }] }
+ ])
+ }
+ }])
+ const { ok, issue } = await findMonitoringIssue({ exec })
+ expect(ok).toBe(true)
+ expect(issue.number).toBe(42)
+ expect(issue.labels).toContain('needs attention')
+ })
+
+ it('distinguishes a failed read (ok:false) from an empty list (ok:true)', async () => {
+ const fail = makeExec([{ match: argsHave('issue', 'list'), result: { code: 1, stdout: '', stderr: 'gh boom' } }])
+ expect(await findMonitoringIssue({ exec: fail })).toEqual({ ok: false, issue: null })
+
+ const empty = makeExec([{ match: argsHave('issue', 'list'), result: { code: 0, stdout: '' } }])
+ expect(await findMonitoringIssue({ exec: empty })).toEqual({ ok: true, issue: null })
+ })
+})
+
+describe('runSelfDiagnostics', () => {
+ const loadLearning = async () => ({ byTaskType: sampleMetrics })
+
+ it('creates a new monitoring issue with both labels when none exists and there are failures', async () => {
+ const exec = makeExec([
+ { match: argsHave('issue', 'list'), result: { code: 0, stdout: '[]' } },
+ { match: argsHave('label', 'create'), result: { code: 0, stdout: '' } },
+ { match: argsHave('issue', 'create'), result: { code: 0, stdout: 'https://github.com/acme/repo/issues/99\n' } }
+ ])
+ const res = await runSelfDiagnostics({ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ expect(res.failingCount).toBe(3)
+ expect(res.issue).toMatchObject({ number: 99, created: true })
+ const createCall = exec.mock.calls.find(c => c[1].includes('create') && c[1].includes('issue'))
+ expect(createCall[1]).toContain('--label')
+ expect(createCall[1]).toContain(MONITORING_LABEL)
+ expect(createCall[1]).toContain(NEEDS_ATTENTION_LABEL)
+ })
+
+ it('reuses (edits) an existing monitoring issue instead of filing a duplicate', async () => {
+ const exec = makeExec([
+ { match: argsHave('issue', 'list'), result: { code: 0, stdout: JSON.stringify([
+ { number: 7, title: 't', body: `<!-- lil-slug: ${DIAGNOSTICS_SLUG} -->`, labels: [{ name: 'monitoring' }, { name: 'needs attention' }] }
+ ]) } },
+ { match: argsHave('label', 'create'), result: { code: 0, stdout: '' } },
+ { match: argsHave('issue', 'edit'), result: { code: 0, stdout: '' } }
+ ])
+ const res = await runSelfDiagnostics({ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ expect(res.issue).toMatchObject({ number: 7, created: false })
+ // No create call happened.
+ expect(exec.mock.calls.find(c => c[1].includes('issue') && c[1].includes('create'))).toBeUndefined()
+ // Edit happened; attention label already present so it isn't re-added.
+ const editCall = exec.mock.calls.find(c => c[1].includes('edit'))
+ expect(editCall[1]).toContain('--body')
+ expect(editCall[1]).not.toContain('--add-label')
+ })
+
+ it('does NOT file when the issue read failed (avoids duplicate on a transient gh blip)', async () => {
+ const exec = makeExec([{ match: argsHave('issue', 'list'), result: { code: 1, stdout: '', stderr: 'boom' } }])
+ const res = await runSelfDiagnostics({ loadLearning, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ expect(res.issue).toBeNull()
+ expect(exec.mock.calls.find(c => c[1].includes('create'))).toBeUndefined()
+ })
+
+ it('does not create a new issue when everything is passing and none exists', async () => {
+ const allGood = async () => ({ byTaskType: { 'self-improve:update': sampleMetrics['self-improve:update'] } })
+ const exec = makeExec([{ match: argsHave('issue', 'list'), result: { code: 0, stdout: '[]' } }])
+ const res = await runSelfDiagnostics({ loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ expect(res.failingCount).toBe(0)
+ expect(res.issue).toBeNull()
+ expect(exec.mock.calls.find(c => c[1].includes('create') && c[1].includes('issue'))).toBeUndefined()
+ })
+
+ it('clears the needs-attention label when a previously-failing summary recovers', async () => {
+ const allGood = async () => ({ byTaskType: { 'self-improve:update': sampleMetrics['self-improve:update'] } })
+ const exec = makeExec([
+ { match: argsHave('issue', 'list'), result: { code: 0, stdout: JSON.stringify([
+ { number: 7, title: 't', body: `<!-- lil-slug: ${DIAGNOSTICS_SLUG} -->`, labels: [{ name: 'monitoring' }, { name: 'needs attention' }] }
+ ]) } },
+ { match: argsHave('label', 'create'), result: { code: 0, stdout: '' } },
+ { match: argsHave('issue', 'edit'), result: { code: 0, stdout: '' } }
+ ])
+ await runSelfDiagnostics({ loadLearning: allGood, exec, now: () => '2026-07-12T00:00:00.000Z' })
+ const editCall = exec.mock.calls.find(c => c[1].includes('edit'))
+ expect(editCall[1]).toContain('--remove-label')
+ expect(editCall[1]).toContain(NEEDS_ATTENTION_LABEL)
+ })
+
+ it('has a stable title', () => {
+ expect(buildDiagnosticsIssueTitle()).toBe('CoS self-diagnostics: self-healing failures')
+ })
+})