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: route investigations through PR delivery

[._.]/ Adam Eivy83e10d009c17
diff --git a/server/lib/README.md b/server/lib/README.md
index cf53e3746a..699f00b4d2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -367,7 +367,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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, the approval policy, and the auto-retry decision — 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); `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; `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. |
| `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. |
| `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |
diff --git a/server/lib/investigationTasks.js b/server/lib/investigationTasks.js
index 9e619cbc6d..241f7ac0df 100644
--- a/server/lib/investigationTasks.js
+++ b/server/lib/investigationTasks.js
@@ -10,6 +10,7 @@
*/
import { NON_AUTO_RETRY_BLOCK_CATEGORIES } from './taskBlockCategories.js';
+import { PR_COMPLETIONS } from './prDisposition.js';
export { NON_AUTO_RETRY_BLOCK_CATEGORIES };
@@ -20,6 +21,17 @@ export { NON_AUTO_RETRY_BLOCK_CATEGORIES };
// reach).
export const INVESTIGATION_HEADLINE_PREFIX = '[Auto] Investigate agent failure';
+// Investigation tasks are unattended code-repair work. Keep them out of the
+// checkout that spawned them and send every change through the normal PR gate;
+// otherwise the generic commit handoff writes directly to the current branch.
+// This is top-level task data (rather than nested metadata) because both the
+// shared producer and the agent-failure producer pass it to addTask().
+export const INVESTIGATION_TASK_DELIVERY = Object.freeze({
+ useWorktree: true,
+ openPR: true,
+ prCompletion: PR_COMPLETIONS.MERGE_ON_GREEN,
+});
+
// 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/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index b9f5f1212e..5ee83f7ec9 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -16,6 +16,7 @@ import { retryHoldMetadata } from '../lib/taskRetryHold.js';
import {
INVESTIGATION_CIRCUIT_MAX_CREATIONS,
INVESTIGATION_HEADLINE_PREFIX,
+ INVESTIGATION_TASK_DELIVERY,
LOOP_REASON_PROSE,
MAX_AUTO_RETRIES_PER_TASK,
buildInvestigationFingerprint,
@@ -1254,6 +1255,7 @@ ${actionBlock}
${unblocks}`;
const investigationTask = await addTask({
+ ...INVESTIGATION_TASK_DELIVERY,
description,
priority: 'HIGH',
context: `Auto-generated from agent ${agentId} failure`,
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 36fc262fd2..b20d6db5ce 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -660,6 +660,9 @@ describe('createInvestigationTask guards (#2615)', () => {
expect(addTask).toHaveBeenCalledWith(expect.objectContaining({
priority: 'HIGH',
approvalRequired: false, // isolated failure — runs unattended (#3714)
+ useWorktree: true,
+ openPR: true,
+ prCompletion: 'merge-on-green',
isInvestigation: true,
investigationFingerprint: 'startup-failure:user:none',
affectedTasks: ['task-1']
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 36b5187be9..86fb62bb5b 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -39,6 +39,7 @@ import { resolveSpawnCwd, usesCreativeDirectorScratchCwd, creativeDirectorScratc
import { enforceSafeBranchUpstream } from '../lib/branchUpstreamGuard.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';
+import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';
const ROOT_DIR = PATHS.root;
@@ -174,6 +175,13 @@ export async function prepareAgentWorkspace({ agentId, task }) {
};
}
+ // Pre-change investigation tasks may already be persisted without delivery
+ // flags. Normalize them at the last common spawn boundary so an old queued
+ // investigation cannot fall back to committing in the shared checkout.
+ if (isInvestigationTask(task)) {
+ task.metadata = { ...(task.metadata || {}), ...INVESTIGATION_TASK_DELIVERY };
+ }
+
// Determine workspace path and resolve app name
const isReadOnly = isTruthyMeta(task.metadata?.readOnly);
let workspacePath = task.metadata?.app
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index ed1da4c556..40160b16c2 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -103,6 +103,32 @@ describe('prepareAgentWorkspace — Creative Director scratch cwd (#4650)', () =
});
describe('prepareAgentWorkspace', () => {
+ it('normalizes legacy investigations into isolated PR delivery', async () => {
+ ensureLatest.mockResolvedValue({ success: true, upToDate: true });
+ createWorktree.mockResolvedValue({
+ worktreePath: '/mock/worktrees/agent-investigation',
+ branchName: 'cos/sys-investigation/agent-investigation',
+ baseBranch: 'main',
+ });
+ const task = {
+ id: 'sys-investigation',
+ taskType: 'internal',
+ description: '[Auto] Investigate agent failure: legacy task',
+ metadata: {},
+ };
+
+ const r = await prepareAgentWorkspace({ agentId: 'agent-investigation', task });
+
+ expect(task.metadata).toMatchObject({
+ useWorktree: true,
+ openPR: true,
+ prCompletion: 'merge-on-green',
+ });
+ expect(r.outcome).toBe('ready');
+ expect(r.explicitWorktree).toBe(true);
+ expect(createWorktree).toHaveBeenCalled();
+ });
+
it('read-only task: returns ready with the shared workspace and skips the git pull', async () => {
const task = { id: 't-ro', taskType: 'user', metadata: { readOnly: true } };
const r = await prepareAgentWorkspace({ agentId: 'agent-ro', task });
diff --git a/server/services/investigationTaskProducer.js b/server/services/investigationTaskProducer.js
index 9b667e7626..8042ba8362 100644
--- a/server/services/investigationTaskProducer.js
+++ b/server/services/investigationTaskProducer.js
@@ -29,6 +29,7 @@ import { addTask, getAllTasks } from './cos.js';
import {
INVESTIGATION_CIRCUIT_MAX_CREATIONS,
INVESTIGATION_CIRCUIT_WINDOW_MS,
+ INVESTIGATION_TASK_DELIVERY,
UNATTENDED_APPROVAL_VERDICT,
resolveInvestigationApproval,
} from '../lib/investigationTasks.js';
@@ -130,6 +131,7 @@ export async function fileInvestigationTask({ fingerprint, description, affected
const task = await addTask({
...extra,
+ ...INVESTIGATION_TASK_DELIVERY,
description: body,
approvalRequired: verdict.approvalRequired,
approvalReason: verdict.approvalReason,
diff --git a/server/services/investigationTaskProducer.test.js b/server/services/investigationTaskProducer.test.js
index 32ee4b439d..34b9310146 100644
--- a/server/services/investigationTaskProducer.test.js
+++ b/server/services/investigationTaskProducer.test.js
@@ -46,6 +46,9 @@ describe('fileInvestigationTask', () => {
expect(addTask).toHaveBeenCalledWith({
description: 'Investigate AI provider failure',
priority: 'MEDIUM',
+ useWorktree: true,
+ openPR: true,
+ prCompletion: 'merge-on-green',
approvalRequired: false,
approvalReason: null,
isInvestigation: true,