Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore(worktree): remove parallel agent worktree feature

Steven Enamakel1a048406f894
diff --git a/app/src/components/worktree/WorktreeActions.test.tsx b/app/src/components/worktree/WorktreeActions.test.tsx
deleted file mode 100644
index 82ac94340b..0000000000
--- a/app/src/components/worktree/WorktreeActions.test.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-import { render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { worktreeApi } from '../../services/api/worktreeApi';
-import { revealPath } from '../../utils/openUrl';
-import WorktreeActions from './WorktreeActions';
-
-vi.mock('../../services/api/worktreeApi', () => ({
- worktreeApi: { diff: vi.fn(), remove: vi.fn() },
-}));
-vi.mock('../../utils/openUrl', () => ({ revealPath: vi.fn().mockResolvedValue(undefined) }));
-vi.mock('../../lib/i18n/I18nContext', () => ({ useT: () => ({ t: (k: string) => k }) }));
-
-const mockDiff = vi.mocked(worktreeApi.diff);
-const mockRemove = vi.mocked(worktreeApi.remove);
-const mockReveal = vi.mocked(revealPath);
-
-const PATH = '/r/.claude/worktrees/worker-a';
-
-describe('WorktreeActions', () => {
- beforeEach(() => {
- mockDiff.mockReset();
- mockRemove.mockReset().mockResolvedValue(true);
- mockReveal.mockReset().mockResolvedValue(undefined);
- });
-
- it('open reveals the path in the OS file manager', async () => {
- const user = userEvent.setup();
- render(<WorktreeActions path={PATH} />);
- await user.click(screen.getByTestId('worktree-open'));
- expect(mockReveal).toHaveBeenCalledWith(PATH);
- });
-
- it('diff fetches once and renders the summary, toggling closed on second click', async () => {
- mockDiff.mockResolvedValue(' src/a.rs | 2 +-');
- const user = userEvent.setup();
- render(<WorktreeActions path={PATH} />);
- await user.click(screen.getByTestId('worktree-diff'));
- await waitFor(() =>
- expect(screen.getByTestId('worktree-diff-output')).toHaveTextContent('src/a.rs')
- );
- expect(mockDiff).toHaveBeenCalledTimes(1);
- await user.click(screen.getByTestId('worktree-diff'));
- expect(screen.queryByTestId('worktree-diff-output')).toBeNull();
- });
-
- it('removes a clean worktree in one click (force=false)', async () => {
- const onRemoved = vi.fn();
- const user = userEvent.setup();
- render(<WorktreeActions path={PATH} isDirty={false} onRemoved={onRemoved} />);
- await user.click(screen.getByTestId('worktree-remove'));
- await waitFor(() => expect(mockRemove).toHaveBeenCalledWith(PATH, false));
- expect(onRemoved).toHaveBeenCalledWith(PATH);
- });
-
- it('a dirty worktree requires explicit confirmation before removal', async () => {
- const onRemoved = vi.fn();
- const user = userEvent.setup();
- render(<WorktreeActions path={PATH} isDirty onRemoved={onRemoved} />);
- await user.click(screen.getByTestId('worktree-remove'));
- // No removal yet — a confirm row appears instead.
- expect(mockRemove).not.toHaveBeenCalled();
- expect(screen.getByTestId('worktree-remove-confirm')).toBeInTheDocument();
- // Discard & remove forces.
- await user.click(screen.getByTestId('worktree-remove-confirm-yes'));
- await waitFor(() => expect(mockRemove).toHaveBeenCalledWith(PATH, true));
- expect(onRemoved).toHaveBeenCalledWith(PATH);
- });
-
- it('resets the removing state after success when no onRemoved parent drops the row', async () => {
- // Inline timeline use (ToolTimelineBlock) renders without onRemoved, so the
- // component is never unmounted by a parent — it must reset its own state or
- // the button stays stuck on "worktree.removing" with disabled forever.
- const user = userEvent.setup();
- render(<WorktreeActions path={PATH} isDirty={false} />);
- await user.click(screen.getByTestId('worktree-remove'));
- await waitFor(() => expect(mockRemove).toHaveBeenCalledWith(PATH, false));
- await waitFor(() => {
- const btn = screen.getByTestId('worktree-remove');
- expect(btn).toHaveTextContent('worktree.action.remove');
- expect(btn).not.toBeDisabled();
- });
- });
-
- it('preserve cancels the dirty-removal confirm without removing', async () => {
- const user = userEvent.setup();
- render(<WorktreeActions path={PATH} isDirty />);
- await user.click(screen.getByTestId('worktree-remove'));
- await user.click(screen.getByTestId('worktree-preserve'));
- expect(mockRemove).not.toHaveBeenCalled();
- expect(screen.queryByTestId('worktree-remove-confirm')).toBeNull();
- expect(screen.getByTestId('worktree-remove')).toBeInTheDocument();
- });
-});
diff --git a/app/src/components/worktree/WorktreeActions.tsx b/app/src/components/worktree/WorktreeActions.tsx
deleted file mode 100644
index b0a7f054dc..0000000000
--- a/app/src/components/worktree/WorktreeActions.tsx
+++ /dev/null
@@ -1,195 +0,0 @@
-/**
- * WorktreeActions — open / diff / remove affordances for one isolated worker
- * `git worktree` (#3376). Shared between the inline subagent row (compact) in
- * the conversation timeline and the Worktrees command-center panel (full).
- *
- * Safety contract (acceptance criterion of #3376): a **clean** worktree removes
- * in one click; a **dirty** worktree requires an explicit user decision — the
- * Remove button expands into a confirm row offering "Discard & remove" (force)
- * or "Preserve" (cancel, keep the worktree + its `worker/*` branch). The core
- * itself also refuses a dirty removal without `force`, so this is defense in
- * depth, not the only guard.
- */
-import debug from 'debug';
-import { useCallback, useState } from 'react';
-
-import { useT } from '../../lib/i18n/I18nContext';
-import { worktreeApi } from '../../services/api/worktreeApi';
-import { revealPath } from '../../utils/openUrl';
-
-const log = debug('worktree:actions');
-
-interface WorktreeActionsProps {
- /** Absolute worktree checkout path. */
- path: string;
- /** Whether the worktree has uncommitted changes. */
- isDirty?: boolean;
- /** Compact styling for the inline subagent row (vs the full panel row). */
- compact?: boolean;
- /** Called after a successful remove so the parent can refetch / drop the row. */
- onRemoved?: (path: string) => void;
-}
-
-const btnBase =
- 'rounded-md border px-2 py-0.5 font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50';
-const btnNeutral = 'border-line text-content-secondary hover:bg-surface-hover';
-const btnDanger =
- 'border-coral-200 text-coral-600 hover:bg-coral-50 dark:border-coral-500/40 dark:text-coral-300 dark:hover:bg-coral-500/10';
-
-export default function WorktreeActions({
- path,
- isDirty,
- compact,
- onRemoved,
-}: WorktreeActionsProps) {
- const { t } = useT();
- const [diffOpen, setDiffOpen] = useState(false);
- const [diffText, setDiffText] = useState<string | null>(null);
- const [diffLoading, setDiffLoading] = useState(false);
- const [confirmRemove, setConfirmRemove] = useState(false);
- const [removing, setRemoving] = useState(false);
- const [error, setError] = useState<string | null>(null);
-
- const sizeText = compact ? 'text-[10px]' : 'text-xs';
-
- const handleOpen = useCallback(() => {
- log('open path=%s', path);
- void revealPath(path).catch(err => {
- log('open failed %O', err);
- setError(err instanceof Error ? err.message : String(err));
- });
- }, [path]);
-
- const handleDiff = useCallback(async () => {
- if (diffOpen) {
- setDiffOpen(false);
- return;
- }
- setDiffOpen(true);
- setError(null);
- // Fetch once; cache for subsequent toggles.
- if (diffText !== null) return;
- setDiffLoading(true);
- try {
- const summary = await worktreeApi.diff(path);
- setDiffText(summary);
- log('diff loaded path=%s chars=%d', path, summary.length);
- } catch (err) {
- log('diff failed %O', err);
- setError(t('worktree.diffFailed'));
- setDiffOpen(false);
- } finally {
- setDiffLoading(false);
- }
- }, [diffOpen, diffText, path, t]);
-
- const doRemove = useCallback(
- async (force: boolean) => {
- setRemoving(true);
- setError(null);
- try {
- await worktreeApi.remove(path, force);
- log('removed path=%s force=%s', path, force);
- // The parent (e.g. the Worktrees panel) drops the row on success and
- // this component unmounts. But inline in the chat timeline
- // (`ToolTimelineBlock`) there is no `onRemoved`, so nothing unmounts
- // us — reset local state here or the row stays stuck on "Removing…"
- // with the button disabled forever even though the checkout is gone.
- if (onRemoved) {
- onRemoved(path);
- } else {
- setRemoving(false);
- setConfirmRemove(false);
- }
- } catch (err) {
- log('remove failed %O', err);
- setError(t('worktree.removeFailed'));
- setRemoving(false);
- setConfirmRemove(false);
- }
- },
- [path, onRemoved, t]
- );
-
- const handleRemoveClick = useCallback(() => {
- // Dirty worktrees must not be removed without an explicit choice.
- if (isDirty) {
- setConfirmRemove(true);
- return;
- }
- void doRemove(false);
- }, [isDirty, doRemove]);
-
- return (
- <div className={`space-y-1.5 ${sizeText}`} data-testid="worktree-actions">
- {!confirmRemove ? (
- <div className="flex flex-wrap items-center gap-1.5">
- <button
- type="button"
- onClick={handleOpen}
- className={`${btnBase} ${btnNeutral}`}
- data-testid="worktree-open">
- {t('worktree.action.open')}
- </button>
- <button
- type="button"
- onClick={() => void handleDiff()}
- className={`${btnBase} ${btnNeutral}`}
- data-testid="worktree-diff">
- {diffOpen ? t('worktree.action.hideDiff') : t('worktree.action.diff')}
- </button>
- <button
- type="button"
- onClick={handleRemoveClick}
- disabled={removing}
- className={`${btnBase} ${btnDanger}`}
- data-testid="worktree-remove">
- {removing ? t('worktree.removing') : t('worktree.action.remove')}
- </button>
- </div>
- ) : (
- <div
- className="space-y-1.5 rounded-md border border-coral-200 bg-coral-50 p-2 dark:border-coral-500/40 dark:bg-coral-500/10"
- data-testid="worktree-remove-confirm">
- <p className="text-coral-700 dark:text-coral-300">{t('worktree.dirtyConfirm')}</p>
- <div className="flex flex-wrap items-center gap-1.5">
- <button
- type="button"
- onClick={() => void doRemove(true)}
- disabled={removing}
- className={`${btnBase} ${btnDanger}`}
- data-testid="worktree-remove-confirm-yes">
- {removing ? t('worktree.removing') : t('worktree.action.removeAnyway')}
- </button>
- <button
- type="button"
- onClick={() => setConfirmRemove(false)}
- disabled={removing}
- className={`${btnBase} ${btnNeutral}`}
- data-testid="worktree-preserve">
- {t('worktree.action.preserve')}
- </button>
- </div>
- </div>
- )}
-
- {diffOpen ? (
- <pre
- className="max-h-48 overflow-auto rounded-md border border-line bg-surface-muted p-2 font-mono text-[10px] leading-snug text-content-secondary"
- data-testid="worktree-diff-output">
- {diffLoading
- ? t('worktree.diffLoading')
- : diffText && diffText.trim().length > 0
- ? diffText
- : t('worktree.diffEmpty')}
- </pre>
- ) : null}
-
- {error ? (
- <p className="text-coral-600 dark:text-coral-300" data-testid="worktree-error">
- {error}
- </p>
- ) : null}
- </div>
- );
-}
diff --git a/app/src/features/conversations/aui/ParallelAgentsCard.test.tsx b/app/src/features/conversations/aui/ParallelAgentsCard.test.tsx
deleted file mode 100644
index fa14d9f05c..0000000000
--- a/app/src/features/conversations/aui/ParallelAgentsCard.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { ParallelAgentsCard } from './ParallelAgentsCard';
-
-vi.mock('../../../lib/i18n/I18nContext', () => ({
- useT: () => ({
- t: (key: string) => (key === 'chat.subagents.ofTotal' ? '{complete} of {total}' : key),
- }),
-}));
-vi.mock('../../../providers/AssistantUiRuntimeProvider', () => ({ useAuiThreadId: () => 't1' }));
-vi.mock('./SubagentActivityCard', () => ({ SubagentActivityCard: () => null }));
-
-const timeline = vi.hoisted(() => ({ entries: [] as ToolTimelineEntry[] }));
-vi.mock('../../../store/hooks', () => ({
- useAppSelector: (select: (state: unknown) => unknown) =>
- select({ chatRuntime: { toolTimelineByThread: { t1: timeline.entries } } }),
-}));
-
-function child(id: string, seq: number, status: string): ToolTimelineEntry {
- return {
- id,
- name: 'subagent',
- round: 1,
- seq,
- status: status === 'running' ? 'running' : 'success',
- subagent: { taskId: id, agentId: id, status, parentCallId: 'call-p', toolCalls: [] },
- } as ToolTimelineEntry;
-}
-
-function renderCard(status: 'running' | 'complete') {
- return render(
- <ParallelAgentsCard
- type="tool-call"
- toolName="spawn_parallel_agents"
- toolCallId="call-p"
- args={{} as never}
- argsText="{}"
- result={undefined}
- status={{ type: status } as never}
- addResult={() => {}}
- resume={() => {}}
- respondToApproval={async () => {}}
- />
- );
-}
-
-describe('ParallelAgentsCard', () => {
- it('counts complete, running and failed workers', () => {
- timeline.entries = [
- child('a', 1, 'running'),
- child('b', 2, 'completed'),
- child('c', 3, 'failed'),
- ];
- renderCard('running');
- const header = screen.getByTestId('parallel-agents-header');
- expect(header).toHaveTextContent('2 of 3');
- expect(header).toHaveTextContent('chat.subagents.runningCount · chat.subagents.failedCount');
- expect(screen.queryByTestId('parallel-agents-aggregating')).toBeNull();
- });
-
- it('reports an incomplete worker as partial rather than silently complete', () => {
- timeline.entries = [child('a', 1, 'completed'), child('b', 2, 'incomplete')];
- renderCard('complete');
- const header = screen.getByTestId('parallel-agents-header');
- expect(header).toHaveTextContent('1 of 2');
- expect(header).toHaveTextContent('chat.subagents.incompleteCount');
- expect(header).not.toHaveTextContent('chat.subagents.runningCount');
- expect(header).not.toHaveTextContent('chat.subagents.failedCount');
- });
-
- it('says the parent is processing once every worker is back but the call is still open', () => {
- timeline.entries = [child('a', 1, 'completed'), child('b', 2, 'completed')];
- renderCard('running');
- expect(screen.getByTestId('parallel-agents-aggregating')).toHaveTextContent(
- 'chat.subagents.settled'
- );
- });
-
- it('drops the processing line once the call settles', () => {
- timeline.entries = [child('a', 1, 'completed')];
- renderCard('complete');
- expect(screen.queryByTestId('parallel-agents-aggregating')).toBeNull();
- });
-});
diff --git a/app/src/features/conversations/aui/ParallelAgentsCard.tsx b/app/src/features/conversations/aui/ParallelAgentsCard.tsx
deleted file mode 100644
index 85c3a12827..0000000000
--- a/app/src/features/conversations/aui/ParallelAgentsCard.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-'use client';
-
-/**
- * `spawn_parallel_agents` toolkit entry (`aui/toolkit.tsx`): renders the
- * vendored `SubagentList` element above the individual `TaskCard` rows for
- * every worker the call fanned out.
- *
- * The core sends one `spawn_parallel_agents` tool-call part plus one
- * `subagent:*` timeline row per worker task, each carrying
- * `subagent.parentCallId === <this call's toolCallId>`
- * (`SubagentProgressDetail.parent_call_id` — see
- * `store/chatRuntimeSlice.ts#SubagentActivity.parentCallId` and
- * `selectSubagentChildrenByParentCallId`). Workers are NOT part of this call's
- * own `messages`/nested transcript the way a single `task` delegation is —
- * they are independent timeline rows, read here straight from the thread's
- * live tool timeline.
- */
-import type { ToolCallMessagePartComponent } from '@assistant-ui/react';
-
-import {
- type SubagentItem,
- SubagentList,
-} from '../../../components/assistant-ui/elements/subagent-list';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { useAuiThreadId } from '../../../providers/AssistantUiRuntimeProvider';
-import {
- isActiveTimelineStatus,
- selectSubagentChildrenByParentCallId,
-} from '../../../store/chatRuntimeSlice';
-import { useAppSelector } from '../../../store/hooks';
-import { SubagentActivityCard } from './SubagentActivityCard';
-
-const EMPTY_TIMELINE: never[] = [];
-
-function childName(entry: ReturnType<typeof selectSubagentChildrenByParentCallId>[number]): string {
- const sub = entry.subagent;
- return (
- (sub?.displayName && sub.displayName.trim()) || sub?.agentId || entry.displayName || 'sub-agent'
- );
-}
-
-function childProgressPct(
- entry: ReturnType<typeof selectSubagentChildrenByParentCallId>[number]
-): number {
- const sub = entry.subagent;
- if (!sub) return entry.status === 'running' ? 50 : 100;
- if (!isActiveTimelineStatus(sub.status ?? entry.status)) return 100;
- if (
- typeof sub.childIteration === 'number' &&
- typeof sub.childMaxIterations === 'number' &&
- sub.childMaxIterations > 0
- ) {
- return Math.max(
- 0,
- Math.min(100, Math.round((sub.childIteration / sub.childMaxIterations) * 100))
- );
- }
- return 50;
-}
-
-function isFailedChild(status: string | undefined): boolean {
- return status === 'error' || status === 'failed' || status === 'cancelled';
-}
-
-function isIncompleteChild(status: string | undefined): boolean {
- return status === 'incomplete';
-}
-
-/** Adapt a `spawn_parallel_agents` tool-call part onto `SubagentList` + per-child `TaskCard` rows. */
-export const ParallelAgentsCard: ToolCallMessagePartComponent = ({ toolCallId, status }) => {
- const { t } = useT();
- const threadId = useAuiThreadId();
- const timeline = useAppSelector(state =>
- threadId ? (state.chatRuntime.toolTimelineByThread[threadId] ?? EMPTY_TIMELINE) : EMPTY_TIMELINE
- );
- const children = selectSubagentChildrenByParentCallId(timeline, toolCallId);
-
- if (children.length === 0) return null;
-
- const childStatus = (entry: (typeof children)[number]) => entry.subagent?.status ?? entry.status;
- const agents: SubagentItem[] = children.map(entry => ({
- name: childName(entry),
- model: '',
- done: !isActiveTimelineStatus(childStatus(entry)),
- }));
- const runningCount = agents.filter(agent => !agent.done).length;
- const incompleteCount = children.filter(entry => isIncompleteChild(childStatus(entry))).length;
- // An incomplete worker has settled but did not finish: it is neither running
- // nor complete, so the completed total leaves it out.
- const completedCount = children.length - runningCount - incompleteCount;
- const failedCount = children.filter(entry => isFailedChild(childStatus(entry))).length;
- const progress = children.map(childProgressPct);
- const anyRunning = runningCount > 0;
- // Every worker is back but the parent call has not settled: it is reading
- // their results, which used to look like the card had simply stalled.
- const aggregating = !anyRunning && status?.type === 'running';
- const counts = [
- runningCount > 0
- ? t('chat.subagents.runningCount').replace('{count}', String(runningCount))
- : null,
- failedCount > 0
- ? t('chat.subagents.failedCount').replace('{count}', String(failedCount))
- : null,
- incompleteCount > 0
- ? t('chat.subagents.incompleteCount').replace('{count}', String(incompleteCount))
- : null,
- ].filter(Boolean);
-
- return (
- <div className="flex flex-col gap-2" data-testid="assistant-ui-parallel-agents-call">
- <div
- data-testid="parallel-agents-header"
- className="flex items-baseline justify-between gap-2 text-[12.5px]">
- <span className="text-content-secondary font-medium">
- {t('chat.subagents.ofTotal')
- .replace('{complete}', String(completedCount))
- .replace('{total}', String(children.length))}
- </span>
- {counts.length > 0 && (
- <span className="text-content-muted tabular-nums">{counts.join(' · ')}</span>
- )}
- </div>
- {aggregating && (
- <p data-testid="parallel-agents-aggregating" className="text-content-muted text-[12px]">
- {t('chat.subagents.settled')}
- </p>
- )}
- <SubagentList
- agents={agents}
- completedCount={completedCount}
- progress={progress}
- showSummary={anyRunning}
- summaryAgent={{ name: t('conversations.tools.parallelAgentsAggregating'), model: '' }}
- />
- <div className="flex flex-col gap-2">
- {children.map(entry =>
- entry.subagent ? <SubagentActivityCard key={entry.id} activity={entry.subagent} /> : null
- )}
- </div>
- </div>
- );
-};
-
-export default ParallelAgentsCard;
diff --git a/app/src/features/conversations/aui/__tests__/ParallelAgentsCard.test.tsx b/app/src/features/conversations/aui/__tests__/ParallelAgentsCard.test.tsx
deleted file mode 100644
index 8f5011357b..0000000000
--- a/app/src/features/conversations/aui/__tests__/ParallelAgentsCard.test.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { configureStore } from '@reduxjs/toolkit';
-import { render, screen } from '@testing-library/react';
-import type React from 'react';
-import { Provider } from 'react-redux';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { SubagentActivity, ToolTimelineEntry } from '../../../../store/chatRuntimeSlice';
-import { ParallelAgentsCard } from '../ParallelAgentsCard';
-
-const THREAD_ID = 'thread-1';
-const PARENT_CALL_ID = 'call-spawn-parallel';
-
-vi.mock('../../../../providers/AssistantUiRuntimeProvider', () => ({
- useAuiThreadId: () => THREAD_ID,
-}));
-
-function sub(partial: Partial<SubagentActivity> & { taskId: string }): SubagentActivity {
- return { agentId: 'researcher', toolCalls: [], parentCallId: PARENT_CALL_ID, ...partial };
-}
-
-function entry(
- id: string,
- status: ToolTimelineEntry['status'],
- subagent: SubagentActivity
-): ToolTimelineEntry {
- return { id, name: 'subagent:x', round: 0, seq: 0, status, subagent };
-}
-
-function buildStore(timeline: ToolTimelineEntry[]) {
- return configureStore({
- reducer: { chatRuntime: () => ({ toolTimelineByThread: { [THREAD_ID]: timeline } }) },
- });
-}
-
-function renderCard(timeline: ToolTimelineEntry[], toolCallId = PARENT_CALL_ID) {
- return render(
- <Provider store={buildStore(timeline)}>
- <ParallelAgentsCard
- {...({
- toolCallId,
- type: 'tool-call',
- toolName: 'spawn_parallel_agents',
- args: { tasks: [] },
- status: { type: 'running' },
- addResult: vi.fn(),
- resume: vi.fn(),
- respondToApproval: vi.fn(),
- } as unknown as React.ComponentProps<typeof ParallelAgentsCard>)}
- />
- </Provider>
- );
-}
-
-describe('ParallelAgentsCard', () => {
- it('renders nothing when no worker shares this call id', () => {
- const { container } = renderCard([
- entry('e1', 'running', sub({ taskId: 'sub-1', parentCallId: 'other-call' })),
- ]);
- expect(container.querySelector('[data-testid="assistant-ui-parallel-agents-call"]')).toBeNull();
- });
-
- it('renders the SubagentList + a TaskCard row per worker sharing parentCallId', () => {
- renderCard([
- entry(
- 'e1',
- 'running',
- sub({ taskId: 'sub-1', displayName: 'Researcher', status: 'running' })
- ),
- entry(
- 'e2',
- 'success',
- sub({ taskId: 'sub-2', displayName: 'Archivist', status: 'completed' })
- ),
- entry(
- 'e3',
- 'running',
- sub({ taskId: 'sub-3', parentCallId: 'other-call', displayName: 'Unrelated' })
- ),
- ]);
-
- expect(screen.getAllByText('Researcher').length).toBeGreaterThan(0);
- expect(screen.getAllByText('Archivist').length).toBeGreaterThan(0);
- expect(screen.queryByText('Unrelated')).toBeNull();
-
- const rows = screen.getAllByTestId('assistant-ui-subagent-call');
- expect(rows).toHaveLength(2);
- });
-
- it('shows the aggregating summary row while a worker is still active', () => {
- renderCard([entry('e1', 'running', sub({ taskId: 'sub-1', status: 'running' }))]);
- expect(screen.getByText('Aggregating results')).toBeInTheDocument();
- });
-});
diff --git a/app/src/services/api/worktreeApi.test.ts b/app/src/services/api/worktreeApi.test.ts
deleted file mode 100644
index 154ee8cce1..0000000000
--- a/app/src/services/api/worktreeApi.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { callCoreRpc } from '../coreRpcClient';
-import { worktreeApi } from './worktreeApi';
-
-vi.mock('../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
-
-const mockRpc = vi.mocked(callCoreRpc);
-
-describe('worktreeApi', () => {
- beforeEach(() => {
- mockRpc.mockReset();
- });
-
- it('list calls worktree_list and returns the view', async () => {
- const view = { worktrees: [], overlaps: [] };
- mockRpc.mockResolvedValueOnce(view);
- const out = await worktreeApi.list();
- expect(mockRpc).toHaveBeenCalledWith({ method: 'openhuman.worktree_list', params: {} });
- expect(out).toBe(view);
- });
-
- it('status forwards the path', async () => {
- const status = { path: '/r/.claude/worktrees/a', isDirty: false, changedFiles: [] };
- mockRpc.mockResolvedValueOnce(status);
- const out = await worktreeApi.status('/r/.claude/worktrees/a');
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.worktree_status',
- params: { path: '/r/.claude/worktrees/a' },
- });
- expect(out).toBe(status);
- });
-
- it('status rejects a blank path without calling RPC', async () => {
- await expect(worktreeApi.status(' ')).rejects.toThrow('path is required');
- expect(mockRpc).not.toHaveBeenCalled();
- });
-
- it('diff unwraps the summary string', async () => {
- mockRpc.mockResolvedValueOnce({ summary: ' src/a.rs | 2 +-' });
- const out = await worktreeApi.diff('/r/.claude/worktrees/a');
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.worktree_diff',
- params: { path: '/r/.claude/worktrees/a' },
- });
- expect(out).toBe(' src/a.rs | 2 +-');
- });
-
- it('remove defaults force to false and unwraps removed', async () => {
- mockRpc.mockResolvedValueOnce({ removed: true });
- const out = await worktreeApi.remove('/r/.claude/worktrees/a');
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.worktree_remove',
- params: { path: '/r/.claude/worktrees/a', force: false },
- });
- expect(out).toBe(true);
- });
-
- it('remove forwards force=true', async () => {
- mockRpc.mockResolvedValueOnce({ removed: true });
- await worktreeApi.remove('/r/.claude/worktrees/a', true);
- expect(mockRpc).toHaveBeenCalledWith({
- method: 'openhuman.worktree_remove',
- params: { path: '/r/.claude/worktrees/a', force: true },
- });
- });
-});
diff --git a/app/src/services/api/worktreeApi.ts b/app/src/services/api/worktreeApi.ts
deleted file mode 100644
index 246913e1ee..0000000000
--- a/app/src/services/api/worktreeApi.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Frontend client for the git-worktree manager (#3376) — the isolated worker
- * worktrees created by `spawn_parallel_agents` when a worker opts into
- * `isolation = "worktree"`.
- *
- * Wraps four read/cleanup RPCs under the `worktree` namespace:
- * - `openhuman.worktree_list` — managed worktrees + cross-worker overlaps.
- * - `openhuman.worktree_status` — branch / dirty / changed-files for one path.
- * - `openhuman.worktree_diff` — human-readable `--stat` diff for one path.
- * - `openhuman.worktree_remove` — remove a worktree (refuses dirty unless force).
- *
- * The wire payloads are already camelCase (the Rust `WorktreeStatus` serializes
- * with `#[serde(rename_all = "camelCase")]`), so this client only types the
- * shape — no snake/camel transform.
- */
-import debug from 'debug';
-
-import { callCoreRpc } from '../coreRpcClient';
-
-const log = debug('worktreeApi');
-
-/** Snapshot of a single worktree. Mirrors the Rust `WorktreeStatus`. */
-interface WorktreeStatus {
- /** Absolute path to the worktree checkout. */
- path: string;
- /** Checked-out branch (or `(detached HEAD)`), when resolvable. */
- branch?: string | null;
- /** Whether the worktree has uncommitted changes. */
- isDirty: boolean;
- /** Paths (relative to the worktree root) that differ from HEAD. */
- changedFiles: string[];
-}
-
-/** A file changed by more than one worker worktree (pre-merge conflict hint). */
-interface WorktreeOverlap {
- /** Relative path touched by multiple worktrees. */
- file: string;
- /** Branches (or path fallbacks) of the worktrees that touched it. */
- branches: string[];
-}
-
-/** Response from `openhuman.worktree_list`. */
-interface WorktreeListView {
- worktrees: WorktreeStatus[];
- overlaps: WorktreeOverlap[];
-}
-
-export const worktreeApi = {
- /** List managed worker worktrees plus cross-worktree file overlaps. */
- list: async (): Promise<WorktreeListView> => {
- log('list');
- const view = await callCoreRpc<WorktreeListView>({
- method: 'openhuman.worktree_list',
- params: {},
- });
- log('list received count=%d overlaps=%d', view.worktrees.length, view.overlaps.length);
- return view;
- },
-
- /** Fetch the branch / dirty / changed-files snapshot for one worktree. */
- status: async (path: string): Promise<WorktreeStatus> => {
- if (!path.trim()) throw new Error('worktreeApi.status: path is required');
- log('status path=%s', path);
- return callCoreRpc<WorktreeStatus>({ method: 'openhuman.worktree_status', params: { path } });
- },
-
- /** Fetch a human-readable `git diff HEAD --stat` (plus untracked files). */
- diff: async (path: string): Promise<string> => {
- if (!path.trim()) throw new Error('worktreeApi.diff: path is required');
- log('diff path=%s', path);
- const res = await callCoreRpc<{ summary: string }>({
- method: 'openhuman.worktree_diff',
- params: { path },
- });
- return res.summary;
- },
-
- /**
- * Remove a worktree checkout. The core refuses a dirty worktree unless
- * `force` is `true`, so a clean worktree removes silently while a dirty one
- * rejects (the caller surfaces a confirm prompt and retries with force).
- */
- remove: async (path: string, force = false): Promise<boolean> => {
- if (!path.trim()) throw new Error('worktreeApi.remove: path is required');
- log('remove path=%s force=%s', path, force);
- const res = await callCoreRpc<{ removed: boolean }>({
- method: 'openhuman.worktree_remove',
- params: { path, force },
- });
- return res.removed;
- },
-};
diff --git a/app/test/playwright/specs/assistant-ui-subagent-list.spec.ts b/app/test/playwright/specs/assistant-ui-subagent-list.spec.ts
deleted file mode 100644
index e29ac4058f..0000000000
--- a/app/test/playwright/specs/assistant-ui-subagent-list.spec.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- * `subagent-list` — the fan-out roster a parallel delegation renders.
- *
- * Family: `components/assistant-ui/elements/subagent-list.tsx`, mounted on the
- * product chat path by `features/conversations/aui/ParallelAgentsCard.tsx`,
- * which `aui/toolkit.tsx` registers for `spawn_parallel_agents`. Zero e2e
- * coverage before this spec.
- *
- * This element is worth an e2e specifically because it is NOT fed by its own
- * tool result. `ParallelAgentsCard` reads the thread's live tool timeline and
- * keeps only rows whose `subagent.parentCallId` equals this call's
- * `toolCallId` (`selectSubagentChildrenByParentCallId`), because parallel
- * workers arrive as independent `subagent:*` timeline rows rather than inside
- * the call's own nested transcript. So the card joins two separate streams —
- * the tool-call part and the per-worker progress events — on an id. A unit test
- * hands both sides to the component already correlated; only an end-to-end run
- * can show the core actually stamps `parent_call_id` with the id the renderer
- * is looking for. If that correlation breaks, `children.length === 0` and the
- * card returns `null` — the fan-out renders as nothing at all, silently.
- *
- * ⚠️ STATUS 2026-09-24: THIS SPEC DOES NOT PASS YET, and the failure is NOT
- * isolated. Observed: `assistant-ui-parallel-agents-call` never appeared within
- * 60s. That is all that is known. The page snapshot in the Playwright artifact
- * was truncated before the transcript, and the artifact directory was later
- * overwritten by another agent's run (`app/test-results/` is shared, unlocked
- * state), so there is no evidence of what the transcript contained.
- *
- * Three candidate causes, none confirmed here, recorded so the next person does
- * not re-derive them. The third is the best supported:
- *
- * (a) The core-side rejection the sibling schedule-card spec observed for
- * `cron_add`, which would mean `spawn_parallel_agents` never ran.
- * (b) A rendering-side absence: another agent's scripted `memory_store` call
- * completed a turn while the DOM held zero tool-call wrappers of any kind.
- * (c) **Socket events not reaching the browser on this lane.** This card's rows
- * come from `state.chatRuntime.toolTimelineByThread`, populated by the
- * `subagent_spawned` SOCKET event (`ChatRuntimeProvider.tsx:890-930`, whose
- * own comment calls it "this socket ... event"). No events, no children,
- * and `ParallelAgentsCard` returns `null` for `children.length === 0` —
- * exactly the observed symptom. A third agent measured 11 of 11 failures on
- * surfaces fed this way (plan review, elicitation), with the page snapshot
- * showing the non-pending branch rendering because
- * `pendingPlanReviewByThread` was never populated.
- *
- * Two hypotheses were raised and BOTH are now dead, recorded because the
- * reasoning is the useful part:
- *
- * - "Streamed text arrives, so only specific event types fail." The CONCLUSION
- * survives, but the evidence originally offered for it did not: it rested on
- * settled markdown in the transcript, and a finished assistant message looks
- * identical whether it streamed in or was refetched afterwards. The DOM does
- * not record how content arrived.
- * - "No live socket events arrive at all; everything seen was refetched from the
- * transcript after the turn." Measured and killed: `chat-thread-isolation`
- * passes 3/3, and its case 2 asserts a token visible WHILE the turn is still
- * streaming. Live `text_delta` demonstrably arrives on this lane.
- *
- * So streaming works. That makes this spec's failure HARDER to explain, not
- * easier, and rules out the tidy "one cause, four slices" story:
- * `subagent_spawned` is published by `web_chat/progress_bridge_subagent_events.rs`
- * (`on_subagent_spawned` -> `publish_seq_stamped`) — the progress bridge, the
- * same publisher as the streaming that works. It does NOT share a publisher with
- * `plan_review_request`, which is bridged separately by `ApprovalSurfaceSubscriber`
- * off the DomainEvent bus (`web_chat/event_bus.rs:41`, `:594-686`). A
- * plan-review-shaped explanation therefore does not transfer here, and these
- * should be filed as two findings with a noted resemblance rather than one.
- *
- * ⛔ UPSTREAM BREAKAGE, established by a CONTROL rather than by inference:
- * **tool calls do not render in the Playwright web lane on this branch.** The
- * pre-existing `test/playwright/specs/tool-call-presentation.spec.ts` (tracked,
- * last touched by `cd3806b19`, authored by nobody in this round) fails at
- * `expect(page.getByTestId('tool-timeline')).toBeVisible()` — and fails AFTER
- * its canary assertion passes, so the turn completed and the agent replied
- * while no tool call rendered.
- *
- * That control is sound on its own terms: its `beforeEach` boots the page
- * BEFORE the test body sets `llmForcedResponses`, so the ordered-queue hazard
- * (boot-time LLM requests eating queue entries) cannot apply to it, and the
- * canary rendering proves the scripted sequence was consumed by the intended
- * turn.
- *
- * It went unnoticed because that spec DOES run in ci-full's 64-shard sweep, but
- * the job carries `continue-on-error: true` and is excluded from the gate
- * (#3615) — a broken tool-render path fails there invisibly. Which is the
- * regression class a non-blocking lane is built to hide.
- *
- * Bisect window for that breakage, since the obvious suspects are innocent:
- * the control was restored by `cd3806b19` at 06:14 on 2026-09-24 and the
- * breakage was observed the same evening. Two commits on this branch SOUND like
- * the cause — `71d8874af` "handle missing toolkit in AUI conversation" and
- * `d5e81a916` "handle missing toolkit state on initial render" — and are not:
- * their complete diffs add this very `spawn_parallel_agents` toolkit entry and
- * its import, nothing else. Auto-generated subjects describing a fix that is not
- * in the diff. `7e1f5d90a` (18:12, desktop shell + chat chrome) touches
- * `thread.tsx` but its only tool/part change there is a comment. One entry in
- * the window was NOT examined at all: `58407ea53`, the 15:51 upstream merge.
- * That is a gap in the search, not a suspicion about the commit — it is
- * recorded so the next person knows which stone is unturned, and nothing here
- * should be read as nominating it.
- *
- * This supersedes the by-elimination reasoning that preceded it. `ParallelAgentsCard`
- * is a toolkit render ON a tool-call part, so if no tool call renders this card
- * cannot render regardless of whether `spawn_parallel_agents` ran, whether its
- * workers spawned, or whether `subagent_spawned` was delivered. The spec is
- * blocked upstream of everything it asserts.
- *
- * Deciding between them needs one run that captures the transcript. Copy the
- * artifact out of the tree before releasing the ci-slot: `e2e-web-session.sh`
- * wipes `test-results/` at start, its wrapper exits 0 even when tests fail, and
- * the directory is shared with every other agent's run.
- *
- * Two workers because the tool's own schema sets `minItems: 2` on `tasks`
- * (`spawn_parallel_agents_policy_tests.rs:11`); one task is not a valid call.
- */
-import { expect, type Page, test } from '@playwright/test';
-
-import { resetMock, sendTurn, setKeywordRules, startNewThread } from '../helpers/chat-drive';
-import { bootAuthenticatedPage, dismissWalkthroughIfPresent } from '../helpers/core-rpc';
-
-const USER_ID = 'pw-aui-subagent-list';
-
-const TRIGGER = 'PARALLEL-FANOUT please';
-
-/** `conversations.tools.parallelAgentsAggregating` (en.ts:3793). */
-const AGGREGATING = 'Aggregating results';
-
-const RULES = [
- {
- keyword: 'PARALLEL-FANOUT',
- toolCalls: [
- {
- name: 'spawn_parallel_agents',
- arguments: {
- tasks: [
- { agent_id: 'researcher', prompt: 'Summarise branch ALPHA and stop.' },
- { agent_id: 'researcher', prompt: 'Summarise branch BRAVO and stop.' },
- ],
- },
- },
- ],
- },
- // The workers themselves reach the same mock; keep their turns short so both
- // settle inside the spec's budget rather than streaming for its duration.
- { keyword: 'branch ALPHA', streamScript: [{ text: 'alpha done' }, { finish: 'stop' }] },
- { keyword: 'branch BRAVO', streamScript: [{ text: 'bravo done' }, { finish: 'stop' }] },
-];
-
-async function openChat(page: Page): Promise<void> {
- await bootAuthenticatedPage(page, USER_ID, '/chat');
- await dismissWalkthroughIfPresent(page);
- await expect(page.getByTestId('chat-message-input')).toBeVisible({ timeout: 30_000 });
-}
-
-test.beforeEach(async () => {
- await resetMock();
- await setKeywordRules(RULES);
-});
-
-test.describe('assistant-ui subagent list', () => {
- // `spawn_parallel_agents` was removed from the chat orchestrator's direct
- // tool belt; the supported path is async delegation. This legacy direct-call
- // contract remains as documentation until its replacement is landed.
- test.skip(true, 'legacy spawn_parallel_agents surface; async delegation is the supported path');
-
- test('a parallel fan-out renders both workers and settles when both finish', async ({ page }) => {
- test.setTimeout(120_000);
-
- await openChat(page);
- const threadId = await startNewThread(page);
-
- await sendTurn(page, threadId, TRIGGER);
-
- // The card renders at all only if `parentCallId` correlation succeeded —
- // `children.length === 0` returns null. So its presence is the join
- // assertion, not decoration.
- const card = page.getByTestId('assistant-ui-parallel-agents-call');
- await expect(card).toBeVisible({ timeout: 60_000 });
-
- // Terminal state, observed through the element's own logic rather than a
- // sleep: `showSummary={anyRunning}`, and `anyRunning` is
- // `completedCount < children.length`. The aggregating summary row is
- // present exactly while at least one worker is live and disappears when
- // the last one settles, so waiting for it to go is waiting for both
- // workers to reach a non-active status.
- await expect(card.getByText(AGGREGATING, { exact: false })).toHaveCount(0, { timeout: 90_000 });
-
- // One progressbar per worker (`subagent-list.tsx:66-67`), counted AFTER the
- // summary row has gone so the count is workers only — `showSummary` adds a
- // progressbar of its own (`:95-96`) and would otherwise inflate it.
- //
- // Counted rather than name-matched on purpose. The label is
- // `${agent.name} progress` where `name` is `displayName || agentId ||
- // 'sub-agent'`, so matching on "researcher" would bind this spec to which
- // of those three the core happened to populate. The count is the claim
- // anyway: exactly two, because a fan-out that correlated only its first
- // worker still renders a card and still looks plausible.
- await expect(card.getByRole('progressbar')).toHaveCount(2, { timeout: 30_000 });
- });
-});
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel.rs
deleted file mode 100644
index 6860762134..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel.rs
+++ /dev/null
@@ -1,44 +0,0 @@
-//! Host-side execution pipeline for `spawn_parallel_agents`.
-//!
-//! The tool wrapper still owns `ToolResult` translation. This module owns
-//! tool request parsing, parent-context validation,
-//! worktree preflight, progress/event projection, worker fanout, final JSON
-//! formatting, and the topology surface.
-//!
-//! **Write safety.** Whether a worker *needs* a claim on the shared workspace is
-//! an OpenHuman decision — it reads sandbox mode, tool permissions and the
-//! isolation request. Whether the claims of a whole batch can be granted
-//! together is not, and goes through
-//! [`plan_shared_workspace_dispatch`](tinyagents_graph::parallel::plan_shared_workspace_dispatch).
-//! The rejection sentences stay here, which is why the crate reports conflicts
-//! as data.
-//!
-//! ## Module layout
-//!
-//! - [`types`] — shared worker/result/lineage types.
-//! - [`staging`] — OpenHuman policy admission (an `AdmissionPolicy` over
-//! `tinyagents_orchestration::parallel::Plan`, which owns arbitration).
-//! - [`dispatch`] — worktree preflight and progress projection for the
-//! `dispatch` phase, turning admitted tasks into staged workers.
-//! - [`workers`] — single-worker execution; ordering, the serial fallback and
-//! bounded fan-out are `tinyagents_orchestration::parallel::run`.
-//! - [`collect`] — collecting fanned-out results into the tool's final shape.
-//! - [`run`] — the public entry points that tie the above together.
-
-mod collect;
-mod dispatch;
-mod run;
-mod staging;
-mod types;
-mod workers;
-
-pub(crate) use collect::{format_spawn_parallel_success, SpawnParallelGraphOutcome};
-pub(crate) use run::run_spawn_parallel_tasks_with_cancellation_and_workspace;
-pub(crate) use types::ParallelAgentTask;
-
-#[cfg(test)]
-pub(crate) use staging::{
- prepare_spawn_parallel_tasks_from_defs, ParallelTaskRejectionKind, SpawnParallelTaskPreflight,
-};
-#[cfg(test)]
-pub(crate) use types::{ParallelAgentLineage, ParallelAgentResult, ParallelAgentStatus};
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/collect.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/collect.rs
deleted file mode 100644
index 2e18f05e9a..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/collect.rs
+++ /dev/null
@@ -1,246 +0,0 @@
-//! Collecting fanned-out worker results into the tool's final shape: overlap
-//! detection, stale-parent-read annotation, progress projection for
-//! completed/failed workers, and the outcome enum the graph run resolves to.
-
-use serde_json::json;
-use tokio::sync::mpsc::Sender;
-
-use crate::progress::AgentProgress;
-use tinyagents_orchestration::parallel::{BranchReport, Collected};
-use tinytools_std::file_state;
-
-use super::types::{ParallelAgentResult, ParallelAgentStatus};
-
-pub(crate) type SpawnParallelCollected = Collected<ParallelAgentResult>;
-
-impl BranchReport for ParallelAgentResult {
- fn branch_id(&self) -> &str {
- &self.task_id
- }
- fn succeeded(&self) -> bool {
- self.success
- }
- fn changed_files(&self) -> &[String] {
- &self.changed_files
- }
-}
-
-pub(crate) enum SpawnParallelGraphOutcome {
- Collected(SpawnParallelCollected),
- Rejected(String),
- Cancelled(String),
-}
-
-pub(crate) fn collect_spawn_parallel_results(
- parent_session: &str,
- mut results: Vec<ParallelAgentResult>,
-) -> SpawnParallelCollected {
- annotate_stale_parent_reads(&mut results);
- let collected = Collected::new(results);
- if !collected.overlap_warnings.is_empty() {
- tracing::warn!(
- parent_session = %parent_session,
- overlap_count = collected.overlap_warnings.len(),
- "[spawn_parallel_agents] detected overlapping changed files across workers"
- );
- }
- collected
-}
-
-pub(crate) fn format_spawn_parallel_success(collected: &SpawnParallelCollected) -> String {
- serde_json::to_string_pretty(&json!({
- "parallel_agents": {
- "total": collected.total(),
- "succeeded": collected.succeeded(),
- "failed": collected.failures,
- "results": collected.results,
- "overlap_warnings": collected.overlap_warnings,
- }
- }))
- .unwrap_or_else(|_| "{}".to_string())
-}
-
-pub(crate) async fn project_spawn_parallel_result(
- parent_session: &str,
- progress_sink: Option<&Sender<AgentProgress>>,
- result: &ParallelAgentResult,
-) {
- match result.status {
- ParallelAgentStatus::Completed | ParallelAgentStatus::Incomplete => {
- let ParallelAgentResult {
- agent_id,
- task_id,
- elapsed_ms,
- iterations,
- output,
- worktree_path,
- changed_files,
- dirty_status,
- emit_lifecycle_effects,
- error,
- ..
- } = result;
- if !emit_lifecycle_effects {
- return;
- }
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %agent_id,
- elapsed_ms = *elapsed_ms,
- iterations = *iterations,
- "[spawn_parallel_agents] publishing_subagent_completed"
- );
- crate::agent::orchestration::subagent_events::publish_subagent_completed(
- parent_session.to_string(),
- task_id.clone(),
- agent_id.clone(),
- *elapsed_ms,
- output.as_ref().map(|s| s.chars().count()).unwrap_or(0),
- *iterations as usize,
- );
- if let Some(tx) = progress_sink {
- if let Err(err) = tx
- .send(AgentProgress::SubagentCompleted {
- agent_id: agent_id.clone(),
- task_id: task_id.clone(),
- elapsed_ms: *elapsed_ms,
- iterations: *iterations,
- output_chars: output.as_ref().map(|s| s.chars().count()).unwrap_or(0),
- output: output.clone().unwrap_or_default(),
- // Rebuilt from an already-observed event, which carries no
- // usage to copy — so this path stays silent. See the field's docs.
- usage: None,
- worktree_path: worktree_path.clone(),
- changed_files: changed_files.clone(),
- dirty_status: *dirty_status,
- // An incomplete worker was stopped early (breaker /
- // cap); its span closes at WARNING with that stop.
- stop: matches!(result.status, ParallelAgentStatus::Incomplete).then(|| {
- crate::agent::session_host::stop_summary::stop_from_incomplete_with_cause(
- error.as_deref().unwrap_or(""),
- result.failure_cause.clone(),
- )
- }),
- })
- .await
- {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %agent_id,
- error = %err,
- "[spawn_parallel_agents] progress_send_failed completed"
- );
- }
- }
- }
- ParallelAgentStatus::AwaitingUser => {
- let ParallelAgentResult {
- agent_id,
- task_id,
- awaiting_question,
- checkpoint_path,
- emit_lifecycle_effects,
- ..
- } = result;
- if !emit_lifecycle_effects {
- return;
- }
- let question = awaiting_question
- .clone()
- .unwrap_or_else(|| "parallel subagent needs input".into());
- crate::agent::orchestration::subagent_events::publish_subagent_awaiting_user(
- parent_session.to_string(),
- task_id.clone(),
- agent_id.clone(),
- question.clone(),
- );
- if let Some(tx) = progress_sink {
- if let Err(err) = tx
- .send(AgentProgress::SubagentAwaitingUser {
- agent_id: agent_id.clone(),
- task_id: task_id.clone(),
- question,
- worker_thread_id: None,
- checkpoint_path: checkpoint_path.clone(),
- })
- .await
- {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %agent_id,
- error = %err,
- "[spawn_parallel_agents] progress_send_failed awaiting_user"
- );
- }
- }
- }
- ParallelAgentStatus::Cancelled | ParallelAgentStatus::Failed => {
- let ParallelAgentResult {
- agent_id,
- task_id,
- error,
- emit_lifecycle_effects,
- ..
- } = result;
- if !emit_lifecycle_effects && matches!(result.status, ParallelAgentStatus::Cancelled) {
- return;
- }
- let message = error
- .clone()
- .unwrap_or_else(|| "unknown failure".to_string());
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %agent_id,
- error = %message,
- "[spawn_parallel_agents] publishing_subagent_failed"
- );
- crate::agent::orchestration::subagent_events::publish_subagent_failed(
- parent_session.to_string(),
- task_id.clone(),
- agent_id.clone(),
- message.clone(),
- );
- if let Some(tx) = progress_sink {
- if let Err(err) = tx
- .send(AgentProgress::SubagentFailed {
- agent_id: agent_id.clone(),
- task_id: task_id.clone(),
- error: message,
- })
- .await
- {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %agent_id,
- error = %err,
- "[spawn_parallel_agents] progress_send_failed failed"
- );
- }
- }
- }
- }
-}
-
-fn annotate_stale_parent_reads(results: &mut [ParallelAgentResult]) {
- if let Some(parent_agent_id) = file_state::current_file_state_agent_id() {
- let child_ids: Vec<String> = results.iter().map(|r| r.task_id.clone()).collect();
- let stale = file_state::parent_stale_files(&parent_agent_id, &child_ids);
- if !stale.is_empty() {
- let stale_strings: Vec<String> =
- stale.iter().map(|p| p.display().to_string()).collect();
- tracing::debug!(
- parent = %parent_agent_id,
- stale_count = stale.len(),
- "[file_state] parent reads stale after child writes"
- );
- for result in results {
- result.stale_parent_reads = stale_strings.clone();
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/dispatch.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/dispatch.rs
deleted file mode 100644
index 5e28287872..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/dispatch.rs
+++ /dev/null
@@ -1,352 +0,0 @@
-//! Staging admitted tasks into live [`SpawnParallelWorker`] values: worktree
-//! preflight for isolated workers, lineage stamping, and the
-//! `subagent_spawned` progress/event projection for the `dispatch` phase.
-
-use std::collections::HashMap;
-use std::path::Path;
-
-use tinyagents_harness::workspace::WorkspaceIsolation;
-use tinyagents_orchestration::parallel::Worker;
-use tinyagents_orchestration::parallel::WorkerDispatchMode;
-use tinytools::WorkspaceDescriptor;
-use tokio::sync::mpsc::Sender;
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::worktree;
-use crate::agent_registry::host_definition::AgentDefinition;
-use crate::progress::AgentProgress;
-use tinyagents_definition::SandboxMode;
-
-use super::staging::{
- prepare_spawn_parallel_tasks_from_defs, worktree_request_for_task, ParallelTaskRejectionKind,
- ParallelWorktreeRequest, SpawnParallelTaskPreflight,
-};
-use super::types::{
- ParallelAgentLineage, ParallelAgentResult, ParallelAgentStatus, ParallelAgentTask,
- SpawnParallelWorker,
-};
-
-pub(crate) fn spawn_parallel_lineage(
- parent_session: &str,
- session_parent_prefix: Option<&str>,
- task_id: &str,
-) -> ParallelAgentLineage {
- let root_session = session_parent_prefix
- .and_then(|prefix| prefix.split("__").next())
- .filter(|root| !root.is_empty())
- .unwrap_or(parent_session);
- ParallelAgentLineage {
- parent_session: parent_session.to_string(),
- root_session: root_session.to_string(),
- child_task_id: task_id.to_string(),
- }
-}
-
-async fn create_spawn_parallel_worktree(
- parent_session: &str,
- action_root: Option<&Path>,
- task_id: &str,
- definition: &AgentDefinition,
- task: &ParallelAgentTask,
- session_parent_prefix: Option<&str>,
-) -> Result<Option<WorkspaceDescriptor>, ParallelAgentResult> {
- match worktree_request_for_task(task) {
- ParallelWorktreeRequest::SharedWorkspace => Ok(None),
- ParallelWorktreeRequest::Isolated { base_ref } => match action_root {
- Some(repo_root) => {
- let sandbox = match definition.sandbox_mode {
- SandboxMode::Sandboxed => tinytools::SandboxMode::Required,
- SandboxMode::None | SandboxMode::ReadOnly => tinytools::SandboxMode::Inherit,
- };
- let isolation = worktree::OpenHumanWorktreeIsolation::new(repo_root)
- .with_base_ref(base_ref)
- .with_sandbox(sandbox);
- match isolation.prepare(task_id, Some(&definition.id)).await {
- Ok(descriptor) => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- worktree = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- base_ref = base_ref.as_str(),
- "[spawn_parallel_agents] prepared isolated workspace descriptor"
- );
- Ok(Some(descriptor))
- }
- Err(err) => {
- tracing::warn!(
- parent_session = %parent_session,
- task_id = %task_id,
- error = %err,
- "[spawn_parallel_agents] workspace_prepare_failed"
- );
- Err(ParallelAgentResult {
- task_id: task_id.to_string(),
- agent_id: definition.id.clone(),
- lineage: spawn_parallel_lineage(
- parent_session,
- session_parent_prefix,
- task_id,
- ),
- success: false,
- status: ParallelAgentStatus::Failed,
- output: None,
- error: Some(format!("worktree isolation failed: {err}")),
- failure_cause: None,
- awaiting_question: None,
- checkpoint_path: None,
- ownership: task.ownership.clone(),
- elapsed_ms: 0,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- emit_lifecycle_effects: false,
- })
- }
- }
- }
- None => {
- tracing::warn!(
- parent_session = %parent_session,
- task_id = %task_id,
- "[spawn_parallel_agents] worktree_requested_but_no_action_dir"
- );
- Err(ParallelAgentResult {
- task_id: task_id.to_string(),
- agent_id: definition.id.clone(),
- lineage: spawn_parallel_lineage(parent_session, session_parent_prefix, task_id),
- success: false,
- status: ParallelAgentStatus::Failed,
- output: None,
- error: Some(
- "worktree isolation requested but action_dir is unavailable".to_string(),
- ),
- failure_cause: None,
- awaiting_question: None,
- checkpoint_path: None,
- ownership: task.ownership.clone(),
- elapsed_ms: 0,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- emit_lifecycle_effects: false,
- })
- }
- },
- }
-}
-
-pub(crate) async fn stage_spawn_parallel_workers_from_defs(
- parent_session: &str,
- progress_sink: Option<&Sender<AgentProgress>>,
- tasks: Vec<ParallelAgentTask>,
- definitions: &HashMap<String, AgentDefinition>,
- parent: &ParentExecutionContext,
- action_root: Option<&Path>,
- parent_workspace_descriptor: Option<&WorkspaceDescriptor>,
- parent_call_id: Option<&str>,
-) -> (Vec<Worker<SpawnParallelWorker>>, Vec<ParallelAgentResult>) {
- let mut immediate_results = Vec::new();
- let mut prepared = Vec::new();
-
- for preflight in prepare_spawn_parallel_tasks_from_defs(tasks, definitions, parent).await {
- let (definition, prompt, task, task_id, dispatch_mode) = match preflight {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- match rejection.kind {
- ParallelTaskRejectionKind::MissingAgentOrPrompt => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- "[spawn_parallel_agents] invalid_task_missing_agent_or_prompt"
- );
- }
- ParallelTaskRejectionKind::UnknownAgent => {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- "[spawn_parallel_agents] invalid_task_unknown_agent"
- );
- }
- ParallelTaskRejectionKind::OutsideAllowlist => {
- tracing::warn!(
- parent_session = %parent_session,
- parent_agent = %parent.agent_definition_id,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- allowed = ?parent.allowed_subagent_ids,
- "[spawn_parallel_agents] rejected_task_outside_subagent_allowlist"
- );
- }
- ParallelTaskRejectionKind::RequiresIsolation => {
- tracing::warn!(
- parent_session = %parent_session,
- task_id = %rejection.task_id,
- agent_id = %rejection.agent_id,
- ownership = rejection.ownership.as_deref().unwrap_or(""),
- "[spawn_parallel_agents] rejected_shared_workspace_write_capable_task"
- );
- }
- }
- let lineage = spawn_parallel_lineage(
- parent_session,
- parent.session_parent_prefix.as_deref(),
- &rejection.task_id,
- );
- immediate_results.push(ParallelAgentResult {
- task_id: rejection.task_id,
- agent_id: rejection.agent_id,
- lineage,
- success: false,
- status: ParallelAgentStatus::Failed,
- output: None,
- error: Some(rejection.error),
- failure_cause: None,
- awaiting_question: None,
- checkpoint_path: None,
- ownership: rejection.ownership,
- elapsed_ms: 0,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- emit_lifecycle_effects: false,
- });
- continue;
- }
- SpawnParallelTaskPreflight::Prepared(prepared_task) => (
- prepared_task.definition,
- prepared_task.prompt,
- prepared_task.task,
- prepared_task.task_id,
- prepared_task.dispatch_mode,
- ),
- };
- project_spawn_parallel_spawned(
- parent_session,
- progress_sink,
- &definition,
- &task_id,
- &prompt,
- task.ownership
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .is_some(),
- parent_call_id,
- )
- .await;
- let workspace_descriptor = match create_spawn_parallel_worktree(
- parent_session,
- action_root,
- &task_id,
- &definition,
- &task,
- parent.session_parent_prefix.as_deref(),
- )
- .await
- {
- Ok(descriptor) => descriptor,
- Err(result) => {
- immediate_results.push(result);
- continue;
- }
- };
- let worktree_path = workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone());
- let worker_workspace_descriptor = workspace_descriptor
- .clone()
- .or_else(|| parent_workspace_descriptor.cloned());
- let lineage = spawn_parallel_lineage(
- parent_session,
- parent.session_parent_prefix.as_deref(),
- &task_id,
- );
- prepared.push(Worker {
- id: task_id,
- prompt,
- ownership: task.ownership.clone(),
- payload: SpawnParallelWorker {
- definition,
- task,
- lineage,
- worktree_path,
- workspace_descriptor: worker_workspace_descriptor,
- },
- dispatch_mode,
- });
- }
-
- tracing::debug!(
- parent_session = %parent_session,
- prepared_count = prepared.len(),
- immediate_count = immediate_results.len(),
- serial_write_count = prepared
- .iter()
- .filter(|worker| matches!(
- worker.dispatch_mode,
- WorkerDispatchMode::SerialSharedWorkspaceWrite
- ))
- .count(),
- "[spawn_parallel_agents] prepared_tasks"
- );
- (prepared, immediate_results)
-}
-
-async fn project_spawn_parallel_spawned(
- parent_session: &str,
- progress_sink: Option<&Sender<AgentProgress>>,
- definition: &AgentDefinition,
- task_id: &str,
- prompt: &str,
- has_ownership: bool,
- parent_call_id: Option<&str>,
-) {
- let prompt_chars = prompt.chars().count();
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %definition.id,
- prompt_chars,
- has_ownership,
- "[spawn_parallel_agents] publishing_subagent_spawned"
- );
- crate::agent::orchestration::subagent_events::publish_subagent_spawned(
- parent_session.to_string(),
- definition.id.clone(),
- "typed".to_string(),
- task_id.to_string(),
- prompt_chars,
- );
- if let Some(tx) = progress_sink {
- if let Err(err) = tx
- .send(AgentProgress::SubagentSpawned {
- agent_id: definition.id.clone(),
- task_id: task_id.to_string(),
- mode: "typed".to_string(),
- dedicated_thread: false,
- prompt_chars,
- prompt: prompt.to_string(),
- worker_thread_id: None,
- display_name: Some(definition.display_name().to_string()),
- parent_call_id: parent_call_id.map(str::to_string),
- })
- .await
- {
- tracing::debug!(
- parent_session = %parent_session,
- task_id = %task_id,
- agent_id = %definition.id,
- error = %err,
- "[spawn_parallel_agents] progress_send_failed spawned"
- );
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/run.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/run.rs
deleted file mode 100644
index 3fe8077b94..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/run.rs
+++ /dev/null
@@ -1,196 +0,0 @@
-//! Host-side execution of an already-decoded `spawn_parallel_agents` batch.
-//!
-//! The fixed phase graph formerly here duplicated the graph crate's bounded
-//! fanout facility while capturing OpenHuman-only policy, progress, and
-//! execution adapters in every node. The tool now decodes its JSON contract;
-//! this module runs the host stages directly and delegates concurrent work to
-//! [`tinyagents_graph::parallel::map_reduce`] in `workers`.
-
-use std::path::PathBuf;
-
-use tinyagents_harness::CancellationToken;
-use tinytools::WorkspaceDescriptor;
-
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-
-use super::collect::{
- collect_spawn_parallel_results, project_spawn_parallel_result, SpawnParallelGraphOutcome,
-};
-use super::dispatch::stage_spawn_parallel_workers_from_defs;
-use super::staging::snapshot_agent_definitions;
-use super::types::ParallelAgentTask;
-use super::workers::run_spawn_parallel_workers;
-
-pub(crate) async fn run_spawn_parallel_tasks_with_cancellation_and_workspace(
- tasks: Vec<ParallelAgentTask>,
- cancel: CancellationToken,
- parent_workspace_descriptor: Option<WorkspaceDescriptor>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: &tinyagents_harness::context::RunContext<
- crate::agent::tinyagents::host::OpenHumanRunContext,
- >,
- parent_call_id: Option<String>,
-) -> Result<SpawnParallelGraphOutcome, String> {
- let parent = match run_context.parent.clone() {
- Some(parent) => parent,
- None => {
- tracing::debug!("[spawn_parallel_agents] rejected_outside_agent_turn");
- return Ok(SpawnParallelGraphOutcome::Rejected(
- "spawn_parallel_agents called outside of an agent turn".to_string(),
- ));
- }
- };
- let max_parallel = parent.agent_config.max_parallel_tools.max(2);
- tracing::debug!(
- parent_session = %parent.session_id,
- task_count = tasks.len(),
- max_parallel,
- "[spawn_parallel_agents] validated_parent_context"
- );
- let registry = match AgentDefinitionRegistry::current() {
- Some(registry) => registry,
- None => {
- tracing::debug!("[spawn_parallel_agents] registry_unavailable");
- return Ok(SpawnParallelGraphOutcome::Rejected(
- "spawn_parallel_agents: AgentDefinitionRegistry has not been initialised"
- .to_string(),
- ));
- }
- };
-
- let parent_session = parent.session_id.clone();
- let progress_sink = parent.on_progress.clone();
- let action_root =
- resolve_spawn_parallel_action_root(parent_workspace_descriptor.as_ref()).await;
- let definitions = snapshot_agent_definitions(&registry);
- if cancel.is_cancelled() {
- return Ok(SpawnParallelGraphOutcome::Cancelled(
- "spawn_parallel_agents cancelled at validate".to_string(),
- ));
- }
- if tasks.len() > max_parallel {
- return Ok(SpawnParallelGraphOutcome::Rejected(format!(
- "spawn_parallel_agents received {} tasks but max_parallel_tools is {}",
- tasks.len(),
- max_parallel
- )));
- }
- if cancel.is_cancelled() {
- return Ok(SpawnParallelGraphOutcome::Cancelled(
- "spawn_parallel_agents cancelled at dispatch".to_string(),
- ));
- }
- let (prepared, immediate_results) = stage_spawn_parallel_workers_from_defs(
- &parent_session,
- progress_sink.as_ref(),
- tasks,
- &definitions,
- &parent,
- action_root.as_deref(),
- parent_workspace_descriptor.as_ref(),
- parent_call_id.as_deref(),
- )
- .await;
- if cancel.is_cancelled() {
- return Ok(SpawnParallelGraphOutcome::Cancelled(
- "spawn_parallel_agents cancelled at worker".to_string(),
- ));
- }
- let fanned = match run_spawn_parallel_workers(
- prepared,
- action_root,
- cancel.clone(),
- run_context,
- live_parent,
- )
- .await
- {
- Ok(fanned) => fanned,
- Err(tinyagents_harness::TinyAgentsError::Cancelled) => {
- return Ok(SpawnParallelGraphOutcome::Cancelled(
- "spawn_parallel_agents cancelled at worker".to_string(),
- ));
- }
- Err(err) => return Err(err.to_string()),
- };
- if cancel.is_cancelled() {
- return Ok(SpawnParallelGraphOutcome::Cancelled(
- "spawn_parallel_agents cancelled at collect".to_string(),
- ));
- }
- let mut results = immediate_results;
- for result in fanned {
- project_spawn_parallel_result(&parent_session, progress_sink.as_ref(), &result).await;
- results.push(result);
- }
- if cancel.is_cancelled() {
- return Ok(SpawnParallelGraphOutcome::Cancelled(
- "spawn_parallel_agents cancelled at finalize".to_string(),
- ));
- }
- let outcome = SpawnParallelGraphOutcome::Collected(collect_spawn_parallel_results(
- &parent_session,
- results,
- ));
- match &outcome {
- SpawnParallelGraphOutcome::Collected(collected) => {
- tracing::debug!(
- parent_session = %parent_session,
- total = collected.total(),
- succeeded = collected.succeeded(),
- failed = collected.failures,
- overlaps = collected.overlap_warnings.len(),
- "[spawn_parallel_agents] execute exit"
- );
- }
- SpawnParallelGraphOutcome::Rejected(message) => {
- tracing::debug!(
- parent_session = %parent_session,
- error = %message,
- "[spawn_parallel_agents] rejected_by_graph_validate"
- );
- }
- SpawnParallelGraphOutcome::Cancelled(message) => {
- tracing::debug!(
- parent_session = %parent_session,
- message = %message,
- "[spawn_parallel_agents] cancelled_by_graph"
- );
- }
- }
- Ok(outcome)
-}
-
-/// Resolve the agent sandbox root once for the graph run.
-///
-/// This is `Config.action_dir` (the user's project repo the coding agent edits),
-/// NOT OpenHuman's own tree. It is only consulted when a worker asks for
-/// git-worktree isolation; failures preserve the previous `None` fallback.
-async fn resolve_spawn_parallel_action_root(
- parent_workspace_descriptor: Option<&WorkspaceDescriptor>,
-) -> Option<PathBuf> {
- if let Some(descriptor) = parent_workspace_descriptor {
- tracing::debug!(
- action_root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[spawn_parallel_agents] using ToolExecutionContext workspace root for graph"
- );
- return Some(descriptor.root.clone());
- }
- match crate::config::Config::load_or_init().await {
- Ok(config) => {
- tracing::debug!(
- action_root = %config.action_dir.display(),
- "[spawn_parallel_agents] resolved action root for graph"
- );
- Some(config.action_dir.clone())
- }
- Err(err) => {
- tracing::debug!(
- error = %err,
- "[spawn_parallel_agents] config load failed; worktree isolation will use missing-root fallback"
- );
- None
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/staging.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/staging.rs
deleted file mode 100644
index 910385706c..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/staging.rs
+++ /dev/null
@@ -1,409 +0,0 @@
-//! OpenHuman policy admission for a `spawn_parallel_agents` task batch:
-//! identity, the parent's subagent allowlist, and whether a worker can write
-//! the shared workspace at all — plus the crate-side arbitration over the resulting workspace claims.
-//!
-//! **Write safety.** Whether a worker *needs* a claim on the shared workspace is
-//! an OpenHuman decision — it reads sandbox mode, tool permissions and the
-//! isolation request. Whether the claims of a whole batch can be granted
-//! together is not, and goes through
-//! [`plan_shared_workspace_dispatch`](tinyagents_graph::parallel::plan_shared_workspace_dispatch).
-//! The rejection sentences stay here, which is why the crate reports conflicts
-//! as data.
-//!
-//! The host resolves definitions and normalizes prompts in the owner's async
-//! `Plan::stage_with_preflight` seam. That preparation has no external side
-//! effects: policy admission and whole-batch workspace arbitration finish
-//! before dispatch creates worktrees or emits spawn progress/events.
-
-use std::collections::HashMap;
-use std::path::PathBuf;
-
-use parking_lot::Mutex;
-
-use tinyagents_graph::parallel::{parse_relative_claim_paths, ClaimConflict, ClaimPathError};
-use tinyagents_orchestration::parallel::WorkerDispatchMode;
-use tinyagents_orchestration::parallel::{
- AdmissionPolicy, AdmissionVerdict, Plan, Preflight, Rejection, RejectionKind, Task,
-};
-
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent_registry::host_definition::{AgentDefinition, AgentDefinitionRegistry};
-use tinyagents_definition::{SandboxMode, ToolScope};
-use tinyagents_harness::workspace::GitWorktreeBaseRef;
-use tinytools::PermissionLevel;
-
-use super::types::ParallelAgentTask;
-
-/// Prepared worker ready for the live dispatch/worker phases.
-pub(crate) struct PreparedParallelTask {
- pub(crate) definition: AgentDefinition,
- pub(crate) prompt: String,
- pub(crate) task: ParallelAgentTask,
- pub(crate) task_id: String,
- pub(crate) dispatch_mode: WorkerDispatchMode,
-}
-
-impl PreparedParallelTask {
- /// How this worker will be dispatched relative to its siblings.
- ///
- /// Exposed so the write-safety decision can be asserted directly: it is the
- /// one property of a preflight whose regression corrupts a shared checkout
- /// silently rather than failing a run.
- pub(crate) fn dispatch_mode(&self) -> WorkerDispatchMode {
- self.dispatch_mode
- }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum ParallelTaskRejectionKind {
- MissingAgentOrPrompt,
- UnknownAgent,
- OutsideAllowlist,
- RequiresIsolation,
-}
-
-pub(crate) struct ParallelTaskRejection {
- pub(crate) task_id: String,
- pub(crate) agent_id: String,
- pub(crate) error: String,
- pub(crate) ownership: Option<String>,
- pub(crate) kind: ParallelTaskRejectionKind,
-}
-
-pub(crate) enum SpawnParallelTaskPreflight {
- Prepared(PreparedParallelTask),
- Rejected(ParallelTaskRejection),
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum ParallelWorktreeRequest {
- SharedWorkspace,
- Isolated { base_ref: GitWorktreeBaseRef },
-}
-
-pub(crate) fn worktree_request_for_task(task: &ParallelAgentTask) -> ParallelWorktreeRequest {
- let isolated = task
- .isolation
- .as_deref()
- .map(str::trim)
- .map(|s| s.eq_ignore_ascii_case("worktree"))
- .unwrap_or(false);
- if isolated {
- ParallelWorktreeRequest::Isolated {
- base_ref: GitWorktreeBaseRef::parse(task.base_ref.as_deref()),
- }
- } else {
- ParallelWorktreeRequest::SharedWorkspace
- }
-}
-
-fn definition_visible_tool_permissions(
- definition: &AgentDefinition,
- parent: &ParentExecutionContext,
-) -> Vec<(String, PermissionLevel)> {
- let skill_prefix = definition
- .skill_filter
- .as_ref()
- .map(|skill| format!("{skill}__"));
- parent
- .all_tools
- .iter()
- .filter_map(|tool| {
- let name = tool.name();
- if crate::tools::rules::glob_list_matches(&definition.disallowed_tools, name) {
- return None;
- }
- if let Some(prefix) = skill_prefix.as_deref() {
- if !name.starts_with(prefix) {
- return None;
- }
- }
- let allowed = match &definition.tools {
- ToolScope::Wildcard => true,
- ToolScope::Named(names) => {
- names.iter().any(|allowed| allowed == name)
- || definition.extra_tools.iter().any(|extra| extra == name)
- || (crate::inference::tokenjuice::is_recovery_tool(name)
- && !names.is_empty())
- }
- };
- allowed.then(|| (name.to_string(), tool.permission_level()))
- })
- .collect()
-}
-
-fn shared_workspace_write_capable_tools(
- definition: &AgentDefinition,
- parent: &ParentExecutionContext,
-) -> Vec<String> {
- let mut write_capable_tools = definition_visible_tool_permissions(definition, parent)
- .into_iter()
- .filter(|(_, level)| *level > PermissionLevel::ReadOnly)
- .map(|(name, level)| format!("{name}:{level}"))
- .collect::<Vec<_>>();
- write_capable_tools.sort();
- write_capable_tools.dedup();
- write_capable_tools
-}
-
-fn shared_workspace_write_preview(write_capable_tools: &[String]) -> String {
- let preview = write_capable_tools
- .iter()
- .take(6)
- .cloned()
- .collect::<Vec<_>>()
- .join(", ");
- let suffix = if write_capable_tools.len() > 6 {
- format!(", +{} more", write_capable_tools.len() - 6)
- } else {
- String::new()
- };
- format!("{preview}{suffix}")
-}
-
-/// Parse OpenHuman's `files: a.rs, b.rs` ownership syntax into claimed paths.
-///
-/// The `files:` prefix is this tool's parameter shape, so it is stripped here;
-/// validating what follows is generic and belongs to
-/// [`parse_relative_claim_paths`]. Its typed rejection is rendered into the
-/// sentence the model reads at this boundary, which is why the crate returns
-/// data rather than a message.
-fn ownership_file_paths(ownership: Option<&str>) -> Result<Vec<PathBuf>, String> {
- let Some(ownership) = ownership.map(str::trim).filter(|s| !s.is_empty()) else {
- return Ok(Vec::new());
- };
- let Some(rest) = ownership.strip_prefix("files:") else {
- return Ok(Vec::new());
- };
- parse_relative_claim_paths(rest).map_err(|err| {
- let raw = match &err {
- ClaimPathError::Absolute { raw } | ClaimPathError::Escaping { raw } => raw,
- };
- format!("ownership path '{raw}' must be a relative file path under the workspace")
- })
-}
-
-fn shared_workspace_write_claim(
- task: &ParallelAgentTask,
- definition: &AgentDefinition,
- parent: &ParentExecutionContext,
-) -> Result<Option<Vec<PathBuf>>, String> {
- if matches!(
- worktree_request_for_task(task),
- ParallelWorktreeRequest::Isolated { .. }
- ) {
- return Ok(None);
- }
- if matches!(definition.sandbox_mode, SandboxMode::ReadOnly) {
- return Ok(None);
- }
- let write_capable_tools = shared_workspace_write_capable_tools(definition, parent);
- if write_capable_tools.is_empty() {
- return Ok(None);
- }
- let paths = ownership_file_paths(task.ownership.as_deref())?;
- if paths.is_empty() {
- return Err(format!(
- "agent '{}' can use write/execute tools in the shared workspace ({}); \
- set isolation=\"worktree\" for edit-capable parallel workers, use a read-only agent, \
- or provide disjoint files: ownership for serial fallback",
- definition.id,
- shared_workspace_write_preview(&write_capable_tools)
- ));
- }
- Ok(Some(paths))
-}
-
-pub(crate) fn snapshot_agent_definitions(
- registry: &AgentDefinitionRegistry,
-) -> HashMap<String, AgentDefinition> {
- registry
- .list()
- .into_iter()
- .map(|definition| (definition.id.clone(), definition.clone()))
- .collect()
-}
-
-/// Host payload carried through the module's [`Plan`]: the decoded request and,
-/// once the agent id resolved, its definition.
-#[derive(Clone)]
-struct AdmitPayload {
- task: ParallelAgentTask,
- /// Trimmed requested id, or the resolved definition id.
- agent_id: String,
- definition: Option<AgentDefinition>,
-}
-
-/// OpenHuman policy over the module's admission seam: identity, the parent's
-/// subagent allowlist, and whether a worker can write the shared workspace at
-/// all. The module owns arbitration and prompt framing.
-struct SpawnParallelPolicy<'a> {
- parent: &'a ParentExecutionContext,
- /// Rejection kind per input index (the module carries only the sentence).
- kinds: Mutex<HashMap<usize, ParallelTaskRejectionKind>>,
-}
-
-impl SpawnParallelPolicy<'_> {
- fn reject(
- &self,
- index: usize,
- kind: ParallelTaskRejectionKind,
- message: String,
- ) -> AdmissionVerdict {
- self.kinds.lock().insert(index, kind);
- AdmissionVerdict::Reject(message)
- }
-}
-
-impl AdmissionPolicy<AdmitPayload> for SpawnParallelPolicy<'_> {
- fn admit(&self, index: usize, task: &Task<AdmitPayload>) -> AdmissionVerdict {
- let payload = &task.payload;
- if payload.agent_id.is_empty() || task.prompt.is_empty() {
- return self.reject(
- index,
- ParallelTaskRejectionKind::MissingAgentOrPrompt,
- "agent_id and prompt are required".to_string(),
- );
- }
- let Some(definition) = payload.definition.as_ref() else {
- return self.reject(
- index,
- ParallelTaskRejectionKind::UnknownAgent,
- format!("unknown agent_id '{}'", payload.agent_id),
- );
- };
- if !self.parent.allowed_subagent_ids.contains(&definition.id) {
- return self.reject(
- index,
- ParallelTaskRejectionKind::OutsideAllowlist,
- format!(
- "agent '{}' is not in parent agent '{}' subagents.allowlist",
- definition.id, self.parent.agent_definition_id
- ),
- );
- }
- match shared_workspace_write_claim(&payload.task, definition, self.parent) {
- Ok(Some(paths)) => AdmissionVerdict::Writes(paths),
- Ok(None) => {
- if matches!(
- worktree_request_for_task(&payload.task),
- ParallelWorktreeRequest::Isolated { .. }
- ) {
- AdmissionVerdict::Isolated
- } else {
- AdmissionVerdict::ReadOnly
- }
- }
- Err(error) => self.reject(index, ParallelTaskRejectionKind::RequiresIsolation, error),
- }
- }
-}
-
-pub(crate) async fn prepare_spawn_parallel_tasks_from_defs(
- tasks: Vec<ParallelAgentTask>,
- definitions: &HashMap<String, AgentDefinition>,
- parent: &ParentExecutionContext,
-) -> Vec<SpawnParallelTaskPreflight> {
- let plan = Plan::new(
- tasks
- .into_iter()
- .map(|task| {
- let requested = task.agent_id.trim().to_string();
- Task {
- id: format!("sub-{}", uuid::Uuid::new_v4()),
- prompt: task.prompt.clone(),
- ownership: task.ownership.clone(),
- payload: AdmitPayload {
- agent_id: requested,
- definition: None,
- task,
- },
- }
- })
- .collect(),
- );
- let policy = SpawnParallelPolicy {
- parent,
- kinds: Mutex::new(HashMap::new()),
- };
- // Resolve product definitions and normalize the prompt in the owner's
- // async staging seam. This preparation is side-effect free, so the shared
- // workspace admission/arbitration still completes before dispatch creates
- // any worktrees or publishes spawn effects.
- let staged = plan
- .stage_with_preflight(&policy, |_, mut task| async move {
- task.payload.definition = definitions.get(&task.payload.agent_id).cloned();
- task.prompt = task.prompt.trim().to_string();
- Ok(task)
- })
- .await;
- let kinds = policy.kinds.into_inner();
- staged
- .into_iter()
- .enumerate()
- .map(|(index, item)| match item {
- Preflight::Prepared(worker) => {
- let AdmitPayload {
- task, definition, ..
- } = worker.payload;
- SpawnParallelTaskPreflight::Prepared(PreparedParallelTask {
- definition: definition.expect("admitted task has a definition"),
- prompt: worker.prompt,
- task,
- task_id: worker.id,
- dispatch_mode: worker.dispatch_mode,
- })
- }
- Preflight::Rejected(rejection) => {
- let Rejection { task, kind } = rejection;
- let agent_id = task
- .payload
- .definition
- .as_ref()
- .map(|d| d.id.clone())
- .unwrap_or_else(|| task.payload.agent_id.clone());
- let (error, kind) = match kind {
- RejectionKind::Policy(message) => (
- message,
- kinds
- .get(&index)
- .copied()
- .unwrap_or(ParallelTaskRejectionKind::RequiresIsolation),
- ),
- RejectionKind::Conflict(conflict) => (
- shared_workspace_conflict_message(&agent_id, &conflict),
- ParallelTaskRejectionKind::RequiresIsolation,
- ),
- };
- SpawnParallelTaskPreflight::Rejected(ParallelTaskRejection {
- task_id: task.id,
- agent_id,
- error,
- ownership: task.ownership,
- kind,
- })
- }
- })
- .collect()
-}
-
-/// Render a claim conflict as the sentence the calling model reads.
-///
-/// The crate reports conflicts as data precisely so this phrasing — the
-/// `isolation="worktree"` remedy, the `files:` vocabulary — stays a product
-/// decision rather than becoming API.
-fn shared_workspace_conflict_message(agent_id: &str, conflict: &ClaimConflict) -> String {
- match conflict {
- ClaimConflict::Overlap {
- other_worker_id,
- path,
- ..
- } => format!(
- "agent '{agent_id}' requested shared-workspace write access to '{}' but it overlaps with serial worker {other_worker_id}; set isolation=\"worktree\" or use disjoint files: ownership",
- path.display()
- ),
- ClaimConflict::UnboundedWrite { .. } => format!(
- "agent '{agent_id}' can write the shared workspace without declaring which files it owns; set isolation=\"worktree\" or provide disjoint files: ownership"
- ),
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/types.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/types.rs
deleted file mode 100644
index 0feb2e4b24..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/types.rs
+++ /dev/null
@@ -1,108 +0,0 @@
-//! Shared worker and result types passed between the staging, worker-fanout,
-//! and collection phases.
-
-use std::path::PathBuf;
-
-use serde::{Deserialize, Serialize};
-use tinytools::WorkspaceDescriptor;
-
-use crate::agent_registry::host_definition::AgentDefinition;
-
-/// One worker admitted by the `spawn_parallel_agents` tool.
-///
-/// This is intentionally a host request contract: its ownership syntax and
-/// worktree options are OpenHuman product policy. The tool owns JSON
-/// decoding; the execution pipeline receives this typed value only. A legacy
-/// `toolkit` key from an older caller is ignored (unknown fields are not
-/// denied).
-#[derive(Debug, Clone, Deserialize)]
-pub(crate) struct ParallelAgentTask {
- pub(crate) agent_id: String,
- pub(crate) prompt: String,
- #[serde(default)]
- pub(crate) context: Option<String>,
- #[serde(default)]
- pub(crate) ownership: Option<String>,
- #[serde(default)]
- pub(crate) isolation: Option<String>,
- #[serde(default)]
- pub(crate) base_ref: Option<String>,
-}
-
-/// Host payload of a module `Worker`: resolved definition, lineage and worktree
-/// placement. Id, prompt (ownership boundary applied) and dispatch mode live on
-/// the module's `Worker`.
-#[derive(Clone)]
-pub(crate) struct SpawnParallelWorker {
- pub(crate) definition: AgentDefinition,
- pub(crate) task: ParallelAgentTask,
- pub(crate) lineage: ParallelAgentLineage,
- pub(crate) worktree_path: Option<PathBuf>,
- pub(crate) workspace_descriptor: Option<WorkspaceDescriptor>,
-}
-
-/// Terminal or suspended lifecycle state projected by one parallel worker.
-/// `success` remains the concise aggregate flag, while this preserves enough
-/// detail to avoid treating a pause or cancellation as a completed child.
-#[derive(Debug, Clone, Copy, Serialize)]
-#[serde(rename_all = "snake_case")]
-pub(crate) enum ParallelAgentStatus {
- Completed,
- AwaitingUser,
- Incomplete,
- Cancelled,
- Failed,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct ParallelAgentLineage {
- pub(crate) parent_session: String,
- pub(crate) root_session: String,
- pub(crate) child_task_id: String,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct ParallelAgentResult {
- pub(crate) task_id: String,
- pub(crate) agent_id: String,
- pub(crate) lineage: ParallelAgentLineage,
- pub(crate) success: bool,
- pub(crate) status: ParallelAgentStatus,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) output: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) error: Option<String>,
- /// Typed terminal cause retained for incomplete-result projections.
- #[serde(skip)]
- pub(crate) failure_cause: Option<tinyagents_harness::no_progress::ClassifiedStopCause>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) awaiting_question: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) checkpoint_path: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) ownership: Option<String>,
- pub(crate) elapsed_ms: u64,
- pub(crate) iterations: u32,
- #[serde(skip_serializing_if = "Vec::is_empty")]
- pub(crate) stale_parent_reads: Vec<String>,
- /// Absolute path to the worker's isolated `git worktree` checkout, when
- /// it ran with `isolation = "worktree"`. `None` for non-isolated workers.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) worktree_path: Option<String>,
- /// Files (relative to the worktree root) the worker changed, collected
- /// from `git status` after the run. Empty for non-isolated workers or a
- /// clean worktree.
- #[serde(skip_serializing_if = "Vec::is_empty")]
- pub(crate) changed_files: Vec<String>,
- /// Whether the worker's worktree had uncommitted changes after the run.
- /// A dirty worktree must not be auto-removed (surfaced to the UI so the
- /// user can choose). `None` for non-isolated workers.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub(crate) dirty_status: Option<bool>,
- /// True only when this worker invocation committed the neutral lifecycle
- /// record, and therefore owns terminal event/progress publication.
- #[serde(skip)]
- pub(crate) emit_lifecycle_effects: bool,
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/workers.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel/workers.rs
deleted file mode 100644
index 26f5016b43..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/spawn_parallel/workers.rs
+++ /dev/null
@@ -1,233 +0,0 @@
-//! Running the staged workers on the module's [`run`]: the serial
-//! shared-workspace-write fallback and bounded fan-out are tinyagents-owned.
-//! This file keeps only the single-worker execution (`run_subagent` + post-run
-//! worktree status snapshot) and the result projection.
-
-use std::path::PathBuf;
-
-use tinyagents_harness::CancellationToken;
-use tinyagents_orchestration::parallel::{resolve_concurrency, run, Worker};
-
-use crate::agent::subagent_host::{
- run_subagent_with_parent, SubagentRunOptions, SubagentRunStatus,
-};
-
-use super::types::{ParallelAgentResult, ParallelAgentStatus, SpawnParallelWorker};
-
-pub(crate) async fn run_spawn_parallel_workers(
- prepared: Vec<Worker<SpawnParallelWorker>>,
- action_root: Option<PathBuf>,
- cancel: CancellationToken,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: &tinyagents_harness::context::RunContext<
- crate::agent::tinyagents::host::OpenHumanRunContext,
- >,
-) -> tinyagents_harness::Result<Vec<ParallelAgentResult>> {
- let concurrency = resolve_concurrency(0, prepared.len());
- tracing::debug!(
- target: "orchestration",
- workers = prepared.len(),
- concurrency,
- "[orchestration] running spawn_parallel_agents on tinyagents-orchestration parallel::run"
- );
- run(
- prepared,
- concurrency,
- cancel,
- |_| run_context.child(),
- |worker, child_context| {
- run_one_parallel_task(worker, action_root.clone(), child_context, live_parent)
- },
- )
- .await
-}
-
-async fn run_one_parallel_task(
- worker: Worker<SpawnParallelWorker>,
- repo_root: Option<PathBuf>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: &tinyagents_harness::context::RunContext<
- crate::agent::tinyagents::host::OpenHumanRunContext,
- >,
-) -> ParallelAgentResult {
- let Worker {
- id: task_id,
- prompt,
- payload:
- SpawnParallelWorker {
- definition,
- task,
- lineage,
- worktree_path,
- workspace_descriptor,
- },
- ..
- } = worker;
- let started = std::time::Instant::now();
- tracing::debug!(
- task_id = %task_id,
- agent_id = %definition.id,
- context_chars = task.context.as_ref().map(|s| s.chars().count()).unwrap_or(0),
- prompt_chars = prompt.chars().count(),
- isolated = worktree_path.is_some(),
- "[spawn_parallel_agents] task_start"
- );
- let worktree_action_dir = worktree_path.clone().or_else(|| {
- workspace_descriptor
- .as_ref()
- .map(|descriptor| descriptor.root.clone())
- });
- let options = SubagentRunOptions {
- skill_filter_override: None,
- context: task.context.clone(),
- model_override: None,
- task_id: Some(task_id.clone()),
- thread_id: None,
- run_context,
- worker_thread_id: None,
- initial_history: None,
- checkpoint_dir: None,
- worktree_action_dir,
- workspace_descriptor,
- run_queue: None,
- message_run_queue: None,
- };
- let run_result =
- run_subagent_with_parent(live_parent, definition.clone(), prompt.clone(), options).await;
-
- // After the worker finishes, snapshot the worktree's changed files +
- // dirty status so the parent can detect cross-worker overlaps and the UI
- // can surface diff/cleanup actions. Best-effort: a status error degrades
- // to "no changes recorded" rather than failing the task.
- let worktree_str = worktree_path
- .as_ref()
- .map(|p| p.to_string_lossy().to_string());
- let (changed_files, dirty_status) = match (&worktree_path, &repo_root) {
- (Some(wt), Some(root)) => {
- match tinyagents_harness::workspace::git_worktree_status(root, wt) {
- Ok(st) => {
- tracing::debug!(
- task_id = %task_id,
- worktree = %wt.display(),
- is_dirty = st.is_dirty,
- changed = st.changed_files.len(),
- "[spawn_parallel_agents] worktree_post_run_status"
- );
- let files = st
- .changed_files
- .iter()
- .map(|p| p.to_string_lossy().to_string())
- .collect();
- (files, Some(st.is_dirty))
- }
- Err(err) => {
- tracing::warn!(
- task_id = %task_id,
- worktree = %wt.display(),
- error = %err,
- "[spawn_parallel_agents] worktree_status_failed"
- );
- (Vec::new(), None)
- }
- }
- }
- _ => (Vec::new(), None),
- };
-
- match run_result {
- Ok(outcome) => {
- let emit_lifecycle_effects = outcome.should_emit_lifecycle_effects();
- let (status, success, error, awaiting_question, checkpoint_path) = match &outcome.status
- {
- SubagentRunStatus::Completed => {
- (ParallelAgentStatus::Completed, true, None, None, None)
- }
- SubagentRunStatus::AwaitingUser {
- question,
- checkpoint,
- ..
- } => (
- ParallelAgentStatus::AwaitingUser,
- false,
- None,
- Some(question.clone()),
- checkpoint
- .as_ref()
- .map(|path| path.to_string_lossy().to_string()),
- ),
- SubagentRunStatus::Incomplete { reason } => (
- ParallelAgentStatus::Incomplete,
- false,
- Some(reason.clone()),
- None,
- None,
- ),
- SubagentRunStatus::Cancelled => (
- ParallelAgentStatus::Cancelled,
- false,
- Some("parallel subagent was cancelled".into()),
- None,
- None,
- ),
- };
- tracing::debug!(
- task_id = %outcome.task_id,
- agent_id = %outcome.agent_id,
- elapsed_ms = outcome.elapsed.as_millis() as u64,
- iterations = outcome.iterations,
- output_chars = outcome.output.chars().count(),
- status = ?status,
- "[spawn_parallel_agents] task_outcome"
- );
- ParallelAgentResult {
- task_id: outcome.task_id,
- agent_id: outcome.agent_id,
- lineage,
- success,
- status,
- output: Some(outcome.output),
- error,
- failure_cause: outcome.failure_cause.clone(),
- awaiting_question,
- checkpoint_path,
- ownership: task.ownership,
- elapsed_ms: outcome.elapsed.as_millis() as u64,
- iterations: outcome.iterations as u32,
- stale_parent_reads: Vec::new(),
- worktree_path: worktree_str,
- changed_files,
- dirty_status,
- emit_lifecycle_effects,
- }
- }
- Err(err) => {
- tracing::debug!(
- task_id = %task_id,
- agent_id = %definition.id,
- elapsed_ms = started.elapsed().as_millis() as u64,
- error = %err,
- "[spawn_parallel_agents] task_error"
- );
- ParallelAgentResult {
- task_id,
- agent_id: definition.id,
- lineage,
- success: false,
- status: ParallelAgentStatus::Failed,
- output: None,
- error: Some(err.to_string()),
- failure_cause: None,
- awaiting_question: None,
- checkpoint_path: None,
- ownership: task.ownership,
- elapsed_ms: started.elapsed().as_millis() as u64,
- iterations: 0,
- stale_parent_reads: Vec::new(),
- worktree_path: worktree_str,
- changed_files,
- dirty_status,
- emit_lifecycle_effects: false,
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
deleted file mode 100644
index 3c8d6bfff9..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs
+++ /dev/null
@@ -1,283 +0,0 @@
-//! Tool: `spawn_parallel_agents` — fan out independent sub-agent tasks.
-
-#[cfg(test)]
-use crate::agent::orchestration::spawn_parallel::ParallelAgentLineage;
-#[cfg(test)]
-use crate::agent::orchestration::spawn_parallel::ParallelAgentResult;
-use crate::agent::orchestration::spawn_parallel::ParallelAgentTask;
-use crate::agent::orchestration::spawn_parallel::{
- format_spawn_parallel_success, run_spawn_parallel_tasks_with_cancellation_and_workspace,
- SpawnParallelGraphOutcome,
-};
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use async_trait::async_trait;
-use serde_json::json;
-use std::sync::Arc;
-use tinyagents_harness::context::RunContext;
-use tinyagents_harness::tool::ToolDispatch;
-use tinytools::ToolRunContext;
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};
-
-pub struct SpawnParallelAgentsTool;
-
-impl SpawnParallelAgentsTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for SpawnParallelAgentsTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// Typed-parent dispatch for `spawn_parallel_agents`.
-///
-/// The canonical `Tool` declaration remains usable for schema, policy, and
-/// capability registration, while this dispatch is the only harness execution
-/// path. It receives the live parent run rather than recovering cancellation
-/// from a task-local, so nested graph fan-out observes the exact parent token
-/// and workspace grant.
-pub(crate) struct SpawnParallelAgentsDispatch {
- tool: Arc<dyn Tool>,
-}
-
-impl SpawnParallelAgentsDispatch {
- pub(crate) fn new(tool: Arc<dyn Tool>) -> Self {
- Self { tool }
- }
-}
-
-#[async_trait]
-impl ToolDispatch<(), crate::agent::tinyagents::host::OpenHumanRunContext>
- for SpawnParallelAgentsDispatch
-{
- fn tool(&self) -> Arc<dyn Tool> {
- self.tool.clone()
- }
-
- async fn execute(
- &self,
- _state: &(),
- call_id: tinyagents_harness::CallId,
- arguments: serde_json::Value,
- _options: ToolCallOptions,
- parent: &RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>,
- ) -> anyhow::Result<ToolResult> {
- execute_spawn_parallel_agents(
- arguments,
- parent.cancellation.clone(),
- parent.workspace.clone(),
- parent.data.child(),
- Some(parent),
- Some(call_id.as_str().to_string()),
- )
- .await
- }
-}
-
-/// Executes the graph from explicitly supplied parent-run values.
-///
-/// This is shared by typed harness callers and requires their live parent;
-/// standalone raw-tool execution fails closed.
-pub(crate) async fn execute_spawn_parallel_agents(
- args: serde_json::Value,
- cancellation: tinyagents_harness::CancellationToken,
- workspace_descriptor: Option<tinytools::WorkspaceDescriptor>,
- run_context: crate::agent::tinyagents::host::OpenHumanRunContext,
- live_parent: Option<&RunContext<crate::agent::tinyagents::host::OpenHumanRunContext>>,
- parent_call_id: Option<String>,
-) -> anyhow::Result<ToolResult> {
- tracing::debug!("[spawn_parallel_agents] execute entry");
- let tasks = match parse_parallel_agent_tasks(&args) {
- Ok(tasks) => tasks,
- Err(ParallelAgentTaskRequestError::MissingTasks(message))
- | Err(ParallelAgentTaskRequestError::InvalidTasks(message)) => {
- return Err(anyhow::anyhow!(message));
- }
- Err(ParallelAgentTaskRequestError::Rejected(message)) => {
- return Ok(ToolResult::error(message));
- }
- };
- let Some(live_parent) = live_parent else {
- return Ok(ToolResult::error(
- "spawn_parallel_agents called outside of an agent turn",
- ));
- };
- let outcome = run_spawn_parallel_tasks_with_cancellation_and_workspace(
- tasks,
- cancellation,
- workspace_descriptor,
- run_context,
- live_parent,
- parent_call_id,
- )
- .await
- .map_err(|e| anyhow::anyhow!(e))?;
- match outcome {
- SpawnParallelGraphOutcome::Collected(collected) => Ok(ToolResult::success(
- format_spawn_parallel_success(&collected),
- )),
- SpawnParallelGraphOutcome::Rejected(message) => Ok(ToolResult::error(message)),
- SpawnParallelGraphOutcome::Cancelled(message) => Ok(ToolResult::error(message)),
- }
-}
-
-/// Decode the tool's JSON request before it reaches host execution policy.
-///
-/// This remains beside the tool rather than becoming a TinyAgents API: the
-/// parameter shape includes OpenHuman-specific ownership and worktree-policy
-/// fields.
-fn parse_parallel_agent_tasks(
- args: &serde_json::Value,
-) -> Result<Vec<ParallelAgentTask>, ParallelAgentTaskRequestError> {
- let tasks_value = args.get("tasks").cloned().ok_or_else(|| {
- ParallelAgentTaskRequestError::MissingTasks("Missing 'tasks' parameter".into())
- })?;
- let tasks: Vec<ParallelAgentTask> = serde_json::from_value(tasks_value).map_err(|err| {
- ParallelAgentTaskRequestError::InvalidTasks(format!("Invalid tasks array: {err}"))
- })?;
- if tasks.len() < 2 {
- return Err(ParallelAgentTaskRequestError::Rejected(
- "spawn_parallel_agents requires at least two tasks".into(),
- ));
- }
- Ok(tasks)
-}
-
-enum ParallelAgentTaskRequestError {
- MissingTasks(String),
- InvalidTasks(String),
- Rejected(String),
-}
-
-#[async_trait]
-impl Tool for SpawnParallelAgentsTool {
- fn name(&self) -> &str {
- "spawn_parallel_agents"
- }
-
- fn description(&self) -> &str {
- "Run two or more independent sub-agent tasks concurrently and collect their results. \
- Read-only and worktree-isolated workers run in parallel; shared-workspace workers with \
- write-capable tools require disjoint `files:` ownership and run through a serial fallback. \
- Each task has `{agent_id, prompt, context?, ownership?, isolation?, base_ref?}`."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- let agent_ids: Vec<String> = AgentDefinitionRegistry::current()
- .map(|reg| reg.list().iter().map(|d| d.id.clone()).collect())
- .unwrap_or_default();
- let agent_id_schema = if agent_ids.is_empty() {
- json!({ "type": "string" })
- } else {
- json!({ "type": "string", "enum": agent_ids })
- };
- json!({
- "type": "object",
- "required": ["tasks"],
- "properties": {
- "tasks": {
- "type": "array",
- "minItems": 2,
- "items": {
- "type": "object",
- "required": ["agent_id", "prompt"],
- "properties": {
- "agent_id": agent_id_schema,
- "prompt": { "type": "string" },
- "context": { "type": "string" },
- "ownership": {
- "type": "string",
- "description": "Disjoint file/module/responsibility boundary for this worker."
- },
- "isolation": {
- "type": "string",
- "enum": ["none", "worktree"],
- "description": "File-isolation strategy. `none` (default) shares the workspace; write-capable shared workers need disjoint `files:` ownership and are serialized. `worktree` gives an edit-capable worker its own git worktree checkout so parallel edits never collide."
- },
- "base_ref": {
- "type": "string",
- "enum": ["head", "fresh"],
- "description": "For `isolation = worktree`: branch the worktree from current HEAD (`head`, default) or the repo's default branch (`fresh`)."
- }
- }
- }
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- /// Run **without** the global per-tool wall-clock deadline. This is a
- /// fan-out primitive: it spawns N independent sub-agents and awaits them
- /// concurrently via `spawn_parallel`'s bounded `map_reduce`. Under the
- /// default `Inherit` policy the whole fan-out is hard-killed at the
- /// single-tool timeout (120s by default) — so a group of long workers is
- /// truncated at one worker's budget instead of running to ~the slowest, and
- /// each worker's research is cut short. The fan-out is already bounded
- /// internally — by `max_concurrency`, the run cancellation token, and each
- /// sub-agent's own iteration/turn caps — so it governs its own lifetime,
- /// like the long-running shell tool.
- fn timeout_policy(&self, _args: &serde_json::Value) -> ToolTimeout {
- ToolTimeout::Unbounded
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_context(args, ToolCallOptions::default(), None)
- .await
- }
-
- async fn execute_with_context(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- tool_context: Option<&dyn ToolRunContext>,
- ) -> anyhow::Result<ToolResult> {
- let parent_call_id = crate::tools::host_extensions::tool_call_id(tool_context);
- let workspace_descriptor = tool_context.and_then(|ctx| ctx.workspace().cloned());
- execute_spawn_parallel_agents(
- args,
- tinyagents_harness::CancellationToken::new(),
- workspace_descriptor,
- crate::agent::tinyagents::host::OpenHumanRunContext::new().with_core(
- crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context)
- .into_core(),
- ),
- None,
- parent_call_id,
- )
- .await
- }
-}
-
-#[cfg(test)]
-impl SpawnParallelAgentsTool {
- /// Drive the tool the way a live parent turn does, over an explicit
- /// `parent` execution context. Tests only: production turns reach the tool
- /// through [`SpawnParallelAgentsDispatch`] with their own carrier.
- pub(crate) async fn execute_under_parent(
- &self,
- args: serde_json::Value,
- parent: crate::agent::harness::ParentExecutionContext,
- ) -> anyhow::Result<ToolResult> {
- let live_parent = super::live_parent_run_context("direct-spawn-parallel", parent);
- execute_spawn_parallel_agents(
- args,
- live_parent.cancellation.clone(),
- live_parent.workspace.clone(),
- live_parent.data.child(),
- Some(&live_parent),
- None,
- )
- .await
- }
-}
-
-#[cfg(test)]
-#[path = "spawn_parallel_agents_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_policy_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_policy_tests.rs
deleted file mode 100644
index fdbeb8d853..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_policy_tests.rs
+++ /dev/null
@@ -1,615 +0,0 @@
-use super::*;
-
-#[test]
-fn metadata_methods_expose_execute_permission_and_schema() {
- let tool = SpawnParallelAgentsTool;
- assert_eq!(tool.name(), "spawn_parallel_agents");
- assert!(tool.description().contains("independent sub-agent tasks"));
- assert_eq!(tool.permission_level(), PermissionLevel::Execute);
- let schema = tool.parameters_schema();
- assert_eq!(schema["required"][0], "tasks");
- assert_eq!(schema["properties"]["tasks"]["minItems"], 2);
-}
-
-#[test]
-fn schema_advertises_isolation_and_base_ref() {
- let tool = SpawnParallelAgentsTool;
- let schema = tool.parameters_schema();
- let props = &schema["properties"]["tasks"]["items"]["properties"];
- assert_eq!(props["isolation"]["enum"][0], "none");
- assert_eq!(props["isolation"]["enum"][1], "worktree");
- assert_eq!(props["base_ref"]["enum"][0], "head");
- assert_eq!(props["base_ref"]["enum"][1], "fresh");
-}
-
-#[test]
-fn task_deserializes_isolation_and_base_ref() {
- let task: ParallelAgentTask = serde_json::from_value(json!({
- "agent_id": "coder",
- "prompt": "do it",
- "isolation": "worktree",
- "base_ref": "fresh"
- }))
- .expect("deserialize task");
- assert_eq!(task.isolation.as_deref(), Some("worktree"));
- assert_eq!(task.base_ref.as_deref(), Some("fresh"));
-}
-
-#[test]
-fn task_isolation_defaults_to_none() {
- let task: ParallelAgentTask = serde_json::from_value(json!({
- "agent_id": "researcher",
- "prompt": "read it"
- }))
- .expect("deserialize task");
- assert!(task.isolation.is_none());
- assert!(task.base_ref.is_none());
-}
-
-#[test]
-fn result_omits_worktree_fields_when_absent() {
- let result = ParallelAgentResult {
- task_id: "t1".into(),
- agent_id: "a".into(),
- lineage: test_lineage("t1"),
- success: true,
- status: crate::agent::orchestration::spawn_parallel::ParallelAgentStatus::Completed,
- output: Some("ok".into()),
- error: None,
- failure_cause: None,
- awaiting_question: None,
- checkpoint_path: None,
- ownership: None,
- elapsed_ms: 5,
- iterations: 1,
- stale_parent_reads: Vec::new(),
- worktree_path: None,
- changed_files: Vec::new(),
- dirty_status: None,
- emit_lifecycle_effects: false,
- };
- let v = serde_json::to_value(&result).unwrap();
- assert!(v.get("worktreePath").is_none());
- assert!(v.get("changedFiles").is_none());
- assert!(v.get("dirtyStatus").is_none());
-}
-
-#[test]
-fn result_serializes_worktree_fields_when_present() {
- let result = ParallelAgentResult {
- task_id: "t2".into(),
- agent_id: "coder".into(),
- lineage: test_lineage("t2"),
- success: true,
- status: crate::agent::orchestration::spawn_parallel::ParallelAgentStatus::Completed,
- output: None,
- error: None,
- failure_cause: None,
- awaiting_question: None,
- checkpoint_path: None,
- ownership: None,
- elapsed_ms: 9,
- iterations: 2,
- stale_parent_reads: Vec::new(),
- worktree_path: Some("/repo/.claude/worktrees/t2".into()),
- changed_files: vec!["src/a.rs".into()],
- dirty_status: Some(true),
- emit_lifecycle_effects: false,
- };
- let v = serde_json::to_value(&result).unwrap();
- assert_eq!(v["worktreePath"], "/repo/.claude/worktrees/t2");
- assert_eq!(v["changedFiles"][0], "src/a.rs");
- assert_eq!(v["dirtyStatus"], true);
-}
-
-#[tokio::test]
-async fn rejects_single_task() {
- let tool = SpawnParallelAgentsTool::new();
- let result = tool
- .execute(json!({
- "tasks": [{ "agent_id": "researcher", "prompt": "only one" }]
- }))
- .await
- .unwrap();
- assert!(result.is_error);
- assert!(
- result.output().contains("at least two"),
- "got: {}",
- result.output()
- );
-}
-
-#[tokio::test]
-async fn rejects_missing_or_invalid_tasks_before_parent_lookup() {
- let tool = SpawnParallelAgentsTool::new();
-
- let missing = tool.execute(json!({})).await.expect_err("missing tasks");
- assert!(missing.to_string().contains("Missing 'tasks'"));
-
- let invalid = tool
- .execute(json!({ "tasks": "not an array" }))
- .await
- .expect_err("invalid tasks");
- assert!(invalid.to_string().contains("Invalid tasks array"));
-}
-
-#[tokio::test]
-async fn rejects_two_tasks_outside_agent_turn() {
- let tool = SpawnParallelAgentsTool::new();
- let result = tool
- .execute(json!({
- "tasks": [
- { "agent_id": "researcher", "prompt": "one" },
- { "agent_id": "planner", "prompt": "two" }
- ]
- }))
- .await
- .expect("tool result");
- assert!(result.is_error);
- assert!(result.output().contains("outside of an agent turn"));
-}
-
-#[tokio::test]
-async fn rejects_more_tasks_than_parent_parallel_limit() {
- // The parallel-limit check now runs inside the execution graph, which is
- // reached only after the registry lookup — so this test needs the global
- // builtins initialised (as its siblings already do) rather than relying on
- // whichever test happened to initialise them first.
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let tool = SpawnParallelAgentsTool::new();
- let parent = parent_context(2);
- let result = (async {
- tool.execute_under_parent(
- json!({
- "tasks": [
- { "agent_id": "researcher", "prompt": "one" },
- { "agent_id": "planner", "prompt": "two" },
- { "agent_id": "critic", "prompt": "three" }
- ]
- }),
- parent.clone(),
- )
- .await
- })
- .await
- .expect("tool result");
- assert!(result.is_error);
- assert!(
- result.output().contains("max_parallel_tools"),
- "unexpected result: {}",
- result.output()
- );
-}
-
-#[tokio::test]
-async fn collects_immediate_task_validation_failures() {
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let tool = SpawnParallelAgentsTool::new();
- let parent = parent_context(4);
-
- let result = (async {
- tool.execute_under_parent(
- json!({
- "tasks": [
- { "agent_id": " ", "prompt": "missing agent", "ownership": "files: none" },
- { "agent_id": "__missing_agent__", "prompt": "unknown agent" }
- ]
- }),
- parent.clone(),
- )
- .await
- })
- .await
- .expect("tool result");
-
- assert!(!result.is_error, "{}", result.output());
- let body: serde_json::Value = serde_json::from_str(&result.output()).expect("json output");
- assert_eq!(body["parallel_agents"]["total"], 2);
- assert_eq!(body["parallel_agents"]["failed"], 2);
- let errors = body["parallel_agents"]["results"]
- .as_array()
- .expect("results")
- .iter()
- .map(|result| result["error"].as_str().unwrap_or_default())
- .collect::<Vec<_>>();
- assert!(errors
- .iter()
- .any(|error| error.contains("agent_id and prompt")));
- assert!(errors
- .iter()
- .any(|error| error.contains("unknown agent_id")));
-}
-
-#[tokio::test]
-async fn shared_workspace_rejects_write_capable_named_worker_without_worktree() {
- let definition = definition_with_tool_scope(
- "researcher",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let definitions = HashMap::from([(definition.id.clone(), definition)]);
- let parent = parent_context_with_tools(
- 4,
- vec![Box::new(PermissionFixtureTool {
- name: "write_fixture",
- level: PermissionLevel::Write,
- })],
- );
-
- let preflight = prepare_spawn_parallel_tasks_from_defs(
- vec![ParallelAgentTask {
- agent_id: "researcher".into(),
- prompt: "edit a file".into(),
- context: None,
- ownership: None,
- isolation: None,
- base_ref: None,
- }],
- &definitions,
- &parent,
- )
- .await;
-
- match preflight.into_iter().next().expect("one preflight result") {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- assert_eq!(rejection.kind, ParallelTaskRejectionKind::RequiresIsolation);
- assert!(rejection.error.contains("write_fixture:Write"));
- assert!(rejection.error.contains("isolation=\"worktree\""));
- }
- SpawnParallelTaskPreflight::Prepared(_) => {
- panic!("write-capable shared worker must require worktree isolation")
- }
- }
-}
-
-#[tokio::test]
-async fn shared_workspace_allows_readonly_or_explicitly_isolated_workers() {
- let readonly = definition_with_tool_scope(
- "researcher",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::ReadOnly,
- );
- let writer = definition_with_tool_scope(
- "critic",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let definitions = HashMap::from([(readonly.id.clone(), readonly), (writer.id.clone(), writer)]);
- let parent = parent_context_with_tools(
- 4,
- vec![Box::new(PermissionFixtureTool {
- name: "write_fixture",
- level: PermissionLevel::Write,
- })],
- );
-
- let preflight = prepare_spawn_parallel_tasks_from_defs(
- vec![
- ParallelAgentTask {
- agent_id: "researcher".into(),
- prompt: "read only".into(),
- context: None,
- ownership: None,
- isolation: None,
- base_ref: None,
- },
- ParallelAgentTask {
- agent_id: "critic".into(),
- prompt: "isolated edit".into(),
- context: None,
- ownership: Some("files: src/b.rs".into()),
- isolation: Some("worktree".into()),
- base_ref: None,
- },
- ],
- &definitions,
- &parent,
- )
- .await;
-
- assert!(preflight
- .into_iter()
- .all(|item| matches!(item, SpawnParallelTaskPreflight::Prepared(_))));
-}
-
-// This exercises the full parallel-subagent path (parent turn → spawn N
-// subagents → each runs several nested tool-call iterations). It is a deep
-// async state machine whose stacked frames exceed the default ~2 MiB libtest
-// per-test thread stack in debug/coverage builds; the thread overflows and
-// SIGABRTs the *entire* test process, which then non-deterministically tags an
-// unrelated concurrently-running test as FAILED (issue #5209 — the
-// experience-recall test was a frequent victim). CI only avoided this by
-// exporting a 64 MiB `RUST_MIN_STACK`; a raw `cargo test` has no such env.
-// Production drives agent turns on an explicit large stack for the same reason
-// (`agent::bus::handle_agent_run_turn_on_large_stack`). Mirror that here so the
-// test never aborts the process regardless of `RUST_MIN_STACK`.
-#[test]
-fn agent_turn_runs_long_parallel_subagent_flow_with_many_nested_tool_calls() {
- std::thread::Builder::new()
- .name("parallel-subagent-flow-test".to_string())
- .stack_size(64 * 1024 * 1024)
- .spawn(|| {
- tokio::runtime::Builder::new_current_thread()
- .enable_all()
- .build()
- .expect("build large-stack test runtime")
- .block_on(
- agent_turn_runs_long_parallel_subagent_flow_with_many_nested_tool_calls_inner(),
- );
- })
- .expect("spawn large-stack test thread")
- .join()
- .expect("large-stack parallel-subagent test thread panicked");
-}
-
-#[test]
-fn spawn_parallel_agents_opts_out_of_the_global_tool_timeout() {
- // A fan-out of N long sub-agents must not be hard-killed at the single-tool
- // wall-clock default (120s): that truncates every worker and bounds the whole
- // group at one worker's budget. The tool governs its own lifetime via its
- // internal max_concurrency, cancellation token, and per-sub-agent caps.
- assert_eq!(
- SpawnParallelAgentsTool::new().timeout_policy(&json!({})),
- ToolTimeout::Unbounded,
- );
-}
-
-/// An absolute or parent-escaping ownership path is rejected with the host's
-/// own sentence, not the crate's typed error.
-#[tokio::test]
-async fn invalid_ownership_paths_are_rejected_with_the_host_message() {
- for raw in ["files: /etc/passwd", "files: ../outside.rs"] {
- let definition = definition_with_tool_scope(
- "writer",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let definitions = HashMap::from([(definition.id.clone(), definition)]);
- let parent = parent_admitting(&["writer"], write_fixture_tools());
-
- let preflight = prepare_spawn_parallel_tasks_from_defs(
- vec![dispatch_task("writer", Some(raw), None)],
- &definitions,
- &parent,
- )
- .await;
-
- match &preflight[0] {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- assert_eq!(rejection.kind, ParallelTaskRejectionKind::RequiresIsolation);
- assert!(
- rejection.error.contains("must be a relative file path"),
- "ownership rejection wording changed for {raw}: {}",
- rejection.error
- );
- }
- SpawnParallelTaskPreflight::Prepared(_) => {
- panic!("an out-of-workspace ownership path must be rejected: {raw}")
- }
- }
- }
-}
-
-/// Pins the write-safety dispatch decision for a mixed batch.
-///
-/// This is the assertion that must not move: a regression here does not fail a
-/// run, it lets two edit-capable workers into one checkout at the same time and
-/// returns a plausible result built on a torn tree. The sequence below —
-/// worktree-isolated writer parallel, shared read-only agent parallel, shared
-/// writer with disjoint ownership serialized, shared writer claiming an
-/// already-claimed path rejected — is the contract.
-#[tokio::test]
-async fn mixed_batch_dispatch_modes_and_claim_conflicts_are_stable() {
- let isolated_writer = definition_with_tool_scope(
- "isolated_writer",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let reader = definition_with_tool_scope(
- "reader",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::ReadOnly,
- );
- let writer = definition_with_tool_scope(
- "writer",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let clasher = definition_with_tool_scope(
- "clasher",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- // Defined but deliberately omitted from the parent allowlist below, so it
- // is policy-rejected *before* any claim is admitted. An earlier rejection
- // must not advance `admitted_index`, or every later admitted task would
- // resolve to the wrong plan slot and the clasher's conflict would be
- // misattributed — this batch pins that the index stays admission-scoped.
- let outside = definition_with_tool_scope(
- "outside",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let definitions = HashMap::from([
- (isolated_writer.id.clone(), isolated_writer),
- (reader.id.clone(), reader),
- (writer.id.clone(), writer),
- (clasher.id.clone(), clasher),
- (outside.id.clone(), outside),
- ]);
- let parent = parent_admitting(
- &["isolated_writer", "reader", "writer", "clasher"],
- write_fixture_tools(),
- );
-
- let preflight = prepare_spawn_parallel_tasks_from_defs(
- vec![
- dispatch_task("outside", None, None),
- dispatch_task("isolated_writer", None, Some("worktree")),
- dispatch_task("reader", None, None),
- dispatch_task("writer", Some("files: src/a.rs"), None),
- dispatch_task("clasher", Some("files: src/a.rs"), None),
- ],
- &definitions,
- &parent,
- )
- .await;
-
- // The earlier policy rejection is surfaced in place, without advancing the
- // admission index the later dispatch decisions key off.
- match &preflight[0] {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- assert_eq!(rejection.kind, ParallelTaskRejectionKind::OutsideAllowlist);
- assert_eq!(rejection.agent_id, "outside");
- }
- SpawnParallelTaskPreflight::Prepared(_) => {
- panic!("an agent outside the allowlist must be rejected")
- }
- }
-
- let modes: Vec<Option<WorkerDispatchMode>> = preflight
- .iter()
- .map(|entry| match entry {
- SpawnParallelTaskPreflight::Prepared(prepared) => Some(prepared.dispatch_mode()),
- SpawnParallelTaskPreflight::Rejected(_) => None,
- })
- .collect();
-
- assert_eq!(
- modes,
- vec![
- None,
- Some(WorkerDispatchMode::Parallel),
- Some(WorkerDispatchMode::Parallel),
- Some(WorkerDispatchMode::SerialSharedWorkspaceWrite),
- None,
- ],
- "write-safety dispatch decision changed after an earlier rejection"
- );
-
- // The rejection is the *later* claimant; the earlier one keeps its claim.
- // Index 4 (not 3) because the leading `outside` rejection did not consume
- // an admission slot.
- match &preflight[4] {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- assert_eq!(rejection.kind, ParallelTaskRejectionKind::RequiresIsolation);
- assert_eq!(rejection.agent_id, "clasher");
- assert!(
- rejection.error.contains("src/a.rs"),
- "rejection must name the contended path: {}",
- rejection.error
- );
- }
- SpawnParallelTaskPreflight::Prepared(_) => {
- panic!("a worker claiming an already-claimed path must be rejected")
- }
- }
-}
-
-/// A shared-workspace writer whose ownership paths are disjoint from every
-/// earlier claim is admitted, and serialized rather than run in parallel.
-#[tokio::test]
-async fn disjoint_ownership_admits_both_writers_serially() {
- let first = definition_with_tool_scope(
- "first",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let second = definition_with_tool_scope(
- "second",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let definitions = HashMap::from([(first.id.clone(), first), (second.id.clone(), second)]);
- let parent = parent_admitting(&["first", "second"], write_fixture_tools());
-
- let preflight = prepare_spawn_parallel_tasks_from_defs(
- vec![
- dispatch_task("first", Some("files: src/a.rs"), None),
- dispatch_task("second", Some("files: src/b.rs"), None),
- ],
- &definitions,
- &parent,
- )
- .await;
-
- let modes: Vec<Option<WorkerDispatchMode>> = preflight
- .iter()
- .map(|entry| match entry {
- SpawnParallelTaskPreflight::Prepared(prepared) => Some(prepared.dispatch_mode()),
- SpawnParallelTaskPreflight::Rejected(_) => None,
- })
- .collect();
-
- assert_eq!(
- modes,
- vec![
- Some(WorkerDispatchMode::SerialSharedWorkspaceWrite),
- Some(WorkerDispatchMode::SerialSharedWorkspaceWrite),
- ]
- );
-}
-
-/// Directory-level ownership contains the files beneath it, so a worker
-/// claiming `src` collides with one claiming `src/a.rs`.
-#[tokio::test]
-async fn directory_ownership_contains_files_beneath_it() {
- let owner = definition_with_tool_scope(
- "owner",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let nested = definition_with_tool_scope(
- "nested",
- ToolScope::Named(vec!["write_fixture".into()]),
- SandboxMode::None,
- );
- let definitions = HashMap::from([(owner.id.clone(), owner), (nested.id.clone(), nested)]);
- let parent = parent_admitting(&["owner", "nested"], write_fixture_tools());
-
- let preflight = prepare_spawn_parallel_tasks_from_defs(
- vec![
- dispatch_task("owner", Some("files: src"), None),
- dispatch_task("nested", Some("files: src/a.rs"), None),
- ],
- &definitions,
- &parent,
- )
- .await;
-
- // The directory-level owner keeps its claim and serializes against any
- // sibling write rather than fanning out.
- let owner = match &preflight[0] {
- SpawnParallelTaskPreflight::Prepared(prepared) => prepared,
- SpawnParallelTaskPreflight::Rejected(_) => panic!("owner must be admitted"),
- };
- assert_eq!(
- owner.dispatch_mode(),
- WorkerDispatchMode::SerialSharedWorkspaceWrite,
- "directory-level owner serializes against shared-workspace writes"
- );
-
- // A file beneath an already-claimed directory is rejected with the
- // rejected task's ownership claim, the rejecting agent's identity, and
- // an error naming the contended owner directory — rather than silently
- // overlapping the owner.
- match &preflight[1] {
- SpawnParallelTaskPreflight::Rejected(rejection) => {
- assert_eq!(rejection.kind, ParallelTaskRejectionKind::RequiresIsolation);
- assert_eq!(rejection.agent_id, "nested");
- assert_eq!(
- rejection.ownership.as_deref(),
- Some("files: src/a.rs"),
- "rejection must carry the rejected task's ownership claim"
- );
- assert!(
- rejection.error.contains("'src'"),
- "rejection error must name the contended owner directory: {}",
- rejection.error
- );
- }
- SpawnParallelTaskPreflight::Prepared(_) => {
- panic!("a file beneath an already-claimed directory must be rejected")
- }
- }
-}
diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
deleted file mode 100644
index c688170a0f..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents_tests.rs
+++ /dev/null
@@ -1,671 +0,0 @@
-use super::*;
-use crate::agent::harness::fork_context::ParentExecutionContext;
-use crate::agent::orchestration::spawn_parallel::{
- prepare_spawn_parallel_tasks_from_defs, ParallelTaskRejectionKind, SpawnParallelTaskPreflight,
-};
-use crate::agent::tinyagents::host::OpenHumanRunContext;
-use crate::agent::OpenHumanSessionHost;
-use crate::agent_registry::host_definition::AgentDefinition;
-use crate::agent_registry::host_definition::AgentDefinitionRegistry;
-use crate::config::AgentConfig;
-use async_trait::async_trait;
-use parking_lot::Mutex;
-use serde_json::json;
-use std::collections::HashMap;
-use std::sync::{
- atomic::{AtomicUsize, Ordering},
- Arc,
-};
-use tinyagents_definition::{
- AgentTier, DefinitionSource, ModelSpec, PromptSource, SandboxMode, ToolScope,
-};
-use tinyagents_harness::tool::ToolDispatch;
-use tinyagents_orchestration::parallel::WorkerDispatchMode;
-use tinyinference_llm::message::{AssistantMessage, Message};
-use tinyinference_llm::model::{ChatModel, ModelProfile, ModelRequest, ModelResponse};
-use tinyinference_llm::tool::ToolCall;
-use tinytools::ToolTimeout;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-use tinytools_agent::dialect::NativeDialect;
-use tinytools_agent::dialect::ToolCallFormat;
-use tinytools_agent::dialect::TranscriptEntry;
-use tokio::time::{sleep, timeout, Duration};
-
-const PARENT_PROMPT_CANARY: &str = "parallel-fanout-e2e-canary";
-const RESEARCH_PROMPT_CANARY: &str = "research-branch-canary";
-const PLANNER_PROMPT_CANARY: &str = "planner-branch-canary";
-const RESEARCH_DONE_CANARY: &str = "research-finished-canary";
-const PLANNER_DONE_CANARY: &str = "planner-finished-canary";
-const FINAL_CANARY: &str = "parallel-summary-canary";
-
-fn test_lineage(task_id: &str) -> ParallelAgentLineage {
- ParallelAgentLineage {
- parent_session: "parent-session".into(),
- root_session: "root-session".into(),
- child_task_id: task_id.into(),
- }
-}
-
-fn parent_context(max_parallel_tools: usize) -> ParentExecutionContext {
- let agent_config = AgentConfig {
- max_parallel_tools,
- ..Default::default()
- };
- let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =
- Arc::new(tinyagents_harness::testkit::ScriptedModel::replies(vec![
- "ok",
- ]));
- ParentExecutionContext {
- workspace_descriptor: None,
- agent_definition_id: "orchestrator".into(),
- allowed_subagent_ids: ["researcher".to_string(), "critic".to_string()]
- .into_iter()
- .collect(),
- turn_model_source: crate::agent::tinyagents::TurnModelSource::from_model(model),
- all_tools: Arc::new(Vec::new()),
- all_tool_specs: Arc::new(Vec::new()),
- visible_tool_specs: Arc::new(Vec::new()),
- visible_tool_names: std::collections::HashSet::new(),
- subagent_tool_ceiling_names: std::collections::HashSet::new(),
- model_name: "test-model".into(),
- temperature: 0.2,
- workspace_dir: std::env::temp_dir(),
- agent_config,
- workflows: Arc::new(Vec::new()),
- memory_context: Arc::new(None),
- session_id: "session-test".into(),
- channel: "test".into(),
- connected_integrations: Vec::new(),
- tool_call_format: ToolCallFormat::PFormat,
- session_key: "0_test".into(),
- session_parent_prefix: None,
- on_progress: None,
- run_queue: None,
- host_env: Default::default(),
- }
-}
-
-fn parent_context_with_tools(
- max_parallel_tools: usize,
- tools: Vec<Box<dyn Tool>>,
-) -> ParentExecutionContext {
- let mut parent = parent_context(max_parallel_tools);
- parent.all_tools = Arc::new(tools);
- parent
-}
-
-/// The live harness does not recover ambient cancellation. Its typed
-/// dispatch receives the parent `RunContext`, so an already-cancelled parent
-/// token rejects the fan-out before worker dispatch with the same workspace
-/// grant.
-#[tokio::test]
-async fn typed_dispatch_uses_the_parent_token_for_fanout_cancellation() {
- let _ = AgentDefinitionRegistry::init_global_builtins();
- let cancellation = tinyagents_harness::CancellationToken::new();
- let workspace = tinytools::WorkspaceDescriptor::new("/work/parent-action");
- let dispatch = SpawnParallelAgentsDispatch::new(Arc::new(SpawnParallelAgentsTool::new()));
- let parent = parent_context(4);
- let parent_run = OpenHumanRunContext::new()
- .with_parent(parent.clone())
- .with_cancellation(cancellation.clone())
- .with_workspace(workspace.clone())
- .into_tinyagents(tinyagents_harness::context::RunConfig::new("parent"));
-
- cancellation.cancel();
- let result = (async {
- dispatch
- .execute(
- &(),
- tinyagents_harness::CallId::new("test-call"),
- json!({
- "tasks": [
- { "agent_id": "researcher", "prompt": "one" },
- { "agent_id": "critic", "prompt": "two" }
- ]
- }),
- tinytools::ToolCallOptions::default(),
- &parent_run,
- )
- .await
- })
- .await
- .expect("typed dispatch result");
-
- assert_eq!(parent_run.workspace, Some(workspace));
- assert!(result.is_error, "{}", result.output());
- assert!(
- result.output().contains("cancelled at validate"),
- "typed dispatch must pass the parent token into fan-out: {}",
- result.output()
- );
-}
-
-fn definition_with_tool_scope(
- id: &str,
- tools: ToolScope,
- sandbox_mode: SandboxMode,
-) -> AgentDefinition {
- AgentDefinition {
- id: id.to_string(),
- when_to_use: "test definition".into(),
- display_name: None,
- system_prompt: PromptSource::Inline("test prompt".into()),
- model: ModelSpec::Inherit,
- temperature: 0.0,
- tools,
- disallowed_tools: Vec::new(),
- skill_filter: None,
- extra_tools: Vec::new(),
- deferred_tools: Vec::new(),
- tool_rules: None,
- max_iterations: 3,
- iteration_policy: Default::default(),
- max_result_chars: None,
- max_turn_output_tokens: None,
- timeout_secs: None,
- sandbox_mode,
- background: false,
- subagents: Vec::new(),
- delegate_name: None,
- agent_tier: AgentTier::Worker,
- source: DefinitionSource::Builtin,
- extensions: crate::agent_registry::host_definition::AgentExt {
- omit_identity: true,
- omit_memory_context: true,
- omit_safety_preamble: true,
- tokenjuice_compression: Default::default(),
- searches_connected_mcp: false,
- ..Default::default()
- },
- role: None,
- }
-}
-
-#[derive(Default)]
-struct FixtureStepState {
- calls: AtomicUsize,
-}
-
-struct FixtureStepTool {
- state: Arc<FixtureStepState>,
-}
-
-#[async_trait]
-impl Tool for FixtureStepTool {
- fn name(&self) -> &str {
- "fixture_step"
- }
-
- fn description(&self) -> &str {
- "Fixture tool used by parallel subagent tests."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "required": ["branch", "step"],
- "properties": {
- "branch": { "type": "string" },
- "step": { "type": "integer" }
- }
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let branch = args
- .get("branch")
- .and_then(|v| v.as_str())
- .unwrap_or("unknown");
- let step = args.get("step").and_then(|v| v.as_u64()).unwrap_or(0);
- self.state.calls.fetch_add(1, Ordering::SeqCst);
- Ok(ToolResult::success(format!("{branch}-step-{step}-ok")))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-}
-
-struct PermissionFixtureTool {
- name: &'static str,
- level: PermissionLevel,
-}
-
-#[async_trait]
-impl Tool for PermissionFixtureTool {
- fn name(&self) -> &str {
- self.name
- }
-
- fn description(&self) -> &str {
- "Fixture tool with a configurable permission level."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({ "type": "object" })
- }
-
- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
- Ok(ToolResult::success("ok"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- self.level
- }
-}
-
-struct ParallelHarnessState {
- total_calls: AtomicUsize,
- active_subagent_calls: AtomicUsize,
- max_active_subagent_calls: AtomicUsize,
- /// Sequence counter over subagent provider calls. The first two calls (one
- /// from each parallel subagent) rendezvous at [`Self::overlap_barrier`].
- subagent_call_seq: AtomicUsize,
- /// Deterministic overlap gate: the first provider call of each parallel
- /// subagent waits here until both have arrived, guaranteeing the
- /// `max_active_subagent_calls >= 2` assertion without depending on a timing
- /// window (the old fixed `sleep` raced under load and flaked — see #5209).
- overlap_barrier: tokio::sync::Barrier,
- seen_payloads: Mutex<Vec<String>>,
-}
-
-impl Default for ParallelHarnessState {
- fn default() -> Self {
- Self {
- total_calls: AtomicUsize::new(0),
- active_subagent_calls: AtomicUsize::new(0),
- max_active_subagent_calls: AtomicUsize::new(0),
- subagent_call_seq: AtomicUsize::new(0),
- overlap_barrier: tokio::sync::Barrier::new(2),
- seen_payloads: Mutex::new(Vec::new()),
- }
- }
-}
-
-#[derive(Clone, Default)]
-struct ParallelHarnessProvider {
- state: Arc<ParallelHarnessState>,
-}
-
-impl ParallelHarnessProvider {
- fn total_calls(&self) -> usize {
- self.state.total_calls.load(Ordering::SeqCst)
- }
-
- fn max_active_subagent_calls(&self) -> usize {
- self.state.max_active_subagent_calls.load(Ordering::SeqCst)
- }
-
- fn record_active_peak(&self, current: usize) {
- let mut observed = self.state.max_active_subagent_calls.load(Ordering::SeqCst);
- while current > observed {
- match self.state.max_active_subagent_calls.compare_exchange(
- observed,
- current,
- Ordering::SeqCst,
- Ordering::SeqCst,
- ) {
- Ok(_) => break,
- Err(next) => observed = next,
- }
- }
- }
-
- async fn respond_for_subagent(
- &self,
- flattened: &str,
- ) -> tinyinference_llm::Result<ModelResponse> {
- let current = self
- .state
- .active_subagent_calls
- .fetch_add(1, Ordering::SeqCst)
- + 1;
- self.record_active_peak(current);
-
- // The two parallel subagents' first provider calls rendezvous at the
- // barrier, deterministically forcing them to be active simultaneously
- // (peak >= 2). The old approach slept a fixed 25ms and hoped the second
- // call started before the first woke — a window scheduling jitter could
- // miss, so the `max_active >= 2` assertion flaked run-to-run (#5209).
- // The wait is timeout-guarded so a genuine loss of parallelism fails the
- // assertion instead of hanging the test. Later calls (seq >= 2) yield
- // briefly to keep the interleaving realistic.
- let seq = self.state.subagent_call_seq.fetch_add(1, Ordering::SeqCst);
- if seq < 2 {
- let _ = timeout(Duration::from_secs(5), self.state.overlap_barrier.wait()).await;
- } else {
- sleep(Duration::from_millis(5)).await;
- }
-
- let response = if flattened.contains(RESEARCH_PROMPT_CANARY) {
- if flattened.contains("research-step-3-ok") {
- Ok(text_response(RESEARCH_DONE_CANARY))
- } else if flattened.contains("research-step-2-ok") {
- Ok(tool_response(
- "fixture_step",
- json!({ "branch": "research", "step": 3 }),
- ))
- } else if flattened.contains("research-step-1-ok") {
- Ok(tool_response(
- "fixture_step",
- json!({ "branch": "research", "step": 2 }),
- ))
- } else {
- Ok(tool_response(
- "fixture_step",
- json!({ "branch": "research", "step": 1 }),
- ))
- }
- } else if flattened.contains(PLANNER_PROMPT_CANARY) {
- if flattened.contains("planner-step-3-ok") {
- Ok(text_response(PLANNER_DONE_CANARY))
- } else if flattened.contains("planner-step-2-ok") {
- Ok(tool_response(
- "fixture_step",
- json!({ "branch": "planner", "step": 3 }),
- ))
- } else if flattened.contains("planner-step-1-ok") {
- Ok(tool_response(
- "fixture_step",
- json!({ "branch": "planner", "step": 2 }),
- ))
- } else {
- Ok(tool_response(
- "fixture_step",
- json!({ "branch": "planner", "step": 1 }),
- ))
- }
- } else {
- Err(tinyinference_llm::Error::Model(format!(
- "unexpected subagent payload: {flattened}"
- )))
- };
-
- self.state
- .active_subagent_calls
- .fetch_sub(1, Ordering::SeqCst);
- response
- }
-}
-
-#[async_trait]
-impl ChatModel<()> for ParallelHarnessProvider {
- fn profile(&self) -> Option<&ModelProfile> {
- static PROFILE: std::sync::LazyLock<ModelProfile> =
- std::sync::LazyLock::new(|| ModelProfile {
- provider: Some("parallel-harness-test".to_string()),
- tool_calling: true,
- parallel_tool_calls: true,
- ..ModelProfile::default()
- });
- Some(&PROFILE)
- }
-
- async fn invoke(
- &self,
- _state: &(),
- request: ModelRequest,
- ) -> tinyinference_llm::Result<ModelResponse> {
- self.state.total_calls.fetch_add(1, Ordering::SeqCst);
- let flattened = request
- .messages
- .iter()
- .map(|message| {
- let role = match message {
- Message::System(_) => "system",
- Message::User(_) => "user",
- Message::Assistant(_) => "assistant",
- Message::Tool(_) => "tool",
- Message::Custom(_) => "custom",
- };
- format!("{role}:{}", message.text())
- })
- .collect::<Vec<_>>()
- .join("\n");
- self.state.seen_payloads.lock().push(flattened.clone());
-
- if flattened.contains(PARENT_PROMPT_CANARY) {
- if flattened.contains(RESEARCH_DONE_CANARY) && flattened.contains(PLANNER_DONE_CANARY) {
- return Ok(text_response(format!(
- "{FINAL_CANARY}: merged {RESEARCH_DONE_CANARY} and {PLANNER_DONE_CANARY}"
- )));
- }
-
- return Ok(tool_response(
- "spawn_parallel_agents",
- json!({
- "tasks": [
- {
- "agent_id": "__test_inherit_parallel_worker",
- "prompt": format!("Work the research branch: {RESEARCH_PROMPT_CANARY}"),
- "ownership": "scope: research"
- },
- {
- "agent_id": "__test_inherit_parallel_worker",
- "prompt": format!("Work the planning branch: {PLANNER_PROMPT_CANARY}"),
- "ownership": "scope: planning"
- }
- ]
- }),
- ));
- }
-
- self.respond_for_subagent(&flattened).await
- }
-}
-
-fn text_response(text: impl Into<String>) -> ModelResponse {
- ModelResponse::assistant(text)
-}
-
-fn tool_response(name: &str, arguments: serde_json::Value) -> ModelResponse {
- ModelResponse {
- message: AssistantMessage {
- id: None,
- content: Vec::new(),
- tool_calls: vec![ToolCall::new(format!("call-{name}"), name, arguments)],
- usage: None,
- origin: None,
- },
- usage: None,
- finish_reason: Some("tool_calls".to_string()),
- raw: None,
- resolved_model: None,
- continue_turn: None,
- served_from_cache: false,
- correlation: None,
- resolved_route: None,
- }
-}
-
-async fn agent_turn_runs_long_parallel_subagent_flow_with_many_nested_tool_calls_inner() {
- // `create_memory` below needs the global embedding host. This test never
- // installed it, so it only passed when some other test file in the same
- // binary happened to run first — and failed outright under any filter
- // narrow enough to exclude them all. `install_for_tests` is `Once`-guarded,
- // so calling it here is free when a sibling already did.
- AgentDefinitionRegistry::init_global_builtins().unwrap();
-
- let workspace = tempfile::TempDir::new().expect("temp workspace");
- let workspace_path = workspace.path().to_path_buf();
- let provider = ParallelHarnessProvider::default();
- let fixture_state = Arc::new(FixtureStepState::default());
-
- let tools: Vec<Box<dyn Tool>> = vec![
- Box::new(SpawnParallelAgentsTool::new()),
- Box::new(FixtureStepTool {
- state: Arc::clone(&fixture_state),
- }),
- ];
-
- let mut agent = OpenHumanSessionHost::builder()
- .chat_model(Arc::new(provider.clone()))
- .tools(tools)
- .tool_dispatcher(Box::new(NativeDialect))
- .workspace_dir(workspace_path)
- .build()
- .unwrap();
-
- let response = agent
- .turn("Run a long parallel delegation pass. parallel-fanout-e2e-canary")
- .await
- .unwrap_or_else(|err| {
- panic!(
- "agent turn failed: {err}\nseen payloads:\n{}",
- provider.state.seen_payloads.lock().join("\n---\n")
- )
- });
-
- assert!(
- response.contains(FINAL_CANARY),
- "final orchestrator response should contain the synthesis canary: {response}"
- );
- assert!(
- response.contains(RESEARCH_DONE_CANARY) && response.contains(PLANNER_DONE_CANARY),
- "final response should include both subagent completions: {response}"
- );
- assert_eq!(
- fixture_state.calls.load(Ordering::SeqCst),
- 6,
- "expected three nested tool calls per parallel subagent"
- );
- assert!(
- provider.max_active_subagent_calls() >= 2,
- "expected overlapping subagent provider calls, max_active={}",
- provider.max_active_subagent_calls()
- );
- assert!(
- provider.total_calls() >= 10,
- "expected parent + subagent loop to hit the provider many times, total_calls={}",
- provider.total_calls()
- );
-
- let history = agent.history();
- let mut saw_parallel_call = false;
- let mut saw_parallel_result = false;
- let mut iterations = Vec::new();
-
- for message in history {
- match message {
- TranscriptEntry::AssistantToolCalls { tool_calls, .. } => {
- if tool_calls
- .iter()
- .any(|call| call.name == "spawn_parallel_agents")
- {
- saw_parallel_call = true;
- }
- }
- TranscriptEntry::ToolResults(results) => {
- for result in results {
- if !result.content.contains("\"parallel_agents\"") {
- continue;
- }
- saw_parallel_result = true;
- let payload: serde_json::Value =
- serde_json::from_str(&result.content).expect("parallel tool result json");
- assert_eq!(payload["parallel_agents"]["succeeded"], 2);
- assert_eq!(payload["parallel_agents"]["failed"], 0);
-
- let results = payload["parallel_agents"]["results"]
- .as_array()
- .expect("parallel results array");
- assert_eq!(results.len(), 2);
- for item in results {
- assert_eq!(item["success"], true);
- iterations.push(
- item["iterations"]
- .as_u64()
- .expect("parallel result iterations"),
- );
- }
- }
- }
- TranscriptEntry::Chat(message) if message.role.as_str() == "assistant" => {
- if message.content.contains("spawn_parallel_agents") {
- saw_parallel_call = true;
- }
- }
- TranscriptEntry::Chat(message) if message.role.as_str() == "tool" => {
- let content = serde_json::from_str::<serde_json::Value>(&message.content)
- .ok()
- .and_then(|envelope| {
- envelope
- .get("content")
- .and_then(serde_json::Value::as_str)
- .map(str::to_owned)
- })
- .unwrap_or_else(|| message.content.clone());
- if !content.contains("\"parallel_agents\"") {
- continue;
- }
- saw_parallel_result = true;
- let payload: serde_json::Value =
- serde_json::from_str(&content).expect("parallel tool result json");
- assert_eq!(payload["parallel_agents"]["succeeded"], 2);
- assert_eq!(payload["parallel_agents"]["failed"], 0);
-
- let results = payload["parallel_agents"]["results"]
- .as_array()
- .expect("parallel results array");
- assert_eq!(results.len(), 2);
- for item in results {
- assert_eq!(item["success"], true);
- iterations.push(
- item["iterations"]
- .as_u64()
- .expect("parallel result iterations"),
- );
- }
- }
- _ => {}
- }
- }
-
- assert!(
- saw_parallel_call,
- "parent history should record spawn_parallel_agents"
- );
- assert!(
- saw_parallel_result,
- "parent history should record the parallel tool result"
- );
- assert_eq!(
- iterations,
- vec![4, 4],
- "each subagent should run three tool calls plus a final completion iteration"
- );
-}
-
-/// Helper: parent context whose subagent allowlist admits `ids`.
-fn parent_admitting(ids: &[&str], tools: Vec<Box<dyn Tool>>) -> ParentExecutionContext {
- let mut parent = parent_context_with_tools(8, tools);
- parent.allowed_subagent_ids = ids.iter().map(|id| id.to_string()).collect();
- parent
-}
-
-/// Helper: the single write-capable tool the dispatch fixtures share.
-fn write_fixture_tools() -> Vec<Box<dyn Tool>> {
- vec![Box::new(PermissionFixtureTool {
- name: "write_fixture",
- level: PermissionLevel::Write,
- })]
-}
-
-/// Helper: build a fan-out task with only the fields a dispatch decision reads.
-fn dispatch_task(
- agent_id: &str,
- ownership: Option<&str>,
- isolation: Option<&str>,
-) -> ParallelAgentTask {
- ParallelAgentTask {
- agent_id: agent_id.into(),
- prompt: "do the thing".into(),
- context: None,
- ownership: ownership.map(str::to_string),
- isolation: isolation.map(str::to_string),
- base_ref: None,
- }
-}
-
-#[path = "spawn_parallel_agents_policy_tests.rs"]
-mod policy_tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree.rs b/crates/openhuman-core/src/agent/orchestration/worktree.rs
deleted file mode 100644
index b2eba02104..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/worktree.rs
+++ /dev/null
@@ -1,188 +0,0 @@
-//! Git-worktree isolation for parallel, edit-capable agent workers.
-//!
-//! Parallel coding workers spawned via [`super::tools::spawn_parallel_agents`]
-//! historically shared one workspace (`Config.action_dir`). Two workers editing
-//! overlapping files left the parent with stale assumptions and silent
-//! clobbers. Each isolated worker instead gets its own `git worktree` checkout
-//! of the **user's project repo** (the directory the coding agent edits), so
-//! file edits never collide.
-//!
-//! ## Where the implementation lives
-//!
-//! The git plumbing itself is **TinyAgents'**
-//! ([`tinyagents_harness::workspace::git`]): worktree create/list/status/diff/
-//! remove, repo-root validation, run-id sanitizing, and cross-worker overlap
-//! detection. Callers import that surface directly from the harness.
-//!
-//! What stays in OpenHuman is the part that depends on *this* host: the
-//! [`OpenHumanWorktreeIsolation`] adapter, which stamps an
-//! `openhuman.worktree:{agent}:{run_id}` policy id onto prepared descriptors and
-//! announces workspace lifecycle on the OpenHuman event bus so audit and
-//! observability subscribers can correlate an isolated run with its allowed
-//! root.
-//!
-//! ## Scope and safety
-//!
-//! - This targets the **user's project repository** rooted at the agent's
-//! `action_dir` — it never operates on OpenHuman's own source tree.
-//! - Every operation validates that `repo_root` is a real git repository
-//! first (via `git rev-parse --is-inside-work-tree`), so a stray path can
-//! never be mutated.
-//! - `remove_git_worktree` refuses to delete a **dirty** worktree unless
-//! `force = true`.
-//! Clean worktrees can be auto-reclaimed; dirty ones require an explicit
-//! user decision (acceptance criterion of #3376).
-//!
-//! The wrapper shells out to `git` through [`std::process::Command`] with an
-//! explicit, validated working directory. It does not inherit ambient git
-//! configuration that could redirect operations elsewhere.
-
-use std::path::PathBuf;
-
-use tinyagents_harness::workspace::{
- GitWorktreeBaseRef, GitWorktreeIsolation, GitWorktreeLifecycleHook, WorkspaceIsolation,
-};
-use tinytools::{SandboxMode, WorkspaceDescriptor};
-
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-
-/// OpenHuman's [`WorkspaceIsolation`] adapter over the TinyAgents git-worktree
-/// provider.
-///
-/// The crate's [`GitWorktreeIsolation`] already prepares and cleans up the
-/// checkout. This wrapper adds the two things that are OpenHuman's rather than
-/// every host's: the `openhuman.worktree:*` policy-id convention, and
-/// [`DomainEvent::WorkspacePrepared`] / [`DomainEvent::WorkspaceCleanup`]
-/// announcements on the global bus.
-#[derive(Debug, Clone)]
-pub struct OpenHumanWorktreeIsolation {
- inner: GitWorktreeIsolation,
-}
-
-impl OpenHumanWorktreeIsolation {
- /// Create an isolation provider rooted at the user's project repo.
- pub fn new(repo_root: impl Into<PathBuf>) -> Self {
- Self {
- inner: GitWorktreeIsolation::new(repo_root)
- .with_policy_id_prefix("openhuman.worktree")
- .with_lifecycle_hook(std::sync::Arc::new(OpenHumanWorktreeLifecycle)),
- }
- }
-
- /// Select which ref new worktrees branch from.
- pub fn with_base_ref(mut self, base_ref: GitWorktreeBaseRef) -> Self {
- self.inner = self.inner.with_base_ref(base_ref);
- self
- }
-
- /// Advertise the sandbox expectation on prepared descriptors.
- pub fn with_sandbox(mut self, sandbox: SandboxMode) -> Self {
- self.inner = self.inner.with_sandbox(sandbox);
- self
- }
-
- /// Add an extra root tools may touch alongside the isolated checkout.
- pub fn with_trusted_root(mut self, root: impl Into<PathBuf>) -> Self {
- self.inner = self.inner.with_trusted_root(root);
- self
- }
-}
-
-struct OpenHumanWorktreeLifecycle;
-
-#[async_trait::async_trait]
-impl GitWorktreeLifecycleHook for OpenHumanWorktreeLifecycle {
- async fn prepared(&self, descriptor: &WorkspaceDescriptor) -> tinyagents_harness::Result<()> {
- let _ = BUS.publish(DomainEvent::WorkspacePrepared {
- policy_id: descriptor.policy_id.clone(),
- root: descriptor.root.display().to_string(),
- });
- Ok(())
- }
-
- async fn cleaned(
- &self,
- descriptor: &WorkspaceDescriptor,
- error: Option<&str>,
- ) -> tinyagents_harness::Result<()> {
- let _ = BUS.publish(DomainEvent::WorkspaceCleanup {
- policy_id: descriptor.policy_id.clone(),
- error: error.map(str::to_owned),
- });
- Ok(())
- }
-}
-
-#[async_trait::async_trait]
-impl WorkspaceIsolation for OpenHumanWorktreeIsolation {
- async fn prepare(
- &self,
- run_id: &str,
- agent: Option<&str>,
- ) -> tinyagents_harness::Result<WorkspaceDescriptor> {
- tracing::debug!(
- run_id,
- agent = agent.unwrap_or(""),
- "[worktree] workspace_prepare_start"
- );
-
- let descriptor = self.inner.prepare(run_id, agent).await?;
-
- tracing::debug!(
- root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[worktree] workspace_prepare_done"
- );
- // Announce the prepared workspace so audit/observability subscribers can
- // correlate the isolated run with its allowed root.
- tracing::debug!(
- root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[workspace] workspace_prepared_emit"
- );
- Ok(descriptor)
- }
-
- async fn cleanup(&self, descriptor: &WorkspaceDescriptor) -> tinyagents_harness::Result<()> {
- tracing::debug!(
- root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[worktree] workspace_cleanup_start"
- );
-
- match self.inner.cleanup(descriptor).await {
- Ok(()) => {
- tracing::debug!(
- root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- "[worktree] workspace_cleanup_done"
- );
- tracing::debug!(
- policy_id = %descriptor.policy_id,
- "[workspace] workspace_cleanup_emit_ok"
- );
- Ok(())
- }
- Err(err) => {
- let message = err.to_string();
- tracing::warn!(
- root = %descriptor.root.display(),
- policy_id = %descriptor.policy_id,
- error = %message,
- "[worktree] workspace_cleanup_failed"
- );
- tracing::debug!(
- policy_id = %descriptor.policy_id,
- error = %message,
- "[workspace] workspace_cleanup_emit_err"
- );
- Err(err)
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "worktree_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs b/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs
deleted file mode 100644
index b586d805f1..0000000000
--- a/crates/openhuman-core/src/agent/orchestration/worktree_tests.rs
+++ /dev/null
@@ -1,57 +0,0 @@
-//! Host-typed tests for the worktree wire contract.
-//!
-//! The git-worktree plumbing itself is tested in
-//! `vendor/tinyagents/crates/tinyagents-harness/src/workspace/git/test.rs`.
-
-use tinyagents_harness::workspace::GitWorktreeStatus;
-
-/// Pins the JSON-RPC wire shape of [`GitWorktreeStatus`].
-///
-/// `worktree_schemas.rs` serializes this type straight to the desktop UI, so a
-/// renamed or dropped field surfaces as an empty worktree panel rather than a
-/// failing test. This asserts the exact camelCase key set and value shapes so
-/// the type can be re-pointed at the TinyAgents `GitWorktreeStatus` without
-/// silently changing the contract.
-#[test]
-fn worktree_status_serializes_with_stable_camel_case_keys() {
- let status = GitWorktreeStatus {
- path: std::path::PathBuf::from("/tmp/repo/.claude/worktrees/run-1"),
- branch: Some("agent/run-1".to_string()),
- is_dirty: true,
- changed_files: vec![
- std::path::PathBuf::from("src/a.rs"),
- std::path::PathBuf::from("src/b.rs"),
- ],
- };
-
- let value = serde_json::to_value(&status).expect("GitWorktreeStatus serializes");
- let object = value.as_object().expect("serializes to a JSON object");
-
- let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
- keys.sort_unstable();
- assert_eq!(
- keys,
- vec!["branch", "changedFiles", "isDirty", "path"],
- "worktree status wire keys changed — the desktop worktree panel reads these"
- );
-
- assert_eq!(value["path"], "/tmp/repo/.claude/worktrees/run-1");
- assert_eq!(value["branch"], "agent/run-1");
- assert_eq!(value["isDirty"], true);
- assert_eq!(
- value["changedFiles"],
- serde_json::json!(["src/a.rs", "src/b.rs"])
- );
-
- // A detached worktree serializes `branch` as null, not as an omitted key.
- let detached = GitWorktreeStatus {
- branch: None,
- ..status
- };
- let detached_value = serde_json::to_value(&detached).expect("serializes");
- assert!(
- detached_value.as_object().unwrap().contains_key("branch"),
- "branch must stay present-and-null so the UI can distinguish detached HEAD"
- );
- assert_eq!(detached_value["branch"], serde_json::Value::Null);
-}
diff --git a/crates/openhuman-core/src/agent_runs/worktree_schemas.rs b/crates/openhuman-core/src/agent_runs/worktree_schemas.rs
deleted file mode 100644
index b5059136ed..0000000000
--- a/crates/openhuman-core/src/agent_runs/worktree_schemas.rs
+++ /dev/null
@@ -1,328 +0,0 @@
-//! Controller schemas + JSON-RPC dispatchers for the git-worktree manager
-//! (#3376). Exposes the read + cleanup surface the app needs to list, inspect,
-//! diff, and remove the isolated worker worktrees created by
-//! [`super::tools::spawn_parallel_agents`].
-//!
-//! Namespace `worktree`:
-//! - `worktree_list` — list isolated worker worktrees + cross-worker overlaps.
-//! - `worktree_status` — branch / dirty / changed-files snapshot for one path.
-//! - `worktree_diff` — human-readable `--stat` diff for one worktree.
-//! - `worktree_remove` — remove a worktree (refuses dirty unless `force=true`).
-//!
-//! Handlers delegate to [`super::worktree`]; no business logic lives here. The
-//! repository root every operation anchors on is the agent's `action_dir`
-//! (the user's project repo), resolved from the loaded [`Config`].
-//!
-//! [`Config`]: crate::config::schema::types::Config
-
-use crate::core::runtime::DispatchCtx;
-use std::path::{Path, PathBuf};
-
-use serde_json::{json, Map, Value};
-
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::Outcome;
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use tinyagents_harness::workspace::{
- detect_worktree_overlaps, git_worktree_diff_summary, git_worktree_status, list_git_worktrees,
- remove_git_worktree, GitWorktreeError, GitWorktreeStatus, GIT_WORKTREE_SUBDIR,
-};
-
-/// Controller schemas exposed by the worktree manager.
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- schema_for("worktree_list"),
- schema_for("worktree_status"),
- schema_for("worktree_diff"),
- schema_for("worktree_remove"),
- ]
-}
-
-/// Registered controllers (schema + handler) for the worktree manager.
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: schema_for("worktree_list"),
- handler: handle_list,
- },
- RegisteredController {
- schema: schema_for("worktree_status"),
- handler: handle_status,
- },
- RegisteredController {
- schema: schema_for("worktree_diff"),
- handler: handle_diff,
- },
- RegisteredController {
- schema: schema_for("worktree_remove"),
- handler: handle_remove,
- },
- ]
-}
-
-fn schema_for(function: &str) -> ControllerSchema {
- match function {
- "worktree_list" => ControllerSchema {
- namespace: "worktree",
- function: "list",
- description: "List the isolated worker git worktrees under \
- <repo>/.claude/worktrees, each with branch / dirty / \
- changed-files state, plus cross-worker file overlaps.",
- inputs: vec![],
- outputs: vec![json_output(
- "result",
- "WorktreeListView: { worktrees: WorktreeStatus[], overlaps: \
- { file, branches }[] }.",
- )],
- },
- "worktree_status" => ControllerSchema {
- namespace: "worktree",
- function: "status",
- description: "Branch / dirty / changed-files snapshot for a single \
- worktree by absolute path.",
- inputs: vec![required_str("path", "Absolute worktree checkout path.")],
- outputs: vec![json_output("result", "WorktreeStatus payload.")],
- },
- "worktree_diff" => ControllerSchema {
- namespace: "worktree",
- function: "diff",
- description: "Human-readable `git diff HEAD --stat` (plus untracked \
- files) for a single worktree. Empty for a clean tree.",
- inputs: vec![required_str("path", "Absolute worktree checkout path.")],
- outputs: vec![json_output("result", "{ summary: string }.")],
- },
- "worktree_remove" => ControllerSchema {
- namespace: "worktree",
- function: "remove",
- description: "Remove a worktree checkout. Refuses a dirty worktree \
- unless force=true (uncommitted work needs an explicit \
- user decision). The worker/<id> branch is left intact.",
- inputs: vec![
- required_str("path", "Absolute worktree checkout path."),
- optional_bool(
- "force",
- "Remove even when the worktree has uncommitted changes \
- (default false).",
- ),
- ],
- outputs: vec![json_output("result", "{ removed: bool }.")],
- },
- other => unreachable!("unknown worktree schema: {other}"),
- }
-}
-
-/// Resolve the project repo root every worktree op anchors on — the agent's
-/// `action_dir` from the loaded config.
-async fn repo_root(ctx: &DispatchCtx, cid: &str) -> Result<PathBuf, String> {
- let config = ctx.load_config().await.inspect_err(|err| {
- log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] config_failed err={err}");
- })?;
- Ok(config.action_dir.clone())
-}
-
-/// Resolve and validate the `path` param for status/diff/remove.
-///
-/// These ops must only ever target an isolated worker checkout under
-/// `<repo>/.claude/worktrees`. Requiring an **absolute, managed** path before
-/// delegating keeps `worktree_remove` (and the read ops) from acting on the
-/// main checkout or any arbitrary directory the caller passes.
-fn require_managed_worktree_path(params: &Map<String, Value>) -> Result<PathBuf, String> {
- let path = params
- .get("path")
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .map(PathBuf::from)
- .ok_or_else(|| "missing required param: path".to_string())?;
- if !path.is_absolute() {
- return Err("invalid param `path`: absolute path required".to_string());
- }
- if !is_managed_worktree(&path) {
- return Err("invalid param `path`: not a managed worker worktree".to_string());
- }
- Ok(path)
-}
-
-fn handle_list(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] list.entry");
- let root = repo_root(&ctx, &cid).await?;
- list_view(&root, &cid)
- })
-}
-
-fn handle_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] status.entry");
- let root = repo_root(&ctx, &cid).await?;
- let path = require_managed_worktree_path(&params)?;
- status_view(&root, &path, &cid)
- })
-}
-
-fn handle_diff(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] diff.entry");
- let root = repo_root(&ctx, &cid).await?;
- let path = require_managed_worktree_path(&params)?;
- diff_view(&root, &path, &cid)
- })
-}
-
-fn handle_remove(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let cid = new_correlation_id();
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.entry");
- let root = repo_root(&ctx, &cid).await?;
- let path = require_managed_worktree_path(&params)?;
- let force = params
- .get("force")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
- remove_view(&root, &path, force, &cid)
- })
-}
-
-/// Pure list logic anchored on an already-resolved `repo_root` — split out of
-/// [`handle_list`] so it's unit-testable against a real temp repo without the
-/// global config load.
-fn list_view(root: &Path, cid: &str) -> Result<Value, String> {
- // A non-git action_dir is normal (the user may not have opened a repo).
- // Degrade to an empty list rather than surfacing an error to the panel.
- let all = match list_git_worktrees(root) {
- Ok(list) => list,
- Err(GitWorktreeError::NotAGitRepo(p)) => {
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] list.not_a_git_repo path={}", p.display());
- return to_json(json!({ "worktrees": [], "overlaps": [] }));
- }
- Err(err) => {
- let s = err.to_string();
- log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] list.error err={s}");
- return Err(s);
- }
- };
-
- // Only the isolated worker worktrees are management targets — never the
- // main checkout. Filter to those nested under `.claude/worktrees`.
- let worktrees: Vec<GitWorktreeStatus> = all
- .into_iter()
- .filter(|w| is_managed_worktree(&w.path))
- .collect();
-
- let overlaps = overlaps_json(&worktrees);
- log::debug!(
- target: "worktree_rpc",
- "[worktree_rpc][{cid}] list.success count={} overlaps={}",
- worktrees.len(),
- overlaps.len()
- );
- to_json(json!({ "worktrees": worktrees, "overlaps": overlaps }))
-}
-
-/// Pure status logic anchored on a resolved `repo_root` — see [`list_view`].
-fn status_view(root: &Path, path: &Path, cid: &str) -> Result<Value, String> {
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] status.path={}", path.display());
- let status = git_worktree_status(root, path).map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] status.error err={s}");
- s
- })?;
- to_json(status)
-}
-
-/// Pure diff logic anchored on a resolved `repo_root` — see [`list_view`].
-fn diff_view(root: &Path, path: &Path, cid: &str) -> Result<Value, String> {
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] diff.path={}", path.display());
- let summary = git_worktree_diff_summary(root, path).map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] diff.error err={s}");
- s
- })?;
- to_json(json!({ "summary": summary }))
-}
-
-/// Pure remove logic anchored on a resolved `repo_root` — see [`list_view`].
-fn remove_view(root: &Path, path: &Path, force: bool, cid: &str) -> Result<Value, String> {
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.path={} force={force}", path.display());
- remove_git_worktree(root, path, force).map_err(|e| {
- let s = e.to_string();
- log::warn!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.error err={s}");
- s
- })?;
- log::debug!(target: "worktree_rpc", "[worktree_rpc][{cid}] remove.success path={}", path.display());
- to_json(json!({ "removed": true }))
-}
-
-/// `true` when `path` is an isolated worker worktree (nested under the
-/// `.claude/worktrees` convention dir), i.e. a manageable cleanup target.
-fn is_managed_worktree(path: &Path) -> bool {
- let needle = std::path::Path::new(GIT_WORKTREE_SUBDIR);
- let mut comps = needle.components();
- let (Some(a), Some(b)) = (comps.next(), comps.next()) else {
- return false;
- };
- // Match the consecutive ".claude" / "worktrees" segments anywhere in path.
- let segs: Vec<_> = path.components().collect();
- segs.windows(2).any(|w| w[0] == a && w[1] == b)
-}
-
-/// Compute cross-worktree file overlaps (a changed file touched by more than
-/// one worktree), keyed for display by each worktree's branch (path fallback).
-fn overlaps_json(worktrees: &[GitWorktreeStatus]) -> Vec<Value> {
- let per_worker: Vec<(String, Vec<PathBuf>)> = worktrees
- .iter()
- .filter(|w| !w.changed_files.is_empty())
- .map(|w| {
- let label = w
- .branch
- .clone()
- .unwrap_or_else(|| w.path.to_string_lossy().to_string());
- (label, w.changed_files.clone())
- })
- .collect();
- detect_worktree_overlaps(&per_worker)
- .into_iter()
- .map(|(file, branches)| json!({ "file": file.to_string_lossy(), "branches": branches }))
- .collect()
-}
-
-fn to_json<T: serde::Serialize>(value: T) -> Result<Value, String> {
- Outcome::new(value, vec![]).into_cli_compatible_json()
-}
-
-fn new_correlation_id() -> String {
- uuid::Uuid::new_v4().simple().to_string()[..8].to_string()
-}
-
-fn required_str(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::String,
- comment,
- required: true,
- }
-}
-
-fn optional_bool(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
- comment,
- required: false,
- }
-}
-
-fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
- FieldSchema {
- name,
- ty: TypeSchema::Json,
- comment,
- required: true,
- }
-}
-
-#[cfg(test)]
-#[path = "worktree_schemas_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/agent_runs/worktree_schemas_tests.rs b/crates/openhuman-core/src/agent_runs/worktree_schemas_tests.rs
deleted file mode 100644
index d52bd017ec..0000000000
--- a/crates/openhuman-core/src/agent_runs/worktree_schemas_tests.rs
+++ /dev/null
@@ -1,229 +0,0 @@
-use super::*;
-use crate::core::runtime::DispatchCtx;
-use std::process::Command;
-use tinyagents_harness::workspace::{create_git_worktree, GitWorktreeBaseRef, GitWorktreeStatus};
-
-/// `true` when `git` is invokable on this host. Tests that need real
-/// `git worktree` plumbing skip (pass trivially) when it's absent, so a
-/// git-less CI image doesn't hard-fail — same convention as
-/// `worktree_tests.rs`.
-fn git_available() -> bool {
- Command::new("git")
- .arg("--version")
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
-}
-
-fn git(dir: &Path, args: &[&str]) {
- let out = Command::new("git")
- .current_dir(dir)
- .args(args)
- .output()
- .expect("git invocation");
- assert!(
- out.status.success(),
- "git {args:?} failed: {}",
- String::from_utf8_lossy(&out.stderr)
- );
-}
-
-/// Temp git repo with one commit. Returns the guard (kept alive by the
-/// caller) and the repo root.
-fn init_repo() -> (tempfile::TempDir, PathBuf) {
- let tmp = tempfile::tempdir().expect("tempdir");
- let root = tmp.path().to_path_buf();
- git(&root, &["init", "-b", "main"]);
- git(&root, &["config", "user.email", "[email protected]"]);
- git(&root, &["config", "user.name", "Test User"]);
- std::fs::write(root.join("README.md"), "hello\n").unwrap();
- git(&root, &["add", "README.md"]);
- git(&root, &["commit", "-m", "initial"]);
- (tmp, root)
-}
-
-#[test]
-fn list_view_degrades_to_empty_for_non_git_root() {
- if !git_available() {
- return;
- }
- let tmp = tempfile::tempdir().unwrap();
- // A plain (non-git) directory must yield an empty list, not an error —
- // the panel shows "no worktrees" rather than surfacing a failure.
- let v = list_view(tmp.path(), "cid").expect("non-git root degrades cleanly");
- assert_eq!(v["worktrees"], json!([]));
- assert_eq!(v["overlaps"], json!([]));
-}
-
-#[test]
-fn list_view_surfaces_managed_worktree() {
- if !git_available() {
- return;
- }
- let (_tmp, root) = init_repo();
- let st = create_git_worktree(&root, "run-1", GitWorktreeBaseRef::Head).expect("create");
- assert!(
- is_managed_worktree(&st.path),
- "created under .claude/worktrees"
- );
-
- let v = list_view(&root, "cid").expect("list ok");
- let worktrees = v["worktrees"].as_array().expect("array");
- assert_eq!(worktrees.len(), 1, "the one managed worktree is listed");
- // A fresh worktree is clean → no overlaps.
- assert_eq!(v["overlaps"], json!([]));
-}
-
-/// Drives the full `handle_list` async handler (the public RPC entry point)
-/// through `repo_root` → config load, anchored on a non-git
-/// `OPENHUMAN_ACTION_DIR`. Confirms the panel-facing path degrades to an
-/// empty list rather than erroring. Holds `TEST_ENV_LOCK` because the env
-/// override is process-global.
-#[tokio::test]
-async fn handle_list_degrades_for_non_git_action_dir() {
- let _env = crate::config::TEST_ENV_LOCK.lock().await;
- let tmp = tempfile::tempdir().unwrap();
- let action_dir = tmp.path().join("actions");
- std::fs::create_dir_all(&action_dir).unwrap();
-
- // SAFETY: env writes are serialized by TEST_ENV_LOCK above.
- unsafe {
- std::env::set_var("OPENHUMAN_WORKSPACE", tmp.path());
- std::env::set_var("OPENHUMAN_ACTION_DIR", &action_dir);
- }
-
- let out = handle_list(DispatchCtx::process_default(), Map::new())
- .await
- .expect("list handler degrades cleanly for a non-git action_dir");
- // `into_cli_compatible_json` returns the bare value when there are no
- // logs; the list payload is therefore at the top level.
- let payload = out.get("result").unwrap_or(&out);
- assert_eq!(payload["worktrees"], json!([]));
- assert_eq!(payload["overlaps"], json!([]));
-
- unsafe {
- std::env::remove_var("OPENHUMAN_ACTION_DIR");
- std::env::remove_var("OPENHUMAN_WORKSPACE");
- }
-}
-
-#[test]
-fn status_and_diff_views_round_trip_a_worktree() {
- if !git_available() {
- return;
- }
- let (_tmp, root) = init_repo();
- let st = create_git_worktree(&root, "run-2", GitWorktreeBaseRef::Head).expect("create");
-
- // `WorktreeStatus` serializes `rename_all = "camelCase"` → `isDirty`.
- let status = status_view(&root, &st.path, "cid").expect("status ok");
- assert_eq!(status["isDirty"], json!(false), "fresh worktree is clean");
-
- // A clean worktree diffs to an empty summary.
- let diff = diff_view(&root, &st.path, "cid").expect("diff ok");
- assert_eq!(diff["summary"], json!(""));
-}
-
-#[test]
-fn remove_view_clears_a_clean_worktree() {
- if !git_available() {
- return;
- }
- let (_tmp, root) = init_repo();
- let st = create_git_worktree(&root, "run-3", GitWorktreeBaseRef::Head).expect("create");
- assert!(st.path.exists());
-
- let removed = remove_view(&root, &st.path, false, "cid").expect("remove ok");
- assert_eq!(removed["removed"], json!(true));
- assert!(!st.path.exists(), "worktree dir gone after remove");
-}
-
-#[test]
-fn status_view_errors_on_unknown_path() {
- if !git_available() {
- return;
- }
- let (_tmp, root) = init_repo();
- let bogus = root.join(".claude/worktrees/never-created");
- assert!(status_view(&root, &bogus, "cid").is_err());
-}
-
-#[test]
-fn correlation_id_is_eight_hex_chars() {
- let id = new_correlation_id();
- assert_eq!(id.len(), 8);
- assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
-}
-
-#[test]
-fn registered_controllers_match_schemas() {
- let schemas = all_controller_schemas();
- let registered = all_registered_controllers();
- assert_eq!(schemas.len(), registered.len());
- assert_eq!(schemas.len(), 4);
- assert!(schemas.iter().all(|s| s.namespace == "worktree"));
- assert_eq!(schema_for("worktree_list").function, "list");
- assert_eq!(schema_for("worktree_status").function, "status");
- assert_eq!(schema_for("worktree_diff").function, "diff");
- assert_eq!(schema_for("worktree_remove").function, "remove");
-}
-
-#[test]
-fn managed_worktree_filter() {
- assert!(is_managed_worktree(Path::new(
- "/home/u/proj/.claude/worktrees/worker-abc"
- )));
- assert!(!is_managed_worktree(Path::new("/home/u/proj")));
- assert!(!is_managed_worktree(Path::new("/home/u/proj/.claude")));
-}
-
-#[test]
-fn require_managed_worktree_path_enforces_absolute_and_managed() {
- let mut p = Map::new();
- // Missing / blank path is rejected.
- assert!(require_managed_worktree_path(&p).is_err());
- p.insert("path".into(), Value::String(" ".into()));
- assert!(require_managed_worktree_path(&p).is_err());
-
- // A relative path is rejected even when it looks managed.
- p.insert(
- "path".into(),
- Value::String(".claude/worktrees/worker-x".into()),
- );
- assert!(require_managed_worktree_path(&p).is_err());
-
- // An absolute but unmanaged path (e.g. the main checkout) is rejected —
- // worktree_remove must never target it.
- p.insert("path".into(), Value::String("/home/u/proj".into()));
- assert!(require_managed_worktree_path(&p).is_err());
-
- // An absolute, managed worker checkout is accepted.
- let ok = "/home/u/proj/.claude/worktrees/worker-x";
- p.insert("path".into(), Value::String(ok.into()));
- assert_eq!(
- require_managed_worktree_path(&p).unwrap(),
- PathBuf::from(ok)
- );
-}
-
-#[test]
-fn overlaps_detected_across_branches() {
- let worktrees = vec![
- GitWorktreeStatus {
- path: PathBuf::from("/r/.claude/worktrees/a"),
- branch: Some("worker/a".into()),
- is_dirty: true,
- changed_files: vec![PathBuf::from("src/lib.rs"), PathBuf::from("a.rs")],
- },
- GitWorktreeStatus {
- path: PathBuf::from("/r/.claude/worktrees/b"),
- branch: Some("worker/b".into()),
- is_dirty: true,
- changed_files: vec![PathBuf::from("src/lib.rs")],
- },
- ];
- let overlaps = overlaps_json(&worktrees);
- assert_eq!(overlaps.len(), 1);
- assert_eq!(overlaps[0]["file"], json!("src/lib.rs"));
- assert_eq!(overlaps[0]["branches"], json!(["worker/a", "worker/b"]));
-}