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

run CoS agent-failure investigations unattended unless the failure is a loop

[._.]/ Adam Eivy8c78d397d738
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 16b2c639c9..332d45ab36 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -62,6 +62,8 @@
- **Post-arc character repair no longer invents plot events that the episode plan never stages.** Character reconciliation could improve a supporting cast member by adding new early `atIssue` transitions, then the next foundation verdict correctly penalized structure because those characters were absent from the corresponding synopses. Existing transition beats are now read-only after the macro arc exists: character repair may deepen motivation, arc type, and start/end states, while the structure editor exclusively owns adding or moving dramatized events. Pre-arc character-first planning still authors provisional transitions normally.
+- **A CoS agent failure now gets investigated without waiting on you.** Every `[Auto] Investigate agent failure` task was filed approval-required, so the whole point of the feature — CoS diagnosing its own failures — stalled behind a manual APPROVE click on work that is ordinary, expected traffic. Those tasks now run unattended by default, and a human is asked only when the failure is a *loop*, where spending another agent would just repeat what already didn't work: either the same cause was already investigated within the last 24 hours and has come back, or the hour is already one slot from the circuit breaker that suppresses investigations entirely, meaning failures are cascading rather than isolated. A held task says which of the two it was, in its body and on the APPROVE button, so "why is this one waiting on me?" is answerable without opening it. The existing guards are untouched: one open investigation per cause, no investigations of investigations, no investigation at all when the provider itself is unreachable, and a hard cap of three per hour. The unattended spawn still obeys the CoS autonomy mode and daily budget, so `off` and `dry-run` installs are unaffected.
+
- **Complete LLM answers no longer fail on recoverable JSON serialization mistakes.** Long foundation calls could begin as normal JSON, then emit the complete remaining objects as escaped `\\n` / `\\"` text, leave quotation marks inside prose unescaped, or omit a prose field's closing quote immediately before its structural `}` line. The shared parser now decodes an escaped tail only from the JSON parser's exact failure position, repairs quotes only at structurally unambiguous boundaries, and accepts repairs only when the entire reconstructed response parses—preserving expensive completed work without making partial or arbitrary text look valid.
- **The foundation judge no longer mistakes visual prompt families for binding story canon.** Universe Builder categories are additive image-prompt design systems, but the foundation judge rendered their labels beside the narrative bible and named canon, then penalized duplicate-looking creatures, vehicles, and artifacts even though its world-repair editor can only revise narrative world rules. That produced a structurally unwinnable loop: the critic demanded canon-tier metadata or inventory pruning from a repair path that could not—and must not—delete the user's visual assets. Foundation scoring now reads the universe logline, premise, style, influences, and named canon only; visual prompt families remain intact and available for rendering, but edits to them no longer invalidate or distort a narrative verdict.
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsx
index b22c4e163a..a6aed15ab7 100644
--- a/client/src/components/cos/tabs/TaskItem.jsx
+++ b/client/src/components/cos/tabs/TaskItem.jsx
@@ -37,6 +37,16 @@ const statusIcons = {
challenged: <Scale size={16} aria-hidden="true" className="text-port-warning" />
};
+// Why an approval-required task is waiting on the user, keyed by the namespaced
+// `metadata.approvalReason` token its producer stamped. Today only the auto-filed
+// agent-failure investigations write one (server:
+// agentErrorAnalysis.resolveInvestigationApproval); other producers that hold a
+// task add their own entries here rather than a parallel field.
+const APPROVAL_REASON_HINTS = {
+ 'investigation-loop:repeat-fingerprint': 'Held for you: this same failure cause was investigated within the last 24 hours and came back.',
+ 'investigation-loop:failure-storm': 'Held for you: this hour is nearly out of investigation budget — failures are cascading, not isolated.'
+};
+
// Get success rate styling based on percentage
function getSuccessRateStyle(rate) {
if (rate >= 70) return { bg: 'bg-port-success/15', text: 'text-port-success', label: 'high' };
@@ -51,6 +61,10 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
const taskSource = isSystem ? 'internal' : 'user';
const idScope = isSystem ? 'sys' : 'user';
const requiresApproval = isSystem && task.approvalRequired;
+ // Name the hold's reason on the APPROVE button so "why is this one waiting on
+ // me?" is answerable without opening the body (#3714). Undefined for producers
+ // that stamp no reason, which leaves the button's plain label untouched.
+ const approvalHint = APPROVAL_REASON_HINTS[task.metadata?.approvalReason] || undefined;
const [editing, setEditingInternal] = useState(false);
const setEditing = useCallback((val) => {
setEditingInternal(val);
@@ -257,7 +271,8 @@ export default function TaskItem({ task, isSystem, onRefresh, providers, duratio
onClick={handleApprove}
disabled={approving}
className="px-2 py-0.5 rounded text-xs bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors disabled:opacity-50"
- aria-label={`Approve task ${task.id}`}
+ title={approvalHint}
+ aria-label={approvalHint ? `Approve task ${task.id} — ${approvalHint}` : `Approve task ${task.id}`}
>
{approving ? 'APPROVING…' : 'APPROVE'}
</button>
diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsx
index 0e327166bd..287b510355 100644
--- a/client/src/components/cos/tabs/TaskItem.test.jsx
+++ b/client/src/components/cos/tabs/TaskItem.test.jsx
@@ -252,3 +252,26 @@ describe('TaskItem challenge resolve controls (#2471)', () => {
expect(screen.queryByRole('button', { name: 'Escalate' })).not.toBeInTheDocument();
});
});
+
+describe('TaskItem investigation approval hint (#3714)', () => {
+ const held = {
+ ...task,
+ id: 'sys-inv-held',
+ description: '[Auto] Investigate agent failure [startup-failure:user:none]: Agent exited during startup',
+ approvalRequired: true,
+ metadata: { isInvestigation: true, approvalReason: 'investigation-loop:repeat-fingerprint' },
+ };
+
+ it('names the loop signal on the APPROVE button so the hold is explainable in place', () => {
+ render(<TaskItem task={held} isSystem onRefresh={vi.fn()} providers={providers} />);
+ const approve = screen.getByRole('button', { name: /^Approve task sys-inv-held — / });
+ expect(approve).toHaveAttribute('title', expect.stringContaining('last 24 hours'));
+ });
+
+ it('leaves the plain approve label on an approval-required task that is not a failure loop', () => {
+ const plain = { ...held, id: 'sys-approve-plain', metadata: {} };
+ render(<TaskItem task={plain} isSystem onRefresh={vi.fn()} providers={providers} />);
+ const approve = screen.getByRole('button', { name: 'Approve task sys-approve-plain' });
+ expect(approve).not.toHaveAttribute('title');
+ });
+});
diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.md
index 38aabf8db4..cca3d3c3bc 100644
--- a/docs/features/cos-enhancement.md
+++ b/docs/features/cos-enhancement.md
@@ -107,6 +107,7 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
1. **Mission Autonomy**: Full autonomy - COS can implement changes, run tests, commit without approval for managed apps
2. **Model Usage**: Local-first with LM Studio, no cloud API costs for thinking
3. **Self-Modification**: Full autonomy - COS can change its own base thinking model without user approval
+4. **Failure Investigation**: Unattended by default - an `[Auto] Investigate agent failure` task runs without approval, because an isolated agent failure is exactly the work CoS exists to diagnose for itself. Approval is reserved for a failure *loop*, where another unattended agent would only repeat what already didn't work: the same cause investigated again within 24h (`repeat-fingerprint`), or the circuit-breaker hour already one slot from its cap (`failure-storm`). The reason is stamped on the task as the producer-agnostic `metadata.approvalReason` (`investigation-loop:<signal>`), which the Tasks UI turns into a hint on the APPROVE button. See `resolveInvestigationApproval` in `server/services/agentErrorAnalysis.js`.
## Test Coverage
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index d48225d6a5..1627808d61 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -888,9 +888,16 @@ export const INVESTIGATION_CIRCUIT_WINDOW_MS = 60 * 60 * 1000; // 1 hour
export const INVESTIGATION_CIRCUIT_MAX_CREATIONS = 3;
let investigationCreationStamps = []; // ms timestamps, newest-last
-function investigationCircuitOpen(now) {
+/**
+ * How many investigation creations are still inside the rolling circuit window.
+ * Prunes aged-out stamps as a side effect, so the circuit auto-closes without a
+ * manual reset. The count (not just a boolean "open?") is what the caller needs:
+ * at the cap it suppresses the task entirely, and below the cap a non-zero count
+ * is the `failure-storm` loop signal that holds the task for a human.
+ */
+function recentInvestigationCreations(now) {
investigationCreationStamps = investigationCreationStamps.filter(t => now - t < INVESTIGATION_CIRCUIT_WINDOW_MS);
- return investigationCreationStamps.length >= INVESTIGATION_CIRCUIT_MAX_CREATIONS;
+ return investigationCreationStamps.length;
}
// Test hook — the stamp list is module state, so suites reset it between cases.
@@ -931,17 +938,116 @@ export function isInvestigationTask(task) {
&& task.description.trimStart().startsWith(INVESTIGATION_HEADLINE_PREFIX);
}
-// Find an existing investigation task (user or internal queue) still tracking
-// this fingerprint in a non-terminal status.
-async function findOpenInvestigation(fingerprint) {
+// Every task across both queues, flattened. One read serves both the
+// fingerprint dedup scan and the failure-loop detection below.
+async function readAllTasksFlat() {
const { user, cos } = await getAllTasks();
- const tasks = [...(user?.tasks || []), ...(cos?.tasks || [])];
+ return [...(user?.tasks || []), ...(cos?.tasks || [])];
+}
+
+// Find an existing investigation task (user or internal queue) still tracking
+// this fingerprint in a non-terminal status. Pure.
+function findOpenInvestigationIn(tasks, fingerprint) {
return tasks.find(t =>
OPEN_INVESTIGATION_STATUSES.has(t.status) &&
t.metadata?.investigationFingerprint === fingerprint
) || null;
}
+// ===== Failure-loop detection / approval policy (#3714) =====
+
+// How recently a PRIOR investigation of the same cause must have finished for a
+// fresh failure to count as a LOOP rather than an unrelated recurrence. The
+// same fingerprint tripping again months later is new work (fingerprints are
+// coarse — `category:kind:app`, deliberately not keyed on the message); the same
+// fingerprint tripping again the day after we investigated it means the last
+// investigation did not hold, and burning another unattended agent on it just
+// spins. Wider than the circuit window on purpose: the circuit measures a storm
+// in progress, this measures "we already tried and it came back".
+export const INVESTIGATION_LOOP_WINDOW_MS = 24 * 60 * 60 * 1000; // 24 hours
+
+// How many investigations already filed inside the circuit window make the NEXT
+// one a storm rather than ordinary traffic. Derived from the circuit cap, not a
+// magic number: the last slot before the circuit stops filing tasks at all is
+// the one worth a human. A couple of unrelated agent failures in an hour is
+// normal on a busy install and must stay unattended — otherwise this gate
+// re-creates the stall it exists to remove.
+// The `max(1, …)` floor keeps a hypothetical cap of 1 from making the threshold
+// 0, which would hold EVERY investigation — the exact inversion of this policy.
+export const INVESTIGATION_STORM_HOLD_THRESHOLD = Math.max(1, INVESTIGATION_CIRCUIT_MAX_CREATIONS - 1);
+
+/**
+ * Did a genuine investigation of this fingerprint already finish inside the loop
+ * window? `auto-expired` completions don't count — the reaper flips those to
+ * `completed` because their origin tasks went away (cosTaskStore's
+ * `sweepResolvedFailureTasks`), so nothing was ever actually attempted and
+ * holding the next one for a human would punish a cleanup, not a loop. Pure.
+ */
+function priorInvestigationSettledRecently(tasks, fingerprint, now) {
+ return tasks.some((t) => {
+ if (t.status !== 'completed') return false;
+ if (t.metadata?.investigationFingerprint !== fingerprint) return false;
+ if (t.metadata?.resolution === 'auto-expired') return false;
+ const settledAt = Date.parse(t.metadata?.updatedAt);
+ // An undated completion can't be proved recent — treat it as old, so the
+ // default stays "auto-approve" rather than silently gating on a legacy task.
+ if (!Number.isFinite(settledAt)) return false;
+ return now - settledAt < INVESTIGATION_LOOP_WINDOW_MS;
+ });
+}
+
+/**
+ * Approval policy for a new investigation task.
+ *
+ * An agent failure is ordinary, expected traffic: the whole point of an
+ * investigation task is that CoS diagnoses its own failures without a human in
+ * the loop, so the DEFAULT is auto-approved and unattended. Human approval is
+ * reserved for a failure LOOP — the two shapes where letting another agent run
+ * unattended would just repeat what already didn't work:
+ *
+ * - `repeat-fingerprint` — we investigated this exact cause within the last
+ * {@link INVESTIGATION_LOOP_WINDOW_MS} and it is back.
+ * - `failure-storm` — the circuit window is already at
+ * {@link INVESTIGATION_STORM_HOLD_THRESHOLD} investigations, i.e. failures
+ * are cascading rather than isolated. (One slot later the circuit stops
+ * filing tasks at all; this is the last one before that ceiling.)
+ *
+ * Pure — every input is injected so the branching is unit-testable.
+ *
+ * @param {{ fingerprint: string, tasks: object[], recentCreations?: number, now?: number }} args
+ * @returns {{ approvalRequired: boolean, loopReason: 'repeat-fingerprint'|'failure-storm'|null }}
+ */
+export function resolveInvestigationApproval({
+ fingerprint,
+ tasks = [],
+ recentCreations = 0,
+ now = Date.now()
+} = {}) {
+ if (priorInvestigationSettledRecently(tasks, fingerprint, now)) {
+ return { approvalRequired: true, loopReason: 'repeat-fingerprint' };
+ }
+ if (recentCreations >= INVESTIGATION_STORM_HOLD_THRESHOLD) {
+ return { approvalRequired: true, loopReason: 'failure-storm' };
+ }
+ return { approvalRequired: false, loopReason: null };
+}
+
+// Namespace for the loop reason when it is stamped as the task's generic
+// `metadata.approvalReason` — the shared "why is this waiting on me?" key that
+// any approval-required producer can write (cosTaskGenerator already computes
+// the same concept for its safety-kind / confidence holds). Prefixing keeps this
+// producer's vocabulary from colliding with theirs in one flat namespace.
+const INVESTIGATION_APPROVAL_REASON_PREFIX = 'investigation-loop:';
+
+// Human-facing prose for each loop reason, rendered into the task body so the
+// user reading the queue knows WHY this one stopped for them when the previous
+// investigation did not. Counts are interpolated from the constants above so the
+// prose can't drift from the thresholds it describes.
+const LOOP_REASON_PROSE = {
+ 'repeat-fingerprint': `This exact failure cause was already investigated within the last ${INVESTIGATION_LOOP_WINDOW_MS / (60 * 60 * 1000)} hours and it has come back — the previous fix did not hold, so this one is held for you instead of spawning another unattended agent that would repeat it.`,
+ 'failure-storm': `${INVESTIGATION_STORM_HOLD_THRESHOLD} other agent failure(s) were already filed for investigation this hour, one slot short of the circuit breaker suppressing them entirely — failures are cascading rather than isolated, so this one is held for you rather than spending another unattended agent on a symptom.`
+};
+
/**
* Create an investigation task in COS-TASKS.md for a failed agent.
*
@@ -972,7 +1078,8 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {
// Durable-fingerprint dedup: one open investigation per failure cause.
const fingerprint = buildInvestigationFingerprint(originalTask, analysis);
- const existing = await findOpenInvestigation(fingerprint);
+ const allTasks = await readAllTasksFlat();
+ const existing = findOpenInvestigationIn(allTasks, fingerprint);
if (existing) {
emitLog('info', `⏭️ Skipping duplicate investigation for ${fingerprint}: ${existing.id} is still ${existing.status}`, {
agentId, taskId: originalTask.id, fingerprint, existingTaskId: existing.id, existingStatus: existing.status
@@ -993,13 +1100,20 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {
// Rolling circuit breaker: cap creations per window across all fingerprints.
const now = Date.now();
- if (investigationCircuitOpen(now)) {
+ const recentCreations = recentInvestigationCreations(now);
+ if (recentCreations >= INVESTIGATION_CIRCUIT_MAX_CREATIONS) {
emitLog('warn', `🔌 Investigation circuit OPEN — ${INVESTIGATION_CIRCUIT_MAX_CREATIONS} investigations created within the last hour; suppressing task for ${fingerprint}`, {
agentId, taskId: originalTask.id, fingerprint
});
return null;
}
+ // Auto-approved unless this failure is a LOOP (#3714) — an isolated agent
+ // failure is exactly the work CoS is meant to diagnose for itself.
+ const { approvalRequired, loopReason } = resolveInvestigationApproval({
+ fingerprint, tasks: allTasks, recentCreations, now
+ });
+
// 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. `message`
@@ -1011,10 +1125,23 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {
// 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
+ const remedy = analysis.escalation
|| analysis.suggestedFix
|| 'Review the agent output, decide whether to fix the underlying config/code and retry, or close the task.';
+ // The body addresses whoever will actually act on this task: an unattended
+ // investigation agent in the default (auto-approved) case, the single PortOS
+ // user in the held case. Same remedy prose either way — only the framing, the
+ // held-reason section, and the "what unblocks" consequence differ.
+ const actionBlock = approvalRequired
+ ? [
+ `## What to approve\n${remedy}`,
+ `## Why this is held for you\n${LOOP_REASON_PROSE[loopReason]}`
+ ].join('\n\n')
+ : `## What to do\nNo approval needed — this investigation runs unattended. Diagnose the failure above, apply the fix, and leave the task's findings in your summary.\n\n${remedy}`;
+
+ const unblocks = `${approvalRequired ? 'Approving and applying' : 'Applying'} the fix lets the original task \`${originalTask.id}\` be retried; it will resume: ${originalDesc}.`;
+
// The fingerprint rides in the headline so addTask's first-line dedup —
// which sees no `metadata.app` on investigation tasks — tracks fingerprint
// identity exactly: identical messages from different apps OR different
@@ -1030,19 +1157,21 @@ Agent \`${agentId}\` failed while working on task \`${originalTask.id}\` (${orig
- **Provider/model**: ${modelAttribution || 'not attributed'}
${snippet ? `- **Failure snippet (redacted)**:\n > ${snippet}` : '- **Failure snippet**: (none captured)'}
-## What to approve
-${whatToApprove}
+${actionBlock}
## What unblocks
-Approving and applying the fix lets the original task \`${originalTask.id}\` be retried; it will resume: ${originalDesc}.`;
+${unblocks}`;
const investigationTask = await addTask({
description,
priority: 'HIGH',
context: `Auto-generated from agent ${agentId} failure`,
- approvalRequired: true, // Require human approval before auto-fixing
+ approvalRequired,
isInvestigation: true, // Meta-cascade guard marker (#2615)
investigationFingerprint: fingerprint,
+ // Durable record of WHY this stopped for a human (null when it ran
+ // unattended) — readable from the queue without re-deriving the verdict.
+ approvalReason: loopReason && `${INVESTIGATION_APPROVAL_REASON_PREFIX}${loopReason}`,
affectedTasks: [originalTask.id] // later same-fingerprint failures union in
}, 'internal');
@@ -1050,17 +1179,21 @@ Approving and applying the fix lets the original task \`${originalTask.id}\` be
// description-level dedup returning an existing task is not a new creation.
if (!investigationTask.duplicate) investigationCreationStamps.push(now);
- emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId}`, {
+ emitLog('info', `Created investigation task ${investigationTask.id} for failed agent ${agentId} — ${loopReason ? `held for approval (${loopReason})` : 'auto-approved'}`, {
agentId,
taskId: investigationTask.id,
- errorCategory: category
+ errorCategory: category,
+ approvalRequired,
+ loopReason
});
cosEvents.emit('investigation:created', {
investigationTaskId: investigationTask.id,
failedAgentId: agentId,
originalTaskId: originalTask.id,
- errorAnalysis
+ errorAnalysis,
+ approvalRequired,
+ loopReason
});
return investigationTask;
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index b4a4eed75b..150dd9e567 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -21,6 +21,9 @@ import {
MAX_TASK_RETRIES,
INVESTIGATION_CIRCUIT_WINDOW_MS,
INVESTIGATION_CIRCUIT_MAX_CREATIONS,
+ INVESTIGATION_LOOP_WINDOW_MS,
+ INVESTIGATION_STORM_HOLD_THRESHOLD,
+ resolveInvestigationApproval,
__resetInvestigationCircuit
} from './agentErrorAnalysis.js';
import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';
@@ -503,11 +506,12 @@ describe('createInvestigationTask guards (#2615)', () => {
await createInvestigationTask('agent-1', failedTask, analysis);
expect(addTask).toHaveBeenCalledWith(expect.objectContaining({
priority: 'HIGH',
- approvalRequired: true,
+ approvalRequired: false, // isolated failure — runs unattended (#3714)
isInvestigation: true,
investigationFingerprint: 'startup-failure:user:none',
affectedTasks: ['task-1']
}), 'internal');
+ expect(addTask.mock.calls[0][0].approvalReason).toBeFalsy();
});
it('unions a later same-fingerprint failure into the surviving investigation\'s affectedTasks and body', async () => {
@@ -639,6 +643,135 @@ describe('createInvestigationTask guards (#2615)', () => {
});
});
+describe('resolveInvestigationApproval (failure-loop policy, #3714)', () => {
+ const FP = 'startup-failure:user:none';
+ const NOW = Date.parse('2026-08-10T12:00:00.000Z');
+ const settled = (offsetMs, overrides = {}) => ({
+ id: 'inv-old',
+ status: 'completed',
+ metadata: {
+ investigationFingerprint: FP,
+ updatedAt: new Date(NOW - offsetMs).toISOString(),
+ ...overrides
+ }
+ });
+
+ it('auto-approves an isolated failure — the default, so CoS diagnoses itself unattended', () => {
+ expect(resolveInvestigationApproval({ fingerprint: FP, tasks: [], now: NOW }))
+ .toEqual({ approvalRequired: false, loopReason: null });
+ });
+
+ it('holds for a human when the same cause was already investigated inside the loop window', () => {
+ const tasks = [settled(INVESTIGATION_LOOP_WINDOW_MS - 1000)];
+ expect(resolveInvestigationApproval({ fingerprint: FP, tasks, now: NOW }))
+ .toEqual({ approvalRequired: true, loopReason: 'repeat-fingerprint' });
+ });
+
+ it('auto-approves again once the prior investigation ages out of the loop window', () => {
+ const tasks = [settled(INVESTIGATION_LOOP_WINDOW_MS + 1000)];
+ expect(resolveInvestigationApproval({ fingerprint: FP, tasks, now: NOW }).approvalRequired).toBe(false);
+ });
+
+ it('ignores an auto-expired prior — the reaper completed it, nothing was ever attempted', () => {
+ const tasks = [settled(1000, { resolution: 'auto-expired' })];
+ expect(resolveInvestigationApproval({ fingerprint: FP, tasks, now: NOW }).approvalRequired).toBe(false);
+ });
+
+ it('ignores an undated prior completion rather than gating on an unprovable timestamp', () => {
+ const tasks = [{ id: 'inv-legacy', status: 'completed', metadata: { investigationFingerprint: FP } }];
+ expect(resolveInvestigationApproval({ fingerprint: FP, tasks, now: NOW }).approvalRequired).toBe(false);
+ });
+
+ it('ignores a recent completion for a DIFFERENT fingerprint', () => {
+ const tasks = [settled(1000, { investigationFingerprint: 'network-error:user:none' })];
+ expect(resolveInvestigationApproval({ fingerprint: FP, tasks, now: NOW }).approvalRequired).toBe(false);
+ });
+
+ it('holds for a human once the circuit window is at the storm threshold', () => {
+ expect(resolveInvestigationApproval({
+ fingerprint: FP, tasks: [], recentCreations: INVESTIGATION_STORM_HOLD_THRESHOLD, now: NOW
+ })).toEqual({ approvalRequired: true, loopReason: 'failure-storm' });
+ });
+
+ it('leaves ordinary traffic below the storm threshold unattended', () => {
+ expect(resolveInvestigationApproval({
+ fingerprint: FP, tasks: [], recentCreations: INVESTIGATION_STORM_HOLD_THRESHOLD - 1, now: NOW
+ }).approvalRequired).toBe(false);
+ });
+
+ it('keeps the storm threshold below the circuit cap so the held slot is reachable', () => {
+ // At the cap no task is filed at all, so a threshold >= cap would mean the
+ // failure-storm hold could never actually happen.
+ expect(INVESTIGATION_STORM_HOLD_THRESHOLD).toBeGreaterThan(0);
+ expect(INVESTIGATION_STORM_HOLD_THRESHOLD).toBeLessThan(INVESTIGATION_CIRCUIT_MAX_CREATIONS);
+ });
+
+ it('prefers the repeat-fingerprint reason over failure-storm when both fire', () => {
+ const tasks = [settled(1000)];
+ expect(resolveInvestigationApproval({
+ fingerprint: FP, tasks, recentCreations: INVESTIGATION_STORM_HOLD_THRESHOLD, now: NOW
+ }).loopReason).toBe('repeat-fingerprint');
+ });
+});
+
+describe('createInvestigationTask approval wiring (#3714)', () => {
+ const failedTask = { id: 'task-1', description: 'do the thing', taskType: 'user', metadata: {} };
+ const analysis = { category: 'startup-failure', message: 'Agent exited during startup' };
+
+ beforeEach(() => {
+ addTask.mockReset();
+ addTask.mockResolvedValue({ id: 'investigation-1' });
+ updateTask.mockReset();
+ updateTask.mockResolvedValue({});
+ mockEmptyStore();
+ __resetInvestigationCircuit();
+ });
+
+ it('runs unattended up to the storm threshold, then holds and records the loop reason', async () => {
+ // Distinct categories so each call mints its own fingerprint and reaches
+ // the circuit rather than deduping into the previous investigation.
+ for (let i = 0; i < INVESTIGATION_STORM_HOLD_THRESHOLD; i++) {
+ await createInvestigationTask(`agent-${i}`, { ...failedTask, id: `task-${i}` }, { category: `cat-${i}`, message: 'x' });
+ expect(addTask.mock.calls[i][0].approvalRequired).toBe(false);
+ }
+
+ await createInvestigationTask('agent-storm', { ...failedTask, id: 'task-storm' }, { category: 'network-error', message: 'x' });
+ const held = addTask.mock.calls[INVESTIGATION_STORM_HOLD_THRESHOLD][0];
+ expect(held.approvalRequired).toBe(true);
+ expect(held.approvalReason).toBe('investigation-loop:failure-storm');
+ expect(held.description).toContain('## What to approve');
+ expect(held.description).toContain('## Why this is held for you');
+ expect(held.description).toContain('cascading');
+ });
+
+ it('holds a repeat of a cause investigated within the loop window', async () => {
+ const done = {
+ id: 'inv-done',
+ status: 'completed',
+ metadata: {
+ investigationFingerprint: 'startup-failure:user:none',
+ updatedAt: new Date(Date.now() - 60_000).toISOString()
+ }
+ };
+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [done] } });
+
+ await createInvestigationTask('agent-1', failedTask, analysis);
+ const created = addTask.mock.calls[0][0];
+ expect(created.approvalRequired).toBe(true);
+ expect(created.approvalReason).toBe('investigation-loop:repeat-fingerprint');
+ expect(created.description).toContain('## Why this is held for you');
+ // The held body asks the USER to approve; the unattended one never does.
+ expect(created.description).toContain('Approving and applying the fix');
+ });
+
+ it('marks an auto-approved investigation as unattended in its own body', async () => {
+ await createInvestigationTask('agent-1', failedTask, analysis);
+ const body = addTask.mock.calls[0][0].description;
+ expect(body).toContain('No approval needed');
+ expect(body).not.toContain('Approving and applying the fix');
+ });
+});
+
describe('redactFailureSnippet', () => {
it('strips OS usernames, emails, IPs, hostnames, and secrets, collapsing to one line', () => {
const raw = [
@@ -926,7 +1059,7 @@ describe('createInvestigationTask body', () => {
const bodyOf = () => addTask.mock.calls[0][0].description;
- it('renders the What happened / What to approve / What unblocks template with category-specific prose', async () => {
+ it('renders the What happened / What to do / 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',
@@ -936,7 +1069,10 @@ describe('createInvestigationTask body', () => {
});
const body = bodyOf();
expect(body).toContain('## What happened');
- expect(body).toContain('## What to approve');
+ // Isolated failure → unattended, so the action section addresses the agent.
+ expect(body).toContain('## What to do');
+ expect(body).not.toContain('## What to approve');
+ expect(body).not.toContain('## Why this is held for you');
expect(body).toContain('## What unblocks');
expect(body).toContain('model-not-found');
expect(body).toContain('claude-4-ultra'); // provider/model attribution
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 7c4cb29b18..69d80385e1 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -332,6 +332,11 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
// affectedTasks names every task blocked on the cause (later dedup hits union in).
if (taskData.isInvestigation === true) metadata.isInvestigation = true;
if (taskData.investigationFingerprint) metadata.investigationFingerprint = taskData.investigationFingerprint;
+ // Why an approval-required task is waiting on the user, as a namespaced token
+ // (e.g. `investigation-loop:repeat-fingerprint`). Producer-agnostic on purpose
+ // — any producer that holds a task can write it and the UI explains the hold
+ // without a per-producer key. Absent on auto-approved tasks.
+ if (taskData.approvalReason) metadata.approvalReason = taskData.approvalReason;
if (Array.isArray(taskData.affectedTasks) && taskData.affectedTasks.length > 0) metadata.affectedTasks = taskData.affectedTasks;
if (taskData.createJiraTicket) metadata.createJiraTicket = true;
// Boolean flags: persist both true and false so users can explicitly override defaults.