Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(bots): refuse the fleet level the roster cannot see

Jean-Christophe Tourniera5dee2c8db31
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.md
index 81aa74f4..aee1d5c8 100644
--- a/BOTS-ARCHITECTURE.md
+++ b/BOTS-ARCHITECTURE.md
@@ -101,6 +101,8 @@ autonomy:
**Persona is a markdown file, not config** (Grok's prompts are literally versioned templates; Hermes/OpenClaw both use markdown persona files; Mercury already does this for soul). `persona.md` holds character, voice, standing instructions, output conventions for each surface the bot serves.
+**Fleet hierarchy is a relation, not a record.** `fleetRole: lead|crew` plus `parent: <leadId>` on the crew member's `bot.yaml`, and the profile folder nests physically under its lead (`research-lead/analyst/`). A lead heads exactly one crew; a bot belongs to at most one fleet; a lead may itself have a parent (mid-level lead). The tree is capped at `MAX_FLEET_DEPTH` (3) levels — CEO → Engineering Lead → Backend — and the cap is checked at creation and on every save, so what can exist is what `list()`/`crewOf()` walk and the roster can show.
+
### 2.2 Execution model — the decision
**Chosen: in-process async coroutines with a bot lane queue. No per-bot processes, no per-bot threads.**
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.ts
index 2ccd5c13..1a5686ee 100644
--- a/src/bots/bot-manager.ts
+++ b/src/bots/bot-manager.ts
@@ -10,7 +10,7 @@ import type { TokenBudget } from '../utils/tokens.js';
import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import { UserMemoryStore as UserMemoryStoreImpl } from '../memory/user-memory.js';
-import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression } from './store.js';
+import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression, MAX_FLEET_DEPTH } from './store.js';
import { BotJournal, type BotTranscript, type BotUsage } from './journal.js';
import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';
import { sweepSharedSandbox } from './retention.js';
@@ -1346,10 +1346,11 @@ export class BotManager {
if (lead.fleetRole !== 'lead') {
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.
+ // Multi-level guard: no cycles, bounded depth (MAX_FLEET_DEPTH levels — e.g.
+ // CEO → Engineering Lead → Backend, the deepest level list() and crewOf() walk).
+ // `level` is the level the NEW bot would take: one below the lead it joins.
let ancestor: string | undefined = leadId;
- let depth = 0;
+ let level = 1;
const seen = new Set<string>();
while (ancestor) {
if (seen.has(ancestor)) return { ok: false, error: 'Fleet cycle detected in parent chain' };
@@ -1357,8 +1358,13 @@ export class BotManager {
if (ancestor === spec.id.toLowerCase()) {
return { ok: false, error: `Cannot add **${spec.id}** — it would become its own ancestor` };
}
+ // Refuse the level the reader cannot reach: a bot created below this lead
+ // would exist on disk and answer by id while staying out of the roster.
+ if (level >= MAX_FLEET_DEPTH) {
+ return { ok: false, error: `Fleet nesting is capped at ${MAX_FLEET_DEPTH} levels` };
+ }
ancestor = this.store.get(ancestor)?.parent;
- if (++depth > 3) return { ok: false, error: 'Fleet nesting is capped at 3 levels' };
+ level += 1;
}
// Replay-safety BEFORE the crew cap: a re-run "build the crew" turn
// (durable job replayed after an interrupted session) re-derives its
diff --git a/src/bots/fleet-layout.test.ts b/src/bots/fleet-layout.test.ts
index 70264ede..b2f66f88 100644
--- a/src/bots/fleet-layout.test.ts
+++ b/src/bots/fleet-layout.test.ts
@@ -187,6 +187,64 @@ describe('fleet physical layout (crew nests under the lead)', () => {
});
});
+describe('fleet depth cap (creation allows exactly what the roster can see)', () => {
+ let root: string;
+ let manager: BotManager;
+ let store: BotStore;
+
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'mercury-fleet-depth-'));
+ manager = makeManager(root);
+ store = manager['store'];
+ });
+
+ afterEach(() => {
+ for (const m of activeManagers.splice(0)) m.dispose();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it('addCrew builds the third level and refuses the fourth', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ expect(manager.addCrew('ceo', { id: 'eng-lead', name: 'Eng Lead' }).ok).toBe(true);
+ manager.promoteLead('eng-lead');
+
+ const third = manager.addCrew('eng-lead', { id: 'backend', name: 'Backend' });
+ expect(third.ok).toBe(true);
+ // Level 3 is the deepest level list() and crewOf() reach — a bot created
+ // there is a bot the roster can show. Anything deeper used to be created
+ // and then disappear from both.
+ expect(store.list().map(m => m.id)).toContain('backend');
+ expect(store.crewOf('eng-lead').map(m => m.id)).toContain('backend');
+
+ manager.promoteLead('backend');
+ const fourth = manager.addCrew('backend', { id: 'intern', name: 'Intern' });
+ expect(fourth.ok).toBe(false);
+ if (!fourth.ok) expect(fourth.error).toMatch(/3 levels/);
+ expect(store.get('intern')).toBeNull();
+ expect(existsSync(join(root, 'bots', 'ceo', 'eng-lead', 'backend', 'intern'))).toBe(false);
+ expect(store.list().map(m => m.id).sort()).toEqual(['backend', 'ceo', 'eng-lead']);
+ });
+
+ it('a hand-written fourth level is refused on create and on save', () => {
+ store.create({ id: 'ceo', name: 'CEO', manifest: { fleetRole: 'lead' } });
+ store.create({ id: 'eng-lead', name: 'Eng Lead', manifest: { fleetRole: 'lead', parent: 'ceo' } });
+ store.create({ id: 'backend', name: 'Backend', manifest: { fleetRole: 'lead', parent: 'eng-lead' } });
+
+ expect(() =>
+ store.create({ id: 'intern', name: 'Intern', manifest: { fleetRole: 'crew', parent: 'backend' } }))
+ .toThrow(/3 levels/);
+
+ // Re-parenting into the same depth is refused before the profile dir moves,
+ // so a refused write leaves the disk where it was.
+ store.create({ id: 'qaid', name: 'QA' });
+ expect(() => store.update('qaid', m => { m.fleetRole = 'crew'; m.parent = 'backend'; }))
+ .toThrow(/3 levels/);
+ expect(existsSync(join(root, 'bots', 'qaid', 'bot.yaml'))).toBe(true);
+ expect(existsSync(join(root, 'bots', 'ceo', 'eng-lead', 'backend', 'qaid'))).toBe(false);
+ expect(store.get('qaid')!.parent).toBeUndefined();
+ });
+});
+
describe('fleet cascade delete (manager lifecycle)', () => {
let root: string;
let manager: BotManager;
diff --git a/src/bots/store.ts b/src/bots/store.ts
index 86663d19..391f11e2 100644
--- a/src/bots/store.ts
+++ b/src/bots/store.ts
@@ -614,6 +614,9 @@ export class BotStore {
if (errors.length > 0) {
throw new Error(`Invalid bot manifest: ${errors.join('; ')}`);
}
+ // Fleet depth: refuse before the profile dir exists. save() would refuse the
+ // same write, but only after mkdir left an empty ghost directory behind.
+ this.assertFleetParentValid(manifest);
// Fleet layout: a crew bot's profile is created INSIDE its lead's
// directory. The lead must exist — fail closed rather than placing a
// profile the hierarchy cannot account for.
@@ -652,10 +655,16 @@ export class BotStore {
}
update(id: string, mutator: (m: BotManifest) => void): BotManifest {
- const manifest = this.get(id);
- if (!manifest) throw new Error(`Bot "${id}" does not exist`);
+ const current = this.get(id);
+ if (!current) throw new Error(`Bot "${id}" does not exist`);
+ // Mutate a copy: a mutator that re-parents into a refused depth (or onto a cycle)
+ // must leave the cached manifest — and the disk — exactly as they were.
+ const manifest: BotManifest = { ...current };
mutator(manifest);
manifest.updatedAt = new Date().toISOString();
+ // Validate BEFORE moving anything: save() would refuse the same write, but only
+ // after the profile dir had already been relocated into the refused depth.
+ this.assertFleetParentValid(manifest);
// Re-parent moves the profile dir to keep the physical layout in sync
// (crew nested under its lead; promote/detach moves back to the root).
this.relocateToParent(manifest);
@@ -709,7 +718,12 @@ export class BotStore {
throw new Error(`Fleet cycle detected at "${ancestor}"`);
}
seen.add(ancestor);
- if (++depth > MAX_FLEET_DEPTH) {
+ // `depth` counts ancestors, so this bot's level is depth + 1: a bot at level
+ // MAX_FLEET_DEPTH has MAX_FLEET_DEPTH - 1 ancestors and is the deepest one list()
+ // walks to. `depth > MAX_FLEET_DEPTH` compared ancestors to levels, letting a
+ // fourth level be created and then never listed.
+ depth += 1;
+ if (depth >= MAX_FLEET_DEPTH) {
throw new Error(`Fleet nesting exceeds ${MAX_FLEET_DEPTH} levels`);
}
const next: string | undefined = this.get(ancestor)?.parent;