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: give CoS investigation tasks a human-facing what-happened/approve/unblocks template with a redacted failure snippet (#2442)

Adam Eivyff4ce701b479
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9fd8713f56..6b944d3bc1 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changes
+- **CoS investigation tasks now use a human-facing "What happened / What to approve / What unblocks" template with a redacted failure snippet (#2442).** When a CoS agent failure is classified as *actionable*, `createInvestigationTask()` filed a fixed 6-field stub (Failed Agent / Original Task / Error Category / Suggested Fix / Model) that read identically for every category, while the useful diagnostic context stayed buried in `learning.json` telemetry. The body is now restructured into three sections — **What happened** (plain-language category + provider/model attribution + a short captured failure snippet), **What to approve** (the concrete decision/action to take), and **What unblocks** (which original task resumes) — and each `ERROR_PATTERN` may optionally supply category-specific escalation prose so the note varies by failure kind (model-not-found, context-length, spawn-error, task-rejected, content-filtered, etc.) instead of being uniform. The folded-in snippet and task description are passed through a new `redactFailureSnippet()` helper that strips OS usernames from home paths, emails, IPs, Tailscale/mDNS hostnames, and bearer/secret tokens before anything lands in the human-facing (and potentially federated) task body. Additive copy/structure change to one function plus optional per-pattern fields — no status-model change.
+
- **The dashboard's Quick Image widget now offers custom output dimensions and no longer shows a blank size dropdown for off-preset sizes (#2437).** The quick widget had its own inline resolution `<select>` over the universal presets and never gained the **Custom…** option added to the full Image Gen page, so its size picker was inconsistent — and a remix/off-preset size (any width/height not on the preset list) rendered a blank dropdown because no matching `<option>` existed. It now reuses the shared `ResolutionField` control, so selecting **Custom…** reveals Width/Height inputs (any edge 64–3840px, total ≤ 8,294,400px, matching the server's `imageEdgeSchema` + pixel cap), and an off-preset size auto-opens those inputs with the exact dimensions visible instead of collapsing to a blank select. No behavior change to the presets themselves.
- **Duplicated child-process stream/discovery helpers converged into shared lib modules (#2392).** Three hand-copied "split a stdout/stderr chunk stream into lines with a carry buffer" implementations (`ytdlpAudioImport.js`, `videoDownload.js`, `hfDownload.js`) had already drifted — only hfDownload's copy flushed the final unterminated line. They now share `server/lib/streamLines.js#createLineReader(onLine, {splitRe?, maxCarry?})`, which carries the partial trailing line across chunks, exposes a `flush()` for the last newline-less line (so the two yt-dlp paths stop dropping it — and skip the flush on cancel so a partial marker can't fire a stray progress frame), clamps the carry buffer against a newline-less runaway stream, and takes a `splitRe: /[\r\n]+/` option for bare-`\r` torch/tqdm progress redraws. The four bare-`\r` progress-splitter siblings (`midiRuntime.js`, `videoGen.js`, `music.js` install-log routes, and `pythonSetup.js#streamSpawn`) are converged onto the same reader with that option, so a progress line split across a chunk boundary is no longer torn. Separately, the inline `which`/`where` PATH probes in `ytdlp.js`, `ffmpeg.js` (×2), `pythonSetup.js`, and voice `bootstrap.js` are replaced by a single `whichFirst(name)` in `server/lib/processEnv.js` (Malloc-stripped env, 5s timeout, first-line result). The vendored `aiToolkit/providers.js` copy is intentionally left alone (self-contained by design). Behavior-preserving; both new helpers are unit-tested.
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index bc0e7f1b85..a1241a05cf 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -9,10 +9,56 @@ import { emitLog } from './cosEvents.js';
import { addTask, updateTask } from './cos.js';
import { cosEvents } from './cosEvents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
+import { redactOutput } from '../lib/commandSecurity.js';
// Max retries before blocking a task
export const MAX_TASK_RETRIES = 3;
+// Longest redacted failure snippet folded into a human-facing investigation body.
+const SNIPPET_MAX_CHARS = 240;
+
+// Machine-identity / network / PII fragments stripped before a captured failure
+// snippet (or any interpolated free text) lands in a human-facing — and possibly
+// federated — investigation task body. See the "Sensitive Data & Privacy" section
+// in CLAUDE.md: the *shape* of the failure is what a human needs, never the live
+// hostnames, paths, addresses, or secrets pulled off the running instance.
+const SNIPPET_REDACTIONS = [
+ // Home-dir paths that embed an OS username → strip the user segment only.
+ [/\/(Users|home)\/[^/\s"']+/gi, '/$1/<user>'],
+ // Email addresses.
+ [/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, '<email>'],
+ // Tailscale MagicDNS / mDNS hostnames.
+ [/\b[A-Za-z0-9-]+\.(?:ts\.net|local)\b/gi, '<host>'],
+ // IPv4 addresses (LAN / Tailscale / public alike).
+ [/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, '<ip>'],
+ // Bearer tokens and common secret-key formats.
+ [/\bbearer\s+[\w.\-/+=]{12,}/gi, 'bearer <token>'],
+ [/\bsk-[A-Za-z0-9\-_]{16,}/g, '<token>'],
+];
+
+/**
+ * Redact machine identity, network info, PII, and secrets from free text before
+ * it is embedded in an investigation-task body. Also normalizes whitespace and
+ * caps length so a captured multi-line snippet stays a single readable line.
+ * Pure — safe to unit-test directly.
+ */
+export function redactFailureSnippet(text) {
+ if (typeof text !== 'string' || !text.trim()) return '';
+ let out = redactOutput(text); // JSON secret key/value pairs
+ for (const [re, replacement] of SNIPPET_REDACTIONS) out = out.replace(re, replacement);
+ out = out.replace(/\s+/g, ' ').trim();
+ return out.length > SNIPPET_MAX_CHARS ? `${out.slice(0, SNIPPET_MAX_CHARS)}…` : out;
+}
+
+// Extract the single output line containing `index` — the matched failure line
+// makes the most useful snippet without dragging in surrounding noise.
+function snippetAround(text, index) {
+ const start = text.lastIndexOf('\n', index) + 1; // -1 → 0 (first line)
+ const nl = text.indexOf('\n', index);
+ const end = nl === -1 ? text.length : nl;
+ return text.slice(start, end).trim();
+}
+
/**
* Error patterns that warrant investigation tasks.
* Patterns are checked in order — first match wins.
@@ -24,6 +70,7 @@ export const ERROR_PATTERNS = [
pattern: /API Error: 404.*model:\s*(\S+)/i,
category: 'model-not-found',
actionable: true,
+ escalation: 'Set a valid model id for this task (or clear its model override so the CLI falls back to its own configured default), then approve the retry.',
extract: (match, output, task, model) => ({
message: `Model "${match[1]}" not found`,
suggestedFix: `Update model configuration - "${match[1]}" doesn't exist. Check provider settings or task metadata.`,
@@ -35,6 +82,7 @@ export const ERROR_PATTERNS = [
pattern: /(?:model:\s*)?["']?([A-Za-z0-9._:-]+)["']?\s+model is not supported|model\s+["']?([A-Za-z0-9._:-]+)["']?.*not supported/i,
category: 'model-not-supported',
actionable: true,
+ escalation: 'Pick a model the provider account supports (or clear the override to use the CLI default), then approve the retry.',
extract: (match, output, task, model) => ({
message: `Model "${match[1] || match[2] || model || 'configured model'}" is not supported`,
suggestedFix: 'Update the provider model configuration or leave the model blank so the CLI can use its own configured default.',
@@ -122,6 +170,7 @@ export const ERROR_PATTERNS = [
pattern: /context.?length|max.?tokens|token.?limit|context.?window/i,
category: 'context-length',
actionable: true,
+ escalation: 'Approve splitting the original task into smaller subtasks (or route it to a larger-context model), then retry — the retry already carries compaction hints.',
extract: (match, output) => ({
message: 'Context length exceeded',
suggestedFix: 'Task is too large for the context window. Break into smaller subtasks or use a model with larger context.',
@@ -316,6 +365,7 @@ export const ERROR_PATTERNS = [
pattern: /spawn.?(?:error|failed)|EACCES|command.?not.?found/i,
category: 'spawn-error',
actionable: true,
+ escalation: 'Confirm the required CLI/tool is installed and on PATH for the agent user (or fix the command), then approve the retry.',
extract: () => ({
message: 'Command spawn failed',
suggestedFix: 'Failed to start subprocess. Check that required CLI tools are installed and accessible.'
@@ -365,6 +415,7 @@ export const ERROR_PATTERNS = [
pattern: /task.?(?:rejected|declined|refused)|cannot.?(?:complete|perform)/i,
category: 'task-rejected',
actionable: true,
+ escalation: 'Rephrase or narrow the original task description so it is actionable, then approve the retry — the agent declined it as written.',
extract: () => ({
message: 'Agent rejected task',
suggestedFix: 'Agent could not or would not complete the task. Rephrase or simplify the request.'
@@ -396,6 +447,7 @@ export const ERROR_PATTERNS = [
pattern: /content.?(?:filter|policy)|safety.?(?:filter|block)|harmful.?content/i,
category: 'content-filtered',
actionable: true,
+ escalation: 'Reword the task description to avoid the content that tripped the safety filter, then approve the retry.',
extract: () => ({
message: 'Content filtered',
suggestedFix: 'Request was blocked by content safety filter. Rephrase the task description.'
@@ -421,7 +473,9 @@ export function analyzeAgentFailure(output, task, model) {
category: 'startup-failure',
actionable: false,
message: 'Agent failed to start or produced no output',
- suggestedFix: 'Agent process exited immediately. Check system resources and provider availability.'
+ suggestedFix: 'Agent process exited immediately. Check system resources and provider availability.',
+ snippet: (output || '').trim(),
+ escalation: null
};
}
@@ -434,6 +488,10 @@ export function analyzeAgentFailure(output, task, model) {
return {
category: errorDef.category,
actionable: errorDef.actionable,
+ // Captured for the human-facing investigation body; redacted at embed time.
+ snippet: snippetAround(analysisOutput, match.index ?? 0),
+ // Optional category-specific "what to approve" prose (may be undefined).
+ escalation: errorDef.escalation || null,
...extracted
};
}
@@ -454,6 +512,8 @@ export function analyzeAgentFailure(output, task, model) {
actionable: false,
message: summary,
details: contextLines.map(l => l.trim()).join('\n'),
+ snippet: contextLines.map(l => l.trim()).join(' '),
+ escalation: null,
suggestedFix: 'Error did not match known patterns. Review the details or agent output logs.'
};
}
@@ -462,16 +522,36 @@ export function analyzeAgentFailure(output, task, model) {
* Create an investigation task in COS-TASKS.md for a failed agent.
*/
export async function createInvestigationTask(agentId, originalTask, errorAnalysis) {
- const description = `[Auto] Investigate agent failure: ${errorAnalysis.message}
-
-**Failed Agent**: ${agentId}
-**Original Task**: ${originalTask.id} - ${(originalTask.description || '').substring(0, 100)}
-**Error Category**: ${errorAnalysis.category}
-**Suggested Fix**: ${errorAnalysis.suggestedFix}
-${errorAnalysis.configuredModel ? `**Configured Model**: ${errorAnalysis.configuredModel}` : ''}
-${errorAnalysis.affectedModel ? `**Affected Model**: ${errorAnalysis.affectedModel}` : ''}
-
-Review the error, fix the configuration or code issue, and retry the original task.`;
+ const analysis = errorAnalysis || {};
+ const category = analysis.category || 'unknown';
+ const message = analysis.message || 'Agent failed with an unrecognized error';
+ const modelAttribution = analysis.affectedModel || analysis.configuredModel || null;
+
+ // Every interpolated free-text field is redacted before it lands in the body —
+ // this task is human-facing and may sync across federated peers, so no
+ // hostnames/paths/IPs/PII/secrets from the live instance may leak in.
+ const snippet = redactFailureSnippet(analysis.snippet || analysis.details || message);
+ const originalDesc = redactFailureSnippet((originalTask.description || '').substring(0, 160)) || '(no description)';
+
+ // Prefer the pattern's category-specific escalation prose; fall back to the
+ // generic suggestedFix so uncustomized categories still read as an action.
+ const whatToApprove = analysis.escalation
+ || analysis.suggestedFix
+ || 'Review the agent output, decide whether to fix the underlying config/code and retry, or close the task.';
+
+ const description = `[Auto] Investigate agent failure: ${message}
+
+## What happened
+Agent \`${agentId}\` failed while working on task \`${originalTask.id}\` (${originalDesc}).
+- **Classification**: ${category} — ${message}
+- **Provider/model**: ${modelAttribution || 'not attributed'}
+${snippet ? `- **Failure snippet (redacted)**:\n > ${snippet}` : '- **Failure snippet**: (none captured)'}
+
+## What to approve
+${whatToApprove}
+
+## What unblocks
+Approving and applying the fix lets the original task \`${originalTask.id}\` be retried; it will resume: ${originalDesc}.`;
const investigationTask = await addTask({
description,
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 8ed56c1f40..6a2cb33be2 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -8,6 +8,8 @@ import {
analyzeAgentFailure,
resolveFailedTaskDecision,
maybeCreateInvestigationTask,
+ createInvestigationTask,
+ redactFailureSnippet,
MAX_TASK_RETRIES
} from './agentErrorAnalysis.js';
import { addTask } from './cos.js';
@@ -232,3 +234,102 @@ describe('maybeCreateInvestigationTask', () => {
expect(addTask).toHaveBeenCalledTimes(1);
});
});
+
+describe('redactFailureSnippet', () => {
+ it('strips OS usernames, emails, IPs, hostnames, and secrets, collapsing to one line', () => {
+ const raw = [
+ 'error at /Users/alice/github.com/app/index.js:42',
+ 'contact [email protected] or reach host node-alpha.tailnet.ts.net',
+ 'connect ECONNREFUSED 192.0.2.10:5555',
+ 'Authorization: Bearer abcdef0123456789abcdef',
+ ].join('\n');
+ const out = redactFailureSnippet(raw);
+ expect(out).not.toContain('alice');
+ expect(out).not.toContain('[email protected]');
+ expect(out).not.toContain('node-alpha.tailnet.ts.net');
+ expect(out).not.toContain('192.0.2.10');
+ expect(out).not.toContain('abcdef0123456789abcdef');
+ expect(out).toContain('/Users/<user>/github.com/app/index.js');
+ expect(out).toContain('<email>');
+ expect(out).toContain('<host>');
+ expect(out).toContain('<ip>');
+ expect(out).not.toContain('\n'); // collapsed to a single line
+ });
+
+ it('returns an empty string for non-string / blank input', () => {
+ expect(redactFailureSnippet(null)).toBe('');
+ expect(redactFailureSnippet(' ')).toBe('');
+ });
+
+ it('caps overly long snippets with an ellipsis', () => {
+ const out = redactFailureSnippet('x'.repeat(500));
+ expect(out.length).toBeLessThanOrEqual(241);
+ expect(out.endsWith('…')).toBe(true);
+ });
+});
+
+describe('analyzeAgentFailure — snippet & escalation enrichment', () => {
+ it('captures the matched failure line as a snippet and category-specific escalation prose', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 404 - model: claude-4-ultra not found'), { id: 't' }, 'claude-4-ultra');
+ expect(analysis.snippet).toContain('claude-4-ultra');
+ expect(analysis.escalation).toMatch(/approve the retry/i);
+ });
+
+ it('leaves escalation null for categories without custom prose', () => {
+ const analysis = analyzeAgentFailure(withLead('API Error: 429 Too Many Requests, please slow down'), { id: 't' }, 'x');
+ expect(analysis.escalation).toBeNull();
+ });
+});
+
+describe('createInvestigationTask body', () => {
+ beforeEach(() => {
+ addTask.mockReset();
+ addTask.mockResolvedValue({ id: 'investigation-1' });
+ });
+
+ const bodyOf = () => addTask.mock.calls[0][0].description;
+
+ it('renders the What happened / What to approve / What unblocks template with category-specific prose', async () => {
+ await createInvestigationTask('agent-1', { id: 'task-9', description: 'ship the thing' }, {
+ category: 'model-not-found',
+ message: 'Model "claude-4-ultra" not found',
+ configuredModel: 'claude-4-ultra',
+ snippet: 'API Error: 404 - model: claude-4-ultra not found',
+ escalation: 'Set a valid model id for this task, then approve the retry.',
+ });
+ const body = bodyOf();
+ expect(body).toContain('## What happened');
+ expect(body).toContain('## What to approve');
+ expect(body).toContain('## What unblocks');
+ expect(body).toContain('model-not-found');
+ expect(body).toContain('claude-4-ultra'); // provider/model attribution
+ expect(body).toContain('Set a valid model id'); // category-specific escalation prose
+ expect(body).toContain('task-9'); // which task unblocks
+ });
+
+ it('falls back to suggestedFix when a category supplies no escalation prose', async () => {
+ await createInvestigationTask('agent-2', { id: 'task-10', description: 'do x' }, {
+ category: 'unknown',
+ message: 'boom',
+ suggestedFix: 'Review the details or agent output logs.',
+ escalation: null,
+ });
+ expect(bodyOf()).toContain('Review the details or agent output logs.');
+ });
+
+ it('never leaks host/path/PII data from the snippet or task description into the body', async () => {
+ await createInvestigationTask('agent-3', {
+ id: 'task-11',
+ description: 'fix bug for user alice at /Users/alice/app',
+ }, {
+ category: 'file-not-found',
+ message: 'File not found',
+ snippet: 'ENOENT: /Users/alice/secret.json — see [email protected] or node-alpha.ts.net at 192.0.2.10',
+ });
+ const body = bodyOf();
+ expect(body).not.toContain('/Users/alice');
+ expect(body).not.toContain('[email protected]');
+ expect(body).not.toContain('node-alpha.ts.net');
+ expect(body).not.toContain('192.0.2.10');
+ });
+});