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
22 changes: 19 additions & 3 deletions src/solver/agentTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ function followupObjective(task: AgentTeamTask, message: string): string {
return !inherited.length || agentTeamProfileSelection(message).length ? message : 'Profiles: ' + inherited.join(', ') + '\n' + message;
}

function openRouteTask(task: AgentTeamTask) {
return !task.cancelRequested && !task.deliveryId && ['queued', 'running', 'paused', 'interrupted'].includes(task.status);
}

function correctableSourceFailure(error: unknown) {
return error instanceof SolverSourceError || error instanceof Error && error.message === 'math_source_outside_ownership';
}
Expand Down Expand Up @@ -297,7 +301,7 @@ export class AgentResearchTeam {
for (const worker of this.archive.workers) {
const pending = worker.pendingDelivery?.taskId;
const affected = worker.tasks.filter(task => task.routeId === input.routeId &&
(['queued', 'running', 'paused'].includes(task.status) || pending === task.id || task.helperSubmission));
(openRouteTask(task) || pending === task.id || task.helperSubmission));
if (!affected.length) continue;
const executing = affected.find(task => task.status === 'running' || pending === task.id || task.helperSubmission);
for (const task of affected) {
Expand All @@ -310,7 +314,7 @@ export class AgentResearchTeam {
}
}
const live = this.live.get(worker.id);
if (!worker.tasks.some(task => !task.cancelRequested && ['queued', 'running', 'paused'].includes(task.status))) {
if (!worker.tasks.some(openRouteTask)) {
worker.status = 'stopped';
worker.activity = live ? 'stopping' : 'idle';
releasedAgentIds.push(worker.id);
Expand Down Expand Up @@ -977,6 +981,7 @@ export class AgentResearchTeam {
turnId = activeTurnId; milestone.start();
worker.threadId = entry.session!.threadId;
worker.cursor = context.inboxThrough ?? worker.cursor;
worker.previewCursor = context.inboxPreviewThrough ?? worker.previewCursor;
usage.turnStarted(turnId); this.input.save();
if (worker.threadId !== worker.native!.threadId) throw new Error('math_team_native_start_identity_changed');
const accepted = this.nativeControl.accepted(worker, entry.session!, turnId);
Expand Down Expand Up @@ -1241,7 +1246,7 @@ export class AgentResearchTeam {
if (this.live.get(targetId)?.session || target?.writerStopUnconfirmed || targetId === 'lead' && (this.leadSession || state.writerStopUnconfirmed))
throw new Error('math_team_target_writing');
const worktree = target?.worktree ?? state.worktree;
const helpers = this.archive.deliveries.filter(delivery => delivery.kind === 'helpers' &&
const helpers = target?.status === 'stopped' ? [] : this.archive.deliveries.filter(delivery => delivery.kind === 'helpers' &&
!this.archive.adoptions.some(adoption => adoption.deliveryId === delivery.id && adoption.targetId === targetId));
const queued = this.archive.adoptions.filter(item => item.targetId === targetId && ['queued', 'integrating'].includes(item.status));
if (!helpers.length && !queued.length) return;
Expand Down Expand Up @@ -1361,6 +1366,17 @@ export class AgentResearchTeam {
}
await this.flushHelperSubmissions(worker);
if (worker.pendingDelivery) await this.finishDelivery(worker);
// Older hosts left interrupted assignments open even after Lead retired their route.
let closedRetiredTask = false;
for (const task of worker.tasks) {
if (task.status !== 'interrupted' || !openRouteTask(task)) continue;
const retirement = this.archive.retiredRoutes?.find(route => route.routeId === task.routeId);
if (!retirement) continue;
task.cancelRequested = { at: retirement.retiredAt, reason: retirement.reason };
task.status = 'cancelled'; task.finishedAt = retirement.retiredAt;
closedRetiredTask = true;
}
if (closedRetiredTask && !worker.tasks.some(openRouteTask)) worker.status = 'stopped';
}
await this.flushAdoptions();
for (const worker of this.archive.workers) {
Expand Down
7 changes: 3 additions & 4 deletions src/solver/agentTeamContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,16 @@ export function agentTeamWorkerDeliveryHelp(): string {

/** Refresh current work without promoting a prior task, peer message or Lead check into this member's result. */
export function agentTeamWorkerSection(state: Readonly<SolverRunState>, role: AgentTeamRole,
assignment: AgentTeamAssignment): { section: ContextSection; inboxThrough: number } {
assignment: AgentTeamAssignment): { section: ContextSection; inboxThrough: number; inboxPreviewThrough: number } {
const worker = state.agentTeam?.workers.find(item => item.id === role.id);
if (!worker) throw new Error('math_team_agent_unknown:' + role.id);
const current = worker.tasks.find(item => item.id === assignment.taskId);
if (!current || current.message !== assignment.message) throw new Error('math_team_assignment_changed');
const overview = agentTeamOverview(state, { focusAgentId: role.id, assignmentTaskId: current.id });
const own = overview.workers.find(item => item.id === role.id)!;
const prior = own.tasks.filter(item => item.id !== current.id && ['completed', 'failed', 'interrupted', 'cancelled', 'paused'].includes(item.status)).at(-1);
const inbox = agentTeamInboxPreview(state.agentTeam!, role.id, worker.cursor);
const inboxThrough = inbox.through;
return { inboxThrough, section: { id: 'agent-team-assignment', kind: 'assignment',
const inbox = agentTeamInboxPreview(state.agentTeam!, role.id, worker.cursor, worker.previewCursor);
return { inboxThrough: inbox.through, inboxPreviewThrough: inbox.previewThrough, section: { id: 'agent-team-assignment', kind: 'assignment',
text: 'Current native task instructions (latest accepted followup; earlier instructions remain in native history; frozen problem and source constraints still apply):\n' + JSON.stringify({
agentId: role.id, coordinator: 'lead', taskId: current.id, objective: assignment.message,
objectiveRevision: current.objectiveRevision ?? 1, workKind: current.workKind,
Expand Down
3 changes: 2 additions & 1 deletion src/solver/agentTeamState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ export const agentTeamStateSchema = z.object({ schema: z.literal('theorem-os.age
pendingSourceBase: z.string().regex(/^[a-f0-9]{40,64}$/u).optional(),
pendingPeerDeliveries: z.array(z.string().regex(/^[a-f0-9]{64}$/u)).optional(),
writerProcess: writerProcessSchema.optional(),
cursor: z.number().int().nonnegative(), pendingDelivery: z.object({ taskId: z.string(),
cursor: z.number().int().nonnegative(), previewCursor: z.number().int().nonnegative().optional(),
pendingDelivery: z.object({ taskId: z.string(),
seedCommit: z.string(), declarations: z.array(declaration), commit: z.string().optional(),
sourceDigest: z.string().optional() }).strict().optional(),
writerStopUnconfirmed: z.object({ at: z.number(), reason: z.string() }).strict().optional(),
Expand Down
9 changes: 5 additions & 4 deletions src/solver/agentTeamViews.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,21 +335,22 @@ function eventPreview(event: AgentTeamState['events'][number]) {
}

/** A truncated preview never acknowledges the unreturned message body. */
export function agentTeamInboxPreview(team: Readonly<AgentTeamState>, actor: string, after: number) {
export function agentTeamInboxPreview(team: Readonly<AgentTeamState>, actor: string, after: number, previewAfter = after) {
const events: ReturnType<typeof eventPreview>[] = [];
let through = after, truncated = false, more = false;
const start = Math.max(after, previewAfter);
for (const item of team.events) {
if (item.to !== actor || item.sequence <= after) continue;
if (item.to !== actor || item.sequence <= start) continue;
if (events.length === EVENTS) {
more = true;
break;
}
const event = eventPreview(item);
events.push(event);
truncated ||= Boolean(event.textTruncated);
if (!truncated) through = event.sequence;
if (start === after && !truncated) through = event.sequence;
}
return { after, through, previewThrough: events.at(-1)?.sequence ?? after, events,
return { after, through, previewAfter: start, previewThrough: events.at(-1)?.sequence ?? start, events,
more: more || truncated,
continuation: 'Read addressed native messages for complete updates; use history and inspect-research for saved task results. Previews do not acknowledge their bodies.' };
}
Expand Down
9 changes: 8 additions & 1 deletion src/solver/incrementalHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@ import type { DeclarationArtifactIdentity } from './declarationArtifacts';
import { checkProjectedDeclarations } from './modules/evidence';
import { assertSolverSources, committedSource, commitSolverSources, git, solverProofImports,
SolverSourceError, withSolverWorktree } from './problem';
import { proofReuseEnvironment } from './proofReuse';
import { hasDeterministicLeanFailure, hasLeanResourceLimitFailure, proofReuseEnvironment } from './proofReuse';
import { solverSourceContext } from './sourceContext';
import { allowedKnowledgeFile, locateKnowledgeDeclaration } from './theoremKnowledge';
import type { CooperativeTask } from './tasks';
import { VerifierFailureError } from './verifierFailure';

const leanName = z.string().min(1).max(1000).refine(isSimpleLeanName);
const leanFile = z.string().refine(value => value.endsWith('.lean') && allowedKnowledgeFile(value));
Expand Down Expand Up @@ -213,6 +214,12 @@ export async function landVerifiedHelpers(input: VerifiedHelpersInput): Promise<
return reject('source_rejected', error.message);
throw error;
});
const receipt = verification.verification;
// An interrupted or unbound check must leave the frozen nomination available for recovery.
if (receipt.results.some(result => result.cleanupError) ||
!verification.passed && !hasDeterministicLeanFailure(receipt) &&
!(batch.length === 1 && hasLeanResourceLimitFailure(receipt)))
throw new VerifierFailureError({ stage: 'incremental-helper-check', sourceCommit, verification: receipt });
for (const [index, declaration] of batch.entries()) {
const result = verification.verification.results[index];
if (result?.status !== 'kernel_verified' || result.verifier !== 'lean-kernel' || result.cleanupError || result.sorryCount !== 0 ||
Expand Down
3 changes: 2 additions & 1 deletion src/solver/proofReuse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ export function hasDeterministicLeanFailure(verification: MathematicsVerifierBat
return verification.status === 'failed' && verification.results.some(result => result.status === 'failed') &&
verification.results.every(result => {
const output = `${result.error || ''}\n${result.stdoutPreview || ''}\n${result.stderrPreview || ''}`;
const sourceRejection = result.error === 'Proof source contains sorry or admit.' &&
const sourceRejection = (result.error === 'Proof source contains sorry or admit.' ||
result.error === 'Helper source contains sorry or admit.') &&
((Number.isSafeInteger(result.sorryCount) && result.sorryCount > 0) ||
(Number.isSafeInteger(result.admitCount) && result.admitCount > 0)) ||
Boolean(result.axioms?.length && result.error === `Proof source declares explicit axioms: ${result.axioms.join(', ')}.`) ||
Expand Down
4 changes: 2 additions & 2 deletions src/solver/skillResearchContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function agentTeamContextSection(state: Readonly<SolverRunState>): Contex

/** Stable host contracts and current facts; research methods live in the pinned skill. */
export function buildSkillResearchContext(problem: SolverProblem, state: Readonly<SolverRunState>,
access: ContextAccess & { researchSkill: MathAgentSkill }): ContextBundle & { inboxThrough?: number } {
access: ContextAccess & { researchSkill: MathAgentSkill }): ContextBundle & { inboxThrough?: number; inboxPreviewThrough?: number } {
const skill = access.researchSkill;
assertMathAgentSkillsCurrent([skill]);
if (!state.researchSkill || state.researchSkill.digest !== skill.digest || state.researchSkill.name !== skill.name ||
Expand Down Expand Up @@ -158,6 +158,6 @@ export function buildSkillResearchContext(problem: SolverProblem, state: Readonl
maxOptionalContextBytes: access.maxOptionalContextBytes, inlineManifest: false });
const continued = compile({ continuation: true });
return { instructions, ...compile(), continuationMessage: continued.message, continuationManifest: continued.manifest,
compileDispatch: compile, inboxThrough: workerContext?.inboxThrough,
compileDispatch: compile, inboxThrough: workerContext?.inboxThrough, inboxPreviewThrough: workerContext?.inboxPreviewThrough,
scope: 'original-problem-and-allowed-library', sources: { problemReceiptDigest: problem.receiptDigest } };
}
68 changes: 68 additions & 0 deletions tests/agentTeamNativeLifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,74 @@ describe('native AgentControl preserves the mathematical team lifecycle', () =>
expect(f.sessions[2].message).toContain('Continue the original approach');
});

it('releases an interrupted route for a replacement, retaining the stopped draft', async () => {
const f = fixture();
await f.spawn('analyst', 'Route: obsolete\nInvestigate the initial route.');
const worker = f.team.archive.workers[0], task = worker.tasks[0];
fs.writeFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'Partial result.\n');
await f.native('interrupt', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, version: 'v2' });
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
expect(task.status).toBe('interrupted');
const commit = task.sourceCommit;
await f.spawn('peer');
await expect(f.tool({ operation: 'retire_route', routeId: 'obsolete', reason: 'Refuted by the saved probe.' }))
.resolves.toMatchObject({ cancelledTaskIds: [task.id], releasedAgentIds: [worker.id] });
await f.spawn('replacement');
expect(task).toMatchObject({ status: 'cancelled', sourceCommit: commit });
expect(fs.readFileSync(path.join(worker.worktree, 'RESEARCH.md'), 'utf8')).toBe('Partial result.\n');
});

it('keeps another interrupted route resumable when retiring a paused route', async () => {
const f = fixture();
await f.spawn('analyst', 'Route: keep\nInvestigate this route.');
const worker = f.team.archive.workers[0], target = { kind: 'id', threadId: worker.native!.threadId };
await f.native('interrupt', { caller: ROOT, target, version: 'v2' });
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
const followup = (text: string) => f.native('send', { caller: ROOT, target, input: {
kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text } } });
await followup('Route: obsolete\nExplore another approach.');
await f.tool({ operation: 'yield', reason: 'Awaiting evidence.' }, worker.id);
await f.sessions[1].complete();
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
expect(await f.tool({ operation: 'retire_route', routeId: 'obsolete', reason: 'No longer needed.' }))
.toMatchObject({ releasedAgentIds: [] });
await followup('Continue the remaining approach.');
expect(worker.tasks.map(task => [task.routeId, task.status])).toEqual([['keep', 'running'], ['obsolete', 'cancelled']]);
});

it('releases a slot left on a retired interrupted assignment by an older checkpoint', async () => {
const f = fixture(); await f.spawn('analyst', 'Route: obsolete\nInvestigate this route.');
const worker = f.team.archive.workers[0];
await f.native('interrupt', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, version: 'v2' });
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
f.team.archive.retiredRoutes = [{ routeId: 'obsolete', retiredAt: Date.now(), reason: 'Refuted.', source: 'lead' }];
await f.team.restore();
expect(worker.status).toBe('stopped');
expect(worker.tasks[0]).toMatchObject({ status: 'cancelled', cancelRequested: { reason: 'Refuted.' } });
await f.spawn('peer'); await f.spawn('replacement');
});

it('dispatches the next preview page without acknowledging a truncated body', async () => {
const f = fixture(); await f.spawn('analyst');
await f.sessions[0].complete();
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
const team = f.team.archive, worker = team.workers[0], seq = team.events.at(-1)?.sequence ?? 0;
for (let i = 1; i <= 9; i++) team.events.push({ sequence: seq + i, at: Date.now(), from: 'lead', to: worker.id,
kind: 'message', text: i === 1 ? 'A'.repeat(801) : 'fixed-notice-' + i });
for (let turn = 1; turn <= 2; turn++) {
await f.native('send', { caller: ROOT, target: { kind: 'id', threadId: worker.native!.threadId }, input: {
kind: 'message', mode: 'triggerTurn', message: { kind: 'plaintext', text: 'Check step ' + turn } } });
const message = f.sessions[turn].message;
expect(message).toContain(turn === 1 ? 'fixed-notice-8' : 'fixed-notice-9');
expect(message).not.toContain(turn === 1 ? 'fixed-notice-9' : 'fixed-notice-8');
const saved = readSolverRunState(path.join(f.directory, 'state.json')).agentTeam!.workers[0];
expect(saved.previewCursor).toBeGreaterThanOrEqual(seq + (turn === 1 ? 8 : 9));
expect(saved.cursor).toBeLessThan(seq + 1);
await f.sessions[turn].complete();
await expect.poll(() => f.team.hasActiveWorkers).toBe(false);
}
});

it('holds legacy queued routes for reassignment when the checkpoint has only one native input', async () => {
const f = fixture(); await f.spawn('analyst', 'Route: initial\nInvestigate the first approach.');
const worker = f.state.agentTeam!.workers[0];
Expand Down
Loading
Loading