Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): budgets by default, routine gate, 3-strike pause, visible deliverables (ADR-020)
Salman Qureshi705f6c017874
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.mdindex cb2c6fd9..ddbdf148 100644--- a/BOTS-ARCHITECTURE.md+++ b/BOTS-ARCHITECTURE.md@@ -222,6 +222,19 @@ Plus: **SQLite hygiene** (WAL + periodic idle `wal_checkpoint(TRUNCATE)` + schedNet: a bot running hourly for a year costs tens of MB; a 10-bot fleet stays under ~200 MB before pruning.+### 2.12 Governance and deliverables (ADR-020, Oct 2026)++Added after an audit of real fleets (see ADR-020 for the numbers). Four mechanisms, all computed by the runtime, none by the model:++| Mechanism | Where | Default |+|---|---|---|+| Per-turn caps (tokens, minutes) + context compaction | `bot-turn.ts` governor, `prepareStep` | 300k / 20 min; keep 8 results × 24KB |+| Daily caps (per bot, per fleet) + 80% warning | `BotManager.recordBotTokens` | 5M per bot, 20M per fleet |+| Routine gate (busy / too soon / paused) + bot-schedule limits | `BotManager.enqueue`, `tools/bot-schedule.ts` | 30-minute gap, 3 routines per bot |+| Outcome verdict from the tool trace, one nudge, 3-strike pause, shared-folder write budget | `bot-turn.ts` `computeOutcome`, `wrapBotTools`; `routine-state.json` | `work` for unattended runs |++Deliverables 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.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 f60587af..8260d1d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,20 @@# Changelog+## 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.++- **Per-turn caps.** A turn stops at 300k tokens or 20 minutes (`autonomy.maxTokensPerTurn` / `maxTurnMinutes`). A cut-off is journaled as `turn_budget` / `turn_time` — terminal, no dead-letter, no "needs you", one notice a day.+- **Context compaction.** Tool results older than the last 8 are stubbed on every step; any single result is capped at 24KB. Prompts stop growing with the number of steps.+- **Budgets on by default.** Every bot has a daily cap (5M tokens unless `/bots budget` says otherwise; `none` = unlimited) and the fleet has one (`bots.fleetDailyTokenBudget`, 20M). You are warned at 80%.+- **Routine gate.** A cron tick is skipped — never stacked — while the bot is busy or within 30 minutes of its last run (`schedules[].minIntervalMinutes`). Bot-created routines run at most every 30 minutes, at most 3 per bot; self-scheduled follow-ups are at least 10 minutes out.+- **Outcome verdict.** The tool trace, not the reply, decides what a run did: `deliverable`, `action`, `delegated`, `message` or `none`. An unattended run that only wrote notes gets one nudge to deliver or admit it. A reply that claims delivery with no matching tool call is flagged. Three empty runs in a row pause the routine; `/bots start` resumes it.+- **Shared-folder budget.** Writes to `_shared/` are limited per run (warn at 2 files / 32KB, refuse at 6 / 128KB). The private workspace is unlimited.+- **Deliverables you can find.** Results go to `~/Documents/Mercury/<Bot name>/` (Windows: Documents; Termux: shared storage; `bots.deliverablesDir` overrides) — finals on top, crew work under `work/`, a README index, files named `YYYY-MM-DD <title>`. Shown at onboarding, in the roster, and in every "delivered" message. `/bots outputs [id]` lists them, `/bots folder <id>` opens the folder. The hidden `outputs/` zone is migrated once.+- **Honest failures.** Network cuts ("terminated", socket closed, interrupted streams) and empty streams retry instead of dead-lettering; the provider's real error (an invalid key, a 429) reaches the journal instead of "No output generated".+- **Journal v2.** Real turn start, steps, tool calls, peak prompt size, outcome and delivered paths per run, plus a compact transcript per run (last 50 kept). `/bots journal` shows them; `mercury bots doctor` flags bots whose unattended runs mostly produce nothing, paused routines, and write access to the whole home directory.+- Bot file tools and shell commands now resolve relative paths inside the bot's workspace, never the daemon's working directory. The roster scan ignores profile copies in `sandbox/` and `outputs/`.+## Unreleased — ink 8Mercury's terminal renderer moves from a heavily patched ink 5.2.1 to ink 8.0.0, which now does most of that work itself.diff --git a/DECISIONS.md b/DECISIONS.mdindex eab584dd..47b81e14 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -169,3 +169,19 @@- **Decision**: Vendor ink 8.0.0 (same pipeline as ADR-017) and keep only what upstream still lacks: `<Static itemKey>`, the freeze gate, the live-region guard (trim instead of writing an over-tall frame, which on ink 8 pushes copies of the live region into scrollback), and a small cursor-anchor hunk that resolves Mercury's `internal_cursor` cell after layout and feeds it to ink's own `setCursorPosition`. Mercury turns on `incrementalRendering`, and after the output wrapper sheds writes it calls `instance.clear()` so the next frame is a full repaint. React moves to 19.3; `engines.node` to `>=22`; the build target to `node22`; CI drops Node 20. The bundle banner exits with a clear message on Node < 22 (Bun is exempt) instead of failing at the first render.- **Alternatives considered**: backport ink 6–8 fixes into the 5.2.1 fork one by one (rebuilds ink 8 by hand, and every fix touches internals that changed); move to OpenTUI (native renderer, but needs Node ≥ 26.4 with `--experimental-ffi` or Bun, has no Android build for Termux, and is pre-1.0); stay on ink 5 and Node 20 (Node 20 reached end of life in April 2026).- **Consequence**: The patch shrinks from about a thousand lines to 168 (`patches/ink+8.0.0.patch`). The same four changes are kept as TypeScript commits on the `mercury` branch of the public fork [cosmicstack-labs/ink](https://github.com/cosmicstack-labs/ink), for review, rebasing and upstream proposals; Mercury still vendors from the stock tarball plus the applier, and no package is published from the fork. Node 20 users must upgrade before installing; `mercury doctor` and the docs say Node 22. Hardware-cursor and live-region tests now assert the result on an emulated terminal (`src/ui/vt-screen.ts`) instead of exact escape bytes, so they survive ink's encoding choices. The SQLite driver keeps better-sqlite3 first; Node 22.13+ also has `node:sqlite` (ADR-018).++## ADR-020: Bot turns are governed; runs are judged by their trace++- **Context**: Eleven days of two real fleets (13 bots, ~1,150 runs): 617M input tokens, a median turn of 750k tokens and a maximum of 6.6M, 38% of lead runs failed, and most output was notes about earlier runs ("records", "receipts", "mirror certs") — 372 of 637 files in the shared folder. Causes: no per-turn cap and no context compaction (25 steps × 6 continuations, every step re-sending every tool result); cron and self-schedules firing regardless of whether the bot was busy or anything had changed, with bot-created routines unbounded (one bot made a `*/5` routine whose prompt said "DO NOT EXECUTE"); 900 chars of memory, so the bot's only continuity was files it wrote and re-read; free-text comms with no fan-in; `terminated` and other network cuts classified permanent (135 dead-letters); finals hidden in `~/.mercury/bots/outputs/<botId>/` split across ten crew folders, never mentioned at onboarding; "Full access" plus relative paths resolving against the daemon's cwd, so a bot wrote into whatever repo the daemon was started from.+- **Decision**:+ - **Turn governor** (`bot-turn.ts`): hard caps per turn (300k tokens, 20 minutes; per-bot `autonomy.maxTokensPerTurn` / `maxTurnMinutes`), tripped through a local abort chained to the halt signal. A tripped cap is terminal (`turn_budget` / `turn_time`) but not an escalation: settled done, no DLQ, no needs-you, one owner notice per bot per day. Context is compacted on every step via the SDK's `prepareStep`: the newest 8 tool results stay verbatim (24KB each), older ones become a stub.+ - **Budgets by default** (`bot-manager.ts`): the per-bot daily cap falls back to `bots.suggestedDailyTokenBudget` (5M); `dailyTokenBudget: 0` is the only way to be unlimited. A fleet-wide `bots.fleetDailyTokenBudget` (20M) pauses every bot for the day. 80% warns once.+ - **Routine gate**: a cron tick is rejected (`busy`, `too_soon`, `routine_paused`) rather than queued when the bot has queued or running work, when the routine ran within `minIntervalMinutes` (default 30), or when the routine is paused. Delegated tasks and chat are never gated. `bot_schedule` refuses routines more frequent than 30 minutes, more than 3 per bot, and follow-ups under 10 minutes.+ - **Outcome verdict**: each run carries an expectation set by the manager from its trigger — `work` (cron, self, API), `message` (chat, delegated task), `check` (bare mailbox wake, or a routine declaring `expects: check`). The turn's tool trace yields `deliverable | action | delegated | message | none`; a file write counts as an action only outside the sandbox roots, a command only if its head is not read-only, a delivery always. A `work` run at `none` receives one nudge (at most 8 steps) and is then journaled as it is. The reply's own claims are checked against the trace (`claimedWithoutAction`). Three consecutive `none` runs pause the routine (`routine-state.json`); `/bots start` clears it.+ - **Shared-folder budget**: the bot's write tools are wrapped for the turn; writes into `_shared/` warn past 2 files / 32KB and are refused past 6 / 128KB. The private workspace is not limited.+ - **Deliverables** (`BotStore.deliverablesDir`): `<root>/<Bot name>/` for leads and solos, `<lead>/work/<crew>/` for crew; the root defaults to the platform Documents folder (Termux shared storage; `<MERCURY_HOME>/deliverables` when a custom home is set, so tests and the eval harness never touch a real Documents folder), overridable with `bots.deliverablesDir`. `bot_deliver` takes `title` and `final`; crew cannot produce finals; files are named `YYYY-MM-DD <title>.<ext>` and the folder keeps a README index. The path is in the bot's system prompt, the onboarding messages, the roster and every delivery notice. The legacy `outputs/` zone is migrated once at startup.+ - **Failure classes**: `terminated`, socket closes and interrupted streams are `provider_timeout`; the SDK's "No output generated" is `provider_empty`; both retry. Stream `error` parts are captured so the real provider error is classified. Retry wrappers are unwrapped before classification.+ - **Journal v2 + transcripts**: `turnStartedAt`, `steps`, `toolCalls`, `peakInputTokens`, `outcome`, `deliverables`, `claimedWithoutAction`, `routineId`; a compact JSON transcript per run under `transcripts/` (retention `transcriptRuns`, default 50).+ - **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.diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 641e1e9c..431a40d8 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { mkdirSync, mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync, utimesSync } from 'node:fs';+import { mkdirSync, mkdtempSync, rmSync, existsSync, writeFileSync, readFileSync, readdirSync, utimesSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -1065,11 +1065,14 @@ describe('bot_deliver — final artifact delivery', () => {rmSync(root, { recursive: true, force: true });});- it('moves a shared-folder artifact into the protected outputs zone', () => {+ it('moves a shared-folder artifact into the owner-visible deliverables folder (work/ unless final)', () => {const sharedFile = join(root, 'bots', '_shared', 'final-report.md');const result = manager.deliver('researcher', sharedFile);expect(result.accepted).toBe(true);- expect(result.path).toContain(join('outputs', 'researcher'));+ // Custom bots root → deliverables beside it, never the developer's Documents.+ expect(result.path).toContain(join(root, 'Mercury', 'RESEARCHER', 'work'));+ expect(result.path).toMatch(/\d{4}-\d{2}-\d{2} final report\.md$/);+ expect(existsSync(join(root, 'Mercury', 'RESEARCHER', 'README.md'))).toBe(true);expect(existsSync(sharedFile)).toBe(false); // a MOVE — the shared surface stays leanexpect(existsSync(result.path!)).toBe(true);});@@ -1093,3 +1096,170 @@ describe('bot_deliver — final artifact delivery', () => {expect(existsSync(second.path!)).toBe(true);});});++// ── ADR-020: governance ──────────────────────────────────────────────────────++describe('bot governance (ADR-020)', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-gov-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ });+ afterEach(() => {+ for (const m of activeManagers.splice(0)) m.dispose();+ rmSync(root, { recursive: true, force: true });+ });++ const ok = (text = 'done') => ({ text, finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 5 } } as any);+ const completes = () => mockedGenerateText.mockImplementation(async () => ok());+ const waitIdle = (botId: string) => vi.waitFor(() => {+ expect((manager as any).running.get(botId)?.size ?? 0).toBe(0);+ expect(manager.getQueuedCount(botId)).toBe(0);+ });++ it('a cron tick is skipped while the bot is busy, and until the routine min-interval has passed', async () => {+ seedBot(store, 'ticker');+ let release!: () => void;+ mockedGenerateText.mockImplementationOnce(() => new Promise((resolve) => { release = () => resolve(ok()); }));+ const first = manager.enqueue('ticker', { trigger: 'cron', prompt: 'cycle', routineId: 'bot:ticker:cycle' });+ expect(first.accepted).toBe(true);+ await vi.waitFor(() => expect((manager as any).running.get('ticker')?.size).toBe(1));+ // Busy → the tick is dropped, never stacked (the old behaviour queued it).+ expect(manager.enqueue('ticker', { trigger: 'cron', prompt: 'cycle v2', routineId: 'bot:ticker:cycle' })).toMatchObject({ accepted: false, reasonCode: 'busy' });+ // A delegated task is NOT a tick: it still queues behind the running turn.+ expect(manager.enqueue('ticker', { trigger: 'mailbox', prompt: 'please research X', fromBot: 'lead' }).accepted).toBe(true);+ completes();+ release();+ await waitIdle('ticker');+ // Finished → the next tick is still too soon (30-minute default gap).+ expect(manager.enqueue('ticker', { trigger: 'cron', prompt: 'cycle', routineId: 'bot:ticker:cycle' })).toMatchObject({ accepted: false, reasonCode: 'too_soon' });+ // A routine that declares a shorter gap in bot.yaml is honoured.+ store.update('ticker', m => { m.schedules = [{ name: 'fast', cron: '*/5 * * * *', prompt: 'x', minIntervalMinutes: 0 }]; });+ expect(manager.enqueue('ticker', { trigger: 'cron', prompt: 'x', routineId: 'bot:ticker:fast' }).accepted).toBe(true);+ });++ it('every bot gets the fleet default daily cap; 0 means unlimited; 80% warns once', async () => {+ seedBot(store, 'spender');+ const alerts: string[] = [];+ manager.setAlert(async (m) => { alerts.push(m); });+ expect(manager.dailyCapFor(store.get('spender')!)).toBe(5_000_000);+ store.update('spender', m => { m.autonomy = { dailyTokenBudget: 0 }; });+ expect(manager.dailyCapFor(store.get('spender')!)).toBe(0);+ store.update('spender', m => { m.autonomy = { dailyTokenBudget: 1000 }; });+ // Usage reaches the turn through onStepFinish (the SDK callback), not the result.+ mockedGenerateText.mockImplementation(async (opts: any) => { opts.onStepFinish?.({ usage: { inputTokens: 800, outputTokens: 50 }, toolCalls: [], toolResults: [] }); return ok(); });+ manager.enqueue('spender', { trigger: 'chat', prompt: 'a' });+ await waitIdle('spender');+ expect(alerts.some(a => a.includes('85% of today'))).toBe(true);+ manager.enqueue('spender', { trigger: 'chat', prompt: 'b' });+ await waitIdle('spender');+ expect(alerts.some(a => a.includes('daily token budget reached'))).toBe(true);+ expect(manager.getStatusSummaries().find(s => s.id === 'spender')?.state).toBe('paused');+ });++ it('a work routine that produces nothing three runs in a row is paused, told once, and resumed by start', async () => {+ seedBot(store, 'writer');+ const alerts: string[] = [];+ manager.setAlert(async (m) => { alerts.push(m); });+ // Every run only writes a note into _shared — no deliverable, no action.+ mockedGenerateText.mockImplementation(async (opts: any) => {+ opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 }, toolCalls: [{ toolName: 'write_file', toolCallId: 'w', input: { path: join(store.sharedSandboxDir(), 'record.md'), content: 'x' } }], toolResults: [{ toolCallId: 'w', output: { type: 'text', value: 'Wrote file' } }] });+ return ok('Record filed.');+ });+ store.update('writer', m => { m.schedules = [{ name: 'cycle', cron: '0 * * * *', prompt: 'cycle', minIntervalMinutes: 0 }]; });+ for (let i = 1; i <= 3; i++) {+ const r = manager.enqueue('writer', { trigger: 'cron', prompt: `cycle ${i}`, routineId: 'bot:writer:cycle' });+ expect(r.accepted).toBe(true);+ await waitIdle('writer');+ }+ const journal = manager.getJournal('writer', 5);+ expect(journal.map(r => r.outcome)).toEqual(['none', 'none', 'none']);+ expect(journal.every(r => r.claimedWithoutAction)).toBe(true);+ expect(journal[0].steps).toBeDefined();+ expect(journal[0].toolCalls).toBe(2); // the note, then the note again after the one nudge+ expect(journal[0].routineId).toBe('bot:writer:cycle');+ expect(store.readRoutineState('writer').paused['bot:writer:cycle']).toBeDefined();+ expect(alerts.filter(a => a.includes('is paused')).length).toBe(1);+ expect(manager.enqueue('writer', { trigger: 'cron', prompt: 'cycle 4', routineId: 'bot:writer:cycle' })).toMatchObject({ accepted: false, reasonCode: 'routine_paused' });+ manager.start('writer');+ expect(store.readRoutineState('writer').paused).toEqual({});+ expect(manager.enqueue('writer', { trigger: 'cron', prompt: 'cycle 5', routineId: 'bot:writer:cycle' }).accepted).toBe(true);+ await waitIdle('writer');+ // A completed-but-empty run is shown as such in the bot thread.+ const transcripts = readdirSync(join(store.botDir('writer'), 'transcripts'));+ expect(transcripts.length).toBe(4);+ expect(readFileSync(join(store.botDir('writer'), 'transcripts', transcripts[0]), 'utf-8')).toContain('"trace"');+ });++ it('a turn-limit stop is journaled as failed/turn_budget but is not an escalation', async () => {+ seedBot(store, 'big', { autonomy: { maxTokensPerTurn: 100 } });+ const alerts: string[] = [];+ manager.setAlert(async (m) => { alerts.push(m); });+ mockedGenerateText.mockImplementation(async (opts: any) => {+ opts.onStepFinish?.({ usage: { inputTokens: 500, outputTokens: 5 }, toolCalls: [], toolResults: [] });+ return ok('partial');+ });+ manager.enqueue('big', { trigger: 'chat', prompt: 'huge task' });+ await waitIdle('big');+ const [row] = manager.getJournal('big', 1);+ expect(row.state).toBe('failed');+ expect(row.reasonCode).toBe('turn_budget');+ expect(row.needsYou).toBeUndefined();+ expect(manager.getDlq('big')).toHaveLength(0);+ expect(alerts.some(a => a.includes('per-turn limit'))).toBe(true);+ expect(manager.getStatusSummaries().find(s => s.id === 'big')?.needsYou).toBe(false);+ });++ it('deliverables: human names, finals on top, crew under the lead folder, index, and legacy migration', () => {+ seedBot(store, 'lead', { fleetRole: 'lead', name: 'Article Writer' } as any);+ store.update('lead', m => { m.name = 'Article Writer'; });+ manager.addCrew('lead', { id: 'fact-checker', name: 'Fact Checker' });+ const shared = store.sharedSandboxDir();+ mkdirSync(shared, { recursive: true });+ writeFileSync(join(shared, 'draft-c34-oxide-v2.md'), '# Oxide');+ writeFileSync(join(shared, 'checks.md'), '# checks');+ const final = manager.deliver('lead', join(shared, 'draft-c34-oxide-v2.md'), { title: 'Oxide Series D explained', final: true });+ expect(final.path).toMatch(/Mercury\/Article Writer\/\d{4}-\d{2}-\d{2} Oxide Series D explained\.md$/);+ const crew = manager.deliver('fact-checker', join(shared, 'checks.md'), { final: true });+ expect(crew.final).toBe(false); // crew never produce finals+ expect(crew.path).toMatch(/Mercury\/Article Writer\/work\/fact-checker\/\d{4}-\d{2}-\d{2} checks\.md$/);+ const index = readFileSync(join(store.deliverablesDir('lead'), 'README.md'), 'utf-8');+ expect(index).toContain('Oxide Series D explained.md');+ expect(index).toContain('work/');+ const listed = manager.listDeliverables('lead');+ expect(listed.map(d => d.final)).toEqual([true]);+ expect(manager.listDeliverables().map(d => d.botId).sort()).toEqual(['fact-checker', 'lead']);+ // Legacy outputs zone moves into the visible folder once.+ mkdirSync(join(store.outputsDir(), 'lead'), { recursive: true });+ writeFileSync(join(store.outputsDir(), 'lead', 'old-piece.md'), 'old');+ expect(manager.migrateDeliverables()).toEqual({ moved: 1 });+ expect(existsSync(join(store.deliverablesDir('lead'), 'work', 'old-piece.md'))).toBe(true);+ expect(existsSync(join(store.outputsDir(), 'README.md'))).toBe(true);+ expect(manager.migrateDeliverables()).toEqual({ moved: 0 });+ });++ it('the roster scan ignores profile copies inside sandbox/, outputs/ and other data dirs', () => {+ seedBot(store, 'real');+ // A bot "mirroring" its own profile into its sandbox and the outputs zone.+ for (const copy of [join(store.sandboxDir('real'), 'real'), join(store.outputsDir(), 'real')]) {+ mkdirSync(copy, { recursive: true });+ writeFileSync(join(copy, 'bot.yaml'), readFileSync(join(store.botDir('real'), 'bot.yaml')));+ }+ expect(store.list().map(m => m.id)).toEqual(['real']);+ expect(store.botDir('real')).toBe(join(root, 'bots', 'real'));+ });++ it('bot file tools resolve relative paths inside the bot workspace, not the daemon cwd', () => {+ seedBot(store, 'anchored');+ const registry = createBotCapabilityRegistry({+ botId: 'anchored', manifest: store.get('anchored')!, botDir: store.botDir('anchored'), permissions: {},+ config: getDefaultConfig() as MercuryConfig,+ sandbox: { workspace: store.sandboxDir('anchored'), shared: store.sharedSandboxDir() },+ });+ expect(registry.getCwd()).toBe(store.sandboxDir('anchored'));+ });+});diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 12690b0c..3d5aacf2 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -2,7 +2,7 @@ import { refinePersona } from './persona-template.js';import { randomUUID } from 'node:crypto';import { homedir } from 'node:os';import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';-import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync } from 'node:fs';+import { writeFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, rmSync } from 'node:fs';import type { Tool } from 'ai';import type { MercuryConfig } from '../utils/config.js';import type { ProviderRegistry } from '../providers/registry.js';@@ -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, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression } from './store.js';+import { BotStore, deliverableFileName, BOT_JOURNAL_FILENAME, BOT_PERMISSIONS_FILENAME, isValidCronExpression } from './store.js';import { BotJournal } from './journal.js';import { BotQueue, idempotencyKeyFor, LEASE_SECONDS, type DurableBotJob } from './queue.js';import { sweepSharedSandbox } from './retention.js';@@ -21,7 +21,7 @@ import { createBotDeliverTool } from './tools/bot-deliver.js';import { createBotScheduleTool, type BotScheduler } from './tools/bot-schedule.js';import { createFleetStatusTool } from './tools/fleet-status.js';import { createBotSpawnTool } from './tools/bot-spawn.js';-import { runBotTurn, isTransientFailure, type BotTurnMail, type BotActivityEvent } from './bot-turn.js';+import { runBotTurn, isTransientFailure, isTurnLimitFailure, type BotExpectedOutcome, type BotTurnMail, type BotActivityEvent } from './bot-turn.js';import { parsePersonaAccess, stripPersonaAccessSection } from './persona-access.js';import { mergePathScopes } from './registry-factory.js';import { synthesizeSkill, MIN_TOOLS_FOR_SYNTHESIS } from './skill-synthesis.js';@@ -46,6 +46,8 @@ export interface BotJob {source?: { channelType: string; channelId: string };createdAt: number;attempts: number;+ /** Scheduler task id for cron runs (routine gating + no-outcome streaks). */+ routineId?: string;}/**@@ -80,6 +82,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;const MAILBOX_CAPACITY = 100;/** Bot-thread result display cap — matches CLIChannel.MAX_MESSAGE_CHARS (64KB). */const BOT_RESULT_DISPLAY_CAP = 64 * 1024;@@ -164,6 +168,15 @@ export class BotManager {/** Per-bot daily token usage: botId → { day (UTC yyyy-mm-dd), tokens }. */private dailyTokens: Map<string, { day: string; tokens: number }> = new Map();private pausedForBudget = new Set<string>();+ /** botId → UTC day the 80% budget warning was sent. */+ private budgetWarned: Map<string, string> = new Map();+ /** Fleet-wide daily usage and pause (ADR-020). */+ private fleetDailyTokens: { day: string; tokens: number } = { day: '', tokens: 0 };+ private fleetPausedDay: string | null = null;+ /** routine key → when its last run ended (min-interval gate). */+ private routineLastEnd: Map<string, number> = new Map();+ /** botId → UTC day a turn-limit notice was sent (once a day, not per run). */+ private turnLimitAlerted: Map<string, string> = new Map();/** Periodic due-sweep interval — cleared by dispose() (tests, shutdown). */private dueTimer?: ReturnType<typeof setInterval>;@@ -185,7 +198,7 @@ export class BotManager {}});this.notify = deps.notify;- this.store = deps.store ?? new BotStore();+ 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);// Resume work a crashed predecessor left behind: pending jobs (and@@ -315,7 +328,7 @@ export class BotManager {if (!j) {const manifest = this.store.get(botId);const retention = { ...(this.config.bots?.retention ?? {}), ...(manifest?.retention ?? {}) };- j = new BotJournal(this.store.botDir(botId), retention.journalRotateBytes, retention.journalKeepRotations);+ j = new BotJournal(this.store.botDir(botId), retention.journalRotateBytes, retention.journalKeepRotations, retention.transcriptRuns ?? 50);this.journals.set(botId, j);}return j;@@ -325,13 +338,26 @@ export class BotManager {return this.journalFor(botId);}- enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number }): { jobId: string; accepted: boolean; reasonCode?: string } {+ enqueue(botId: string, job: { trigger: BotTrigger; prompt: string; fromBot?: string; source?: { channelType: string; channelId: string }; attempts?: number; routineId?: string }): { jobId: string; accepted: boolean; reasonCode?: string } {const manifest = this.store.get(botId);if (!manifest) return { jobId: '', accepted: false, reasonCode: 'target_unknown' };if (!manifest.enabled || this.disabled.has(botId)) return { jobId: '', accepted: false, reasonCode: 'target_disabled' };const queue = this.queues.get(botId) ?? [];this.queues.set(botId, queue);++ // Routine gate (ADR-020): a cron tick is an opportunity, not an order.+ // It is skipped — never stacked — when the bot is still busy, when the+ // routine ran too recently, or when the routine was paused for+ // producing nothing. The next tick tries again.+ if (job.trigger === 'cron') {+ const key = job.routineId ?? `bot:${botId}:cron`;+ if (this.store.readRoutineState(botId).paused[key]) return { jobId: '', accepted: false, reasonCode: 'routine_paused' };+ if (queue.length > 0 || (this.running.get(botId)?.size ?? 0) > 0) return { jobId: '', accepted: false, reasonCode: 'busy' };+ const lastEnd = this.routineLastEnd.get(key);+ const minGapMs = this.routineConfig(manifest, key).minIntervalMinutes * 60_000;+ if (lastEnd !== undefined && Date.now() - lastEnd < minGapMs) return { jobId: '', accepted: false, reasonCode: 'too_soon' };+ }if (queue.length >= MAILBOX_CAPACITY) {return { jobId: '', accepted: false, reasonCode: 'queue_full' };}@@ -352,11 +378,32 @@ export class BotManager {return { jobId: durable.job.id, accepted: true };}const id = durable.job.id;- queue.push({ id, botId, trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, createdAt: durable.job.createdAt, attempts: durable.job.attempts });+ queue.push({ id, botId, trigger: job.trigger, prompt: job.prompt, fromBot: job.fromBot, source: job.source, createdAt: durable.job.createdAt, attempts: durable.job.attempts, routineId: job.routineId });this.pump(botId);return { jobId: id, accepted: true };}+ /** A routine's declared contract (bot.yaml schedules) or the defaults. */+ private routineConfig(manifest: BotManifest, routineKey: string): { expects: BotExpectedOutcome; minIntervalMinutes: number } {+ const declared = (manifest.schedules ?? []).find(r => `bot:${manifest.id}:${r.name}` === routineKey);+ return {+ expects: declared?.expects ?? 'work',+ minIntervalMinutes: declared?.minIntervalMinutes ?? 30,+ };+ }++ /**+ * The outcome contract of a job: unattended wakes must produce work; a+ * delegated task or a conversation is answered by its reply; a bare+ * mailbox wake may find nothing.+ */+ private expectationFor(manifest: BotManifest, job: BotJob): BotExpectedOutcome {+ if (job.trigger === 'cron') return this.routineConfig(manifest, job.routineId ?? `bot:${manifest.id}:cron`).expects;+ if (job.trigger === 'mailbox') return job.prompt ? 'message' : 'check';+ if (job.trigger === 'api' || job.trigger === 'cloud') return 'work';+ return 'message';+ }+/*** Fleet task dispatch: a delegated TASK from one bot to another (lead →* crew, crew → lead). Durable job with the task as the prompt — on@@ -425,6 +472,10 @@ export class BotManager {this.activity.set(botId, 'Paused — daily token budget reached');return;}+ if (this.fleetPausedDay === today) {+ this.activity.set(botId, 'Paused — fleet daily token budget reached');+ return;+ }const queue = this.queues.get(botId) ?? [];const running = this.running.get(botId) ?? new Set();this.running.set(botId, running);@@ -443,14 +494,41 @@ export class BotManager {const entry = this.dailyTokens.get(botId);const next = entry && entry.day === today ? entry.tokens + tokens : tokens;this.dailyTokens.set(botId, { day: today, tokens: next });- const cap = manifest.autonomy?.dailyTokenBudget;- if (cap && next >= cap) {+ const cap = this.dailyCapFor(manifest);+ if (cap > 0 && next >= cap) {this.pausedForBudget.add(botId);logger.warn({ botId, used: next, cap }, 'Bot daily token budget reached — pausing until next day');- void this.alertOwner(botId, `🟡 **${manifest.name}** paused — daily token budget reached (${next} ≥ ${cap}). Resumes tomorrow; raise the cap in bot.yaml if this is too tight.`);+ void this.alertOwner(botId, `🟡 **${manifest.name}** paused — daily token budget reached (${next.toLocaleString()} ≥ ${cap.toLocaleString()}). Resumes tomorrow; \`/bots budget ${botId} <tokens>\` to change it.`);+ } else if (cap > 0 && next >= cap * 0.8 && this.budgetWarned.get(botId) !== today) {+ this.budgetWarned.set(botId, today);+ void this.alertOwner(botId, `🟠 **${manifest.name}** has used ${Math.round(100 * next / cap)}% of today's token budget (${next.toLocaleString()} / ${cap.toLocaleString()}).`);+ }+ // Fleet-wide cap: one runaway bot must not spend the whole day's budget.+ if (this.fleetDailyTokens.day !== today) this.fleetDailyTokens = { day: today, tokens: 0 };+ this.fleetDailyTokens.tokens += tokens;+ const fleetCap = this.config.bots?.fleetDailyTokenBudget ?? 0;+ if (fleetCap > 0 && this.fleetDailyTokens.tokens >= fleetCap && this.fleetPausedDay !== today) {+ this.fleetPausedDay = today;+ logger.warn({ used: this.fleetDailyTokens.tokens, cap: fleetCap }, 'Fleet daily token budget reached — all bots paused until next day');+ void this.alertOwner(botId, `🔴 All bots paused — the fleet's daily token budget is used up (${this.fleetDailyTokens.tokens.toLocaleString()} ≥ ${fleetCap.toLocaleString()}). Resumes tomorrow; \`bots.fleetDailyTokenBudget\` in mercury.yaml changes the cap.`);}}+ /** Effective daily cap: the bot's own, else the fleet default; 0 = unlimited. */+ dailyCapFor(manifest: BotManifest): number {+ const own = manifest.autonomy?.dailyTokenBudget;+ if (own !== undefined) return own;+ return this.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;+ }++ /** Today's spend for /bots and the API. */+ dailyUsage(botId: string): { tokens: number; cap: number } {+ const today = new Date().toISOString().slice(0, 10);+ const entry = this.dailyTokens.get(botId);+ const manifest = this.store.get(botId);+ return { tokens: entry && entry.day === today ? entry.tokens : 0, cap: manifest ? this.dailyCapFor(manifest) : 0 };+ }+private fleetRunningCount(): number {let total = 0;for (const s of this.running.values()) total += s.size;@@ -500,6 +578,8 @@ export class BotManager {// it from the newest journal row on restart).const willRetry = output.status === 'failed' && !!output.reasonCode&& isTransientFailure(output.reasonCode) && job.attempts + 1 < MAX_TRANSIENT_ATTEMPTS;+ const turnLimited = output.status === 'failed' && isTurnLimitFailure(output.reasonCode);+ const routineKey = job.trigger === 'cron' ? (job.routineId ?? `bot:${botId}:cron`) : undefined;const record: BotRunRecord = {runId: job.id,botId,@@ -512,12 +592,52 @@ export class BotManager {summary: output.output.slice(0, 300),error: output.error,reasonCode: output.reasonCode,- ...(output.status === 'failed' && !willRetry ? { needsYou: true } : {}),+ // A turn cut off by policy is not an escalation (ADR-020).+ ...(output.status === 'failed' && !willRetry && !turnLimited ? { needsYou: true } : {}),+ turnStartedAt: output.startedAt,+ steps: output.steps,+ toolCalls: output.toolCalls,+ peakInputTokens: output.peakInputTokens,+ outcome: output.outcome,+ ...(output.deliverables.length > 0 ? { deliverables: output.deliverables } : {}),+ ...(output.claimedWithoutAction ? { claimedWithoutAction: true } : {}),+ ...(routineKey ? { routineId: routineKey } : {}),};- this.journalFor(botId).append(record);+ const journal = this.journalFor(botId);+ journal.append(record);+ journal.writeTranscript(record, { prompt: job.prompt, output: output.output, trace: output.trace });this.lastRun.set(botId, { at: Date.now(), state: record.state });this.needsYou.delete(botId);this.recordBotTokens(botId, manifest, output.tokensIn + output.tokensOut);+ if (routineKey) this.routineLastEnd.set(routineKey, Date.now());++ // No-outcome streak (ADR-020): a work routine that produces nothing+ // three runs in a row is paused — the owner is told once, and+ // /bots start resumes it. This is what stops a bot that has+ // talked itself into a loop of records about records.+ if (routineKey && this.expectationFor(manifest, job) === 'work' && output.status !== 'halted') {+ const state = this.store.readRoutineState(botId);+ if (output.outcome === 'none') {+ const streak = (state.noOutcomeStreak[routineKey] ?? 0) + 1;+ state.noOutcomeStreak[routineKey] = streak;+ if (streak >= NO_OUTCOME_PAUSE_AFTER) {+ state.paused[routineKey] = { since: new Date().toISOString(), reason: `${streak} consecutive runs produced no deliverable or action` };+ delete state.noOutcomeStreak[routineKey];+ logger.warn({ botId, routineKey, streak }, 'Bot routine paused — no outcome in consecutive runs');+ void this.alertOwner(botId, `⏸ **${manifest.name}**'s routine \`${routineKey.split(':').pop()}\` is paused: ${streak} runs in a row produced no deliverable or action (only notes). It will not fire again until \`/bots start ${botId}\`. Check its persona for instructions that reward activity over results.`);+ }+ } else {+ delete state.noOutcomeStreak[routineKey];+ }+ this.store.writeRoutineState(botId, state);+ }+ if (turnLimited) {+ const today = new Date().toISOString().slice(0, 10);+ if (this.turnLimitAlerted.get(botId) !== today) {+ this.turnLimitAlerted.set(botId, today);+ void this.alertOwner(botId, `🟠 **${manifest.name}** hit the per-turn limit (${output.reasonCode === 'turn_time' ? 'time' : 'tokens'}) and was stopped. One task is too big for one run — split it, or raise \`autonomy.maxTokensPerTurn\` / \`maxTurnMinutes\` in bot.yaml.`);+ }+ }// Auto-skill synthesis (P2-3): a completed multi-step run is a// procedure worth keeping. Fire-and-forget, gated by config.@@ -553,6 +673,8 @@ export class BotManager {this.queue.retry(job.id, job.attempts + 1, Date.now() + delay);logger.info({ botId, jobId: job.id, reasonCode: output.reasonCode, retryIn: delay }, 'Bot turn failed transiently — retrying in place');setTimeout(() => this.resumeDueJobs(), delay).unref?.();+ } else if (turnLimited) {+ this.queue.settle(job.id, 'done');} else if (output.status === 'failed') {this.queue.settle(job.id, 'dead', output.reasonCode);this.needsYou.add(botId);@@ -593,9 +715,15 @@ export class BotManager {const body = output.output.length > BOT_RESULT_DISPLAY_CAP? output.output.slice(0, BOT_RESULT_DISPLAY_CAP) + `\n\n[…output truncated at ${Math.round(BOT_RESULT_DISPLAY_CAP / 1024)}KB — full text in the run transcripts]`: output.output;+ const delivered = output.deliverables.length > 0+ ? output.deliverables.map(p => `📁 Delivered → ${p}`).join('\n') + '\n\n'+ : '';+ const noOutcome = output.status === 'completed' && output.outcome === 'none' && this.expectationFor(manifest, job) === 'work'+ ? '⚠ No deliverable or action this run — only notes.' + (output.claimedWithoutAction ? ' The reply claims otherwise; the tool trace shows nothing was delivered.' : '') + '\n\n'+ : '';const fullText = output.status === 'halted'? `⏹ Run ${job.id} was stopped by you — no further output. It is recorded in \`/bots journal ${botId}\`.`- : `${icon} (${job.trigger}): ${body}`;+ : `${icon} (${job.trigger}): ${delivered}${noOutcome}${body}`;// 1. Full result → the bot's own thread, always.await this.notify('cli', botThread, fullText).catch((e) =>logger.warn({ e, botId }, 'Bot result deliver to bot thread failed'));@@ -705,6 +833,8 @@ export class BotManager {mail,pollMail: () => this.drainMailbox(botId),sandbox: { workspace: this.store.sandboxDir(botId), shared: this.store.sharedSandboxDir() },+ deliverablesDir: this.store.deliverablesDir(botId),+ expects: this.expectationFor(manifest, job),skillsPrompt,fleet: this.fleetContext(botId, manifest),capabilities: registry,@@ -1214,6 +1344,12 @@ export class BotManager {const manifest = this.store.get(botId);if (!manifest) throw new Error(`Bot "${botId}" does not exist`);this.held.delete(botId);+ // An explicit start is the owner saying "try again": paused routines+ // resume with a clean streak.+ const routines = this.store.readRoutineState(botId);+ if (Object.keys(routines.paused).length > 0 || Object.keys(routines.noOutcomeStreak).length > 0) {+ this.store.writeRoutineState(botId, { paused: {}, noOutcomeStreak: {} });+ }let resumed = this.rehydratePending(botId);if (!manifest.enabled || this.disabled.has(botId)) {this.setEnabled(botId, true); // persists enabled + pumps@@ -1400,15 +1536,23 @@ export class BotManager {}/**- * bot_deliver: move a finished artifact out of the bot's writable areas- * (its private sandbox or the fleet-shared folder) into the owner-curated- * `outputs/<botId>/` zone — exempt from the retention janitor. Only files- * from the bot's OWN writable roots travel (containment is enforced); the- * source is removed on success (a move, not a copy — the shared surface- * stays lean by construction).+ * bot_deliver (ADR-020): move a finished artifact out of the bot's+ * writable areas (its private sandbox or the fleet-shared folder) into+ * the OWNER-VISIBLE deliverables folder (default ~/Documents/Mercury/+ * <Bot name>/). Finals land on top of the folder; everything else goes+ * under work/ (a crew bot's deliveries always do — the lead delivers the+ * final). Files are named "YYYY-MM-DD <title>.<ext>" and the folder keeps+ * a README index. Only files from the bot's OWN writable roots travel+ * (containment is enforced); the source is removed on success (a move).*/- deliver(botId: string, filePath: string, rename?: string): { accepted: boolean; path?: string; reasonCode?: string } {- if (!this.store.get(botId)) return { accepted: false, reasonCode: 'target_unknown' };+ deliver(+ botId: string,+ filePath: string,+ opts: string | { saveAs?: string; title?: string; final?: boolean } = {},+ ): { accepted: boolean; path?: string; final?: boolean; reasonCode?: string } {+ const options = typeof opts === 'string' ? { saveAs: opts } : opts;+ const manifest = this.store.get(botId);+ if (!manifest) return { accepted: false, reasonCode: 'target_unknown' };const candidate = resolve(filePath.replace(/^~(?=$|\/|\\)/, homedir()));const allowedBases = [this.store.sharedSandboxDir(), this.store.sandboxDir(botId)];const inside = allowedBases.some((base) => {@@ -1418,28 +1562,24 @@ export class BotManager {if (!inside || !existsSync(candidate) || !statSync(candidate).isFile()) {return { accepted: false, reasonCode: 'outside_sandbox' };}- const outputsDir = join(this.store.outputsDir(), botId);- mkdirSync(outputsDir, { recursive: true });- // Default name keeps the FULL basename — the extension is part of the- // artifact (a report.md stayed .md; the stem-only default silently- // stripped it). `saveAs` is honored as written; dedupe inserts the -N- // before whatever extension remains.- const ext = extname(rename || basename(candidate));- const stem = basename(rename || basename(candidate), ext);- const requested = (stem)- .replace(/[ <>:"/\\|?*]/g, '-')- .replace(/-+/g, '-')- .replace(/^-|-$/g, '')- .slice(0, 120) || 'output';- const finalExt = ext;- let dest = join(outputsDir, `${requested}${finalExt}`);+ const isCrew = Boolean(manifest.parent);+ const final = Boolean(options.final) && !isCrew;+ const botFolder = this.store.deliverablesDir(botId);+ const destDir = isCrew ? botFolder : final ? botFolder : join(botFolder, 'work');+ mkdirSync(destDir, { recursive: true });+ const sourceName = options.saveAs || basename(candidate);+ const ext = extname(sourceName) || extname(candidate);+ const stem = options.title?.trim() || basename(sourceName, ext);+ const fileName = deliverableFileName(stem, ext);+ const finalExt = extname(fileName);+ const requested = basename(fileName, finalExt);+ let dest = join(destDir, fileName);for (let i = 2; existsSync(dest); i++) {- dest = join(outputsDir, `${requested}-${i}${finalExt}`);+ dest = join(destDir, `${requested} (${i})${finalExt}`);}try {renameSync(candidate, dest);} catch {- // Cross-device fallback: copy then remove the source.try {copyFileSync(candidate, dest);unlinkSync(candidate);@@ -1447,52 +1587,94 @@ export class BotManager {return { accepted: false, reasonCode: 'move_failed' };}}- logger.info({ botId, dest }, 'Bot delivered a final artifact');- // The deliverable moment is the event the owner reacts to: broadcast it- // on the activity bus so the CLI bot-thread region, the /bots roster and- // the web SSE feed all announce the artifact live.+ // The index lives on the fleet folder (finals on top); crew work is+ // reachable from it under work/.+ this.store.writeDeliverablesIndex(isCrew ? this.store.deliverablesDir(manifest.parent!) : botFolder);+ logger.info({ botId, dest, final }, 'Bot delivered an artifact');this.emitBotActivity({botId,jobId: '',kind: 'tool',- label: `Delivered ${basename(dest, extname(dest))}${extname(dest)}`,+ label: `Delivered ${basename(dest)}`,detail: dest,stepIndex: 0,elapsedMs: 0,status: 'done',});- return { accepted: true, path: dest };+ return { accepted: true, path: dest, final };}/**- * Owner-curated deliverables (bot_deliver → outputs/<botId>/). Read-only- * views for the web cockpit: list with newest first; read (text preview,- * 64KB cap) and deletes are containment-guarded — nothing outside the- * bot's own outputs zone is addressable.+ * One-time move of the hidden legacy outputs zone+ * (~/.mercury/bots/outputs/<botId>/) into the visible deliverables folder.+ * Idempotent: whatever is still there moves; a README pointer is left+ * behind so an owner with a bookmark finds the new place.*/- listDeliverables(botId?: string): Array<{ botId: string; name: string; bytes: number; mtimeMs: number }> {- const root = this.store.outputsDir();- if (!existsSync(root)) return [];- const bots = botId- ? [botId]- : readdirSync(root, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name);- const out: Array<{ botId: string; name: string; bytes: number; mtimeMs: number }> = [];- for (const bot of bots) {- const dir = join(root, bot);- if (!existsSync(dir)) continue;- for (const name of readdirSync(dir, { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name)) {+ migrateDeliverables(): { moved: number } {+ const legacy = this.store.outputsDir();+ if (!existsSync(legacy)) return { moved: 0 };+ let moved = 0;+ for (const entry of readdirSync(legacy, { withFileTypes: true })) {+ if (!entry.isDirectory() || !this.store.exists(entry.name)) continue;+ const from = join(legacy, entry.name);+ const manifest = this.store.get(entry.name)!;+ const to = manifest.parent ? this.store.deliverablesDir(entry.name) : join(this.store.deliverablesDir(entry.name), 'work');+ for (const file of readdirSync(from, { withFileTypes: true })) {+ if (!file.isFile()) continue;try {- const stat = statSync(join(dir, name));- out.push({ botId: bot, name, bytes: stat.size, mtimeMs: stat.mtimeMs });+ mkdirSync(to, { recursive: true });+ let dest = join(to, file.name);+ for (let i = 2; existsSync(dest); i++) dest = join(to, `${basename(file.name, extname(file.name))} (${i})${extname(file.name)}`);+ renameSync(join(from, file.name), dest);+ moved++;+ } catch (err: any) {+ logger.warn({ botId: entry.name, file: file.name, err: err?.message }, 'Legacy deliverable could not be moved');+ }+ }+ try { if (readdirSync(from).length === 0) rmSync(from, { recursive: true }); } catch { /* keep */ }+ this.store.writeDeliverablesIndex(manifest.parent ? this.store.deliverablesDir(manifest.parent) : this.store.deliverablesDir(entry.name));+ }+ if (moved > 0) {+ try {+ writeFileSync(join(legacy, 'README.md'), `Deliverables moved to ${this.store.deliverablesRoot()} (Mercury 1.3.1, ADR-020).\nThis folder is no longer used.\n`, 'utf-8');+ } catch { /* best effort */ }+ logger.info({ moved, to: this.store.deliverablesRoot() }, 'Legacy bot outputs moved to the deliverables folder');+ }+ return { moved };+ }++ /** Finals (top of a bot's folder) and work (under work/), newest first. */+ listDeliverables(botId?: string): Array<{ botId: string; name: string; bytes: number; mtimeMs: number; path: string; final: boolean }> {+ const bots = botId ? [botId] : this.store.list().map(m => m.id);+ const out: Array<{ botId: string; name: string; bytes: number; mtimeMs: number; path: string; final: boolean }> = [];+ const scan = (bot: string, dir: string, prefix: string, final: boolean): void => {+ if (!existsSync(dir)) return;+ for (const e of readdirSync(dir, { withFileTypes: true })) {+ if (!e.isFile() || e.name === 'README.md' || e.name.startsWith('.')) continue;+ try {+ const stat = statSync(join(dir, e.name));+ out.push({ botId: bot, name: prefix + e.name, bytes: stat.size, mtimeMs: stat.mtimeMs, path: join(dir, e.name), final });} catch { /* raced a concurrent delete — skip */ }}+ };+ for (const bot of bots) {+ const manifest = this.store.get(bot);+ if (!manifest) continue;+ const dir = this.store.deliverablesDir(bot);+ if (manifest.parent) {+ scan(bot, dir, '', false);+ } else {+ scan(bot, dir, '', true);+ scan(bot, join(dir, 'work'), 'work/', false);+ }}return out.sort((a, b) => b.mtimeMs - a.mtimeMs);}/** Contained path resolution for deliverable access; null when it escapes. Public for the web API's byte-exact download route. */deliverableFile(botId: string, name: string): string | null {- const dir = join(this.store.outputsDir(), botId);+ if (!this.store.exists(botId)) return null;+ const dir = this.store.deliverablesDir(botId);const candidate = resolve(dir, name);const rel = relative(dir, candidate);if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null;diff --git a/src/bots/bot-schedule.test.ts b/src/bots/bot-schedule.test.tsindex a9229d86..cce1ae4f 100644--- a/src/bots/bot-schedule.test.ts+++ b/src/bots/bot-schedule.test.ts@@ -55,10 +55,10 @@ describe('bot_schedule (bot self-scheduling)', () => {it('caps pending one-shots at 10 per bot (runaway-loop guard)', async () => {for (let i = 0; i < 10; i++) {- const reply = await tool.execute({ prompt: `task ${i}`, delayMinutes: i + 1 });+ const reply = await tool.execute({ prompt: `task ${i}`, delayMinutes: i + 10 });expect(reply).toContain('Scheduled');}- const reply = await tool.execute({ prompt: 'task 11', delayMinutes: 5 });+ const reply = await tool.execute({ prompt: 'task 11', delayMinutes: 15 });expect(reply).toContain('pending self-scheduled runs');expect(scheduler.manifests).toHaveLength(10);});@@ -72,10 +72,10 @@ describe('bot_schedule (bot self-scheduling)', () => {it('the cap counts only this bot\'s one-shots', async () => {for (let i = 0; i < 10; i++) {- await tool.execute({ prompt: `t${i}`, delayMinutes: 5 });+ await tool.execute({ prompt: `t${i}`, delayMinutes: 15 });}const otherTool = createBotScheduleTool(scheduler, 'other-bot');- const reply = await (otherTool as any).execute({ prompt: 'other', delayMinutes: 5 });+ const reply = await (otherTool as any).execute({ prompt: 'other', delayMinutes: 15 });expect(reply).toContain('Scheduled');});});\ No newline at end of filediff --git a/src/bots/doctor.ts b/src/bots/doctor.tsindex 52e076d9..6ff2a83f 100644--- a/src/bots/doctor.ts+++ b/src/bots/doctor.ts@@ -72,6 +72,32 @@ export function runBotDoctor(deps: DoctorDeps): DoctorReport {});}+ // ADR-020: a bot whose unattended runs mostly produce nothing is+ // spending tokens on commentary — the owner should look at its persona.+ const recent = deps.journalFor(manifest.id).read(manifest.id, 20).filter(r => r.outcome !== undefined && (r.trigger === 'cron' || r.trigger === 'api'));+ if (recent.length >= 4) {+ const none = recent.filter(r => r.outcome === 'none').length;+ if (none * 2 >= recent.length) {+ findings.push({+ botId: manifest.id,+ severity: 'warning',+ check: 'outcome',+ detail: `${none} of the last ${recent.length} unattended runs produced no deliverable or action — check the persona for instructions that reward activity over results`,+ });+ }+ const claimed = recent.filter(r => r.claimedWithoutAction).length;+ if (claimed > 0) {+ findings.push({ botId: manifest.id, severity: 'warning', check: 'outcome', detail: `${claimed} run(s) claimed delivery or execution the tool trace does not show` });+ }+ }+ const routineState = deps.store.readRoutineState(manifest.id);+ for (const [key, info] of Object.entries(routineState.paused)) {+ findings.push({ botId: manifest.id, severity: 'warning', check: 'routine', detail: `routine "${key.split(':').pop()}" paused since ${info.since.slice(0, 16).replace('T', ' ')}: ${info.reason} — /bots start ${manifest.id} resumes it` });+ }+ const homeGrant = (perms.paths ?? []).find(p => p && typeof p.scope === 'string' && /^~[\\/]?$/.test(p.scope.trim()) && p.write);+ if (homeGrant) {+ findings.push({ botId: manifest.id, severity: 'warning', check: 'permissions', detail: 'write access to the whole home directory — an unattended bot can write anywhere; prefer specific scopes (/bots permissions)' });+ }const dlqDepth = dlqByBot.get(manifest.id) ?? 0;if (dlqDepth > 0) {findings.push({diff --git a/src/bots/journal.ts b/src/bots/journal.tsindex 4c4d26c2..c2100993 100644--- a/src/bots/journal.ts+++ b/src/bots/journal.ts@@ -1,6 +1,6 @@-import { appendFileSync, closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync } from 'node:fs';+import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';import { join } from 'node:path';-import { BOT_JOURNAL_FILENAME, assertValidBotId } from './store.js';+import { BOT_JOURNAL_FILENAME, BOT_TRANSCRIPTS_DIRNAME, assertValidBotId } from './store.js';import type { BotRunRecord } from './types.js';/**@@ -14,10 +14,37 @@ export class BotJournal {private readonly rotateBytes: number;private readonly keepRotations: number;- constructor(dir: string, rotateBytes = 5 * 1024 * 1024, keepRotations = 3) {+ private readonly keepTranscripts: number;++ constructor(dir: string, rotateBytes = 5 * 1024 * 1024, keepRotations = 3, keepTranscripts = 50) {this.dir = dir;this.rotateBytes = rotateBytes;this.keepRotations = keepRotations;+ this.keepTranscripts = keepTranscripts;+ }++ /**+ * Compact per-run transcript (ADR-020): what the run actually did — the+ * tool trace and the full reply — so a journal row can be explained after+ * the fact. Bounded: the oldest files beyond `keepTranscripts` are pruned.+ */+ writeTranscript(record: BotRunRecord, body: { prompt: string; output: string; trace: unknown[] }): string | null {+ assertValidBotId(record.botId);+ if (this.keepTranscripts <= 0) return null;+ const dir = join(this.dir, BOT_TRANSCRIPTS_DIRNAME);+ try {+ mkdirSync(dir, { recursive: true });+ const file = join(dir, `${new Date(record.startedAt).toISOString().slice(0, 19).replace(/[:T]/g, '-')}-${record.runId}.json`);+ writeFileSync(file, JSON.stringify({ record, ...body }, null, 1), 'utf-8');+ const names = readdirSync(dir).filter(n => n.endsWith('.json')).sort();+ for (const stale of names.slice(0, Math.max(0, names.length - this.keepTranscripts))) {+ try { rmSync(join(dir, stale)); } catch { /* best effort */ }+ }+ return file;+ } catch (err: any) {+ console.error(`[bots] transcript write failed for ${record.botId}: ${err?.message}`);+ return null;+ }}append(record: BotRunRecord): void {diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.tsindex 5c0e6d2c..02c8841b 100644--- a/src/bots/registry-factory.ts+++ b/src/bots/registry-factory.ts@@ -117,7 +117,10 @@ export function createBotCapabilityRegistry(deps: BotRegistryDeps): CapabilityRepm.setFailClosed(true);pm.setCurrentContext('bot', deps.botId);- registry.setCwd(process.cwd());+ // Relative paths and shell commands resolve inside the bot's workspace,+ // never the daemon's cwd (a bot with a wide grant wrote "sandbox/…" files+ // into whatever repo the daemon happened to be started from).+ registry.setCwd(deps.sandbox?.workspace ?? process.cwd());registry.registerAll();const tools = filterBotTools(registry.getTools(), deps.manifest, deps.permissions);diff --git a/src/bots/store.ts b/src/bots/store.tsindex d4fe62ce..2eed0846 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -1,5 +1,6 @@import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';-import { join, resolve, sep } from 'node:path';+import { basename, join, resolve, sep } from 'node:path';+import { homedir } from 'node:os';import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';import { getMercuryHome } from '../utils/config.js';import { logger } from '../utils/logger.js';@@ -18,6 +19,61 @@ export const BOT_SHARED_SANDBOX_DIRNAME = '_shared';export const BOT_SANDBOX_DIRNAME = 'sandbox';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';+/** Routine state (paused routines, no-outcome streaks) — ADR-020. */+export const BOT_ROUTINE_STATE_FILENAME = 'routine-state.json';+/**+ * Data directories that live INSIDE a bot's profile dir but are never bot+ * profiles themselves. The roster scan does not descend into them: bots+ * used to copy their own profile folders into sandbox/ and outputs/ as+ * "mirrors", which the scan then reported as duplicate bots on every boot.+ */+export const BOT_DATA_DIRNAMES: ReadonlySet<string> = new Set([BOT_SANDBOX_DIRNAME, 'outputs', 'skills', BOT_TRANSCRIPTS_DIRNAME]);++export interface BotRoutineState {+ /** Routine key → why/when it was paused (cleared by /bots start). */+ paused: Record<string, { since: string; reason: string }>;+ /** Routine key → consecutive runs that produced no outcome. */+ noOutcomeStreak: Record<string, number>;+}++/**+ * Where finished results go — a folder the OWNER can find without knowing+ * about ~/.mercury (ADR-020). Overridable (bots.deliverablesDir); the+ * default is the platform's Documents folder. A custom MERCURY_HOME (eval+ * harness, tests) keeps deliverables inside that home.+ */+export function defaultDeliverablesRoot(): string {+ if (process.env.MERCURY_HOME) return join(getMercuryHome(), 'deliverables');+ const home = homedir();+ const isTermux = Boolean(process.env.TERMUX_VERSION) || (process.env.PREFIX ?? '').includes('com.termux');+ if (isTermux) {+ const shared = join(home, 'storage', 'shared');+ return existsSync(shared) ? join(shared, 'Documents', 'Mercury') : join(home, 'Mercury');+ }+ const documents = join(home, 'Documents');+ return existsSync(documents) ? join(documents, 'Mercury') : join(home, 'Mercury');+}++/** A folder name a person recognises: the bot's display name, filesystem-safe. */+export function deliverablesFolderName(name: string, id: string): string {+ const clean = name.replace(/[<>:"/\\|?*\x00-\x1f]/g, '').replace(/\s+/g, ' ').trim().slice(0, 60);+ return clean || id;+}++/** "2026-10-10 Oxide Series D.md" — date first so a folder sorts by time, then a human title. */+export function deliverableFileName(stemOrTitle: string, ext: string, date: Date = new Date()): string {+ const day = date.toISOString().slice(0, 10);+ const title = stemOrTitle+ .replace(/^\d{4}-\d{2}-\d{2}[ _-]*/, '')+ .replace(/[<>:"/\\|?*\x00-\x1f]/g, '')+ .replace(/[-_]+/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, 80) || 'untitled';+ return `${day} ${title}${ext}`;+}/** Fleet nesting cap — mirrors addCrew's 3-level guard (CEO → Lead → Crew). */export const MAX_FLEET_DEPTH = 3;@@ -154,8 +210,74 @@ export class BotStore {* open journal handles and registry caches for that id are stale. */onRelocate: ((id: string, oldDir: string, newDir: string) => void) | null = null;- constructor(botsRoot?: string) {+ private readonly deliverablesRootDir: string;++ constructor(botsRoot?: string, deliverablesRoot?: string) {this.botsRoot = resolve(botsRoot ?? join(getMercuryHome(), 'bots'));+ // A custom bots root (tests) keeps deliverables beside it, never in the+ // developer's real Documents folder.+ this.deliverablesRootDir = resolve(deliverablesRoot ?? (botsRoot ? join(this.botsRoot, '..', 'Mercury') : defaultDeliverablesRoot()));+ }++ /** The owner-visible deliverables root (e.g. ~/Documents/Mercury). */+ deliverablesRoot(): string {+ return this.deliverablesRootDir;+ }++ /**+ * The folder the owner opens to find a bot's results. Leads and solos get+ * `<root>/<Bot name>/`; a crew bot's work lives under its lead's folder,+ * `<lead folder>/work/<crew id>/`, so one fleet = one folder with the+ * finals on top and the stages underneath.+ */+ deliverablesDir(id: string): string {+ const manifest = this.get(id);+ if (!manifest) return join(this.deliverablesRootDir, id);+ if (manifest.parent && manifest.parent !== id) {+ return join(this.deliverablesDir(manifest.parent), 'work', id);+ }+ return join(this.deliverablesRootDir, deliverablesFolderName(manifest.name, manifest.id));+ }++ /** Rewrite the README index of a deliverables folder (finals on top, stages under work/). */+ writeDeliverablesIndex(dir: string): void {+ try {+ if (!existsSync(dir)) return;+ const files = readdirSync(dir, { withFileTypes: true })+ .filter(e => e.isFile() && e.name !== 'README.md' && !e.name.startsWith('.'))+ .map(e => { const st = statSync(join(dir, e.name)); return { name: e.name, bytes: st.size, mtimeMs: st.mtimeMs }; })+ .sort((a, b) => b.mtimeMs - a.mtimeMs);+ const lines = [+ `# ${basename(dir)} — deliverables`,+ '',+ 'Finished results from this Mercury bot land here, newest first. Work in progress from the crew (research, drafts, checks) is under `work/`.',+ '',+ ];+ if (files.length === 0) lines.push('_Nothing delivered yet._');+ else {+ lines.push('| Delivered | File | Size |', '|---|---|---|');+ for (const f of files) lines.push(`| ${new Date(f.mtimeMs).toISOString().slice(0, 16).replace('T', ' ')} | ${f.name} | ${f.bytes < 1024 ? f.bytes + ' B' : Math.round(f.bytes / 1024) + ' KB'} |`);+ }+ lines.push('', '_Maintained by Mercury. Delete files freely; this index is rewritten on the next delivery._');+ writeFileSync(join(dir, 'README.md'), lines.join('\n') + '\n', 'utf-8');+ } catch { /* an index is a convenience, never a failure */ }+ }++ readRoutineState(id: string): BotRoutineState {+ try {+ const raw = JSON.parse(readFileSync(join(this.botDir(id), BOT_ROUTINE_STATE_FILENAME), 'utf-8'));+ return { paused: raw.paused ?? {}, noOutcomeStreak: raw.noOutcomeStreak ?? {} };+ } catch {+ return { paused: {}, noOutcomeStreak: {} };+ }+ }++ writeRoutineState(id: string, state: BotRoutineState): void {+ try {+ atomicWrite(join(this.botDir(id), BOT_ROUTINE_STATE_FILENAME), JSON.stringify(state, null, 2) + '\n');+ } catch (err: any) {+ logger.warn({ botId: id, err: err?.message }, 'Could not persist routine state');+ }}/** Bot directory for an id, with traversal guard. Throws on invalid ids. */@@ -192,10 +314,11 @@ export class BotStore {}const root = resolve(this.botsRoot);for (const entry of entries) {- if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_') || BOT_DATA_DIRNAMES.has(entry.name)) continue;const sub = join(dir, entry.name);if (!resolve(sub).startsWith(root + sep)) continue;- if (entry.name === id && existsSync(join(sub, BOT_MANIFEST_FILENAME))) return sub;+ if (!existsSync(join(sub, BOT_MANIFEST_FILENAME))) continue;+ if (entry.name === id) return sub;const deeper = this.scanForBotDir(sub, id, depth + 1);if (deeper) return deeper;}@@ -272,8 +395,12 @@ export class BotStore {return;}for (const entry of entries) {- if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_')) continue;+ if (!entry.isDirectory() || entry.name.startsWith('.') || entry.name.startsWith('_') || BOT_DATA_DIRNAMES.has(entry.name)) continue;const sub = join(dir, entry.name);+ // Only a profile dir can contain crew profiles. A root-level data+ // dir (outputs/) or a bot's own sandbox is never descended.+ const isProfile = existsSync(join(sub, BOT_MANIFEST_FILENAME));+ if (!isProfile) continue;try {const m = this.get(entry.name);if (m) {diff --git a/src/bots/tools/bot-deliver.ts b/src/bots/tools/bot-deliver.tsindex f42fa2af..c5ef7c84 100644--- a/src/bots/tools/bot-deliver.ts+++ b/src/bots/tools/bot-deliver.ts@@ -15,20 +15,27 @@ import type { BotManager } from '../bot-manager.js';export function createBotDeliverTool(manager: BotManager, botId: string) {return tool({description:- `Deliver a final artifact you produced (a report, export, dataset, script…) from your sandbox ` +- `or the fleet-shared folder to the owner's outputs zone. Deliverables there are protected ` +- `from automatic cleanup and visible to the owner. Deliver ONCE per artifact — when it is final, not per draft — ` +- `and mention the delivered filename in your reply.`,+ `Deliver a result you produced (an article, report, export, dataset, script…) from your sandbox ` ++ `or the fleet-shared folder to the owner's deliverables folder — the place the owner actually looks. ` ++ `Give it a human title. Mark final: true for the finished piece the owner asked for (it lands on top of the folder); ` ++ `research, drafts and checks are work (they land under work/). Deliver ONCE per artifact, and name the delivered file in your reply. ` ++ `Delivering is what makes a run count as done.`,inputSchema: zodSchema(z.object({file: z.string().min(1).max(500).describe('The file to deliver: an absolute path, or a path relative to your sandbox or the fleet-shared folder (e.g. "_shared/report-2026-09-30.md")',),+ title: z.string().max(120).optional().describe(+ 'Human title for the delivered file, e.g. "Oxide Series D explained" (the date is added automatically).',+ ),+ final: z.boolean().optional().describe(+ 'true = the finished piece the owner asked for (top of the folder). Omit for research, drafts and intermediate stages.',+ ),saveAs: z.string().max(120).optional().describe(- 'Optional filename to store it as (extension auto-kept). Defaults to the current filename.',+ 'Optional filename override (extension auto-kept). Prefer title.',),})),- execute: async ({ file, saveAs }: { file: string; saveAs?: string }) => {- const result = manager.deliver(botId, file, saveAs);+ execute: async ({ file, title, final, saveAs }: { file: string; title?: string; final?: boolean; saveAs?: string }) => {+ const result = manager.deliver(botId, file, { title, final, saveAs });if (!result.accepted) {if (result.reasonCode === 'outside_sandbox') {return `Error: ${file} is not a readable file inside your sandbox or the fleet-shared folder.`;@@ -38,7 +45,7 @@ export function createBotDeliverTool(manager: BotManager, botId: string) {}return `Error: delivering ${file} failed [reason: ${result.reasonCode}]. Keep the file where it is and report the failure in your summary.`;}- return `Delivered to ${result.path} — the owner's outputs zone (protected from automatic cleanup). The source copy has been removed.`;+ return `Delivered to ${result.path} — ${result.final ? 'a FINAL in the owner\'s deliverables folder' : 'work in the owner\'s deliverables folder (under work/)'}. The source copy has been removed.`;},});}\ No newline at end of filediff --git a/src/bots/tools/bot-schedule.ts b/src/bots/tools/bot-schedule.tsindex 36f22abf..eaa64b54 100644--- a/src/bots/tools/bot-schedule.ts+++ b/src/bots/tools/bot-schedule.ts@@ -30,6 +30,26 @@ const SELF_PREFIX = 'self-';const ROUTINE_PREFIX = 'routine-';const MAX_DELAY_MINUTES = 60 * 24 * 30; // 30 daysconst MAX_PENDING_SELF_SCHEDULES = 10;+/** Bot-created routines: never more often than this, never more than this many. ADR-020. */+const MIN_ROUTINE_GAP_MINUTES = 30;+const MAX_SELF_ROUTINES = 3;+const MIN_ONESHOT_DELAY_MINUTES = 10;++/** Smallest gap (minutes) a 5-field cron's minute field can produce; Infinity when it cannot tell. */+export function cronMinGapMinutes(cron: string): number {+ const minute = cron.trim().split(/\s+/)[0] ?? '';+ const hour = cron.trim().split(/\s+/)[1] ?? '';+ if (minute === '*') return 1;+ const step = /^\*\/(\d+)$/.exec(minute);+ if (step) return Math.max(1, Number(step[1]));+ const values = minute.split(',').map(v => Number(v)).filter(v => Number.isInteger(v)).sort((a, b) => a - b);+ if (values.length === 0) return Infinity;+ if (values.length === 1) return hour === '*' || /^\*\//.test(hour) ? 60 : Infinity;+ let gap = Infinity;+ for (let i = 1; i < values.length; i++) gap = Math.min(gap, values[i] - values[i - 1]);+ gap = Math.min(gap, 60 - values[values.length - 1] + values[0]);+ return gap;+}/*** bot_schedule — a bot schedules its OWN future run (durable, persisted with@@ -64,6 +84,14 @@ export function createBotScheduleTool(scheduler: BotScheduler, botId: string) {if (cron.trim().split(/\s+/).length !== 5) {return `Error: "${cron}" is not a 5-field cron expression.`;}+ if (cronMinGapMinutes(cron) < MIN_ROUTINE_GAP_MINUTES) {+ return `Error: routines run at most every ${MIN_ROUTINE_GAP_MINUTES} minutes — "${cron}" fires more often. A wake that finds nothing to do still costs a full turn; schedule follow-ups with delayMinutes instead.`;+ }+ const routines = scheduler.getManifests().filter(m => m.botId === botId && m.id.includes(`:${ROUTINE_PREFIX}`));+ const replacing = routines.some(m => m.id === `bot:${botId}:${ROUTINE_PREFIX}${name.toLowerCase().replace(/[^a-z0-9-]+/g, '-')}`);+ if (!replacing && routines.length >= MAX_SELF_ROUTINES) {+ return `Error: you already have ${MAX_SELF_ROUTINES} routines (${routines.map(m => m.id.split(':' + ROUTINE_PREFIX)[1]).join(', ')}). Re-use one of those names to replace it, or ask the owner to add more in bot.yaml.`;+ }const id = `bot:${botId}:${ROUTINE_PREFIX}${name.toLowerCase().replace(/[^a-z0-9-]+/g, '-')}`;scheduler.addPersistedTask({id,@@ -96,6 +124,9 @@ export function createBotScheduleTool(scheduler: BotScheduler, botId: string) {if ((delayMinutes as number) > MAX_DELAY_MINUTES) {return `Error: delayMinutes exceeds the ${MAX_DELAY_MINUTES / 60 / 24}-day horizon.`;}+ if ((delayMinutes as number) < MIN_ONESHOT_DELAY_MINUTES) {+ return `Error: a follow-up run must be at least ${MIN_ONESHOT_DELAY_MINUTES} minutes out — if the work is not done yet, keep working in this turn.`;+ }delaySeconds = Math.round((delayMinutes as number) * 60);}diff --git a/src/core/agent.ts b/src/core/agent.tsindex 76cbac7a..287fbc37 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -4068,9 +4068,12 @@ export class Agent {const result = this.botManager.enqueue(manifest.botId, {trigger: 'cron',prompt: manifest.prompt || manifest.description,+ routineId: manifest.id,});if (!result.accepted) {- logger.warn({ botId: manifest.botId, reasonCode: result.reasonCode }, 'Bot routine could not be enqueued');+ // Gate skips (busy, too soon, paused) are the governor working, not faults.+ const level = result.reasonCode === 'busy' || result.reasonCode === 'too_soon' || result.reasonCode === 'routine_paused' ? 'info' : 'warn';+ logger[level]({ botId: manifest.botId, task: manifest.id, reasonCode: result.reasonCode }, 'Bot routine tick skipped');}return;}diff --git a/src/core/commands/bots-command.ts b/src/core/commands/bots-command.tsindex 160b5bfa..cef07b86 100644--- a/src/core/commands/bots-command.ts+++ b/src/core/commands/bots-command.ts@@ -7,6 +7,7 @@ import type { ChannelMessage } from '../../types/channel.js';import { formatRelative, formatBytes } from './format.js';import path from 'node:path';import { homedir } from 'node:os';+import { mkdirSync } from 'node:fs';import { refinePersona } from '../../bots/persona-template.js';import { PERMISSION_TIERS, tierPermissionsFile, isPermissionTier, type PermissionTier } from '../../bots/permission-tiers.js';import { buildBotBundle, writeBundle, readBundle, importBotBundle } from '../../bots/bundle.js';@@ -63,7 +64,9 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chanconst lastRun = s.lastRunAt ? ` · last run ${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})${badge} — ${s.state}${crewNote}${attention}${lastRun}${activity}`;+ // Where the owner finds results — on the fleet's folder, not per crew.+ const folder = !s.parent ? `\n${indent} 📁 ${tildify(bm.store.deliverablesDir(s.id))}` : '';+ return `${indent}${icon} **${s.name}** (${s.id})${badge} — ${s.state}${crewNote}${attention}${lastRun}${folder}${activity}`;};const lines: string[] = [`**Bots** (${summaries.length})`, ''];const rendered = new Set<string>();@@ -132,7 +135,7 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chanif (personaText) {bm.store.writePersona(id, personaText + '\n');bm.invalidateRuntime(id);- await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded with your persona — enabled, fail-closed defaults.\nStart using it: \`/bot ${id} <task>\`, \`/bots open ${id}\`, or just \`@${id} <task>\`.`, channelId);+ await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded with your persona — enabled, fail-closed defaults.\n📁 Its results will appear in \`${tildify(bm.store.deliverablesDir(id))}\` (\`/bots folder ${id}\` opens it).\nStart using it: \`/bot ${id} <task>\`, \`/bots open ${id}\`, or just \`@${id} <task>\`.`, channelId);await agent.offerFleetStep(bm, id, manifest.name, msg, channel);return;}@@ -141,11 +144,11 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan(channel as any).enterBotChat(id, manifest.name);agent.pendingPersonaFor = id;await channel.send(- `🤖 **${manifest.name}** onboarded (fail-closed defaults).\n\nNow give it its character — your next message here becomes its **persona** (who it is, how it works, how it reports). Send \`/skip\` to keep the starter template, or \`/persona\` later to change it.`,+ `🤖 **${manifest.name}** onboarded (fail-closed defaults). 📁 Results: \`${tildify(bm.store.deliverablesDir(id))}\`\n\nNow give it its character — your next message here becomes its **persona** (who it is, how it works, how it reports). Send \`/skip\` to keep the starter template, or \`/persona\` later to change it.`,`bot:${id}`,);} else {- await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded — enabled, fail-closed defaults.\nPersona: \`${bm.store.botDir(id)}/persona.md\` — set it now with \`/bots persona ${id} <text>\`.`, channelId);+ await channel.send(`🤖 Bot **${manifest.name}** (\`${id}\`) onboarded — enabled, fail-closed defaults.\n📁 Results will appear in \`${tildify(bm.store.deliverablesDir(id))}\`.\nPersona: \`${bm.store.botDir(id)}/persona.md\` — set it now with \`/bots persona ${id} <text>\`.`, channelId);}} catch (err: any) {await channel.send(`Could not create bot "${id}": ${err?.message}`, channelId);@@ -216,13 +219,14 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chanconst value = (parts[2] ?? '').toLowerCase();if (!target || !value) {const suggested = agent.config.bots?.suggestedDailyTokenBudget ?? 5_000_000;- await channel.send(`Usage: \`/bots budget <id> <tokens|suggest|none>\` — suggest = ${suggested.toLocaleString()}/day, none = no cap (default).`, channelId);+ await channel.send(`Usage: \`/bots budget <id> <tokens|suggest|none>\` — every bot has a daily cap (default ${suggested.toLocaleString()}/day); suggest = that default, none = unlimited.`, channelId);return;}try {bm.store.update(target, m => {- if (value === 'none') { if (m.autonomy) delete m.autonomy.dailyTokenBudget; }- else if (value === 'suggest') { m.autonomy = { ...m.autonomy, dailyTokenBudget: agent.config.bots?.suggestedDailyTokenBudget ?? 5_000_000 }; }+ // 0 = explicitly unlimited; absent = the fleet default applies (ADR-020).+ if (value === 'none') { m.autonomy = { ...m.autonomy, dailyTokenBudget: 0 }; }+ else if (value === 'suggest') { if (m.autonomy) delete m.autonomy.dailyTokenBudget; }else {const n = parseInt(value, 10);if (!Number.isFinite(n) || n <= 0) throw new Error('budget must be a positive integer, "suggest", or "none"');@@ -231,7 +235,8 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan});bm.invalidateRuntime(target);const m = bm.store.get(target);- const applied = m?.autonomy?.dailyTokenBudget ? `${m.autonomy.dailyTokenBudget.toLocaleString()}/day` : 'none (unlimited)';+ const cap = m ? bm.dailyCapFor(m) : 0;+ const applied = cap > 0 ? `${cap.toLocaleString()}/day${m?.autonomy?.dailyTokenBudget === undefined ? ' (fleet default)' : ''}` : 'none (unlimited)';await channel.send(`💰 Budget for **${target}**: ${applied}. Hit the cap → the bot pauses until the next day, never killed.`, channelId);} catch (err: any) {await channel.send(`Failed: ${err?.message}`, channelId);@@ -405,7 +410,10 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chanfor (const r of [...records].reverse()) {const icon = r.state === 'completed' ? '✅' : r.state === 'failed' ? '❌' : r.state === 'paused' ? '⏸' : '⛔';const reason = r.reasonCode ? ` · [reason: ${r.reasonCode}]` : '';- lines.push(`${icon} ${r.runId} · ${r.trigger} · ${r.state} · ${(r.durationMs / 1000).toFixed(1)}s · ${r.tokensIn + r.tokensOut} tok${reason}`);+ const outcome = r.outcome ? ` · ${r.outcome === 'none' ? '⚠ no outcome' : r.outcome}` : '';+ const runFor = r.turnStartedAt ? ((Date.now() - r.turnStartedAt < r.durationMs ? r.durationMs : (r.startedAt + r.durationMs - r.turnStartedAt)) / 1000).toFixed(0) + 's run' : (r.durationMs / 1000).toFixed(1) + 's';+ lines.push(`${icon} ${r.runId} · ${r.trigger} · ${r.state} · ${runFor} · ${(r.tokensIn + r.tokensOut).toLocaleString()} tok${r.steps !== undefined ? ` · ${r.steps} steps` : ''}${outcome}${reason}`);+ for (const d of r.deliverables ?? []) lines.push(` 📁 ${tildify(d)}`);if (r.summary) lines.push(` ${r.summary.slice(0, 100)}`);}await channel.send(lines.join('\n'), channelId);@@ -607,6 +615,42 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chanreturn;}+ if (action === 'outputs' || action === 'deliverables') {+ // /bots outputs [id] — what the bots delivered, and where it is on disk.+ const target = parts[1]?.toLowerCase();+ if (target && !bm.store.exists(target)) {+ await channel.send(`No bot "${target}". See \`/bots\` for the roster.`, channelId);+ return;+ }+ const items = bm.listDeliverables(target).slice(0, 30);+ const root = target ? bm.store.deliverablesDir(target) : bm.store.deliverablesRoot();+ if (items.length === 0) {+ await channel.send(`Nothing delivered yet. Results will appear in \`${tildify(root)}\` — a bot delivers with bot_deliver when a result is finished.`, channelId);+ return;+ }+ const lines = [`**Deliverables** — ${tildify(root)}`, ''];+ for (const d of items) {+ lines.push(`${d.final ? '📄' : '📝'} ${formatRelative(d.mtimeMs)} · **${d.botId}** · ${d.name} (${formatBytes(d.bytes)})`);+ }+ lines.push('', '📄 final · 📝 work in progress (under work/) · `/bots folder <id>` opens the folder');+ 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();+ if (!target || !bm.store.exists(target)) {+ await channel.send('Usage: `/bots folder <id>` — opens the bot\'s deliverables folder.', channelId);+ return;+ }+ const dir = bm.store.deliverablesDir(target);+ mkdirSync(dir, { recursive: true });+ const opened = await openFolder(dir);+ await channel.send(opened ? `📁 Opened \`${tildify(dir)}\`` : `📁 ${tildify(dir)}\n(could not open a file manager here — copy the path)`, channelId);+ return;+ }+if (action === 'storage') {const usage = bm.getStorage();if (usage.length === 0) {@@ -631,7 +675,9 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: Chan'`/bots create <id> "Name" "Description"` — onboard a bot\n' +'`/bot <id> <message>` — message a bot from any channel\n' +'`/bots persona <id> <text>` — set/replace its character (with template conversion)\n' +- '`/bots budget <id> <tokens|suggest|none>` — daily token budget (none = no cap, default)\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 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' +'`/bots inbox <id>` — pending bot-to-bot mail\n' +@@ -649,3 +695,25 @@ export async function handleBotsCommand(agent: Agent, trimmed: string, msg: ChanchannelId,);}++/** ~ for the home dir — paths shown to people, not to tools. */+function tildify(p: string): string {+ const home = homedir();+ return p.startsWith(home) ? '~' + p.slice(home.length) : p;+}++/** Open a folder in the platform file manager; false when there is none (headless/SSH). */+async function openFolder(dir: string): Promise<boolean> {+ const { execFile } = await import('node:child_process');+ const cmd = process.platform === 'darwin' ? ['open', [dir]]+ : process.platform === 'win32' ? ['explorer', [dir]]+ : ['xdg-open', [dir]];+ return new Promise((resolve) => {+ try {+ const child = execFile(cmd[0] as string, cmd[1] as string[], { timeout: 5000 }, (err) => resolve(!err));+ child.on('error', () => resolve(false));+ } catch {+ resolve(false);+ }+ });+}diff --git a/src/index.ts b/src/index.tsindex 30e8eae3..bffd0fd7 100644--- a/src/index.ts+++ b/src/index.ts@@ -2619,6 +2619,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {// single permissions.yaml source.void bot.migrateFleetLayout().then(() => bot.migratePermissions())+ .then(() => bot.migrateDeliverables()).then(() => bot.registerRoutines(scheduler));agent.setBotManager(bot);setWebBotManager(bot);diff --git a/src/utils/config.ts b/src/utils/config.tsindex 5523aa87..514894dc 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -217,8 +217,12 @@ export interface MercuryConfig {/** Lead bots may create/remove their own crew via bot_spawn/bot_retire. */allowLeadSpawn?: boolean;};- /** Suggested per-bot daily token budget offered during onboarding. */+ /** Per-bot daily token cap applied when a bot sets none (0 = unlimited). ADR-020. */suggestedDailyTokenBudget?: number;+ /** Fleet-wide daily token cap across all bots (0 = unlimited). ADR-020. */+ fleetDailyTokenBudget?: number;+ /** Owner-visible folder for finished results (default: ~/Documents/Mercury). */+ deliverablesDir?: string;retention: {transcriptRuns: number;journalRotateBytes: number;@@ -502,6 +506,8 @@ export function getDefaultConfig(): MercuryConfig {allowLeadSpawn: getEnvBool('BOTS_FLEET_LEAD_SPAWN', true),},suggestedDailyTokenBudget: getEnvNum('BOTS_SUGGESTED_DAILY_TOKEN_BUDGET', 5_000_000),+ fleetDailyTokenBudget: getEnvNum('BOTS_FLEET_DAILY_TOKEN_BUDGET', 20_000_000),+ deliverablesDir: getEnv('BOTS_DELIVERABLES_DIR') || undefined,retention: {transcriptRuns: getEnvNum('BOTS_RETENTION_TRANSCRIPT_RUNS', 50),journalRotateBytes: getEnvNum('BOTS_JOURNAL_ROTATE_BYTES', 5 * 1024 * 1024),diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.tsindex fb047b6e..563407be 100644--- a/src/web/api/bots.test.ts+++ b/src/web/api/bots.test.ts@@ -107,18 +107,22 @@ describe('web bots API — cockpit', () => {// Fleet inbox lists itlet list = await jreq(await app.request('/api/bots/outputs'));- expect(list.outputs).toEqual([expect.objectContaining({ botId: 'publisher', name: 'final-report.md' })]);+ // Delivered names are dated + humanised; non-final work lands under work/.+ expect(list.outputs).toEqual([expect.objectContaining({ botId: 'publisher', final: false })]);+ const name: string = list.outputs[0].name;+ expect(name).toMatch(/^work\/\d{4}-\d{2}-\d{2} final report\.md$/);+ const enc = encodeURIComponent(name);// Per-bot listlist = await jreq(await app.request('/api/bots/publisher/outputs'));expect(list.outputs).toHaveLength(1);// Preview- const preview = await jreq(await app.request('/api/bots/publisher/outputs/final-report.md/preview'));+ const preview = await jreq(await app.request(`/api/bots/publisher/outputs/${enc}/preview`));expect(preview.preview).toContain('# The final report');// Download — raw bytes + content type- const dl = await app.request('/api/bots/publisher/outputs/final-report.md/download');+ const dl = await app.request(`/api/bots/publisher/outputs/${enc}/download`);expect(dl.status).toBe(200);expect(dl.headers.get('content-type')).toBe('text/markdown');expect(await dl.text()).toContain('# The final report');@@ -128,7 +132,7 @@ describe('web bots API — cockpit', () => {expect((await app.request('/api/bots/publisher/outputs/ghost.md/preview')).status).toBe(404);// Remove- const del = await app.request('/api/bots/publisher/outputs/final-report.md', { method: 'DELETE' });+ const del = await app.request(`/api/bots/publisher/outputs/${enc}`, { method: 'DELETE' });expect(del.status).toBe(200);expect((await app.request('/api/bots/publisher/outputs')).status ?? 0).toBeLessThan(500);const after = await jreq(await app.request('/api/bots/publisher/outputs'));diff --git a/website/docs/integrations/mercury-bots.mdx b/website/docs/integrations/mercury-bots.mdxindex 4d47b830..442d9434 100644--- a/website/docs/integrations/mercury-bots.mdx+++ b/website/docs/integrations/mercury-bots.mdx@@ -78,13 +78,21 @@ CLI mirrors the read-only surface — `mercury bots doctor` (fleet health check,- The fleet-shared folder `~/.mercury/bots/_shared/` is for cross-bot files — implicit grants for crew members, explicit for leads.- Access scopes (**read / write / execute** per directory) are declared in the bot's `permissions.yaml`; hand-edits apply live; malformed entries skip + warn rather than crash.- Shell approval follows the bot's own allow-list (`permissions.yaml autoApproveCommands`).-- Final artifacts must exit via **`bot_deliver`** (platform folder or download) — nothing lives only inside a sandbox.+- Finished results exit via **`bot_deliver`** into a folder you can actually find: `~/Documents/Mercury/<Bot name>/` (Windows: Documents; Termux: shared storage; `bots.deliverablesDir` in `mercury.yaml` overrides). Finals sit on top, crew work under `work/`, with a README index and files named `2026-10-10 Oxide Series D explained.md`. The path is shown when you onboard a bot and in `/bots`; `/bots outputs` lists deliveries and `/bots folder <id>` opens the folder.+- Writes to the shared folder are budgeted per run — it is for data other bots consume, not for notes. Bots never write to the deliverables folder by hand.- The **retention janitor** enforces per-bot disk caps (journal rotation, DLQ cap), so a forgotten fleet can't fill your disk.## Scheduling & autonomyBots own routines through `bot_schedule` — schedule their own future runs and recurring jobs, visible in `/tasks` and the fleet doctor. Leads additionally self-organize: give a lead a goal and it recruits crew, splits work, and synthesizes results upward.+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.+- **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```@@ -101,7 +109,7 @@ The local dashboard ('Mercury Bots' section) shows the live roster, per-bot thre## Observability- **`/bots` roster** — live per-bot states (running / waiting / stopped / needs-you).-- **Journals** — per-bot run history, tail-read and mtime-cached for speed.+- **Journals** — per-bot run history with real timings, steps, tool calls, the outcome (`deliverable`, `action`, `delegated`, `message`, `none`) and delivered paths; a compact transcript per run is kept (last 50).- **DLQ + replay** — failures classify honestly (`failed`, `timed out`) and replay non-destructively.- **`mercury bots doctor`** — storage health, queue depth, journal rotation, and scheduler linkage (routines registered but never wired are flagged before they silently never fire).