Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/solver/agentTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './so
import { portfolioRouteIdSchema, type RetiredRoute, type routeRetirementSchema } from './routeControl';

type LiveWorker = { session?: MathAgentSession; task: Promise<void>; abort: AbortController; routeAbort: AbortController;
admittedTurnId?: string; runSettled?: boolean };
admittedTurnId?: string; runSettled?: boolean; readyNotice?: boolean };
const CHECKPOINT_CLOSE_GRACE_MS = 10_000;

/** Native AgentControl carries an attributed message rather than a separate route field. */
Expand Down Expand Up @@ -454,6 +454,17 @@ export class AgentResearchTeam {
if (worker.writerStopUnconfirmed) throw new Error('math_writer_stop_unconfirmed:' + worker.id);
if ((worker.status as string) === 'stopped') throw new Error('math_team_agent_stopped');
this.assertRouteAvailable(routeId);
// Integrating checked results can take minutes of Lean work. Do it without holding
// Lead's tool call, then tell Lead that this member is ready for the followup.
if (!worker.tasks.some(task => task.status === 'queued') && this.pendingIntegration(worker)) {
this.launch(worker);
const entry = this.live.get(worker.id);
if (entry) {
entry.readyNotice = true;
throw new NativeAgentControlInputError('math_team_native_member_busy: ' + worker.id +
' is integrating checked results into its workspace. Continue other work. The host sends a message when this member is ready; then repeat this followup.');
}
}
const saved = worker.tasks.findLast(task => ['paused', 'interrupted', 'queued'].includes(task.status) &&
!task.cancelRequested && !task.deliveryId && (routeId === undefined || routeId === task.routeId));
// There is one captured input per native writer. Do not replace it while
Expand All @@ -480,6 +491,15 @@ export class AgentResearchTeam {
return this.waitNativeStart(worker, signal);
}

/** Host work the next writer launch must finish before the member's turn can start. */
private pendingIntegration(worker: AgentTeamWorker) {
if (worker.pendingDelivery || worker.tasks.some(task => task.helperSubmission)) return true;
if (this.archive.adoptions.some(item => item.targetId === worker.id && ['queued', 'integrating'].includes(item.status))) return true;
return this.archive.deliveries.some(delivery => delivery.kind === 'helpers' &&
!this.archive.adoptions.some(adoption => adoption.deliveryId === delivery.id && adoption.targetId === worker.id)) &&
!solverSourceFeedback(this.input.state.problem, worker.worktree);
}

/** Native input is the instruction source; retain it for isolated-workspace resume. */
private updateNativeFollowup(task: AgentTeamTask, message: string, evidence?: AgentTeamTask['profileEvidence']) {
const nextMessage = followupObjective(task, message);
Expand Down Expand Up @@ -809,6 +829,9 @@ export class AgentResearchTeam {
}
pending?.reject(new Error(worker.error ?? 'math_team_native_start_failed'));
this.live.delete(worker.id); this.input.save();
if (entry.readyNotice && !this.stopping && !this.input.signal.aborted && !['failed', 'stopped'].includes(worker.status) &&
!worker.writerStopUnconfirmed && !this.pendingIntegration(worker))
this.event(null, 'lead', 'message', worker.id + ' finished integrating checked results and is ready. Repeat the followup to assign its work.');
// Per-task interruption consumes this controller. Reuse the member only after runTask has
// confirmed shutdown and saved its draft; a global stop or quarantine must never relaunch it.
if (entry.routeAbort.signal.aborted &&
Expand Down
37 changes: 37 additions & 0 deletions tests/agentTeamNativeLifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,43 @@ describe('native AgentControl preserves the mathematical team lifecycle', () =>
} finally { finishCheck.resolve(); }
}, 40_000);

it('answers a followup at once while an idle member integrates checked helpers, then reports readiness to Lead', async () => {
let gate: ReturnType<typeof deferred> | undefined;
const waiting = deferred();
const f = fixture({ beforeVerification: async () => { if (gate) { waiting.resolve(); await gate.promise; } } });
try {
await f.spawn('analyst');
const analyst = f.state.agentTeam!.workers[0]!;
await f.sessions[0]!.complete();
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
await f.spawn('prover');
const prover = f.state.agentTeam!.workers[1]!;
fs.writeFileSync(f.source(prover.worktree), fs.readFileSync(f.source(prover.worktree), 'utf8').replace('end NativeTeam',
'theorem reusable (n : Nat) : n = n := by rfl\nend NativeTeam'));
expect(await f.tool({ operation: 'submit', helpersOnly: true, summary: 'A useful helper.',
declarations: [{ file: 'Submission.lean', name: 'NativeTeam.reusable', type: '∀ n : Nat, n = n' }] }, prover.id))
.toMatchObject({ status: 'pending-writer-stop' });
await f.sessions[1]!.complete();
await expect.poll(() => f.team.archive.deliveries.some(item => item.kind === 'helpers'), { timeout: 30_000 }).toBe(true);
await expect.poll(() => f.team.hasActiveWorkers, { timeout: 30_000 }).toBe(false);
gate = deferred();
const followup = () => f.native('send', { caller: ROOT, target: { kind: 'id', threadId: analyst.native!.threadId },
input: { kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Use the helper for the next step.' } } });
// Lead's tool call does not wait for the member's Lean integration.
await expect(followup()).rejects.toThrow('math_team_native_member_busy');
await waiting.promise;
expect(analyst.activity).toBe('integrating');
expect(analyst.tasks).toHaveLength(1); expect(f.sessions).toHaveLength(2);
await expect(followup()).rejects.toThrow('math_team_native_member_busy');
gate.resolve();
await expect.poll(() => f.team.archive.events.some(event => event.to === 'lead' && event.kind === 'message' &&
event.text.startsWith('analyst finished integrating')), { timeout: 30_000 }).toBe(true);
expect(f.team.archive.adoptions).toContainEqual(expect.objectContaining({ targetId: 'analyst', status: 'completed' }));
await followup();
expect(analyst.tasks).toHaveLength(2); expect(f.sessions).toHaveLength(3);
} finally { gate?.resolve(); }
}, 60_000);

it('keeps a child accepted by the host when its initiating request is subsequently cancelled', async () => {
const f = fixture(), caller = new AbortController();
await f.spawn('analyst', undefined, caller.signal);
Expand Down
Loading