Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): typed tasks with fan-in, pipelines as data, continuity and memory (ADR-021)
Salman Qureshifad01f23e550
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.mdindex ddbdf148..859dd9bf 100644--- a/BOTS-ARCHITECTURE.md+++ b/BOTS-ARCHITECTURE.md@@ -235,6 +235,16 @@ Added after an audit of real fleets (see ADR-020 for the numbers). Four mechanisDeliverables live in an owner-visible folder (`BotStore.deliverablesDir`): finals on top, crew work under `work/`, a README index, dated human names. The hidden `outputs/` zone is legacy and migrated once.+### 2.13 Typed tasks, fan-in, pipelines, continuity (ADR-021, Oct 2026)++| Mechanism | Where | Effect |+|---|---|---|+| Durable typed tasks + batches with a wake policy and a deadline | `tasks.ts`, `BotManager.delegate` / `notifyBatch` | A lead is woken once with a digest, not once per crew mail |+| Pipelines as data (`pipeline.stages` in bot.yaml) | `BotManager.runPipeline` / `advancePipeline` | Stages chain themselves; no lead turn between stages; finals promoted |+| Journal digest + `bot_state` note in every prompt | `BotManager.recentRunsDigest`, `tools/bot-state.ts` | Continuity without status files |+| Memory extraction after productive runs | `memory-extract.ts` | The bot's own namespace accumulates sources, decisions, locations |+| Crew provider lane | `resolveProvider` | Stage work on a cheaper provider |+### 2.11 Devices without native SQLite (old Node versions, Termux)`better-sqlite3` is a native module: on unsupported Node versions or Termux/Android it may fail to install or load. Mercury already handles this exact problem for the second brain (optionalDependency + tmp-dir runtime probe, `src/memory/second-brain-db.ts:19-25`; `sql.js` ships as a regular dependency). Bots follow and extend the pattern:diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8260d1d8..e5f5daac 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,15 @@# Changelog+## Unreleased — fleets that coordinate (ADR-021)++Wave 2 of the bots work: how a lead hands out work and gets it back, how a bot remembers, and how a fleet's standard job runs without a lead turn between every step.++- **Typed tasks with fan-in.** `fleet_delegate` hands several tasks to the crew in one call — each with a goal and what "done" means — and the lead is woken **once** with a digest (status, outcome, delivered files, summary per task) when the batch completes or its deadline passes (default 120 min; stragglers report once each). `bot_send(task: true)` is now a batch of one. `fleet_tasks` lists and cancels; `fleet_status` shows open tasks. Tasks are durable (`tasks.json`) and deduplicated, so a replayed delegation turn never double-dispatches.+- **Pipelines as data.** A lead's standard job in `bot.yaml` (`pipeline.stages`: name, bot, goal with `{{input}}` / `{{previous}}`, optional `final`). `fleet_pipeline` runs it: stages chain themselves, each handing its deliverable to the next, with no lead turn in between; the lead is woken at the end; a `final` stage's deliverable is promoted to the top of the fleet folder.+- **Bots remember.** After a productive run, 0–3 durable facts (sources and their quality, decisions, where things are, what to avoid) are extracted into the bot's own memory (`memory.learn: false` disables). Every turn also starts with a digest of the last five runs from the journal and the bot's own working-state note (`bot_state`, ≤1500 chars, replaced not appended) — the legitimate version of the status files bots used to write.+- **Cheaper crew.** `bots.fleets.crewProvider` routes crew bots without a provider of their own to a cheaper lane; leads keep the default.+- `/bots tasks <leadId>` shows a lead's open and recent tasks from the TUI.+## Unreleased — bots that do work (ADR-020)An audit of eleven days of real fleets found bots spending 617M input tokens (a median turn of 750k, the largest 6.6M), failing 38% of runs, and mostly writing notes about earlier runs. This wave gives every bot turn a governor, every routine a gate, every run an outcome verdict, and every owner a folder they can find.diff --git a/DECISIONS.md b/DECISIONS.mdindex 47b81e14..ed5e67d4 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -185,3 +185,15 @@- **Anchoring and scanning**: the bot registry's cwd is the bot's workspace; the roster scan descends only into profile dirs and never into `sandbox/`, `outputs/`, `skills/`, `transcripts/`.- **Alternatives considered**: judging runs by the reply text (what the bots were already gaming); a cheaper model for routines instead of a gate (still 100% duty cycle); keeping deliverables under `~/.mercury` with a symlink (hidden folders are the problem, not the path); per-bot process isolation (unchanged: cost is the issue, not isolation).- **Consequence**: An idle fleet costs nothing; a busy one is bounded per turn, per bot and per fleet. A bot that narrates instead of delivering is visible in the journal within a run and paused within three. Owners open one folder per fleet. Existing bots change behaviour: cron ticks are now skipped when busy or too soon, every bot gets a 5M/day cap unless set to `none`, and the article-writer-style "every 10 minutes" persona is still accepted but can only fire every 30. Wave 2 (typed task/result protocol with fan-in, bot memory extraction, pipelines as data) builds on the outcome verdict and the deliverables folder.++## ADR-021: Fleet work is typed; leads are woken once; bots remember++- **Context**: After ADR-020 bounded the cost of a turn, the remaining waste was structural. A lead delegating to N crew got N free-text mails and ran N full turns to read them; results were 4,000-character strings a lead had to parse; nothing recorded what a task was, whether it was done, or where its output went; a replayed delegation turn re-dispatched; a fleet's standard job (research → draft → check → voice → package) needed a lead turn between every stage, each re-reading everything. Bots had 900 chars of memory retrieval and no write path, so continuity meant files — the "records about records" of ADR-020.+- **Decision**:+ - **Tasks** (`src/bots/tasks.ts`): a durable, typed unit of delegated work — requester, assignee, goal, acceptance, optional pipeline stage, status (queued → running → done | failed | halted | cancelled), job id, and a typed result (outcome, deliverables, summary, reason). Grouped in **batches** with a wake policy (`all` | `each`) and a deadline (default 120 minutes). Storage is one JSON file beside the queue (atomic rename): volume is small and it works wherever the JSON queue works. Open tasks are deduplicated by (requester, assignee, goal). Settled tasks are pruned after seven days; the journal keeps the run.+ - **Fan-in** (`BotManager.delegate` / `notifyBatch`): the crew's finished run settles its task; the requester is woken with a digest only when the batch is complete (`all`), per task (`each`), once when the deadline passes with work still open, and once per straggler after that. Digests come from a `fleet` sender, never as crew mail, and never reach the owner's chat. `dispatchTask` (used by `bot_send` task) is a batch of one. The 30-second due-sweep also checks deadlines.+ - **Pipelines** (`manifest.pipeline.stages`): data, not prose. `runPipeline` starts stage 0; each settled stage starts the next with the previous result as hand-off (`{{previous}}` resolves to delivered paths or the summary); a failed stage ends the run; the lead is woken once at the end; a `final` stage's deliverables are moved from `work/<crew>/` to the top of the fleet folder (`promoteDeliverable`).+ - **Continuity**: every turn's prompt carries the last five journal rows (time, trigger, state, outcome, delivered file or summary) and the bot's own working-state note (`bot_state`, 1,500 chars, overwrite-only, `state.md`). After a completed run with an outcome, `extractBotMemories` asks the bot's provider for 0–3 durable facts and stores them through `UserMemoryStore.remember` in the bot's namespace (`memory.learn: false` opts out; the daily budget applies).+ - **Crew lane**: `resolveProvider` sends a crew bot with no provider of its own to `bots.fleets.crewProvider` when set.+- **Alternatives considered**: tasks as rows in the SQLite queue (two backends to extend, no gain at this volume); waking the lead per result with a smarter prompt (still N turns); a scheduler-driven pipeline outside the task model (two orchestration paths); summarising the whole journal into the prompt (unbounded — five rows is the budget).+- **Consequence**: A fleet of five crew costs one lead turn to dispatch and one to synthesise, not seven. Pipelines run with zero lead turns in the middle. A bot's continuity is three things it never has to write: the journal digest, its note, and its memory. `bot_send(task)` callers see a digest instead of "✅ Task complete (job …)"; existing tests were updated accordingly. Wave 3 (cost views, run viewer, fleet kill switch, onboarding presets) is UI on top of this data.diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 703f9956..8444ab05 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -910,7 +910,8 @@ describe('Bot fleets (lead + crew)', () => {const dispatch = manager.dispatchTask('researcher', 'ceo', 'Study the market');expect(dispatch.accepted).toBe(true);await vi.waitFor(() => {- expect(sendSpy).toHaveBeenCalledWith('ceo', 'researcher', expect.stringContaining('MARKET REPORT'));+ // ADR-021: the result arrives as a typed batch digest from the fleet, not as crew mail.+ expect(sendSpy).toHaveBeenCalledWith('ceo', 'fleet', expect.stringContaining('MARKET REPORT'));});sendSpy.mockRestore();});@@ -931,7 +932,7 @@ describe('Bot fleets (lead + crew)', () => {mockedGenerateText.mockImplementation(async (opts: any) => {const text = JSON.stringify(opts?.messages ?? '');// Lead wake (mailbox trigger) after the crew result landed: synthesize.- if (text.includes('Task complete')) {+ if (text.includes('is complete')) {return { text: 'SYNTHESIS: combined market report', finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;}// Crew task turn (mailbox trigger with a reply target = the lead).diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 5db3d8f8..e056f06c 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -17,6 +17,10 @@ import { sweepSharedSandbox } from './retention.js';import { proposeCrew } from './fleet-onboarding.js';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';import { createBotSendTool } from './tools/bot-send.js';+import { BotTaskStore, renderTaskPrompt, renderBatchDigest, isTerminalTask, type BotTask, type BotTaskResult } from './tasks.js';+import { createFleetDelegateTool, createFleetTasksTool, createFleetPipelineTool } from './tools/fleet-tasks.js';+import { createBotStateTool } from './tools/bot-state.js';+import { extractBotMemories } from './memory-extract.js';import { createBotDeliverTool } from './tools/bot-deliver.js';import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';import { createFleetStatusTool } from './tools/fleet-status.js';@@ -84,6 +88,8 @@ export interface BotManagerDeps {const MAX_TRANSIENT_ATTEMPTS = 3;/** Consecutive no-outcome runs after which a work routine is paused (ADR-020). */export const NO_OUTCOME_PAUSE_AFTER = 3;+/** A delegated batch wakes its requester with partial results after this long (ADR-021). */+export const DEFAULT_TASK_DEADLINE_MINUTES = 120;const MAILBOX_CAPACITY = 100;/** Bot-thread result display cap — matches CLIChannel.MAX_MESSAGE_CHARS (64KB). */const BOT_RESULT_DISPLAY_CAP = 64 * 1024;@@ -109,6 +115,8 @@ type BotSchedulerLike = {export class BotManager {readonly store: BotStore;readonly queue: BotQueue;+ /** Durable fleet tasks (ADR-021). */+ readonly tasks: BotTaskStore;private readonly config: MercuryConfig;private readonly providers: ProviderRegistry;private readonly tokenBudget: TokenBudget;@@ -201,6 +209,7 @@ export class BotManager {this.store = deps.store ?? new BotStore(undefined, this.config.bots?.deliverablesDir);this.skillsRoot = deps.skillsRoot;this.queue = deps.queue ?? new BotQueue(this.store.botsRoot, this.config.bots?.retention?.dlqCap);+ this.tasks = new BotTaskStore(this.store.botsRoot);// Resume work a crashed predecessor left behind: pending jobs (and// expired-lease claimed jobs) re-enter the in-memory queues. Durable// enqueue happens before any ack, so nothing was lost (§2.6).@@ -236,7 +245,7 @@ export class BotManager {};// Periodic due-sweep: retry-backoff jobs re-enter the in-memory queues// when their run_after elapses (also covers crash-restart backoffs).- this.dueTimer = setInterval(() => this.resumeDueJobs(), 30_000);+ this.dueTimer = setInterval(() => { this.resumeDueJobs(); this.sweepTaskDeadlines(); }, 30_000);this.dueTimer.unref?.();// Retention janitor: on boot + once a day, cool down aged files in the// fleet-shared folder into the archive and expire the archive (disabled@@ -411,9 +420,182 @@ export class BotManager {* (replyTargetFor), closing the delegation loop.*/dispatchTask(targetBotId: string, fromBot: string, task: string): BotSendResult {- const result = this.enqueue(targetBotId, { trigger: 'mailbox', prompt: task, fromBot });- if (!result.accepted) return { accepted: false, reasonCode: result.reasonCode as BotSendResult['reasonCode'] };- return { accepted: true, jobId: result.jobId };+ // One typed task in a batch of one (ADR-021): same wake-once contract+ // and digest as fleet_delegate.+ const r = this.delegate(fromBot, { tasks: [{ bot: targetBotId, goal: task }] });+ if (!r.ok) return { accepted: false, reasonCode: 'not_linked' };+ const t = this.tasks.get(r.tasks[0].id);+ if (!t || t.status === 'failed') return { accepted: false, reasonCode: (t?.result?.reasonCode as BotSendResult['reasonCode']) ?? 'target_disabled' };+ return { accepted: true, jobId: t.jobId };+ }++ // ---- fleet tasks (ADR-021) ------------------------------------------------++ /**+ * Fan-out: typed tasks for several crew at once, grouped in a batch. The+ * requester is woken ONCE with a digest when the batch settles or its+ * deadline passes — never once per task.+ */+ delegate(requester: string, spec: { tasks: Array<{ bot: string; goal: string; acceptance?: string }>; label?: string; deadlineMinutes?: number; wakeWhen?: 'all' | 'each' }): { ok: true; batchId: string; tasks: Array<{ id: string; assignee: string; duplicated: boolean }> } | { ok: false; error: string } {+ const lead = this.store.get(requester);+ if (!lead) return { ok: false, error: `No bot "${requester}"` };+ const roster = this.effectiveRoster(requester, lead);+ for (const t of spec.tasks) {+ if (t.bot === requester) return { ok: false, error: 'You cannot delegate to yourself' };+ if (!roster.includes(t.bot)) return { ok: false, error: `"${t.bot}" is not in your crew (${roster.join(', ') || 'no crew yet — bot_spawn one'})` };+ }+ const deadlineAt = Date.now() + (spec.deadlineMinutes ?? DEFAULT_TASK_DEADLINE_MINUTES) * 60_000;+ const batch = this.tasks.createBatch({ requester, label: spec.label, wakeWhen: spec.wakeWhen ?? 'all', deadlineAt });+ const out: Array<{ id: string; assignee: string; duplicated: boolean }> = [];+ for (const t of spec.tasks) {+ const r = this.startTask({ batchId: batch.id, requester, assignee: t.bot, goal: t.goal, acceptance: t.acceptance });+ out.push({ id: r.task.id, assignee: t.bot, duplicated: r.duplicated });+ }+ logger.info({ requester, batchId: batch.id, tasks: out.length }, 'Fleet batch dispatched');+ return { ok: true, batchId: batch.id, tasks: out };+ }++ private startTask(input: Omit<BotTask, 'id' | 'status' | 'createdAt' | 'jobId'>, previous?: BotTaskResult): { task: BotTask; duplicated: boolean } {+ const created = this.tasks.createTask(input);+ if (created.duplicated) return created;+ const requesterName = this.store.get(input.requester)?.name ?? input.requester;+ const job = this.enqueue(input.assignee, { trigger: 'mailbox', prompt: renderTaskPrompt(created.task, requesterName, previous), fromBot: input.requester });+ if (!job.accepted) {+ this.tasks.update(created.task.id, { status: 'failed', completedAt: Date.now(), result: { outcome: 'none', summary: `could not dispatch: ${job.reasonCode}`, deliverables: [], reasonCode: job.reasonCode } });+ this.onTaskSettled(created.task.id);+ } else {+ // enqueue pumps synchronously: the turn may already be running by the+ // time the job id is known, so record that state here.+ const alreadyRunning = this.running.get(input.assignee)?.has(job.jobId) ?? false;+ this.tasks.update(created.task.id, { jobId: job.jobId, ...(alreadyRunning ? { status: 'running', startedAt: Date.now() } : {}) });+ }+ return created;+ }++ /** A lead's pipeline (bot.yaml) on one input: stages chain themselves. */+ runPipeline(leadId: string, input: string, label?: string): { ok: true; runId: string; total: number; firstStage: string; duplicated: boolean } | { ok: false; error: string } {+ const lead = this.store.get(leadId);+ const stages = lead?.pipeline?.stages ?? [];+ if (!lead || stages.length === 0) return { ok: false, error: 'No pipeline declared in bot.yaml (pipeline.stages)' };+ const roster = this.effectiveRoster(leadId, lead);+ const missing = stages.map(st => st.bot).filter(b => !roster.includes(b));+ if (missing.length > 0) return { ok: false, error: `Pipeline stage bot(s) not in your crew: ${missing.join(', ')}` };+ const runId = randomUUID().slice(0, 8);+ const batch = this.tasks.createBatch({ requester: leadId, label: label ?? `${lead.pipeline?.name ?? 'pipeline'}: ${input.slice(0, 40)}`, wakeWhen: 'all', deadlineAt: Date.now() + stages.length * DEFAULT_TASK_DEADLINE_MINUTES * 60_000 });+ const r = this.startStage(leadId, batch.id, runId, input, 0);+ return { ok: true, runId, total: stages.length, firstStage: stages[0].name, duplicated: r.duplicated };+ }++ private startStage(leadId: string, batchId: string, runId: string, input: string, index: number, previous?: BotTaskResult): { task: BotTask; duplicated: boolean } {+ const stages = this.store.get(leadId)?.pipeline?.stages ?? [];+ const stage = stages[index];+ const handoff = previous ? (previous.deliverables.join(', ') || previous.summary.slice(0, 500)) : '(none)';+ const goal = stage.goal.replace(/\{\{\s*input\s*\}\}/g, input).replace(/\{\{\s*previous\s*\}\}/g, handoff);+ return this.startTask({+ batchId, requester: leadId, assignee: stage.bot, goal, acceptance: stage.acceptance, stage: stage.name,+ pipeline: { runId, index, total: stages.length, input, final: Boolean(stage.final) },+ }, previous);+ }++ private onTaskSettled(taskId: string): void {+ const task = this.tasks.get(taskId);+ if (!task) return;+ if (task.pipeline) {+ this.advancePipeline(task);+ return;+ }+ this.notifyBatch(task.batchId, 'settled', task.id);+ }++ private advancePipeline(task: BotTask): void {+ const stages = this.store.get(task.requester)?.pipeline?.stages ?? [];+ const p = task.pipeline!;+ const isLast = p.index + 1 >= stages.length;+ if (task.status === 'done' && !isLast) {+ this.startStage(task.requester, task.batchId, p.runId, p.input, p.index + 1, task.result);+ return;+ }+ // Last stage done, or a stage failed: promote finals, then wake the lead once.+ if (task.status === 'done' && p.final && task.result) {+ task.result.deliverables = task.result.deliverables.map(d => this.promoteDeliverable(task.requester, d));+ this.tasks.update(task.id, { result: task.result });+ }+ this.notifyBatch(task.batchId, 'settled', task.id);+ }++ /** A crew's finished deliverable becomes the fleet's final: moved from work/<crew>/ to the top of the lead's folder. */+ private promoteDeliverable(leadId: string, path: string): string {+ const leadDir = this.store.deliverablesDir(leadId);+ const rel = relative(join(leadDir, 'work'), path);+ if (rel.startsWith('..') || isAbsolute(rel) || !existsSync(path)) return path;+ let dest = join(leadDir, basename(path));+ for (let i = 2; existsSync(dest); i++) dest = join(leadDir, `${basename(path, extname(path))} (${i})${extname(path)}`);+ try {+ renameSync(path, dest);+ this.store.writeDeliverablesIndex(leadDir);+ logger.info({ leadId, dest }, 'Pipeline final promoted to the fleet folder');+ return dest;+ } catch {+ return path;+ }+ }++ /**+ * Wake the requester with a digest: on settle, when every task in an+ * 'all' batch is terminal (a late result after a deadline wake reports+ * just itself); on deadline, once, with what is done and what is still+ * running. 'each' batches wake per task.+ */+ private notifyBatch(batchId: string, reason: 'settled' | 'deadline', settledTaskId?: string): void {+ const batch = this.tasks.batch(batchId);+ if (!batch) return;+ const tasks = this.tasks.tasksInBatch(batchId);+ const open = tasks.filter(t => !isTerminalTask(t.status));+ const name = (id: string) => this.store.get(id)?.name ?? id;+ let digest: string | null = null;+ if (reason === 'deadline') {+ if (open.length === 0 || batch.notifiedAt) return;+ digest = renderBatchDigest(batch, tasks, name);+ this.tasks.markBatchNotified(batchId);+ } else if (batch.wakeWhen === 'each') {+ const one = tasks.find(t => t.id === settledTaskId);+ if (one) digest = renderBatchDigest(batch, [one], name);+ } else if (open.length === 0) {+ digest = batch.notifiedAt+ ? `Late result for batch "${batch.label ?? batchId}":\n` + renderBatchDigest(batch, tasks.filter(t => t.id === settledTaskId), name)+ : renderBatchDigest(batch, tasks, name);+ this.tasks.markBatchNotified(batchId);+ } else if (batch.notifiedAt) {+ // Deadline already woke the requester; each straggler reports itself once.+ const one = tasks.find(t => t.id === settledTaskId);+ if (one) digest = `Late result for batch "${batch.label ?? batchId}":\n` + renderBatchDigest(batch, [one], name);+ }+ if (!digest) return;+ const sent = this.sendToBot(batch.requester, 'fleet', digest);+ if (!sent.accepted) logger.warn({ requester: batch.requester, batchId, reason: sent.reasonCode }, 'Fleet digest not delivered');+ }++ private sweepTaskDeadlines(): void {+ for (const batch of this.tasks.overdueBatches()) this.notifyBatch(batch.id, 'deadline');+ }++ /** Open and recent tasks a lead asked for, newest first. */+ tasksFor(requester: string): BotTask[] {+ return this.tasks.recent(requester, 20);+ }++ async cancelTask(requester: string, taskId: string): Promise<{ ok: true } | { ok: false; error: string }> {+ const task = this.tasks.get(taskId);+ if (!task || task.requester !== requester) return { ok: false, error: `No task ${taskId} of yours` };+ if (isTerminalTask(task.status)) return { ok: false, error: `Task ${taskId} is already ${task.status}` };+ if (task.jobId) {+ const q = this.queues.get(task.assignee) ?? [];+ this.queues.set(task.assignee, q.filter(j => j.id !== task.jobId));+ if (this.running.get(task.assignee)?.has(task.jobId)) await this.halt(task.assignee, task.jobId);+ else this.queue.settle(task.jobId, 'done');+ }+ this.tasks.update(taskId, { status: 'cancelled', completedAt: Date.now() });+ return { ok: true };}/** Fire-and-forget mailbox delivery from another bot. */@@ -564,6 +746,8 @@ export class BotManager {try { this.queue.heartbeatLease(job.id, LEASE_SECONDS); } catch { /* best effort */ }}, (LEASE_SECONDS / 3) * 1000);heartbeat.unref?.();+ const taskForJob = this.tasks.byJob(job.id);+ if (taskForJob) this.tasks.update(taskForJob.id, { status: 'running', startedAt: Date.now() });const turn = this.buildTurn(botId, manifest, job, controller.signal);const output = await runBotTurn({...turn.input,@@ -652,7 +836,7 @@ export class BotManager {prompt: job.prompt,output: output.output,toolsUsed: output.toolsUsed,- provider: resolveProvider(this.providers, manifest),+ provider: resolveProvider(this.providers, manifest, this.config),// The synthesized skill lands in the BOT'S OWN library (draft:true),// not the global root — it is that bot's learned procedure, usable// by it on the next run (runtime invalidated on success).@@ -741,7 +925,27 @@ export class BotManager {// result back to the sender's mailbox (attributed, plain mail — never a// task, so results can't ping-pong). Paused runs requeue and report// later; the failure/retry machinery above owns transient states.- const replyTarget = replyTargetFor(job);+ // Memory (ADR-021): a productive run teaches the bot something.+ const memoryStore = this.userMemoryFor(botId, manifest);+ if (output.status === 'completed' && memoryStore && manifest.memory?.learn !== false) {+ void extractBotMemories({+ botId, botName: manifest.name, prompt: job.prompt, output: output.output, outcome: output.outcome,+ deliverables: output.deliverables, provider: resolveProvider(this.providers, manifest, this.config), tokenBudget: this.tokenBudget, memory: memoryStore,+ }).then((n) => { if (n > 0) logger.info({ botId, remembered: n }, 'Bot memories extracted'); });+ }++ // Typed task (ADR-021): record the result on the task and let the+ // batch decide whether the requester is woken now.+ const settledTask = output.status !== 'paused' ? this.tasks.byJob(job.id) : null;+ if (settledTask) {+ this.tasks.update(settledTask.id, {+ status: output.status === 'completed' ? 'done' : output.status === 'failed' ? 'failed' : 'halted',+ completedAt: Date.now(),+ result: { outcome: output.outcome, summary: output.output.slice(0, 4000), deliverables: output.deliverables, reasonCode: output.reasonCode },+ });+ this.onTaskSettled(settledTask.id);+ }+ const replyTarget = settledTask ? undefined : replyTargetFor(job);if (replyTarget && (output.status === 'completed' || output.status === 'failed' || output.status === 'halted')) {const icon = output.status === 'completed' ? '✅' : output.status === 'failed' ? '❌' : '⏹';const reply = output.status === 'completed'@@ -835,12 +1039,14 @@ export class BotManager {sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },deliverablesDir: this.store.deliverablesDir(botId),expects: this.expectationFor(manifest, job),+ recentRuns: this.recentRunsDigest(botId),+ stateNote: this.store.readState(botId),skillsPrompt,fleet: this.fleetContext(botId, manifest),capabilities: registry,tools,userMemory,- provider: resolveProvider(this.providers, manifest),+ provider: resolveProvider(this.providers, manifest, this.config),tokenBudget: this.tokenBudget,abortSignal: signal,},@@ -848,6 +1054,17 @@ export class BotManager {};}+ /** Last few runs, one line each — continuity the bot used to write to disk itself. */+ private recentRunsDigest(botId: string): string {+ const rows = this.journalFor(botId).read(botId, 5);+ if (rows.length === 0) return '';+ return [...rows].reverse().map(r => {+ const when = new Date(r.turnStartedAt ?? r.startedAt).toISOString().slice(0, 16).replace('T', ' ');+ const what = r.deliverables?.length ? `delivered ${r.deliverables.map(d => basename(d)).join(', ')}` : (r.summary ?? '').replace(/\s+/g, ' ').slice(0, 120);+ return `- ${when} · ${r.trigger} · ${r.state}${r.outcome ? ` · ${r.outcome}` : ''} — ${what}`;+ }).join('\n');+ }+/** Fleet context for the turn prompt (undefined for solo bots). */private fleetContext(botId: string, manifest: BotManifest) {if (manifest.fleetRole === 'lead') {@@ -929,8 +1146,13 @@ export class BotManager {// (exempt from the retention janitor).filtered.bot_deliver = createBotDeliverTool(this, botId) as Tool;// Fleet tools for leads: monitor the crew, spawn/retire within caps.+ filtered.bot_state = createBotStateTool(this.store, botId) as Tool;if (manifest.fleetRole === 'lead') {filtered.fleet_status = createFleetStatusTool(this, botId);+ filtered.fleet_delegate = createFleetDelegateTool(this, botId) as Tool;+ filtered.fleet_tasks = createFleetTasksTool(this, botId) as Tool;+ const stages = manifest.pipeline?.stages ?? [];+ if (stages.length > 0) filtered.fleet_pipeline = createFleetPipelineTool(this, botId, stages.map(st => st.name)) as Tool;if (this.config.bots?.fleets?.allowLeadSpawn !== false) {const fleet = createBotSpawnTool(this, botId);filtered.bot_spawn = fleet.spawn;@@ -973,7 +1195,7 @@ export class BotManager {/** The bot's provider (public for fleet tools — persona building on spawn). */resolveProviderFor(botId: string): ReturnType<typeof resolveProvider> {const manifest = this.store.get(botId);- return resolveProvider(this.providers, manifest ?? { id: botId, name: botId, enabled: true } as BotManifest);+ return resolveProvider(this.providers, manifest ?? { id: botId, name: botId, enabled: true } as BotManifest, this.config);}/**@@ -1009,7 +1231,7 @@ export class BotManager {if (manifest.fleetRole !== 'lead') this.promoteLead(botId);const persona = this.store.readPersona(botId);const leadDescription = manifest.description ?? '';- const proposals = await proposeCrew(manifest.name, leadDescription, persona, resolveProvider(this.providers, manifest), this.maxCrew());+ const proposals = await proposeCrew(manifest.name, leadDescription, persona, resolveProvider(this.providers, manifest, this.config), this.maxCrew());if (proposals.length === 0) {hooks.onError?.("Crew proposal unavailable (provider) — the lead has an empty crew. Add specialists yourself, or give the lead a task and tell it to hire its own crew (bot_spawn).");return;@@ -1109,7 +1331,7 @@ export class BotManager {schedulePersonaRefinement(botId: string, name: string, rawPersona: string): void {const manifest = this.store.get(botId);if (!manifest) return;- const provider = resolveProvider(this.providers, manifest);+ const provider = resolveProvider(this.providers, manifest, this.config);void refinePersona(rawPersona, name, provider).then((refined) => {if (!refined) return;@@ -1179,6 +1401,7 @@ export class BotManager {this.scheduler.persistSchedules();}this.queue.purgeBot(botId);+ this.tasks.purgeBot(botId);this.store.delete(botId);this.registries.delete(botId);this.journals.delete(botId);@@ -1722,13 +1945,18 @@ export class BotManager {}}-function resolveProvider(providers: ProviderRegistry, manifest: BotManifest) {+function resolveProvider(providers: ProviderRegistry, manifest: BotManifest, config?: MercuryConfig) {const requested = manifest.model?.provider;const provider = requested ? providers.get(requested) : undefined;if (provider) return provider;if (requested) {logger.warn({ botId: manifest.id, requested }, 'Bot provider not registered — falling back to default');}+ // Crew lane (ADR-021): stage work on a cheaper provider when the fleet+ // config names one and the crew bot has no choice of its own.+ const crewProvider = manifest.parent ? config?.bots?.fleets?.crewProvider : undefined;+ const crewLane = crewProvider ? providers.get(crewProvider) : undefined;+ if (crewLane) return crewLane;return providers.getDefault();}diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 112f186f..5fdd848d 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -101,6 +101,10 @@ export interface BotTurnInput {};/** Outcome contract for this run (default 'work'). */expects?: BotExpectedOutcome;+ /** Journal digest of the last few runs (ADR-021): continuity without records. */+ recentRuns?: string;+ /** The bot's own working-state note (bot_state). */+ stateNote?: string;limits?: Partial<BotTurnLimits>;capabilities: CapabilityRegistry;tools: Record<string, Tool>;@@ -804,6 +808,16 @@ Anything outside these two areas and your declared Access grants is denied.`;- Name the delivered file in your reply.`;}+ // Continuity (ADR-021): what the journal already knows, and the bot's own+ // note. Together they replace "records about records" — nothing here+ // needs to be written to disk by the bot.+ if (input.recentRuns) {+ prompt += `\n\nYour recent runs (from the journal — you do not need to record these):\n${input.recentRuns}`;+ }+ if (input.stateNote) {+ prompt += `\n\nYour working state (set with bot_state; replace it when it changes):\n${input.stateNote}`;+ }+const roster = manifest.comms?.canMessage ?? [];if (roster.length > 0) {prompt += `\n\nBots you can message via bot_send: ${roster.join(', ')}.`;@@ -829,8 +843,9 @@ ${roster}Fleet protocol:- SELF-ORGANIZE: if your crew is empty or lacks a specialist the task needs, BUILD IT FIRST with bot_spawn — design each sub-bot's role and persona from YOUR persona and the current task (e.g. a product lead spawns research/QA/support specialists). Do not report that you lack a team; hire one. Then delegate.-- DELEGATE with bot_send (task: true) — be concrete and self-contained; the result arrives in your mailbox when the bot finishes.-- MONITOR with fleet_status — check who is running, idle, or blocked before and after delegating.+- DELEGATE with fleet_delegate — several typed tasks in one call, each with a goal and what "done" means. You are woken ONCE with a digest when they finish (or the deadline passes): finish your turn after delegating, never poll.+- If you have a pipeline (fleet_pipeline), use it for the standard job: the stages chain themselves and you are woken at the end.+- MONITOR with fleet_status / fleet_tasks only when you need to — results come to you.- You may create specialists with bot_spawn (crew cap: ${input.fleet.maxCrew}) and retire your own crew with bot_retire.- Crew run CONCURRENTLY — dispatch independent work in parallel rather than sequentially.- You SYNTHESIZE: crew results arrive in your mailbox attributed by bot; combine them and report a single coherent outcome.${input.fleet.leadName ? `\n- You are also crew of **${input.fleet.leadName}** — your task results return to it automatically; treat it as your manager.` : ''}`;diff --git a/src/bots/fleet-tasks.test.ts b/src/bots/fleet-tasks.test.tsnew file mode 100644index 00000000..f65ed5cb--- /dev/null+++ b/src/bots/fleet-tasks.test.ts@@ -0,0 +1,272 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, basename } from 'node:path';++vi.mock('ai', async (importOriginal) => {+ const actual = await importOriginal<typeof import('ai')>();+ return { ...actual, generateText: vi.fn(), streamText: vi.fn() };+});+import { generateText, streamText } from 'ai';+import { BotManager, DEFAULT_TASK_DEADLINE_MINUTES } from './bot-manager.js';+import { BotStore } from './store.js';+import { BotTaskStore, renderBatchDigest, renderTaskPrompt } from './tasks.js';+import { getDefaultConfig, type MercuryConfig } from '../utils/config.js';++const mockedGenerateText = vi.mocked(generateText);+const mockedStreamText = vi.mocked(streamText);++// Same shim as bot-manager.test.ts: the scripted generateText drives the+// streaming shape runBotTurn consumes.+mockedStreamText.mockImplementation(((opts: unknown) => {+ let final = { text: '', finishReason: 'stop', usage: {} };+ let failed: unknown = null;+ let resolveSettled: () => void = () => {};+ const settled = new Promise<void>((r) => { resolveSettled = r; });+ const gen = (generateText as unknown as (o: unknown) => Promise<typeof final>)(opts) || Promise.resolve(final);+ const fullStream = (async function* () {+ try { final = await gen; } catch (err) { failed = err; }+ resolveSettled();+ yield { type: 'finish' };+ })();+ const once = async (pick: () => unknown) => { await settled; if (failed !== null) throw failed; return pick(); };+ return { fullStream, text: once(() => final.text), finishReason: once(() => final.finishReason), usage: once(() => final.usage).catch(() => ({})) };+}) as never);++type StepOpts = { messages?: Array<{ content: string }>; onStepFinish?: (step: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[] }) => void };+const reply = (text: string) => ({ text, finishReason: 'stop', usage: { inputTokens: 5, outputTokens: 5 } }) as never;+const stubProvider = { name: 'stub', model: 'stub-model', isAvailable: () => true, getModelInstance: () => ({}), getModel: () => 'stub-model' };+const providers = { get: (name?: string) => (name === 'cheap' ? { ...stubProvider, name: 'cheap' } : name === 'stub' ? stubProvider : undefined), getDefault: () => stubProvider } as never;+const tokenBudget = { recordUsage: () => {}, getRemaining: () => 100000, canAfford: () => true, getStatusText: () => 'ok', getUsagePercentage: () => 0 } as never;++describe('fleet tasks (ADR-021)', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;+ const managers: BotManager[] = [];++ function makeManager(overrides: Partial<MercuryConfig['bots']> = {}): BotManager {+ const config = getDefaultConfig() as MercuryConfig;+ config.bots.maxConcurrent = 4;+ Object.assign(config.bots, overrides);+ const m = new BotManager({ config, providers, tokenBudget, store: new BotStore(join(root, 'bots')), userMemoryFactory: () => null });+ managers.push(m);+ return m;+ }++ const idle = (botId: string) => vi.waitFor(() => {+ expect(manager.getStatusSummaries().find(s => s.id === botId)?.state).not.toBe('running');+ expect(manager.getQueuedCount(botId)).toBe(0);+ });++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-tasks-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager();+ mockedGenerateText.mockReset();+ store.create({ id: 'lead', name: 'Lead', manifest: { fleetRole: 'lead' } });+ manager.addCrew('lead', { id: 'alpha', name: 'Alpha' });+ manager.addCrew('lead', { id: 'beta', name: 'Beta' });+ });+ afterEach(() => {+ for (const m of managers.splice(0)) m.dispose();+ rmSync(root, { recursive: true, force: true });+ });++ it('task store: dedupes open goals, tracks batches, finds overdue ones, prunes settled ones', () => {+ const tasks = new BotTaskStore(join(root, 'tasks'));+ const batch = tasks.createBatch({ requester: 'lead', label: 'x', deadlineAt: Date.now() - 1 });+ const a = tasks.createTask({ batchId: batch.id, requester: 'lead', assignee: 'alpha', goal: 'research X' });+ const again = tasks.createTask({ batchId: batch.id, requester: 'lead', assignee: 'alpha', goal: 'research X' });+ expect(again.duplicated).toBe(true);+ expect(again.task.id).toBe(a.task.id);+ expect(tasks.open({ requester: 'lead' })).toHaveLength(1);+ expect(tasks.overdueBatches().map(b => b.id)).toEqual([batch.id]);+ tasks.markBatchNotified(batch.id);+ expect(tasks.overdueBatches()).toHaveLength(0);+ tasks.update(a.task.id, { status: 'done', completedAt: Date.now() - 8 * 24 * 3600 * 1000 });+ expect(tasks.prune()).toBe(1);+ // Survives a reload: the settled task is gone, the (recent) batch row stays.+ const reloaded = new BotTaskStore(join(root, 'tasks'));+ expect(reloaded.tasksInBatch(batch.id)).toHaveLength(0);+ expect(reloaded.batch(batch.id)?.id).toBe(batch.id);+ });++ it('fans out a batch and wakes the lead ONCE with a typed digest when every task is done', async () => {+ const leadPrompts: string[] = [];+ const crewPrompts: string[] = [];+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => {+ const last = opts.messages?.at(-1)?.content ?? '';+ if (last.includes('Task ') && last.includes('from Lead')) {+ crewPrompts.push(last);+ return reply(last.includes('alpha-goal') ? 'Alpha found three sources.' : 'Beta drafted the outline.');+ }+ leadPrompts.push(last);+ return reply('noted');+ }) as never);+ const r = manager.delegate('lead', { tasks: [{ bot: 'alpha', goal: 'alpha-goal: find sources for X', acceptance: '3 sources' }, { bot: 'beta', goal: 'beta-goal: outline X' }], label: 'X research' });+ expect(r.ok).toBe(true);+ await idle('alpha'); await idle('beta');+ await vi.waitFor(() => expect(leadPrompts.length).toBe(1));+ await idle('lead');+ expect(crewPrompts[0]).toContain('Done means: 3 sources');+ expect(crewPrompts[0]).toContain('bot_deliver');+ const digest = leadPrompts[0];+ expect(digest).toContain('Message from 🤖 fleet');+ expect(digest).toContain('Batch "X research" is complete (2 tasks)');+ expect(digest).toContain('✅ Alpha');+ expect(digest).toContain('Alpha found three sources.');+ expect(digest).toContain('✅ Beta');+ expect(manager.tasksFor('lead').every(t => t.status === 'done')).toBe(true);+ // No per-task "Task complete" mails ever reached the lead.+ expect(leadPrompts.some(p => p.includes('Task complete (job'))).toBe(false);+ });++ it('a deadline wakes the lead once with partial results; stragglers report once each', async () => {+ let releaseBeta!: () => void;+ const leadMail: string[] = [];+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => {+ const last = opts.messages?.at(-1)?.content ?? '';+ if (last.includes('alpha-goal')) return reply('alpha done');+ if (last.includes('beta-goal')) return new Promise((resolve) => { releaseBeta = () => resolve(reply('beta done late')); });+ leadMail.push(last); // the lead's wake drains its mailbox into the prompt+ return reply('noted');+ }) as never);+ const r = manager.delegate('lead', { tasks: [{ bot: 'alpha', goal: 'alpha-goal' }, { bot: 'beta', goal: 'beta-goal' }], label: 'slow', deadlineMinutes: 5 });+ expect(r.ok).toBe(true);+ await idle('alpha');+ // Force the deadline.+ const batch = manager.tasks.batch((r as { batchId: string }).batchId)!;+ batch.deadlineAt = Date.now() - 1;+ manager.tasks.markBatchNotified(batch.id); manager.tasks.update(manager.tasks.tasksInBatch(batch.id)[0].id, {}); // persist the edited deadline+ (manager.tasks.batch(batch.id) as { notifiedAt?: number }).notifiedAt = undefined;+ (manager as unknown as { sweepTaskDeadlines: () => void }).sweepTaskDeadlines();+ const mail = () => [...leadMail, ...manager.peekMailbox('lead').map(m => m.content)];+ await vi.waitFor(() => expect(mail().some(m => m.includes('1 of 2 tasks done, 1 still running'))).toBe(true));+ (manager as unknown as { sweepTaskDeadlines: () => void }).sweepTaskDeadlines(); // idempotent+ await idle('lead');+ expect(mail().filter(m => m.includes('still running')).length).toBe(1);+ releaseBeta();+ await idle('beta');+ await vi.waitFor(() => expect(mail().some(m => m.includes('Late result for batch "slow"') && m.includes('beta done late'))).toBe(true));+ });++ it('runs a pipeline stage by stage, hands deliverables forward, promotes the final, wakes the lead at the end', async () => {+ store.update('lead', m => { m.pipeline = { name: 'article', stages: [+ { name: 'research', bot: 'alpha', goal: 'Research {{input}}' },+ { name: 'draft', bot: 'beta', goal: 'Draft from {{previous}}', final: true },+ ] }; });+ manager.invalidateRuntime('lead');+ const seen: string[] = [];+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => {+ const last = opts.messages?.at(-1)?.content ?? '';+ seen.push(last);+ if (last.includes('Research Oxide')) {+ const f = join(store.sandboxDir('alpha'), 'dossier.md'); mkdirSync(store.sandboxDir('alpha'), { recursive: true }); writeFileSync(f, '# dossier');+ const d = manager.deliver('alpha', f, { title: 'Oxide dossier' });+ return reply(`Research done. Delivered ${d.path}`);+ }+ if (last.includes('Draft from')) {+ const f = join(store.sandboxDir('beta'), 'piece.md'); mkdirSync(store.sandboxDir('beta'), { recursive: true }); writeFileSync(f, '# piece');+ const d = manager.deliver('beta', f, { title: 'Oxide explained' });+ // The delivery is reported through the trace in production; here the+ // wrapper is bypassed, so hand the path back through the journal+ // shape the task reads: the summary.+ return reply(`Draft delivered: ${d.path}`);+ }+ return reply('noted');+ }) as never);+ const r = manager.runPipeline('lead', 'Oxide');+ expect(r).toMatchObject({ ok: true, total: 2, firstStage: 'research' });+ await idle('alpha'); await idle('beta');+ await vi.waitFor(() => expect(seen.some(s => s.includes('Message from 🤖 fleet'))).toBe(true));+ await idle('lead');+ const draftPrompt = seen.find(s => s.includes('Draft from'))!;+ expect(draftPrompt).toContain('pipeline stage "draft" (2/2)');+ expect(draftPrompt).toContain('Hand-off from the previous stage');+ const digest = seen.find(s => s.includes('Message from 🤖 fleet'))!;+ expect(digest).toContain('is complete (2 tasks)');+ expect(digest).toContain('(research)');+ expect(digest).toContain('(draft)');+ expect(manager.tasksFor('lead').map(t => t.status)).toEqual(['done', 'done']);+ });++ it('promotes a final-stage deliverable from work/<crew>/ to the top of the fleet folder', () => {+ const work = join(store.deliverablesDir('beta'));+ mkdirSync(work, { recursive: true });+ const file = join(work, '2026-10-10 Oxide explained.md');+ writeFileSync(file, '# piece');+ const promoted = (manager as unknown as { promoteDeliverable: (lead: string, p: string) => string }).promoteDeliverable('lead', file);+ expect(promoted).toBe(join(store.deliverablesDir('lead'), '2026-10-10 Oxide explained.md'));+ expect(existsSync(file)).toBe(false);+ expect(readFileSync(join(store.deliverablesDir('lead'), 'README.md'), 'utf-8')).toContain(basename(promoted));+ // Not under the lead's work/ → untouched.+ expect((manager as unknown as { promoteDeliverable: (lead: string, p: string) => string }).promoteDeliverable('lead', '/nowhere/x.md')).toBe('/nowhere/x.md');+ });++ it('cancel halts a running task and drops a queued one; fleet tools are attached to leads', async () => {+ let release!: () => void;+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => {+ const last = opts.messages?.at(-1)?.content ?? '';+ if (last.includes('long job')) return new Promise((resolve) => { release = () => resolve(reply('late')); });+ return reply('noted');+ }) as never);+ const r = manager.delegate('lead', { tasks: [{ bot: 'alpha', goal: 'long job one' }, { bot: 'alpha', goal: 'long job two' }] });+ expect(r.ok).toBe(true);+ const [first, second] = (r as { tasks: Array<{ id: string }> }).tasks;+ await vi.waitFor(() => expect(manager.tasks.get(first.id)?.status).toBe('running'));+ expect(manager.tasks.get(second.id)?.status).toBe('queued');+ expect(await manager.cancelTask('lead', second.id)).toEqual({ ok: true });+ expect(manager.getQueuedCount('alpha')).toBe(0);+ expect(await manager.cancelTask('lead', first.id)).toEqual({ ok: true });+ release();+ await idle('alpha');+ expect(manager.tasks.get(first.id)?.status).toBe('cancelled');+ expect(await manager.cancelTask('alpha', first.id)).toMatchObject({ ok: false });+ const tools = (manager as unknown as { getOrCreateRuntime: (id: string, m: unknown) => { tools: Record<string, unknown> } }).getOrCreateRuntime('lead', store.get('lead'));+ for (const name of ['fleet_delegate', 'fleet_tasks', 'fleet_status', 'bot_state']) expect(tools.tools[name]).toBeDefined();+ expect(tools.tools.fleet_pipeline).toBeUndefined();+ const crewTools = (manager as unknown as { getOrCreateRuntime: (id: string, m: unknown) => { tools: Record<string, unknown> } }).getOrCreateRuntime('alpha', store.get('alpha'));+ expect(crewTools.tools.fleet_delegate).toBeUndefined();+ expect(crewTools.tools.bot_state).toBeDefined();+ });++ it('delegation refuses bots outside the roster and self-delegation', () => {+ expect(manager.delegate('lead', { tasks: [{ bot: 'ghost', goal: 'anything at all' }] })).toMatchObject({ ok: false });+ expect(manager.delegate('lead', { tasks: [{ bot: 'lead', goal: 'anything at all' }] })).toMatchObject({ ok: false });+ expect(manager.runPipeline('lead', 'x')).toMatchObject({ ok: false });+ });++ it('continuity: the bot sees its recent runs and its own state note instead of writing records', async () => {+ const prompts: string[] = [];+ mockedGenerateText.mockImplementation((async (opts: StepOpts & { system?: string }) => { prompts.push(opts.system ?? ''); return reply('done something'); }) as never);+ store.writeState('alpha', 'Working on: the Oxide dossier. Pending: fact-check.');+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'first' });+ await idle('alpha');+ manager.enqueue('alpha', { trigger: 'chat', prompt: 'second' });+ await idle('alpha');+ expect(prompts[1]).toContain('Your working state');+ expect(prompts[1]).toContain('Pending: fact-check.');+ expect(prompts[1]).toMatch(/Your recent runs[\s\S]*chat · completed · message — done something/);+ expect(prompts[1]).toContain('you do not need to record these');+ store.writeState('alpha', '');+ expect(store.readState('alpha')).toBe('');+ });++ it('crew bots use the configured crew provider when they have none of their own', () => {+ const m = makeManager({ fleets: { maxCrew: 6, allowLeadSpawn: true, crewProvider: 'cheap' } });+ expect(m.resolveProviderFor('alpha').name).toBe('cheap');+ expect(m.resolveProviderFor('lead').name).toBe('stub');+ store.update('alpha', x => { x.model = { provider: 'stub' as never }; });+ expect(m.resolveProviderFor('alpha').name).toBe('stub');+ });++ it('renders prompts and digests', () => {+ const task = { id: 't1', batchId: 'b', requester: 'lead', assignee: 'alpha', goal: 'do it', acceptance: 'a file', status: 'done' as const, createdAt: 0, result: { outcome: 'deliverable', summary: 'done it', deliverables: ['/x/y.md'] } };+ expect(renderTaskPrompt(task, 'Lead', { outcome: 'deliverable', summary: 'prev', deliverables: ['/p.md'] })).toContain('- file: /p.md');+ const digest = renderBatchDigest({ id: 'b', requester: 'lead', wakeWhen: 'all', createdAt: 0 }, [task], (id) => id.toUpperCase());+ expect(digest).toContain('✅ ALPHA — task t1: done · deliverable');+ expect(digest).toContain('📁 /x/y.md');+ expect(DEFAULT_TASK_DEADLINE_MINUTES).toBe(120);+ });+});diff --git a/src/bots/memory-extract.ts b/src/bots/memory-extract.tsnew file mode 100644index 00000000..501efa1b--- /dev/null+++ b/src/bots/memory-extract.ts@@ -0,0 +1,88 @@+import { generateText } from 'ai';+import type { UserMemoryStore, UserMemoryType } from '../memory/user-memory.js';+import type { BaseProvider } from '../providers/base.js';+import type { TokenBudget } from '../utils/tokens.js';+import { logger } from '../utils/logger.js';++type Candidate = Parameters<UserMemoryStore['remember']>[0][number];++/** Only productive runs teach anything; short replies carry nothing durable. */+const MIN_OUTPUT_CHARS = 200;+const MAX_INPUT_CHARS = 6000;++/**+ * After a productive run, keep what the bot learned (ADR-021): sources it+ * found, decisions it took, where things are, what failed. One small call+ * on the bot's own provider; 0–3 facts into the bot's own memory namespace.+ * The main agent has had this since 1.2; bots had 900 chars of retrieval+ * and nothing written back, which is why they wrote their memory to disk+ * as "records".+ */+export async function extractBotMemories(input: {+ botId: string;+ botName: string;+ prompt: string;+ output: string;+ outcome: string;+ deliverables: string[];+ provider: BaseProvider;+ tokenBudget: TokenBudget;+ memory: UserMemoryStore;+}): Promise<number> {+ const { memory, provider, tokenBudget } = input;+ if (memory.isLearningPaused()) return 0;+ if (input.outcome === 'none' || input.output.trim().length < MIN_OUTPUT_CHARS) return 0;+ if (!tokenBudget.canAfford(1200)) return 0;+ try {+ const result = await generateText({+ model: provider.getModelInstance(),+ system: `You maintain the long-term memory of "${input.botName}", an unattended Mercury bot. From one finished run, output a JSON array of 0-3 facts worth keeping for FUTURE runs.++Each: { type, summary (12-220 chars), detail (optional), confidence (0-1), importance (0-1), categories (1-3 lowercase words) }.++TYPES: project (what is being worked on and its state), decision (a choice made and why), constraint (a rule or limit learned, e.g. a source that is unreliable, a tool that fails), episode (a notable one-time event), goal.++RULES:+- Durable and specific only: sources found and their quality, decisions, where deliverables are, what to avoid next time.+- Never store the run's own narration, status, timestamps, or anything the journal already records (tokens, steps, "run completed").+- No greetings, no assistant behaviour, no duplicates.+- Output a pure JSON array, no markdown fences. Output [] when nothing is durable.`,+ messages: [{ role: 'user', content: `Task given:\n${input.prompt.slice(0, 1500)}\n\nOutcome: ${input.outcome}${input.deliverables.length ? `\nDelivered: ${input.deliverables.join(', ')}` : ''}\n\nFinal reply:\n${input.output.slice(0, MAX_INPUT_CHARS)}` }],+ maxOutputTokens: 400,+ });+ tokenBudget.recordUsage({+ provider: provider.name,+ model: provider.getModel(),+ inputTokens: result.usage?.inputTokens ?? 0,+ outputTokens: result.usage?.outputTokens ?? 0,+ totalTokens: (result.usage?.inputTokens ?? 0) + (result.usage?.outputTokens ?? 0),+ channelType: 'bot',+ });+ const text = result.text.trim().replace(/^```(?:json)?\s*|```$/g, '');+ if (!text) return 0;+ let raw: unknown;+ try { raw = JSON.parse(text); } catch { return 0; }+ if (!Array.isArray(raw)) return 0;+ const candidates = raw.slice(0, 3).flatMap((c): Candidate[] => {+ if (!c || typeof c !== 'object') return [];+ const o = c as Record<string, unknown>;+ if (typeof o.summary !== 'string' || o.summary.length < 12) return [];+ const type = (['project', 'decision', 'constraint', 'episode', 'goal'].includes(String(o.type)) ? String(o.type) : 'episode') as UserMemoryType;+ return [{+ type,+ summary: o.summary.slice(0, 220),+ detail: typeof o.detail === 'string' ? o.detail.slice(0, 600) : undefined,+ categories: Array.isArray(o.categories) ? o.categories.filter((x): x is string => typeof x === 'string').slice(0, 3) : ['work'],+ evidenceKind: 'direct',+ confidence: typeof o.confidence === 'number' ? Math.max(0, Math.min(1, o.confidence)) : 0.7,+ importance: typeof o.importance === 'number' ? Math.max(0, Math.min(1, o.importance)) : 0.5,+ durability: 0.7,+ } as Candidate];+ });+ if (candidates.length === 0) return 0;+ return memory.remember(candidates, 'conversation').length;+ } catch (err) {+ logger.warn({ botId: input.botId, err: (err as Error)?.message }, 'Bot memory extraction failed — continuing');+ return 0;+ }+}diff --git a/src/bots/store.ts b/src/bots/store.tsindex a312e9df..42263e27 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -21,6 +21,8 @@ export const BOT_ENV_FILENAME = '.env';export const BOT_JOURNAL_FILENAME = 'journal.jsonl';/** Per-run compact transcripts (tool trace + reply), pruned by retention.transcriptRuns. */export const BOT_TRANSCRIPTS_DIRNAME = 'transcripts';+/** The bot's own working-state note (bot_state) — ADR-021. */+export const BOT_STATE_FILENAME = 'state.md';/** Routine state (paused routines, no-outcome streaks) — ADR-020. */export const BOT_ROUTINE_STATE_FILENAME = 'routine-state.json';/**@@ -266,6 +268,24 @@ export class BotStore {} catch { /* an index is a convenience, never a failure */ }}+ /** The bot's working-state note; '' when none. */+ readState(id: string): string {+ try {+ return readFileSync(join(this.botDir(id), BOT_STATE_FILENAME), 'utf-8').trim();+ } catch {+ return '';+ }+ }++ writeState(id: string, state: string): void {+ const file = join(this.botDir(id), BOT_STATE_FILENAME);+ if (!state) {+ try { rmSync(file, { force: true }); } catch { /* nothing to clear */ }+ return;+ }+ atomicWrite(file, state + '\n');+ }+readRoutineState(id: string): BotRoutineState {try {const raw = JSON.parse(readFileSync(join(this.botDir(id), BOT_ROUTINE_STATE_FILENAME), 'utf-8'));diff --git a/src/bots/tasks.ts b/src/bots/tasks.tsnew file mode 100644index 00000000..819be51f--- /dev/null+++ b/src/bots/tasks.ts@@ -0,0 +1,220 @@+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';++/**+ * Durable fleet tasks (ADR-021). A task is a typed unit of delegated work:+ * who asked, who does it, the goal, the acceptance, a deadline, and — once+ * done — a typed result (outcome, deliverables, summary). Tasks are grouped+ * in batches so a lead that fans out N tasks is woken ONCE with a digest+ * when the batch completes (or its deadline passes), instead of N times+ * with N free-text mails.+ *+ * Storage is one JSON file next to the queue (atomic tmp+rename): task+ * volume is small, and it works on every device the JSON queue works on.+ */++export type BotTaskStatus = 'queued' | 'running' | 'done' | 'failed' | 'halted' | 'cancelled';++export interface BotTaskResult {+ outcome: string;+ summary: string;+ deliverables: string[];+ reasonCode?: string;+}++export interface BotTask {+ id: string;+ batchId: string;+ /** The bot that asked (a lead), or 'owner' for tasks created by a person. */+ requester: string;+ assignee: string;+ goal: string;+ acceptance?: string;+ /** Pipeline stage name when the task belongs to a pipeline run. */+ stage?: string;+ pipeline?: { runId: string; index: number; total: number; input: string; final: boolean };+ status: BotTaskStatus;+ jobId?: string;+ createdAt: number;+ startedAt?: number;+ completedAt?: number;+ result?: BotTaskResult;+}++export interface BotBatch {+ id: string;+ requester: string;+ label?: string;+ /** all = one wake when every task is settled; each = a wake per task. */+ wakeWhen: 'all' | 'each';+ createdAt: number;+ deadlineAt?: number;+ /** The requester has been woken for this batch (complete or deadline). */+ notifiedAt?: number;+}++interface TaskFile {+ batches: BotBatch[];+ tasks: BotTask[];+}++export const TASKS_FILE = 'tasks.json';+/** Settled tasks older than this are dropped from the file (the journal keeps the run). */+const RETAIN_SETTLED_MS = 7 * 24 * 60 * 60 * 1000;++const TERMINAL: ReadonlySet<BotTaskStatus> = new Set(['done', 'failed', 'halted', 'cancelled']);++export function isTerminalTask(status: BotTaskStatus): boolean {+ return TERMINAL.has(status);+}++export class BotTaskStore {+ private readonly file: string;+ private data: TaskFile;++ constructor(dir: string) {+ mkdirSync(dir, { recursive: true });+ this.file = join(dir, TASKS_FILE);+ this.data = this.read();+ }++ private read(): TaskFile {+ if (!existsSync(this.file)) return { batches: [], tasks: [] };+ try {+ const parsed = JSON.parse(readFileSync(this.file, 'utf-8')) as Partial<TaskFile>;+ return { batches: parsed.batches ?? [], tasks: parsed.tasks ?? [] };+ } catch {+ return { batches: [], tasks: [] };+ }+ }++ private flush(): void {+ const tmp = `${this.file}.tmp-${process.pid}`;+ writeFileSync(tmp, JSON.stringify(this.data), 'utf-8');+ renameSync(tmp, this.file);+ }++ createBatch(input: { requester: string; label?: string; wakeWhen?: 'all' | 'each'; deadlineAt?: number }): BotBatch {+ const batch: BotBatch = {+ id: randomUUID().slice(0, 8),+ requester: input.requester,+ label: input.label,+ wakeWhen: input.wakeWhen ?? 'all',+ createdAt: Date.now(),+ deadlineAt: input.deadlineAt,+ };+ this.data.batches.push(batch);+ this.flush();+ return batch;+ }++ /**+ * Create a task, or return the open task that already covers the same+ * goal for the same assignee (a lead re-running a delegation turn after a+ * restart must not double-dispatch).+ */+ createTask(input: Omit<BotTask, 'id' | 'status' | 'createdAt'>): { task: BotTask; duplicated: boolean } {+ const dup = this.data.tasks.find(t => t.requester === input.requester && t.assignee === input.assignee && t.goal === input.goal && !isTerminalTask(t.status));+ if (dup) return { task: dup, duplicated: true };+ const task: BotTask = { ...input, id: randomUUID().slice(0, 8), status: 'queued', createdAt: Date.now() };+ this.data.tasks.push(task);+ this.flush();+ return { task, duplicated: false };+ }++ get(taskId: string): BotTask | null {+ return this.data.tasks.find(t => t.id === taskId) ?? null;+ }++ byJob(jobId: string): BotTask | null {+ return this.data.tasks.find(t => t.jobId === jobId && !isTerminalTask(t.status)) ?? null;+ }++ batch(batchId: string): BotBatch | null {+ return this.data.batches.find(b => b.id === batchId) ?? null;+ }++ tasksInBatch(batchId: string): BotTask[] {+ return this.data.tasks.filter(t => t.batchId === batchId);+ }++ /** Open (unsettled) tasks, optionally for one requester or one assignee. */+ open(filter: { requester?: string; assignee?: string } = {}): BotTask[] {+ return this.data.tasks.filter(t => !isTerminalTask(t.status)+ && (!filter.requester || t.requester === filter.requester)+ && (!filter.assignee || t.assignee === filter.assignee));+ }++ /** Most recent tasks for a requester, newest first (open and settled). */+ recent(requester: string, limit = 20): BotTask[] {+ return this.data.tasks.filter(t => t.requester === requester).sort((a, b) => b.createdAt - a.createdAt).slice(0, limit);+ }++ update(taskId: string, patch: Partial<BotTask>): BotTask | null {+ const task = this.get(taskId);+ if (!task) return null;+ Object.assign(task, patch);+ this.flush();+ return task;+ }++ markBatchNotified(batchId: string): void {+ const batch = this.batch(batchId);+ if (batch) {+ batch.notifiedAt = Date.now();+ this.flush();+ }+ }++ /** Batches whose deadline has passed with open tasks and no wake yet. */+ overdueBatches(now = Date.now()): BotBatch[] {+ return this.data.batches.filter(b => b.deadlineAt !== undefined && b.deadlineAt <= now && !b.notifiedAt+ && this.tasksInBatch(b.id).some(t => !isTerminalTask(t.status)));+ }++ /** Drop settled tasks (and empty batches) older than the retention window. */+ prune(now = Date.now()): number {+ const before = this.data.tasks.length;+ this.data.tasks = this.data.tasks.filter(t => !isTerminalTask(t.status) || (t.completedAt ?? t.createdAt) > now - RETAIN_SETTLED_MS);+ const live = new Set(this.data.tasks.map(t => t.batchId));+ this.data.batches = this.data.batches.filter(b => live.has(b.id) || b.createdAt > now - RETAIN_SETTLED_MS);+ if (this.data.tasks.length !== before) this.flush();+ return before - this.data.tasks.length;+ }++ /** Remove every task a bot asked for or was assigned (delete lifecycle). */+ purgeBot(botId: string): void {+ this.data.tasks = this.data.tasks.filter(t => t.requester !== botId && t.assignee !== botId);+ this.data.batches = this.data.batches.filter(b => b.requester !== botId);+ this.flush();+ }+}++/** The prompt a crew bot receives for a task: typed, self-contained, with the previous stage's hand-off. */+export function renderTaskPrompt(task: BotTask, requesterName: string, previous?: BotTaskResult): string {+ const lines = [`Task ${task.id} from ${requesterName}${task.stage ? ` — pipeline stage "${task.stage}"${task.pipeline ? ` (${task.pipeline.index + 1}/${task.pipeline.total})` : ''}` : ''}:`, '', task.goal];+ if (task.acceptance) lines.push('', `Done means: ${task.acceptance}`);+ if (previous) {+ lines.push('', 'Hand-off from the previous stage:');+ if (previous.deliverables.length > 0) lines.push(...previous.deliverables.map(p => `- file: ${p}`));+ if (previous.summary) lines.push(`- summary: ${previous.summary.slice(0, 1500)}`);+ }+ lines.push('', 'When finished, deliver your result with bot_deliver (a file) and summarise it in your reply. Your reply and deliverables are returned to the requester automatically.');+ return lines.join('\n');+}++/** The digest a requester is woken with when a batch settles (or runs late). */+export function renderBatchDigest(batch: BotBatch, tasks: BotTask[], botName: (id: string) => string): string {+ const open = tasks.filter(t => !isTerminalTask(t.status));+ const head = batch.label ? `Batch "${batch.label}"` : 'Delegated work';+ const lines = [open.length === 0 ? `${head} is complete (${tasks.length} task${tasks.length === 1 ? '' : 's'}):` : `${head}: ${tasks.length - open.length} of ${tasks.length} tasks done, ${open.length} still running past the deadline:`];+ for (const t of tasks) {+ const icon = t.status === 'done' ? '✅' : t.status === 'failed' ? '❌' : t.status === 'cancelled' ? '🚫' : t.status === 'halted' ? '⏹' : '⏳';+ const r = t.result;+ lines.push('', `${icon} ${botName(t.assignee)} — task ${t.id}${t.stage ? ` (${t.stage})` : ''}: ${t.status}${r?.outcome ? ` · ${r.outcome}` : ''}${r?.reasonCode ? ` [${r.reasonCode}]` : ''}`);+ for (const d of r?.deliverables ?? []) lines.push(` 📁 ${d}`);+ if (r?.summary) lines.push(` ${r.summary.slice(0, 1200).replace(/\n+/g, '\n ')}`);+ }+ return lines.join('\n');+}diff --git a/src/bots/tools/bot-state.ts b/src/bots/tools/bot-state.tsnew file mode 100644index 00000000..a998c1a4--- /dev/null+++ b/src/bots/tools/bot-state.ts@@ -0,0 +1,28 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import type { BotStore } from '../store.js';++/** Working state is a note, not a ledger: bounded, replaced, never appended. */+export const BOT_STATE_MAX_CHARS = 1500;++/**+ * bot_state — the one place a bot keeps "what I'm in the middle of": a+ * short note Mercury shows it at the start of every turn (ADR-021). It+ * replaces the records-about-records habit: there is no reason to write a+ * status file when the next turn already sees this, the recent-runs digest+ * and its delegated tasks.+ */+export function createBotStateTool(store: BotStore, botId: string) {+ return tool({+ description:+ 'Set your working state — a short note (≤1500 chars) you will see at the start of your next turn: what you are ' ++ 'working on, what is pending, decisions taken. It REPLACES the previous note. Use it instead of writing status files.',+ inputSchema: zodSchema(z.object({+ state: z.string().max(BOT_STATE_MAX_CHARS).describe('The new note (empty string clears it)'),+ })),+ execute: async ({ state }: { state: string }) => {+ store.writeState(botId, state.trim());+ return state.trim() ? `Working state saved (${state.trim().length} chars). You will see it next turn.` : 'Working state cleared.';+ },+ });+}diff --git a/src/bots/tools/fleet-status.ts b/src/bots/tools/fleet-status.tsindex c70b7beb..fa67fddb 100644--- a/src/bots/tools/fleet-status.ts+++ b/src/bots/tools/fleet-status.ts@@ -26,6 +26,11 @@ export function createFleetStatusTool(manager: BotManager, leadId: string) {const attention = s.needsYou ? ' · ⚠ NEEDS YOU' : '';lines.push(`- ${s.name} (${s.id}) [${s.state}]${attention}${detail}`);}+ const open = manager.tasks.open({ requester: leadId });+ if (open.length > 0) {+ lines.push('', `Open tasks (${open.length}) — you will be woken when they finish:`);+ for (const t of open) lines.push(`- ${t.id} → ${t.assignee}: ${t.status}${t.stage ? ` (${t.stage})` : ''} — ${t.goal.slice(0, 70)}`);+ }return lines.join('\n');},});diff --git a/src/bots/tools/fleet-tasks.ts b/src/bots/tools/fleet-tasks.tsnew file mode 100644index 00000000..28f8b63d--- /dev/null+++ b/src/bots/tools/fleet-tasks.ts@@ -0,0 +1,83 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import type { BotManager } from '../bot-manager.js';++/**+ * Lead-side fleet tools (ADR-021):+ * - fleet_delegate: fan out typed tasks to several crew in one call; the+ * lead is woken ONCE with a digest when the batch completes (or its+ * deadline passes), not once per task.+ * - fleet_tasks: see open/recent tasks, cancel one.+ * - fleet_pipeline: run the lead's declared pipeline (bot.yaml) on an+ * input — stages chain themselves without lead turns in between.+ */+export function createFleetDelegateTool(manager: BotManager, leadId: string) {+ return tool({+ description:+ 'Delegate work to your crew as typed tasks — several at once, in parallel. You are woken ONCE with a digest ' ++ '(status, outcome, delivered files, summary per task) when all of them finish or the deadline passes, so you do not ' ++ 'need to poll. Prefer this over bot_send for any real work.',+ inputSchema: zodSchema(z.object({+ tasks: z.array(z.object({+ bot: z.string().describe('Crew bot id'),+ goal: z.string().min(10).max(8000).describe('Self-contained task: what to produce, inputs, constraints'),+ acceptance: z.string().max(1000).optional().describe('What "done" means — a file delivered, a check passed, a list of N items…'),+ })).min(1).max(12),+ label: z.string().max(60).optional().describe('Short name for this batch, e.g. "C36 research"'),+ deadlineMinutes: z.number().min(5).max(24 * 60).optional().describe('Wake me with partial results after this long even if some tasks are still running (default 120)'),+ wakeWhen: z.enum(['all', 'each']).optional().describe('all (default) = one digest when everything is done; each = a wake per finished task'),+ })),+ execute: async ({ tasks, label, deadlineMinutes, wakeWhen }: { tasks: Array<{ bot: string; goal: string; acceptance?: string }>; label?: string; deadlineMinutes?: number; wakeWhen?: 'all' | 'each' }) => {+ const result = manager.delegate(leadId, { tasks, label, deadlineMinutes, wakeWhen });+ if (!result.ok) return `Error: ${result.error}`;+ const lines = [`Batch ${result.batchId}${label ? ` "${label}"` : ''} dispatched — ${result.tasks.length} task(s):`];+ for (const t of result.tasks) lines.push(`- ${t.id} → ${t.assignee}${t.duplicated ? ' (already in progress — not re-dispatched)' : ''}`);+ lines.push(`You will be woken with a digest when they finish${deadlineMinutes ? ` or after ${deadlineMinutes} minutes` : ' or after 120 minutes'}. Finish this turn now; do not poll.`);+ return lines.join('\n');+ },+ });+}++export function createFleetTasksTool(manager: BotManager, leadId: string) {+ return tool({+ description: 'List your open and recent delegated tasks (with results), or cancel one.',+ inputSchema: zodSchema(z.object({+ action: z.enum(['list', 'cancel']).optional().describe('list (default) or cancel'),+ taskId: z.string().optional().describe('For cancel: the task id'),+ })),+ execute: async ({ action, taskId }: { action?: 'list' | 'cancel'; taskId?: string }) => {+ if (action === 'cancel') {+ if (!taskId) return 'Error: cancel needs a taskId.';+ const r = await manager.cancelTask(leadId, taskId);+ return r.ok ? `Task ${taskId} cancelled.` : `Error: ${r.error}`;+ }+ const recent = manager.tasksFor(leadId);+ if (recent.length === 0) return 'No delegated tasks yet. Use fleet_delegate to hand work to your crew.';+ const lines = ['Your tasks (newest first):'];+ for (const t of recent) {+ const r = t.result;+ lines.push(`- ${t.id} → ${t.assignee}: ${t.status}${r?.outcome ? ` · ${r.outcome}` : ''}${r?.deliverables?.length ? ` · ${r.deliverables.length} file(s)` : ''} — ${t.goal.slice(0, 80)}`);+ }+ return lines.join('\n');+ },+ });+}++export function createFleetPipelineTool(manager: BotManager, leadId: string, stageNames: string[]) {+ return tool({+ description:+ `Run your pipeline (${stageNames.join(' → ')}) on an input. Each stage is delegated to its bot in turn and hands its ` ++ 'deliverable to the next; you are woken once at the end with the final result. Use this for the standard job; do not ' ++ 'run the stages by hand.',+ inputSchema: zodSchema(z.object({+ input: z.string().min(3).max(4000).describe('The subject of this run, e.g. a topic, a URL, a brief'),+ label: z.string().max(60).optional().describe('Short name for the run'),+ })),+ execute: async ({ input, label }: { input: string; label?: string }) => {+ const r = manager.runPipeline(leadId, input, label);+ if (!r.ok) return `Error: ${r.error}`;+ return `Pipeline run ${r.runId} started: stage 1/${r.total} "${r.firstStage}" dispatched${r.duplicated ? ' (a run on this input was already in progress)' : ''}. ` ++ 'You will be woken when the last stage finishes. Finish this turn now.';+ },+ });+}diff --git a/src/bots/types.ts b/src/bots/types.tsindex 6312fa3f..5dd8f8df 100644--- a/src/bots/types.ts+++ b/src/bots/types.ts@@ -31,6 +31,8 @@ export interface BotToolAccess {export interface BotMemoryConfig {/** none = stateless; own = private namespace (default); shared-read = also read listed bots. */scope: BotMemoryScope;+ /** Extract durable facts after productive runs (default true). ADR-021. */+ learn?: boolean;/** Bot ids whose context this bot may search when scope is shared-read. */allowCrossBotRecall?: string[];}@@ -125,10 +127,32 @@ export interface BotManifest {fleetRole?: 'lead' | 'crew';/** Crew bots only: the lead's id. Leads and solos never set this. */parent?: string;+ /**+ * A lead's standard job as data (ADR-021): stages run in order, each a+ * typed task for one crew bot, each handing its deliverable to the next.+ * Goal templates may use {{input}} and {{previous}}. The lead is woken+ * once, at the end. A stage marked final promotes its deliverable to the+ * fleet folder's top level.+ */+ pipeline?: BotPipelineConfig;createdAt?: string;updatedAt?: string;}+export interface BotPipelineStage {+ name: string;+ /** Crew bot id. */+ bot: string;+ goal: string;+ acceptance?: string;+ final?: boolean;+}++export interface BotPipelineConfig {+ name?: string;+ stages: BotPipelineStage[];+}+/*** Per-bot permission manifest — `~/.mercury/bots/<id>/permissions.yaml`.* THE single source of truth for what a bot may do (tool gate + path scopesdiff --git a/src/core/commands/bots-command.ts b/src/core/commands/bots-command.tsindex cef07b86..e765eaf0 100644--- a/src/core/commands/bots-command.ts+++ b/src/core/commands/bots-command.ts@@ -637,6 +637,30 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chanreturn;}+ if (action === 'tasks') {+ // /bots tasks <leadId> — what a lead has delegated and what came back.+ const target = parts[1]?.toLowerCase();+ if (!target || !bm.store.exists(target)) {+ await channel.send('Usage: `/bots tasks <leadId>` — open and recent delegated tasks of a fleet lead.', channelId);+ return;+ }+ const tasks = bm.tasksFor(target);+ if (tasks.length === 0) {+ await channel.send(`**${target}** has not delegated any tasks yet.`, channelId);+ return;+ }+ const icons: Record<string, string> = { queued: '🔵', running: '🟢', done: '✅', failed: '❌', halted: '⏹', cancelled: '🚫' };+ const lines = [`**${target} — delegated tasks** (newest first)`, ''];+ for (const t of tasks) {+ const r = t.result;+ lines.push(`${icons[t.status] ?? '•'} ${t.id} → **${t.assignee}**${t.stage ? ` (${t.stage})` : ''} · ${t.status}${r?.outcome ? ` · ${r.outcome}` : ''} · ${formatRelative(t.completedAt ?? t.startedAt ?? t.createdAt)}`);+ lines.push(` ${t.goal.slice(0, 100)}`);+ for (const d of r?.deliverables ?? []) lines.push(` 📁 ${tildify(d)}`);+ }+ await channel.send(lines.join('\n'), channelId);+ return;+ }+if (action === 'folder') {// /bots folder <id> — open the deliverables folder in Finder / Explorer / the file manager.const target = parts[1]?.toLowerCase();@@ -677,6 +701,7 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan'`/bots persona <id> <text>` — set/replace its character (with template conversion)\n' +'`/bots budget <id> <tokens|suggest|none>` — daily token budget (default 5M/day; none = unlimited)\n' +'`/bots outputs [id]` — what the bots delivered, and where\n' ++ '`/bots tasks <leadId>` — a lead\'s delegated tasks and their results\n' +'`/bots folder <id>` — open a bot\'s deliverables folder\n' +'`/bots edit <id> <field> <value>` — edit any config field anytime\n' +'`/bots journal <id>` — recent runs\n' +diff --git a/src/utils/config.ts b/src/utils/config.tsindex 514894dc..329479d2 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -216,6 +216,8 @@ export interface MercuryConfig {maxCrew?: number;/** Lead bots may create/remove their own crew via bot_spawn/bot_retire. */allowLeadSpawn?: boolean;+ /** Provider crew bots use when their manifest sets none (a cheaper lane for stage work). ADR-021. */+ crewProvider?: string;};/** Per-bot daily token cap applied when a bot sets none (0 = unlimited). ADR-020. */suggestedDailyTokenBudget?: number;@@ -504,6 +506,7 @@ export function getDefaultConfig(): MercuryConfig {fleets: {maxCrew: getEnvNum('BOTS_FLEET_MAX_CREW', 6),allowLeadSpawn: getEnvBool('BOTS_FLEET_LEAD_SPAWN', true),+ crewProvider: getEnv('BOTS_FLEET_CREW_PROVIDER') || undefined,},suggestedDailyTokenBudget: getEnvNum('BOTS_SUGGESTED_DAILY_TOKEN_BUDGET', 5_000_000),fleetDailyTokenBudget: getEnvNum('BOTS_FLEET_DAILY_TOKEN_BUDGET', 20_000_000),diff --git a/website/docs/integrations/mercury-bots.mdx b/website/docs/integrations/mercury-bots.mdxindex 442d9434..3f7da5e1 100644--- a/website/docs/integrations/mercury-bots.mdx+++ b/website/docs/integrations/mercury-bots.mdx@@ -91,6 +91,18 @@ Every unattended run is governed:- **A turn is capped** at 300k tokens and 20 minutes (`autonomy.maxTokensPerTurn`, `maxTurnMinutes` in `bot.yaml`); long context is compacted automatically.- **Every bot has a daily token cap** — 5M unless you set one with `/bots budget <id> <tokens|suggest|none>` — and the fleet has one (`bots.fleetDailyTokenBudget`). You are warned at 80%; at 100% the bot pauses until tomorrow.- **A routine tick is skipped, never queued,** while the bot is still busy or within 30 minutes of its last run (`schedules[].minIntervalMinutes`). Bot-created routines run at most every 30 minutes, at most three per bot.+- **Leads delegate typed tasks** with `fleet_delegate` — several at once, each with a goal and what "done" means — and are woken **once** with a digest when the batch finishes or its deadline passes. A lead's standard job can be declared as a **pipeline** in `bot.yaml` (`pipeline.stages`), and `fleet_pipeline` runs it end to end with no lead turn between stages:++ ```yaml+ pipeline:+ name: article+ stages:+ - { name: research, bot: source-researcher, goal: "Build a sourced dossier on {{input}}" }+ - { name: draft, bot: article-writer-draft, goal: "Write the 800–1000 word piece from {{previous}}" }+ - { name: check, bot: fact-checker, goal: "Fact-check {{previous}} and fix what fails" }+ - { name: package, bot: delivery-packager, goal: "Finalise {{previous}} for delivery", final: true }+ ```+- **Bots remember.** After a productive run, durable facts (sources, decisions, where things are) go into the bot's own memory, and every turn starts with a digest of its last five runs plus its own working-state note (`bot_state`). `bots.fleets.crewProvider` puts crew work on a cheaper provider.- **A run is judged by what it did,** not by what it says: delivered a file, took an action, delegated, or nothing. A routine that only writes notes gets one nudge to deliver; three empty runs in a row pause it (`/bots start` resumes). Monitoring routines can declare `expects: check` to be allowed to find nothing.## Bundles