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: auto-record provenance-stamped recurring-failure insights (#2443)

Adam Eivy53f789dabc46
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9fd8713f56..47935407f9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -14,6 +14,8 @@
- **Image and video generators now share one resolution control (#2436).** The image (`ImageGenControls`) and video (`VideoGen`) size pickers had diverged into two separate "preset dropdown + custom W×H" implementations over the same helper tables — and VideoGen rendered its Width/Height inputs twice. Both now consume a single `components/media/ResolutionField.jsx` (preset `<select>` + a "Custom…" sentinel that reveals gated Width/Height inputs with a blur-clamp), and `clampImageEdge` in `imageGenResolutions.js` is generalized to accept `{ min, max, step }` so video reuses it (clamping to 64–2048 and snapping to the multiple-of-64 grid the server floors to). The controls mirror their routes: the image edge inputs use `step=1` (its route accepts any integer edge, so a hand-typed 705 no longer trips the form's native step validation), while video keeps `step=64` and snaps on blur. Cleanup deferred from the custom-image-dimensions slice.
+- **Recurring CoS agent failures now fold themselves into human-readable "Standing Learnings" the failure path writes automatically (#2443).** CoS learnings previously fed only machinery (routing, cooldowns, skip-gating) — the one prose channel, `recordLearningInsight`, was invoked solely from a manual API route, so no incident ever became a readable operating note. Now, when a single error category recurs to a milestone (3, 10, 25, 50, 100 occurrences), `recordTaskCompletion` auto-records a provenance-stamped insight — timestamp, originating agent id, error category, task type, recurrence count, and provider/model attribution — built only from controlled fields (never the raw error message, so no path/PII leaks). Auto-flagged incidents are distinguished from user-authored notes (`origin: 'auto-incident'` vs `'user'`) and surfaced in a new collapsible **Standing Learnings** panel on the CoS Learning tab. All runtime-only (`data/cos/learning.json`) — nothing is committed to git or federated. Milestone matching is exact so each threshold fires once and escalates rather than spamming.
+
## Fixes
- **Generated agent prompts (swarm, scheduled claim-work, other queued system tasks) no longer double-print their first line.** A task queued through the CoS improvement/claim-work path is persisted to `COS-TASKS.md` by moving its full multi-line prompt into `metadata.context` and keeping only the first line as `description` (so the markdown stays one-line-per-task). Coming back out, `context` therefore led with a verbatim copy of `description`, and every prompt-render path emitted both — so a swarm run opened with the header twice (`# ⚡ SWARM MODE …`, then `### Context`, then `# ⚡ SWARM MODE …` again, the whole body repeated). A new `reconcileSplitContext` step in `agentPromptBuilder.js` detects that exact split signature (context's first non-empty line equals `description`), folds the body back into `description`, and drops the redundant `metadata.context` — so the prompt renders once as one clean body with no spurious `### Context` wrapper. A genuinely-separate user-supplied context (whose first line differs from the description) is left untouched, and the stored task keeps its one-line description for the task-list UI. Pure code fix — reaches every install on update, no data or prompt-template migration.
diff --git a/client/src/components/cos/tabs/LearningTab.jsx b/client/src/components/cos/tabs/LearningTab.jsx
index 1e65ac7902..6e8d50a639 100644
--- a/client/src/components/cos/tabs/LearningTab.jsx
+++ b/client/src/components/cos/tabs/LearningTab.jsx
@@ -18,6 +18,9 @@ import {
Database,
RotateCcw,
Crosshair,
+ BookOpen,
+ Sparkles,
+ User,
Shield,
ShieldCheck,
ShieldAlert,
@@ -49,7 +52,8 @@ export default function LearningTab() {
durations: false,
models: true,
routing: true,
- errors: false
+ errors: false,
+ standing: true
});
const loadData = useCallback(async () => {
@@ -862,6 +866,55 @@ export default function LearningTab() {
</div>
)}
+ {/* Standing Learnings / Operating Notes (issue #2443) */}
+ {learning.standingLearnings?.length > 0 && (
+ <div>
+ <button
+ onClick={() => toggleSection('standing')}
+ className="flex items-center gap-2 w-full text-left mb-3"
+ >
+ {expandedSections.standing ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
+ <BookOpen size={16} className="text-port-accent" />
+ <span className="font-medium text-white">Standing Learnings</span>
+ <span className="text-xs text-gray-500">
+ ({learning.standingLearnings.length} note{learning.standingLearnings.length === 1 ? '' : 's'})
+ </span>
+ </button>
+ {expandedSections.standing && (
+ <>
+ <p className="text-xs text-gray-500 mb-3">
+ Human-readable operating notes — recurring-failure incidents the agent auto-flagged, plus notes you recorded. Runtime-only (never committed to git).
+ </p>
+ <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">
+ {learning.standingLearnings.map((note, idx) => {
+ const isAuto = note.origin === 'auto-incident';
+ return (
+ <div key={idx} className="p-3">
+ <div className="flex items-center justify-between gap-2 mb-1">
+ <span className={`inline-flex items-center gap-1 text-xs font-medium px-1.5 py-0.5 rounded ${isAuto ? 'bg-port-warning/15 text-port-warning' : 'bg-port-border text-gray-300'}`}>
+ {isAuto ? <Sparkles size={11} /> : <User size={11} />}
+ {isAuto ? 'Auto-flagged' : 'Manual'}
+ </span>
+ {note.recordedAt && (
+ <span className="text-xs text-gray-600">{formatDateTime(note.recordedAt)}</span>
+ )}
+ </div>
+ <div className="text-sm text-gray-300">{note.message}</div>
+ {(note.category || note.taskType) && (
+ <div className="text-xs text-gray-500 mt-1 font-mono">
+ {note.category ? `${note.category}` : ''}{note.category && note.taskType ? ' · ' : ''}{note.taskType || ''}
+ {note.recurrenceCount ? ` · ×${note.recurrenceCount}` : ''}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </>
+ )}
+ </div>
+ )}
+
{/* Last Updated */}
{learning.lastUpdated && (
<div className="text-xs text-gray-600 text-center pt-4 border-t border-port-border">
diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.js
index 756b590e22..e58e22d7fb 100644
--- a/server/services/taskLearning/index.js
+++ b/server/services/taskLearning/index.js
@@ -26,6 +26,11 @@ export {
classifyUntypedTask,
isSandboxedTaskType,
summarizeFailureSignatures,
+ appendInsight,
+ buildRecurrenceInsight,
+ recurrenceMilestoneReached,
+ INSIGHT_CAP,
+ RECURRENCE_INSIGHT_MILESTONES,
EXTERNAL_UNTYPED_TASK_TYPE
} from './store.js';
diff --git a/server/services/taskLearning/insights.js b/server/services/taskLearning/insights.js
index 277f1c52b2..8d10f6f732 100644
--- a/server/services/taskLearning/insights.js
+++ b/server/services/taskLearning/insights.js
@@ -12,7 +12,8 @@ import {
saveLearningData,
loadDismissedRecommendations,
saveDismissedRecommendations,
- summarizeFailureSignatures
+ summarizeFailureSignatures,
+ appendInsight
} from './store.js';
import { computeCorrelationQuality, isCorrelationProven, CORRELATION_QUALITY_THRESHOLD } from './correlationQuality.js';
@@ -103,6 +104,10 @@ export async function getLearningInsights() {
modelEffectiveness,
recentUnknownErrors: data.recentUnknownErrors || []
},
+ // Standing learnings / operating notes (issue #2443): human-readable insights
+ // — auto-recorded recurring-failure incidents plus any user-authored notes —
+ // newest first. Runtime-only (data/cos/), surfaced in the CoS UI.
+ standingLearnings: (data.insights || []).slice(-20).reverse(),
recommendations: generateRecommendations(data, bestPerforming, worstPerforming, commonErrors, dismissed, failureSignatures)
};
}
@@ -265,34 +270,23 @@ export async function getDismissedRecommendations() {
}
/**
- * Record a learning insight for future reference
- * Stores observations about what works and what doesn't
+ * Record a learning insight for future reference. Stores observations about what
+ * works and what doesn't. Manual insights (from the API route) default to
+ * `origin: 'user'` — the failure path records `origin: 'auto-incident'` inline
+ * (see `recordTaskCompletion`) to avoid re-entering the non-reentrant store lock.
*/
export async function recordLearningInsight(insight) {
return withLock(async () => {
const data = await loadLearningData();
-
- if (!data.insights) {
- data.insights = [];
- }
-
- data.insights.push({
- ...insight,
- recordedAt: new Date().toISOString()
- });
-
- // Keep only last 50 insights
- if (data.insights.length > 50) {
- data.insights = data.insights.slice(-50);
- }
-
+ appendInsight(data, insight);
await saveLearningData(data);
- return insight;
+ // Return the stamped record (with recordedAt + resolved origin), not the bare input.
+ return data.insights[data.insights.length - 1];
});
}
/**
- * Get recent learning insights
+ * Get recent learning insights (newest last, matching insertion order).
*/
export async function getRecentInsights(limit = 10) {
const data = await loadLearningData();
diff --git a/server/services/taskLearning/insights.test.js b/server/services/taskLearning/insights.test.js
index 4ea2daa2aa..1769868a59 100644
--- a/server/services/taskLearning/insights.test.js
+++ b/server/services/taskLearning/insights.test.js
@@ -78,3 +78,26 @@ describe('insights.getLearningInsights — failureSignatures consumption (issue
expect(view.recommendations.some(r => r.id?.startsWith('failure-signature:'))).toBe(false);
});
});
+
+describe('insights.getLearningInsights — standing learnings surfacing (issue #2443)', () => {
+ it('surfaces recorded insights (newest first) with their origin preserved', async () => {
+ loadLearningData.mockResolvedValue(learningData({
+ insights: [
+ { origin: 'user', message: 'older manual note', recordedAt: '2026-07-08T00:00:00Z' },
+ { origin: 'auto-incident', category: 'timeout', taskType: 'auto-fix', recurrenceCount: 3, message: 'recurring failure', recordedAt: '2026-07-09T00:00:00Z' }
+ ]
+ }));
+ const view = await getLearningInsights();
+ expect(view.standingLearnings).toHaveLength(2);
+ // Newest first.
+ expect(view.standingLearnings[0].origin).toBe('auto-incident');
+ expect(view.standingLearnings[0].recurrenceCount).toBe(3);
+ expect(view.standingLearnings[1].origin).toBe('user');
+ });
+
+ it('returns an empty array when no insights have been recorded', async () => {
+ loadLearningData.mockResolvedValue(learningData());
+ const view = await getLearningInsights();
+ expect(view.standingLearnings).toEqual([]);
+ });
+});
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 4490083eb6..58c30eb588 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -17,7 +17,10 @@ import {
calculateDurationETA,
extractTaskType,
loadLearningData,
- saveLearningData
+ saveLearningData,
+ appendInsight,
+ buildRecurrenceInsight,
+ recurrenceMilestoneReached
} from './store.js';
import { deriveFailureSignalAvoidance, isNonRoutableLearnedTier } from './routing.js';
import { recordCorrelationSample } from './correlationQuality.js';
@@ -359,6 +362,32 @@ export async function recordTaskCompletion(agent, task) {
// execution context + latency) — a no-op on success (issue #2329).
recordFailureSignature(data, telemetry);
+ // Fold a recurring failure category into a standing, provenance-stamped
+ // human-readable insight (issue #2443) — turns a machine aggregate into an
+ // operating note the user can read in the CoS UI, without a manual API call.
+ // Fires only when the per-category recurrence count lands on a milestone so it
+ // escalates instead of spamming. Appended inline (not via recordLearningInsight)
+ // because we already hold the non-reentrant store lock and `data` is about to
+ // be persisted below. Privacy: buildRecurrenceInsight uses only controlled
+ // fields — no raw error message (which could embed a path/PII).
+ if (!outcomeSuccess && errorCategory) {
+ const recurrenceCount = data.errorPatterns[errorCategory]?.count || 0;
+ if (recurrenceMilestoneReached(recurrenceCount)) {
+ appendInsight(data, buildRecurrenceInsight({
+ category: errorCategory,
+ count: recurrenceCount,
+ taskType,
+ agentId: agent.agentId || agent.id || null,
+ failureSignatures: data.failureSignatures
+ }));
+ emitLog('info', `📚 Auto-recorded recurring-failure insight: "${errorCategory}" ×${recurrenceCount} (${taskType})`, {
+ category: errorCategory,
+ recurrenceCount,
+ taskType
+ }, '[TaskLearning]');
+ }
+ }
+
// Update totals
data.totals.completed++;
if (outcomeSuccess) {
diff --git a/server/services/taskLearning/store.js b/server/services/taskLearning/store.js
index b8b1ca90e9..eab3387612 100644
--- a/server/services/taskLearning/store.js
+++ b/server/services/taskLearning/store.js
@@ -217,6 +217,76 @@ export function summarizeFailureSignatures(failureSignatures, { taskType = null,
return summaries.sort((a, b) => b.count - a.count).slice(0, Math.max(0, limit));
}
+// ---------------------------------------------------------------------------
+// Human-readable insights (issue #2443)
+//
+// The insights array is the ONE prose channel in the learning store: standing
+// "operating notes" the user reads in the CoS UI. It is runtime data in
+// `data/cos/learning.json` — never committed to git and never federated — so
+// auto-recorded insight text must stay free of hostnames/paths/PII (build it
+// only from controlled labels: error category, counts, task type, provider/model
+// ids, agent id — never the raw error message, which can embed a path).
+// ---------------------------------------------------------------------------
+
+// Cap on retained insights (oldest pruned first). Matches the pre-existing cap
+// that `recordLearningInsight` enforced before it was factored out here.
+export const INSIGHT_CAP = 50;
+
+// Recurrence counts (of a single error category) at which the failure path
+// auto-records a standing insight. Exact-equality matching over these ascending
+// milestones makes recording idempotent — the per-category count only increments
+// by one per categorized failure, so each milestone fires exactly once and then
+// escalates, rather than spamming an insight on every subsequent failure.
+export const RECURRENCE_INSIGHT_MILESTONES = [3, 10, 25, 50, 100];
+
+/** True when a category's post-increment recurrence count lands on a milestone. */
+export function recurrenceMilestoneReached(count) {
+ return RECURRENCE_INSIGHT_MILESTONES.includes(count);
+}
+
+/**
+ * Append an insight to `data.insights`, stamping `recordedAt` and defaulting
+ * `origin` to `'user'` (a manual API insight) unless the caller marks it
+ * `'auto-incident'`. Pure over `data` (mutates + returns it); enforces the
+ * `INSIGHT_CAP` (oldest pruned). Shared by the manual route (`recordLearningInsight`)
+ * and the failure-path auto-recorder so both stay in one shape.
+ */
+export function appendInsight(data, insight) {
+ if (!Array.isArray(data.insights)) data.insights = [];
+ data.insights.push({ origin: 'user', ...insight, recordedAt: new Date().toISOString() });
+ if (data.insights.length > INSIGHT_CAP) {
+ data.insights = data.insights.slice(-INSIGHT_CAP);
+ }
+ return data;
+}
+
+/**
+ * Build a provenance-stamped, privacy-safe insight for a recurring failure
+ * category (issue #2443). Pure — no I/O. Uses only controlled fields (category
+ * label, recurrence count, task type, provider/model ids, agent id); it reads
+ * the enriched `failureSignatures` map for provider/model attribution but never
+ * echoes the raw error message (which can embed a path/PII). `origin` is
+ * `'auto-incident'` so the UI can distinguish it from user-authored notes.
+ */
+export function buildRecurrenceInsight({ category, count, taskType, agentId = null, failureSignatures = {} } = {}) {
+ const summary = summarizeFailureSignatures(failureSignatures, { taskType })
+ .find((s) => s.category === category);
+ const topProvider = summary?.providers?.[0]?.key || null;
+ const via = topProvider ? `, most recently via ${topProvider}` : '';
+ const message = `Recurring failure: "${category}" errors have occurred ${count} times for ${taskType} tasks${via}. Auto-flagged at ${count} occurrences — investigate the root cause or route this task type away from the failing path.`;
+
+ return {
+ type: 'recurring-failure',
+ origin: 'auto-incident',
+ category,
+ taskType,
+ recurrenceCount: count,
+ provider: topProvider,
+ originatingAgentId: agentId,
+ message
+ };
+}
+
/**
* Ordered description-keyword → concrete-type rules, tried only as a last resort
* before the sandboxed fallback. First match wins. Patterns are whole-word/stem
diff --git a/server/services/taskLearning/store.test.js b/server/services/taskLearning/store.test.js
index df73288600..068a73e924 100644
--- a/server/services/taskLearning/store.test.js
+++ b/server/services/taskLearning/store.test.js
@@ -5,6 +5,11 @@ import {
classifyUntypedTask,
isSandboxedTaskType,
summarizeFailureSignatures,
+ appendInsight,
+ buildRecurrenceInsight,
+ recurrenceMilestoneReached,
+ RECURRENCE_INSIGHT_MILESTONES,
+ INSIGHT_CAP,
EXTERNAL_UNTYPED_TASK_TYPE
} from './store.js';
@@ -263,3 +268,114 @@ describe('store.summarizeFailureSignatures (issue #2333)', () => {
expect(summarizeFailureSignatures(map, { limit: 3 })).toHaveLength(3);
});
});
+
+// -----------------------------------------------------------------------------
+// Human-readable insights (issue #2443) — pure helpers exercised without I/O.
+// -----------------------------------------------------------------------------
+
+describe('store.recurrenceMilestoneReached', () => {
+ it('fires exactly on the configured ascending milestones', () => {
+ for (const m of RECURRENCE_INSIGHT_MILESTONES) {
+ expect(recurrenceMilestoneReached(m)).toBe(true);
+ }
+ });
+
+ it('does not fire on off-milestone counts (idempotency: one insight per milestone)', () => {
+ expect(recurrenceMilestoneReached(1)).toBe(false);
+ expect(recurrenceMilestoneReached(2)).toBe(false);
+ expect(recurrenceMilestoneReached(4)).toBe(false);
+ expect(recurrenceMilestoneReached(11)).toBe(false);
+ expect(recurrenceMilestoneReached(0)).toBe(false);
+ });
+});
+
+describe('store.appendInsight', () => {
+ it('stamps recordedAt and defaults origin to user', () => {
+ const data = {};
+ appendInsight(data, { type: 'observation', message: 'hello' });
+ expect(data.insights).toHaveLength(1);
+ expect(data.insights[0].origin).toBe('user');
+ expect(data.insights[0].message).toBe('hello');
+ expect(typeof data.insights[0].recordedAt).toBe('string');
+ });
+
+ it('preserves an explicit origin (auto-incident) and overrides any passed recordedAt', () => {
+ const data = { insights: [] };
+ appendInsight(data, { origin: 'auto-incident', message: 'auto', recordedAt: 'stale' });
+ expect(data.insights[0].origin).toBe('auto-incident');
+ expect(data.insights[0].recordedAt).not.toBe('stale');
+ });
+
+ it('caps retained insights at INSIGHT_CAP (oldest pruned first)', () => {
+ const data = { insights: [] };
+ for (let i = 0; i < INSIGHT_CAP + 5; i++) {
+ appendInsight(data, { message: `m${i}` });
+ }
+ expect(data.insights).toHaveLength(INSIGHT_CAP);
+ // Oldest five pruned — newest retained.
+ expect(data.insights[0].message).toBe('m5');
+ expect(data.insights[INSIGHT_CAP - 1].message).toBe(`m${INSIGHT_CAP + 4}`);
+ });
+
+ it('initializes a missing/non-array insights field', () => {
+ const data = { insights: 'corrupt' };
+ appendInsight(data, { message: 'x' });
+ expect(Array.isArray(data.insights)).toBe(true);
+ expect(data.insights).toHaveLength(1);
+ });
+});
+
+describe('store.buildRecurrenceInsight', () => {
+ const failureSignatures = {
+ timeout: {
+ count: 3,
+ recent: [
+ { taskType: 'self-improve:ui', provider: 'claude', model: 'opus', modelTier: 'heavy', recordedAt: '2026-07-10T00:00:00.000Z' },
+ { taskType: 'self-improve:ui', provider: 'claude', model: 'opus', modelTier: 'heavy', recordedAt: '2026-07-10T00:01:00.000Z' },
+ { taskType: 'self-improve:ui', provider: 'codex', model: 'gpt', modelTier: 'heavy', recordedAt: '2026-07-10T00:02:00.000Z' }
+ ]
+ }
+ };
+
+ it('produces a provenance-stamped, auto-incident insight with provider attribution', () => {
+ const insight = buildRecurrenceInsight({
+ category: 'timeout',
+ count: 3,
+ taskType: 'self-improve:ui',
+ agentId: 'agent-xyz',
+ failureSignatures
+ });
+ expect(insight.origin).toBe('auto-incident');
+ expect(insight.type).toBe('recurring-failure');
+ expect(insight.category).toBe('timeout');
+ expect(insight.taskType).toBe('self-improve:ui');
+ expect(insight.recurrenceCount).toBe(3);
+ expect(insight.originatingAgentId).toBe('agent-xyz');
+ // Top provider by count (claude/opus appears twice).
+ expect(insight.provider).toBe('claude/opus');
+ expect(insight.message).toContain('"timeout"');
+ expect(insight.message).toContain('3 times');
+ expect(insight.message).toContain('claude/opus');
+ });
+
+ it('never echoes a raw error message (privacy) — message is built only from controlled fields', () => {
+ const withRawMessage = {
+ timeout: {
+ count: 3,
+ recent: [
+ { taskType: 't', provider: 'claude', model: 'opus', messageSnippet: '/Users/secret/path leaked ENOENT', recordedAt: '2026-07-10T00:00:00.000Z' }
+ ]
+ }
+ };
+ const insight = buildRecurrenceInsight({ category: 'timeout', count: 3, taskType: 't', failureSignatures: withRawMessage });
+ expect(insight.message).not.toContain('/Users/secret');
+ expect(insight.message).not.toContain('leaked');
+ });
+
+ it('degrades gracefully when no provider attribution is available', () => {
+ const insight = buildRecurrenceInsight({ category: 'unknown', count: 10, taskType: 't', failureSignatures: {} });
+ expect(insight.provider).toBeNull();
+ expect(insight.message).toContain('10 times');
+ expect(insight.message).not.toContain('via');
+ });
+});