Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): multi-level fleets + imperative lead self-organization
Salman Qureshi0862c9a87d52
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 6dcd99f4..673b3207 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -734,6 +734,23 @@ describe('Bot fleets (lead + crew)', () => {expect(await retire.execute({ id: 'guard' }, {} as any)).toContain('is not crew');});+ it('multi-level fleets: a crew member can lead its own nested crew', () => {+ setupFleet();+ // Promote researcher to a mid-level lead (crew of ceo AND lead of scouts).+ store.update('researcher', m => { m.fleetRole = 'lead'; });+ manager.addCrew('researcher', { id: 'scout', name: 'Scout', persona: '# Scout\n\nScouts markets.' });+ expect(store.get('scout')?.parent).toBe('researcher');+ expect(store.crewOf('ceo').map(c => c.id)).toContain('researcher');+ expect(store.crewOf('researcher').map(c => c.id)).toEqual(['scout']);+ // Mid-level lead gets fleet tools AND its parent in the comms roster+ const rt = (manager as unknown as { getOrCreateRuntime(id: string, m: BotManifest): { tools: Record<string, any> } }).getOrCreateRuntime('researcher', store.get('researcher')!);+ expect(rt.tools.fleet_status).toBeDefined();+ expect(rt.tools.bot_spawn).toBeDefined();+ // Cycle/nesting guards: depth cap and ancestor rejection+ expect(manager.addCrew('scout', { id: 'ceo', name: 'Nope' })).toMatchObject({ ok: false });+ expect(manager.addCrew('scout', { id: 'scout', name: 'Self' })).toMatchObject({ ok: false });+ });+it('solo bots never get fleet tools', () => {store.create({ id: 'loner', name: 'Loner' });const tools = runtimeFor('loner').tools;diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 0aeef199..734ee628 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -598,6 +598,7 @@ export class BotManager {if (manifest.fleetRole === 'lead') {return {role: 'lead' as const,+ leadName: manifest.parent ? this.store.get(manifest.parent)?.name : undefined,crew: this.store.crewOf(botId).map(c => ({id: c.id,name: c.name,@@ -607,7 +608,7 @@ export class BotManager {maxCrew: this.maxCrew(),};}- if (manifest.fleetRole === 'crew' && manifest.parent) {+ if (manifest.parent) {return {role: 'crew' as const,leadName: this.store.get(manifest.parent)?.name,@@ -690,7 +691,8 @@ export class BotManager {if (manifest.fleetRole === 'lead') {for (const crew of this.store.crewOf(botId)) roster.add(crew.id);}- if (manifest.fleetRole === 'crew' && manifest.parent) {+ // A mid-level lead (crew of a parent AND lead of its own crew) talks both ways.+ if (manifest.parent) {roster.add(manifest.parent);}roster.delete(botId);@@ -720,7 +722,21 @@ export class BotManager {const lead = this.store.get(leadId);if (!lead) return { ok: false, error: `No bot "${leadId}"` };if (lead.fleetRole !== 'lead') {- return { ok: false, error: `**${lead.name}** is not a fleet lead — promote it first with /bots create flow or add crew via onboarding` };+ return { ok: false, error: `**${lead.name}** is not a fleet lead — promote it with \`/bots promote ${leadId}\` first` };+ }+ // Multi-level guard: no cycles, bounded depth (v1 supports 3 levels —+ // e.g. CEO → Engineering Lead → Backend). Walk the lead's parent chain.+ let ancestor: string | undefined = leadId;+ let depth = 0;+ const seen = new Set<string>();+ while (ancestor) {+ if (seen.has(ancestor)) return { ok: false, error: 'Fleet cycle detected in parent chain' };+ seen.add(ancestor);+ if (ancestor === spec.id.toLowerCase()) {+ return { ok: false, error: `Cannot add **${spec.id}** — it would become its own ancestor` };+ }+ ancestor = this.store.get(ancestor)?.parent;+ if (++depth > 3) return { ok: false, error: 'Fleet nesting is capped at 3 levels' };}const crew = this.store.crewOf(leadId);const cap = this.maxCrew();diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex 5dcfefa9..b7a6e33f 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -250,16 +250,17 @@ Anything outside these two areas and your declared Access grants is denied.`;if (input.fleet?.role === 'lead') {const roster = input.fleet.crew.length > 0? input.fleet.crew.map(c => `- ${c.name} (${c.id})${c.description ? ` — ${c.description}` : ''} [${c.state}]`).join('\n')- : '(empty — use bot_spawn to add specialists)';+ : '(EMPTY — build your team first, see below)';prompt += `\n\nYou lead a fleet of crew bots:${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.- 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.`;+- 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.` : ''}`;} else if (input.fleet?.role === 'crew') {prompt += `\n\nYou are crew in **${input.fleet.leadName ?? 'your lead'}'s** fleet. Tasks delegated to you (mailbox messages with a task) return your result to the lead automatically when you finish — make your final output a complete, self-contained report. Use bot_send to ask the lead questions mid-task.`;}diff --git a/src/bots/store.ts b/src/bots/store.tsindex 6bdc2dce..855691b6 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -68,13 +68,10 @@ export function validateBotManifest(manifest: Partial<BotManifest>): string[] {for (const other of canMessage) {if (other === manifest.id) errors.push('canMessage cannot include the bot itself');}- // Fleet hierarchy: crew requires a parent that is a lead; leads have no- // parent. Single-level fleets in v1 — a lead-of-lead is a config error- // (nesting would need a deeper cycle check, so it is rejected outright).+ // Fleet hierarchy: `parent` = has a lead; `fleetRole: lead` = leads a crew.+ // Both may be set (mid-level lead, e.g. an Engineering Lead under a CEO).+ // A bare `fleetRole: crew` with no parent is invalid; self-parent invalid.if (manifest.parent) {- if (manifest.fleetRole !== 'crew') {- errors.push('parent is only valid on fleetRole "crew" bots');- }if (manifest.parent === manifest.id) {errors.push('parent cannot be the bot itself');}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 56c6a154..22c81768 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1390,7 +1390,7 @@ export class Agent {const action = (parts[0] ?? '').toLowerCase();// All bot-targeting actions accept id OR name — resolve to the id here.- if (['open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause', 'start', 'run', 'persona', 'crew', 'add-crew', 'remove-crew'].includes(action) && parts[1]) {+ if (['open', 'send', 'journal', 'inbox', 'budget', 'edit', 'delete', 'enable', 'disable', 'stop', 'pause', 'start', 'run', 'persona', 'crew', 'add-crew', 'remove-crew', 'promote', 'demote'].includes(action) && parts[1]) {const resolved = bm.resolveBotId(parts[1]);if (resolved) parts[1] = resolved;}@@ -1411,31 +1411,37 @@ export class Agent {await channel.send('No bots configured. Use `/bots create <id> "Name" "Description"` to onboard one.', channelId);return;}- // Fleet tree: 👑 lead first with crew indented beneath; solos flat.- const leads = summaries.filter(s => s.fleetRole === 'lead');- const crews = summaries.filter(s => s.fleetRole === 'crew');- const solos = summaries.filter(s => !s.fleetRole);+ // Fleet tree: 👑 leads first with crew nested beneath (multi-level,+ // recursive); parentless solos flat after.const fmt = (s: typeof summaries[number], indent: string) => {const icon = stateIcons[s.state] ?? '❓';+ const badge = s.fleetRole === 'lead' ? ' 👑' : '';const lastRun = s.lastRunAt ? ` · last ${(s.lastRunState ?? '')} ${formatRelative(s.lastRunAt)}` : '';const activity = s.activity ? `\n${indent} ↳ ${s.activity}` : '';const attention = s.needsYou ? ' · ⚠ needs you' : '';- return `${indent}${icon} **${s.name}** (${s.id}) — ${s.state}${attention}${lastRun}${activity}`;+ return `${indent}${icon} **${s.name}** (${s.id})${badge} — ${s.state}${attention}${lastRun}${activity}`;};const lines: string[] = [`**Bots** (${summaries.length})`, ''];const rendered = new Set<string>();- for (const lead of leads) {- const crew = crews.filter(c => c.parent === lead.id);- lines.push(fmt(lead, ''));- rendered.add(lead.id);+ const renderCrew = (leadId: string, depth: number) => {+ const crew = summaries.filter(s => s.parent === leadId);for (const c of crew) {- lines.push(fmt(c, ' '));+ const indent = ' '.repeat(depth);+ lines.push(fmt(c, depth > 0 ? `${indent}└─` : ' '));rendered.add(c.id);+ renderCrew(c.id, depth + 1);}- if (crew.length === 0) lines.push(' (empty crew — `/bots add-crew` or the lead can bot_spawn)');+ if (crew.length === 0 && depth === 1) {+ lines.push(`${' '.repeat(depth)}└─ (empty crew — \`/bots add-crew\` or the lead can bot_spawn)`);+ }+ };+ for (const root of summaries.filter(s => !s.parent)) {+ lines.push(fmt(root, ''));+ rendered.add(root.id);+ if (root.fleetRole === 'lead') renderCrew(root.id, 1);}- for (const s of [...crews, ...solos]) {- if (!rendered.has(s.id)) lines.push(fmt(s, ''));+ for (const s of summaries) {+ if (!rendered.has(s.id)) lines.push(fmt(s, '')); // detached crew (defensive)}const running = summaries.filter(s => s.state === 'running').length;lines.push('', `Running: ${running} | Queued: ${summaries.reduce((a, s) => a + (s.state === 'queued' ? 1 : 0), 0)}`);@@ -1764,6 +1770,32 @@ export class Agent {return;}+ if (action === 'promote' || action === 'demote') {+ // /bots promote <id> — solo/crew → fleet lead (demote: lead → solo).+ const target = parts[1]?.toLowerCase();+ if (!target || !bm.store.exists(target)) {+ await channel.send(`Usage: \`/bots ${action} <id>\``, channelId);+ return;+ }+ try {+ bm.store.update(target, m => {+ if (action === 'promote') {+ m.fleetRole = 'lead';+ } else {+ m.fleetRole = undefined;+ if (bm.store.crewOf(target).length > 0) throw new Error(`**${target}** still has crew — remove-crew first`);+ }+ });+ bm.invalidateRuntime(target);+ await channel.send(action === 'promote'+ ? `👑 **${target}** is now a fleet lead. It will self-organize: give it a setup task and it will build its own crew with bot_spawn (persona-derived), or add crew with \`/bots add-crew ${target} …\`.`+ : `⬇ **${target}** demoted to a solo bot.`, channelId);+ } catch (err: any) {+ await channel.send(`Failed: ${err?.message}`, channelId);+ }+ return;+ }+if (action === 'crew') {// /bots crew <leadId> — the fleet tree + per-crew recent runs.const leadId = parts[1]?.toLowerCase();@@ -1887,6 +1919,7 @@ export class Agent {'`/bots enable|disable|stop|start <id>` — control (stop holds queued jobs; start resumes them)\n' +'`/bots run <id> [routineName]` — fire a routine now, or a bare wake turn\n' +'`/bots crew <leadId>` — fleet tree with per-crew runs\n' ++ '`/bots promote <id>` / demote — make a bot a fleet lead (it then self-organizes) / back to solo\n' +'`/bots add-crew <leadId> <id> "Name" "Desc" ["persona"]` — add a sub-bot to a fleet\n' +'`/bots remove-crew <leadId> <crewId>` — retire a crew member\n' +'`/bots delete <id> confirm` — permanently delete',