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: refuse worktree tasks for non-git apps up front (#11976)

Adam Eivyf92046fd5207
diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.js
index dedef77cb6..cc2f0c5648 100644
--- a/server/routes/cosTaskRoutes.js
+++ b/server/routes/cosTaskRoutes.js
@@ -4,6 +4,8 @@
import { Router } from 'express';
import { z } from 'zod';
+import { existsSync } from 'fs';
+import { isRepo, notGitRepoMessage } from '../services/git.js';
import * as cos from '../services/cos.js';
import * as taskWatcher from '../services/taskWatcher.js';
import { enhanceTaskPrompt } from '../services/taskEnhancer.js';
@@ -103,6 +105,18 @@ async function assertAssignableInstance(instanceId) {
throw new ServerError('Unknown instance — pick one of this install\'s federated instances', { status: 400, code: 'UNKNOWN_INSTANCE' });
}
+// Worktree/PR delivery needs a git checkout; refuse at creation rather than
+// letting the task block at spawn. A missing directory is left to the spawn-time
+// workspace validation, which has its own message.
+async function assertWorktreeCapableApp(taskData) {
+ if (!taskData.app || !(taskData.useWorktree || taskData.openPR)) return;
+ const app = await getAppById(taskData.app);
+ if (!app?.repoPath || !existsSync(app.repoPath)) return;
+ if (!(await isRepo(app.repoPath))) {
+ throw new ServerError(notGitRepoMessage(app.name || taskData.app), { status: 400, code: 'NOT_A_GIT_REPO' });
+ }
+}
+
const ISSUE_TRACKERS = new Set(['github', 'gitlab']);
function issueTargetInstructions(target, tracker) {
@@ -474,6 +488,7 @@ router.post('/tasks', asyncHandler(async (req, res) => {
if (!parsed.success) failValidation(parsed);
const { type, isInvestigation, ...taskData } = parsed.data;
if (taskData.targetInstanceId) await assertAssignableInstance(taskData.targetInstanceId);
+ await assertWorktreeCapableApp(taskData);
const preparedTask = await preparePlanOnlyTask(taskData);
// 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 —
diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.js
index b85d9e10dc..d54eb44c58 100644
--- a/server/routes/cosTaskRoutes.test.js
+++ b/server/routes/cosTaskRoutes.test.js
@@ -14,7 +14,8 @@
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import express from 'express';
-import { mkdirSync, rmSync } from 'node:fs';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -297,6 +298,20 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {
expect(clientInvestigationFingerprint({ description: INSTALL_FAILURE })).toBe(first);
});
+ it('refuses a worktree/PR task for an app whose directory is not a git repository', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'portos-nongit-'));
+ getAppById.mockResolvedValue({ id: 'app-1', name: 'Example App', repoPath: dir });
+ const res = await request(buildApp())
+ .post('/api/cos/tasks')
+ .send({ description: 'Do a thing', app: 'app-1', useWorktree: true, openPR: true });
+ rmSync(dir, { recursive: true, force: true });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('NOT_A_GIT_REPO');
+ expect(res.body.error).toContain('Example App is not a git repository');
+ expect(cos.addTask).not.toHaveBeenCalled();
+ });
+
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];
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 80f2db6384..ca42c741fe 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -26,7 +26,7 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';
* the inline code did.
*/
-import { join } from 'path';
+import { basename, join } from 'path';
import { existsSync } from 'fs';
import { execGit } from '../lib/execGit.js';
import { emitLog } from './cosEvents.js';
@@ -170,6 +170,14 @@ async function prepareRequestedWorktree({
forkHead,
allowSharedWorkspaceFallback,
}) {
+ // Fail before any git fetch/branch work: a non-git directory can never host a
+ // worktree, and the raw `fatal: not a git repository` says nothing actionable.
+ if (!(await git.isRepo(workspacePath))) {
+ const reason = git.notGitRepoMessage(task.metadata?.app || basename(workspacePath));
+ emitLog('warn', `🌳 ${reason}`, { taskId: task.id });
+ await blockTask(task, reason, 'worktree-failed');
+ return { outcome: 'blocked', reason };
+ }
const isolateDependencies = resolveTaskHookType(task) === 'dependency-updates';
const baseCommit = isLegacyDeepAudit(task.metadata)
? await (await import('./deepAudit.js')).getDeepAuditSourceRevision(task)
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 2c79e959ee..9188b14755 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -23,6 +23,8 @@ vi.mock('./cos.js', () => ({
vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue(null) }));
vi.mock('./git.js', () => ({
ensureLatest: vi.fn(),
+ isRepo: vi.fn().mockResolvedValue(true),
+ notGitRepoMessage: (name) => `${name} is not a git repository — run \`git init\``,
fetchOrigin: vi.fn(),
getRepoBranches: vi.fn().mockResolvedValue({ baseBranch: 'main' }),
checkout: vi.fn(),
@@ -70,7 +72,7 @@ vi.mock('./deepAudit.js', () => ({ getDeepAuditSourceRevision: vi.fn().mockResol
import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';
import { claimContinuationWorkspace } from '../lib/claimContinuation.js';
import { updateTask, addTask, getAgents } from './cos.js';
-import { ensureLatest } from './git.js';
+import { ensureLatest, isRepo, fetchOrigin } from './git.js';
import { execGit } from '../lib/execGit.js';
import { detectConflicts } from './taskConflict.js';
import { getAppWorkspace } from './agentAppWorkspace.js';
@@ -263,6 +265,23 @@ describe('prepareAgentWorkspace', () => {
}), 'internal');
});
+ it('blocks a worktree task for a non-git app up front, without attempting a fetch', async () => {
+ isRepo.mockResolvedValueOnce(false);
+ getAppWorkspace.mockResolvedValue(process.cwd());
+ const task = { id: 't-nogit', taskType: 'internal', metadata: { readOnly: true, useWorktree: true, app: 'Example App' } };
+
+ const r = await prepareAgentWorkspace({ agentId: 'agent-nogit', task });
+
+ expect(r.outcome).toBe('blocked');
+ expect(r.reason).toContain('Example App is not a git repository');
+ expect(createWorktree).not.toHaveBeenCalled();
+ expect(fetchOrigin).not.toHaveBeenCalled();
+ expect(updateTask).toHaveBeenCalledWith('t-nogit', expect.objectContaining({
+ status: 'blocked',
+ metadata: expect.objectContaining({ blockedCategory: 'worktree-failed' }),
+ }), 'internal');
+ });
+
it('plan-only task: keeps the no-worktree path even with delivery flags present', async () => {
const task = {
id: 't-plan-only',
diff --git a/server/services/git.js b/server/services/git.js
index 6e8a0d6297..693f7a68f9 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -174,6 +174,11 @@ export async function isRepo(dir) {
return result?.stdout.trim() === 'true';
}
+/** Actionable refusal text shared by task creation and spawn-time worktree prep. */
+export function notGitRepoMessage(appName) {
+ return `${appName} is not a git repository — run \`git init\` in its directory (and add a remote if PRs are needed), or disable worktree/PR for this task`;
+}
+
/**
* Get remote info
*/