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

fix: give UI-queued investigations the same identity as auto-filed ones (#6043)

Adam Eivyf691cf948f8f
diff --git a/client/src/components/install/QueueInstallInvestigationButton.jsx b/client/src/components/install/QueueInstallInvestigationButton.jsx
index 8450707cc9..d18b572b1e 100644
--- a/client/src/components/install/QueueInstallInvestigationButton.jsx
+++ b/client/src/components/install/QueueInstallInvestigationButton.jsx
@@ -19,13 +19,13 @@ import { buildInstallFailureTask } from '../../lib/installFailureTask';
import { addCosTask } from '../../services/api';
import toast from '../ui/Toast';
-// Unattended repair work, same posture as `INVESTIGATION_TASK_DELIVERY`
-// (`server/lib/investigationTasks.js`): keep it out of the user's checkout and
-// send it through the PR gate. It deliberately stops short of that constant's
-// `prCompletion: merge-on-green`, and carries no `isInvestigation` marker —
-// `createCosTaskSchema` has no such field, so a client-queued task sits outside
-// the investigation dedup/circuit-breaker machinery. Tracked in #6043.
-const INSTALL_INVESTIGATION_DELIVERY = { useWorktree: true, openPR: true };
+// The task's identity as an investigation (#6043) is the only posture flag sent:
+// the server recognizes `isInvestigation`, derives the dedup fingerprint itself,
+// and applies `CLIENT_INVESTIGATION_DELIVERY` (`server/lib/investigationTasks.js`)
+// — worktree-isolated, PR-gated, reviewed rather than merged on green because a
+// human asked for this one. Keeping the delivery server-side is what stops this
+// button from drifting out of step with the auto-filed posture again.
+const INSTALL_INVESTIGATION_MARKER = { isInvestigation: true };
export default function QueueInstallInvestigationButton({
label,
@@ -47,7 +47,7 @@ export default function QueueInstallInvestigationButton({
// The description is deterministic per installer + stage, so retrying the
// same failing install and clicking again hits the store's duplicate guard
// (409 DUPLICATE_TASK). A task already exists — not a failure to report.
- const duplicateMessage = await addCosTask({ ...task, ...INSTALL_INVESTIGATION_DELIVERY }, { silent: true })
+ const duplicateMessage = await addCosTask({ ...task, ...INSTALL_INVESTIGATION_MARKER }, { silent: true })
.then(() => null)
.catch((err) => {
// The server names the existing task's status ("already pending" /
diff --git a/client/src/components/install/RuntimeInstallModal.test.jsx b/client/src/components/install/RuntimeInstallModal.test.jsx
index bafab6bd5c..a888fa7606 100644
--- a/client/src/components/install/RuntimeInstallModal.test.jsx
+++ b/client/src/components/install/RuntimeInstallModal.test.jsx
@@ -67,7 +67,13 @@ describe('RuntimeInstallModal failure footer', () => {
expect(task.prompt).toContain('fatal: could not build');
// No `app` — the installer code lives in PortOS, which is the server default.
expect(task.app).toBeUndefined();
- expect(task).toMatchObject({ useWorktree: true, openPR: true });
+ // The investigation marker (#6043) is the ONLY posture the client sends: the
+ // server recognizes it, derives the dedup fingerprint, and applies the
+ // worktree/PR delivery, so this button can no longer drift out of step with
+ // the auto-filed investigation posture.
+ expect(task).toMatchObject({ isInvestigation: true });
+ expect(task).not.toHaveProperty('useWorktree');
+ expect(task).not.toHaveProperty('openPR');
// useAsyncAction owns the failure toast, so the request must not toast too.
expect(options).toMatchObject({ silent: true });
diff --git a/server/lib/README.md b/server/lib/README.md
index 4067bf89e8..1360bab309 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -396,7 +396,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |
| `learningVerdict.js` | The three-way success-criteria verdict a completed agent run carries on `result.validationPassed` (#4107). `true`/`false` = a declared criterion was met/missed; `null` = none declared (record the run, fall back to the exit code); `SKIP_LEARNING_VERDICT` = nothing ever evaluated the run, so task-learning must not record it at all (a programmatic-I/O output hook that bailed on `no-app`/`app-not-found`). `isSkipLearningVerdict(v)` gates the skip; `toValidationVerdict(v)` narrows anything non-boolean — including the sentinel — back to `null` for downstream telemetry. JSON-safe string (not a Symbol) because the verdict is persisted and read back by the learning backfill, and older readers already narrow on `typeof v === 'boolean'`. Pure. |
-| `investigationTasks.js` | Investigation-task identity, approval, auto-retry, and PR-backed delivery policy — shared by the producers (`services/investigationTaskProducer.js`), the reaper (`cosTaskStore.js`, which used to hand-copy the predicate to dodge an import cycle) and the retry (`services/investigationRetry.js`). `isInvestigationTask(task)` (durable `isInvestigation` marker, falling back to the `INVESTIGATION_HEADLINE_PREFIX` headline for pre-#2615 / peer-synced tasks); `INVESTIGATION_TASK_DELIVERY` keeps unattended investigations in an isolated worktree and routes them through a PR merged on green; `buildInvestigationFingerprint(task, analysis)` / `investigationFingerprint({category, kind, scope})` → the `category:kind:scope` dedup key; `resolveInvestigationApproval({fingerprint, tasks, recentCreations})` → unattended by default (#3714), held only on a `repeat-fingerprint` or `failure-storm` loop, with `approvalReason` + `loopProse` for the queue UI; `couldReleaseBlockedTasks(investigation)` is the pure pre-read gate for `resolveInvestigationRetryTargets({investigation, tasksById})`, which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its `RETRY_SKIP_REASONS` reason (an `auto-expired` completion, a non-`blocked` task, a `NON_AUTO_RETRY_BLOCK_CATEGORIES` block, or a task past `MAX_AUTO_RETRIES_PER_TASK`); `autoRetryMetadata(task, investigationId, now)` stamps the budget that survives the revive's own `failureCount` reset. Pure. |
+| `investigationTasks.js` | Investigation-task identity, approval, auto-retry, and PR-backed delivery policy — shared by the producers (`services/investigationTaskProducer.js`), the reaper (`cosTaskStore.js`, which used to hand-copy the predicate to dodge an import cycle) and the retry (`services/investigationRetry.js`). `isInvestigationTask(task)` (durable `isInvestigation` marker, falling back to the `INVESTIGATION_HEADLINE_PREFIX` headline for pre-#2615 / peer-synced tasks); `INVESTIGATION_TASK_DELIVERY` keeps unattended investigations in an isolated worktree and routes them through a PR merged on green, while `CLIENT_INVESTIGATION_DELIVERY` + `clientInvestigationFingerprint({description, app})` give a UI-queued investigation (#6043) the same isolation with a review-then-merge PR and a server-derived `ui-investigation` dedup key the client cannot hand-craft; `buildInvestigationFingerprint(task, analysis)` / `investigationFingerprint({category, kind, scope})` → the `category:kind:scope` dedup key; `resolveInvestigationApproval({fingerprint, tasks, recentCreations})` → unattended by default (#3714), held only on a `repeat-fingerprint` or `failure-storm` loop, with `approvalReason` + `loopProse` for the queue UI; `couldReleaseBlockedTasks(investigation)` is the pure pre-read gate for `resolveInvestigationRetryTargets({investigation, tasksById})`, which returns the failure-blocked tasks a just-completed investigation releases plus every skip and its `RETRY_SKIP_REASONS` reason (an `auto-expired` completion, a non-`blocked` task, a `NON_AUTO_RETRY_BLOCK_CATEGORIES` block, or a task past `MAX_AUTO_RETRIES_PER_TASK`); `autoRetryMetadata(task, investigationId, now)` stamps the budget that survives the revive's own `failureCount` reset. Pure. |
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
| `assetProvenance.js` | Stamp-time model/LoRA license provenance (`buildProvenance` / `provenanceForRender` / `rollupProvenance`). Unknown stays `null` (displayed as "unknown") — never a permissive default. Mirrored byte-for-byte to `client/src/lib/assetProvenance.js`. |
| `avatarVariants.js` | Rigged-record avatar variant spelling (`RIGGED_VARIANT_PREFIX`, `AVATAR_VARIANT_PATTERN`, `parseRiggedVariant`, `riggedVariantForId`, `isAnimatedRecordReady`) — the `rigged-<modelId>` namespace over `?variant=`, sharing the route's strict traversal guard. |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 0cc674ae19..57bfb49354 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -178,6 +178,18 @@ export const createCosTaskSchema = z.object({
v => v === 'true' ? true : v === 'false' ? false : v,
z.boolean().optional()
),
+ // Marks a task the user queued as an INVESTIGATION (#6043) — today the
+ // installer-failure "Queue agent to investigate" button. The flag is all a
+ // client may supply: the route derives the dedup fingerprint server-side
+ // (`clientInvestigationFingerprint`) and applies `CLIENT_INVESTIGATION_DELIVERY`,
+ // so a client can neither hand-craft a key that collides with an auto-filed
+ // investigation nor pick its own delivery posture. Without this field Zod
+ // stripped the flag, leaving UI-queued repairs outside the investigation
+ // dedup, the circuit breaker, and the meta-cascade guard.
+ isInvestigation: z.preprocess(
+ v => v === 'true' ? true : v === 'false' ? false : v,
+ z.boolean().optional()
+ ),
whenDone: z.enum(['commit-push', 'leave-uncommitted']).optional(),
// Read-only planning mode: investigate the codebase and file the issue, but
// do not start implementation delivery. The task store expands this into
diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.js
index 693ad67328..abb9f5d904 100644
--- a/server/lib/cosValidation.test.js
+++ b/server/lib/cosValidation.test.js
@@ -254,3 +254,29 @@ describe('reviewerConfig transitional re-export shim (#5702)', () => {
}
});
});
+
+describe('createCosTaskSchema isInvestigation (#6043)', () => {
+ it('survives validation instead of being stripped, in both the boolean and form-string shapes', () => {
+ expect(createCosTaskSchema.parse({ description: 'x', isInvestigation: true }).isInvestigation).toBe(true);
+ expect(createCosTaskSchema.parse({ description: 'x', isInvestigation: 'true' }).isInvestigation).toBe(true);
+ expect(createCosTaskSchema.parse({ description: 'x', isInvestigation: false }).isInvestigation).toBe(false);
+ expect(createCosTaskSchema.parse({ description: 'x', isInvestigation: 'false' }).isInvestigation).toBe(false);
+ });
+
+ it('is absent by default, so an ordinary task stays outside the investigation machinery', () => {
+ expect(createCosTaskSchema.parse({ description: 'x' }).isInvestigation).toBeUndefined();
+ });
+
+ it('rejects a non-boolean rather than coercing a truthy string into the marker', () => {
+ expect(createCosTaskSchema.safeParse({ description: 'x', isInvestigation: 'yes' }).success).toBe(false);
+ });
+
+ it('never accepts a client-supplied fingerprint — the server derives it', () => {
+ const parsed = createCosTaskSchema.parse({
+ description: 'x',
+ isInvestigation: true,
+ investigationFingerprint: 'auth-error:provider-failure:Example CLI',
+ });
+ expect(parsed).not.toHaveProperty('investigationFingerprint');
+ });
+});
diff --git a/server/lib/investigationTasks.js b/server/lib/investigationTasks.js
index 241f7ac0df..f5bda215ca 100644
--- a/server/lib/investigationTasks.js
+++ b/server/lib/investigationTasks.js
@@ -32,6 +32,58 @@ export const INVESTIGATION_TASK_DELIVERY = Object.freeze({
prCompletion: PR_COMPLETIONS.MERGE_ON_GREEN,
});
+// Delivery for an investigation a USER queued from the UI (#6043) — the
+// installer-failure "Queue agent to investigate" button today. Same isolation as
+// the unattended posture above, but the PR waits for a review instead of merging
+// on green: `merge-on-green` exists because an auto-filed investigation has
+// nobody watching it, and that reason is gone the moment a human clicked the
+// button. They are here to look at the fix, so let them.
+export const CLIENT_INVESTIGATION_DELIVERY = Object.freeze({
+ useWorktree: true,
+ openPR: true,
+ prCompletion: PR_COMPLETIONS.REVIEW_THEN_MERGE,
+});
+
+// `kind` segment reserved for client-queued investigations. Auto-filed keys take
+// their kind from an analysis/self-improvement/task type, so this value keeps the
+// two populations in separate fingerprint namespaces: a client can neither
+// collide with an auto-filed investigation's dedup key nor evict it.
+export const CLIENT_INVESTIGATION_KIND = 'ui-investigation';
+
+// Longest subject slug folded into a client fingerprint. The key is stored on
+// every matching task and compared on every dedup scan, so it stays short enough
+// to read in a log line while keeping distinct install failures distinct.
+const CLIENT_INVESTIGATION_SUBJECT_MAX = 80;
+
+/** Lowercase `a-z0-9-` slug of a free-text subject, bounded. Pure. */
+function investigationSubjectSlug(text) {
+ return String(text ?? '')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, CLIENT_INVESTIGATION_SUBJECT_MAX)
+ .replace(/-+$/, '');
+}
+
+/**
+ * The dedup key for an investigation queued from the UI, derived ENTIRELY from
+ * what the client submitted — never from a client-supplied fingerprint. Two
+ * clicks on the same failing installer produce the same key (so the queued task
+ * participates in dedup and the loop policy), while a different failure produces
+ * a different one. Pure.
+ *
+ * `app` narrows the key the way an auto-filed key's `scope` segment does; absent
+ * — the install button's case — means PortOS itself.
+ */
+export function clientInvestigationFingerprint({ description, app } = {}) {
+ const subject = investigationSubjectSlug(description);
+ const appSlug = investigationSubjectSlug(app);
+ return investigationFingerprint({
+ kind: CLIENT_INVESTIGATION_KIND,
+ scope: appSlug ? `${appSlug}/${subject}` : subject,
+ });
+}
+
// Task metadata survives a markdown round-trip, so booleans come back as the
// strings 'true'/'false'. Local to keep this module import-free of the services
// layer, where the generic `isTruthyMeta` lives.
diff --git a/server/lib/investigationTasks.test.js b/server/lib/investigationTasks.test.js
index 031df5916c..deb7c73cdb 100644
--- a/server/lib/investigationTasks.test.js
+++ b/server/lib/investigationTasks.test.js
@@ -1,6 +1,10 @@
import { describe, it, expect } from 'vitest';
import {
+ CLIENT_INVESTIGATION_DELIVERY,
+ CLIENT_INVESTIGATION_KIND,
INVESTIGATION_HEADLINE_PREFIX,
+ INVESTIGATION_TASK_DELIVERY,
+ clientInvestigationFingerprint,
MAX_AUTO_RETRIES_PER_TASK,
RETRY_SKIP_REASONS,
autoRetryCount,
@@ -195,3 +199,51 @@ describe('autoRetryCount / autoRetryMetadata', () => {
});
});
});
+
+describe('clientInvestigationFingerprint (#6043)', () => {
+ const INSTALL_FAILURE = 'Fix Example Runtime installer failure at the download stage';
+
+ it('is deterministic for the same submitted failure — that is what makes dedup work', () => {
+ expect(clientInvestigationFingerprint({ description: INSTALL_FAILURE }))
+ .toBe(clientInvestigationFingerprint({ description: INSTALL_FAILURE }));
+ });
+
+ it('separates two different install failures', () => {
+ expect(clientInvestigationFingerprint({ description: INSTALL_FAILURE }))
+ .not.toBe(clientInvestigationFingerprint({ description: 'Fix Example Runtime installer failure at the verify stage' }));
+ });
+
+ it('scopes by app the way an auto-filed key does', () => {
+ expect(clientInvestigationFingerprint({ description: INSTALL_FAILURE, app: 'Example App' }))
+ .not.toBe(clientInvestigationFingerprint({ description: INSTALL_FAILURE }));
+ });
+
+ it('keeps the client namespace out of reach of an auto-filed key', () => {
+ // Auto-filed keys take their `kind` from an analysis / self-improvement /
+ // task type, never this reserved value — so a client-derived key can neither
+ // match an auto-filed investigation in the dedup scan nor evict it.
+ const key = clientInvestigationFingerprint({ description: INSTALL_FAILURE });
+ expect(key.split(':')[1]).toBe(CLIENT_INVESTIGATION_KIND);
+ expect(buildInvestigationFingerprint(
+ { taskType: CLIENT_INVESTIGATION_KIND, metadata: {} },
+ { category: 'unknown' }
+ )).not.toBe(key);
+ });
+
+ it('survives a description of nothing but punctuation rather than emitting a bare separator', () => {
+ expect(clientInvestigationFingerprint({ description: '!!! ---' })).toBe(`unknown:${CLIENT_INVESTIGATION_KIND}:none`);
+ expect(clientInvestigationFingerprint()).toBe(`unknown:${CLIENT_INVESTIGATION_KIND}:none`);
+ });
+});
+
+describe('investigation delivery postures', () => {
+ it('isolates a client-queued investigation exactly like an unattended one', () => {
+ expect(CLIENT_INVESTIGATION_DELIVERY.useWorktree).toBe(INVESTIGATION_TASK_DELIVERY.useWorktree);
+ expect(CLIENT_INVESTIGATION_DELIVERY.openPR).toBe(INVESTIGATION_TASK_DELIVERY.openPR);
+ });
+
+ it('reviews the client-queued PR instead of merging it on green — a human is present', () => {
+ expect(INVESTIGATION_TASK_DELIVERY.prCompletion).toBe('merge-on-green');
+ expect(CLIENT_INVESTIGATION_DELIVERY.prCompletion).toBe('review-then-merge');
+ });
+});
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index 0b03e64d64..1101fded55 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -16,6 +16,8 @@ import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } f
import { NON_PM2_TYPES } from '../services/streamingDetect.js';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { recordUserAction } from '../services/userActions.js';
+import { fileInvestigationTask } from '../services/investigationTaskProducer.js';
+import { CLIENT_INVESTIGATION_DELIVERY, clientInvestigationFingerprint } from '../lib/investigationTasks.js';
import {
createCosTaskSchema,
slashdoTaskSchema,
@@ -46,7 +48,7 @@ const TASK_CREATE_PAYLOAD_FIELDS = [
'prompt', 'description', 'context', 'provider', 'model', 'effort', 'app',
'orchestrationMode', 'orchestrationProfile',
'useWorktree', 'openPR', 'prCompletion', 'planOnly', 'reviewLoop', 'reviewers',
- 'approvalRequired',
+ 'approvalRequired', 'isInvestigation',
// The one create field with an open shape (`cosTaskDiagnosticsSchema` is a
// passthrough), so it is both the most informative thing to keep and the reason
// `recordUserAction` redacts credential-shaped keys at all.
@@ -406,16 +408,32 @@ router.post('/tasks/jira-ticket', asyncHandler(async (req, res) => {
router.post('/tasks', asyncHandler(async (req, res) => {
const parsed = createCosTaskSchema.safeParse(req.body);
if (!parsed.success) failValidation(parsed);
- const { type, ...taskData } = parsed.data;
+ const { type, isInvestigation, ...taskData } = parsed.data;
if (taskData.targetInstanceId) await assertAssignableInstance(taskData.targetInstanceId);
const preparedTask = await preparePlanOnlyTask(taskData);
- const result = await cos.addTask(preparedTask, type);
+ // A UI-queued investigation (#6043) goes through the SAME producer as an
+ // auto-filed one, so it lands with the markers the shared machinery reads —
+ // `metadata.isInvestigation` (recognized by `isInvestigationTask`, which is
+ // also the meta-cascade guard, so its own failure can't spawn an
+ // investigation of itself) and a server-derived fingerprint (dedup + the loop
+ // policy) — and contributes to the shared storm counter. The client supplies
+ // only the flag: it never names the fingerprint or the delivery posture.
+ const delivery = isInvestigation ? CLIENT_INVESTIGATION_DELIVERY : null;
+ const result = delivery
+ ? (await fileInvestigationTask(
+ { ...preparedTask, fingerprint: clientInvestigationFingerprint(preparedTask) },
+ { taskType: type, delivery }
+ )).task
+ : await cos.addTask(preparedTask, type);
if (result?.duplicate) {
throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });
}
- await logTaskCreated(req, result, preparedTask);
+ // Log the posture the task actually FILED with, not just the submitted fields:
+ // the delivery and the investigation marker are applied here, so a ledger row
+ // built from `preparedTask` alone would omit them for a UI-queued repair.
+ await logTaskCreated(req, result, { ...preparedTask, ...delivery, isInvestigation });
res.json(result);
}));
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
index 7721ef8339..8a7d863d01 100644
--- a/server/routes/cosTaskRoutes.test.js
+++ b/server/routes/cosTaskRoutes.test.js
@@ -73,6 +73,8 @@ import { getAppById, getAppWorkTracker } from '../services/apps.js';
import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';
import cosTaskRoutes from './cosTaskRoutes.js';
import { listUserActions } from '../services/userActions.js';
+import { __resetInvestigationCircuit } from '../services/investigationTaskProducer.js';
+import { clientInvestigationFingerprint } from '../lib/investigationTasks.js';
const SELF = 'self-instance-id';
const PEER = 'peer-instance-id';
@@ -95,6 +97,9 @@ beforeEach(() => {
{ instanceId: PEER, name: 'render-box', isSelf: false },
]);
cos.addTask.mockImplementation(async (taskData) => ({ id: 'task-1', ...taskData }));
+ cos.getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
+ // The producer's storm counter is module state shared across this file's cases.
+ __resetInvestigationCircuit();
cos.updateTask.mockResolvedValue({ id: 'task-1' });
getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS', repoPath: '/example/portos' });
resolveManagedAppIssueTarget.mockResolvedValue({
@@ -179,6 +184,92 @@ describe('CoS task routes — orchestration profiles (#5992)', () => {
});
});
+describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {
+ const INSTALL_FAILURE = 'Fix Example Runtime installer failure at the download stage';
+
+ it('files through the investigation producer with the markers the shared machinery reads', async () => {
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: INSTALL_FAILURE, isInvestigation: true });
+
+ expect(res.status).toBe(200);
+ expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({
+ description: INSTALL_FAILURE,
+ // Recognized by isInvestigationTask() — which is also the meta-cascade
+ // guard, so a failure of THIS task cannot file an investigation of itself.
+ isInvestigation: true,
+ // Server-derived: the request named no fingerprint.
+ investigationFingerprint: clientInvestigationFingerprint({ description: INSTALL_FAILURE }),
+ }), 'user');
+ });
+
+ it('applies the review-then-merge delivery posture rather than the unattended merge-on-green', async () => {
+ await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: INSTALL_FAILURE, isInvestigation: true });
+
+ expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({
+ useWorktree: true,
+ openPR: true,
+ prCompletion: 'review-then-merge',
+ }), 'user');
+ });
+
+ it('ignores a client-supplied fingerprint, so a client cannot collide with an auto-filed investigation', async () => {
+ await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({
+ description: INSTALL_FAILURE,
+ isInvestigation: true,
+ investigationFingerprint: 'auth-error:provider-failure:Example CLI',
+ });
+
+ const filed = cos.addTask.mock.calls[0][0];
+ expect(filed.investigationFingerprint).toBe(clientInvestigationFingerprint({ description: INSTALL_FAILURE }));
+ expect(filed.investigationFingerprint).not.toBe('auth-error:provider-failure:Example CLI');
+ });
+
+ it('gives two different install failures different dedup keys, and the same failure one key', async () => {
+ const app = buildApp();
+ await request(app).post('/api/cos/tasks').send({ description: INSTALL_FAILURE, isInvestigation: true });
+ await request(app).post('/api/cos/tasks').send({ description: 'Fix Other Runtime installer failure', isInvestigation: true });
+
+ const [first, second] = cos.addTask.mock.calls.map(call => call[0].investigationFingerprint);
+ expect(first).not.toBe(second);
+ expect(clientInvestigationFingerprint({ description: INSTALL_FAILURE })).toBe(first);
+ });
+
+ it('leaves an ordinary task untouched by the investigation path', async () => {
+ await request(buildApp()).post('/api/cos/tasks').send({ description: 'Render the opening shot' });
+ const filed = cos.addTask.mock.calls[0][0];
+ expect(filed).not.toHaveProperty('isInvestigation');
+ expect(filed).not.toHaveProperty('investigationFingerprint');
+ });
+
+ it('records the posture it actually filed with in the operator ledger, not just the submitted fields', async () => {
+ await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: INSTALL_FAILURE, isInvestigation: true });
+
+ const [event] = await listUserActions({ type: 'cos.task.create' });
+ expect(event.payload).toMatchObject({
+ isInvestigation: true,
+ useWorktree: true,
+ openPR: true,
+ prCompletion: 'review-then-merge',
+ });
+ });
+
+ it('still reports the store duplicate as a 409 so the button can say the task already exists', async () => {
+ cos.addTask.mockResolvedValue({ id: 'task-1', status: 'pending', duplicate: true });
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: INSTALL_FAILURE, isInvestigation: true });
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('DUPLICATE_TASK');
+ });
+});
+
describe('POST /api/cos/tasks — plan-only tracker gate', () => {
it('rejects issue-only planning for a non-issue tracker', async () => {
getAppWorkTracker.mockResolvedValue({ resolved: 'jira' });
diff --git a/server/services/investigationTaskProducer.js b/server/services/investigationTaskProducer.js
index 8042ba8362..bd1534ec49 100644
--- a/server/services/investigationTaskProducer.js
+++ b/server/services/investigationTaskProducer.js
@@ -121,9 +121,18 @@ export async function resolveAutoInvestigationApproval(fingerprint, { now = Date
*
* @param {{ fingerprint: string, description: string, affectedTasks?: string[] }} args
* plus any further `addTask` fields (priority, context, diagnostics)
+ * @param {{ now?: number, taskType?: string, delivery?: object }} [opts] `taskType`
+ * and `delivery` are the two axes a USER-queued investigation differs on
+ * (#6043): it belongs in the user queue and its PR waits for the human who
+ * asked for it. Both default to the unattended auto-filed posture. `delivery`
+ * is applied AFTER the caller's fields on purpose — an investigation's
+ * isolation and PR posture are set by policy, not by the submitter.
* @returns {Promise<{ task: object|null, approvalRequired: boolean, loopReason: string|null }>}
*/
-export async function fileInvestigationTask({ fingerprint, description, affectedTasks = [], ...extra } = {}, { now = Date.now() } = {}) {
+export async function fileInvestigationTask(
+ { fingerprint, description, affectedTasks = [], ...extra } = {},
+ { now = Date.now(), taskType = 'internal', delivery = INVESTIGATION_TASK_DELIVERY } = {}
+) {
const verdict = await resolveAutoInvestigationApproval(fingerprint, { now });
const body = verdict.loopProse
? `${description}\n\n## Why this is held for you\n${verdict.loopProse}`
@@ -131,7 +140,7 @@ export async function fileInvestigationTask({ fingerprint, description, affected
const task = await addTask({
...extra,
- ...INVESTIGATION_TASK_DELIVERY,
+ ...delivery,
description: body,
approvalRequired: verdict.approvalRequired,
approvalReason: verdict.approvalReason,
@@ -141,7 +150,7 @@ export async function fileInvestigationTask({ fingerprint, description, affected
isInvestigation: true,
investigationFingerprint: fingerprint,
...(affectedTasks.length > 0 && { affectedTasks })
- }, 'internal');
+ }, taskType);
if (!task?.duplicate) noteInvestigationFiled(now);
return { task, approvalRequired: verdict.approvalRequired, loopReason: verdict.loopReason };
diff --git a/server/services/investigationTaskProducer.test.js b/server/services/investigationTaskProducer.test.js
index 34b9310146..055ab52813 100644
--- a/server/services/investigationTaskProducer.test.js
+++ b/server/services/investigationTaskProducer.test.js
@@ -13,7 +13,7 @@ const {
resolveAutoInvestigationApproval,
__resetInvestigationCircuit,
} = await import('./investigationTaskProducer.js');
-const { INVESTIGATION_CIRCUIT_MAX_CREATIONS, INVESTIGATION_CIRCUIT_WINDOW_MS } = await import('../lib/investigationTasks.js');
+const { INVESTIGATION_CIRCUIT_MAX_CREATIONS, INVESTIGATION_CIRCUIT_WINDOW_MS, CLIENT_INVESTIGATION_DELIVERY } = await import('../lib/investigationTasks.js');
const emptyBacklog = () => getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });
@@ -124,3 +124,49 @@ describe('resolveAutoInvestigationApproval', () => {
expect(getAllTasks).not.toHaveBeenCalled();
});
});
+
+describe('fileInvestigationTask — a user-queued investigation (#6043)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ addTask.mockResolvedValue({ id: 'task-1' });
+ emptyBacklog();
+ __resetInvestigationCircuit();
+ });
+
+ it('lands in the user queue with the client delivery posture, keeping the shared markers', async () => {
+ await fileInvestigationTask(
+ { fingerprint: 'unknown:ui-investigation:fix-example-runtime-installer-failure', description: 'Fix Example Runtime installer failure' },
+ { taskType: 'user', delivery: CLIENT_INVESTIGATION_DELIVERY }
+ );
+
+ expect(addTask).toHaveBeenCalledWith({
+ description: 'Fix Example Runtime installer failure',
+ useWorktree: true,
+ openPR: true,
+ prCompletion: 'review-then-merge',
+ approvalRequired: false,
+ approvalReason: null,
+ isInvestigation: true,
+ investigationFingerprint: 'unknown:ui-investigation:fix-example-runtime-installer-failure',
+ }, 'user');
+ });
+
+ it('contributes to the shared storm counter, so UI-queued repairs are visible to the circuit', async () => {
+ await fileInvestigationTask(
+ { fingerprint: 'unknown:ui-investigation:x', description: 'Fix it' },
+ { taskType: 'user', delivery: CLIENT_INVESTIGATION_DELIVERY }
+ );
+ expect(recentInvestigationCreations()).toBe(1);
+ });
+
+ it('sets the delivery posture by policy — a caller cannot pick its own', async () => {
+ await fileInvestigationTask(
+ { fingerprint: 'unknown:ui-investigation:x', description: 'Fix it', useWorktree: false, openPR: false, prCompletion: 'merge-on-green' },
+ { taskType: 'user', delivery: CLIENT_INVESTIGATION_DELIVERY }
+ );
+ expect(addTask).toHaveBeenCalledWith(
+ expect.objectContaining({ useWorktree: true, openPR: true, prCompletion: 'review-then-merge' }),
+ 'user'
+ );
+ });
+});