Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): sandbox retention janitor + bot_deliver for final artifacts
Salman Qureshi497c410ddf9a
diff --git a/BOTS-ARCHITECTURE.md b/BOTS-ARCHITECTURE.mdindex 1c401511..40937980 100644--- a/BOTS-ARCHITECTURE.md+++ b/BOTS-ARCHITECTURE.md@@ -167,6 +167,8 @@ Bots get their **own** `PermissionManager` seeded from `bots/<id>/permissions.ya- **Path scopes**: bot file access is scope-based like the main agent's manifest, defaulting to the bot's own dir + explicitly granted workspace paths. `cwdOnly`-style escape gates apply. The bot's sandbox and the fleet-shared folder are implicit, never configurable away.- **Dangerous-pattern denylist** reused from the main permission system for any allowed shell (plus the hardline set that survives every mode).- **Budgets as security**: per-bot `dailyTokenBudget` and turn caps are hard stops (pause + journal, resume next window), protecting low-end devices and wallets from runaway loops.+- **Retention janitor for the shared folder** (`src/bots/retention.ts`): the fleet-shared folder is a *message surface*, not storage — dated inter-run reports would accumulate forever. A two-stage janitor runs on `BotManager` boot + daily: files older than `retention.sandboxJanitor.hotDays` (default 7) cool down into `_shared/.archive/<yyyy-mm>/`, and archived files are hard-deleted past `archiveDays` (default 30). Guards: nothing younger than 24h is ever moved, dotfiles and `outputs/` are exempt, post-close queue access degrades to no-ops (Windows EBUSY), and a wrongly aged-out file stays recoverable for a month.+- **`bot_deliver`**: a bot moves a FINISHED artifact out of its writable roots (private sandbox or `_shared/`) into the owner-curated `outputs/<botId>/` zone — exempt from the janitor, deleted only by the owner. Containment is enforced (nothing outside the bot's own writable roots travels); delivery is a MOVE, so the shared surface stays lean by construction.### 2.6 Never-fail contractdiff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex dc7daadb..41eacad0 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -879,3 +879,53 @@ describe('Bot fleets (lead + crew)', () => {expect(tools.bot_spawn).toBeUndefined();});});++describe('bot_deliver — final artifact delivery', () => {+ let root: string;+ let store: BotStore;+ let manager: BotManager;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'mercury-bot-deliver-'));+ store = new BotStore(join(root, 'bots'));+ manager = makeManager(root);+ store.get('researcher') ?? seedBot(store, 'researcher');+ mkdirSync(join(root, 'bots', '_shared'), { recursive: true });+ writeFileSync(join(root, 'bots', '_shared', 'final-report.md'), '# Final');+ mkdirSync(store.sandboxDir('researcher'), { recursive: true });+ writeFileSync(store.sandboxDir('researcher') + '/draft.md', 'draft body');+ });++ afterEach(() => {+ for (const m of activeManagers.splice(0)) m.dispose();+ rmSync(root, { recursive: true, force: true });+ });++ it('moves a shared-folder artifact into the protected outputs zone', () => {+ 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'));+ expect(existsSync(sharedFile)).toBe(false); // a MOVE — the shared surface stays lean+ expect(existsSync(result.path!)).toBe(true);+ });++ it('rejects files outside the bot\'s writable roots (containment)', () => {+ writeFileSync(join(root, 'escape-me.md'), 'secret');+ const result = manager.deliver('researcher', join(root, 'escape-me.md'));+ expect(result.accepted).toBe(false);+ expect(result.reasonCode).toBe('outside_sandbox');+ });++ it('moves from the bot\'s private sandbox and dedupes delivered names', () => {+ const sandboxFile = join(store.sandboxDir('researcher'), 'draft.md');+ const first = manager.deliver('researcher', sandboxFile);+ expect(first.accepted).toBe(true);+ writeFileSync(sandboxFile, 'second body');+ const second = manager.deliver('researcher', sandboxFile);+ expect(second.accepted).toBe(true);+ expect(second.path).not.toBe(first.path);+ expect(existsSync(first.path!)).toBe(true);+ expect(existsSync(second.path!)).toBe(true);+ });+});diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex b76a3c50..1858ee08 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1,7 +1,7 @@import { cpus } from 'node:os';import { randomUUID } from 'node:crypto';-import { resolve, join } from 'node:path';-import { statSync } from 'node:fs';+import { basename, extname, isAbsolute, relative, resolve, join } from 'node:path';+import { copyFileSync, existsSync, mkdirSync, renameSync, statSync, unlinkSync } from 'node:fs';import type { Tool } from 'ai';import type { MercuryConfig } from '../utils/config.js';import type { ProviderRegistry } from '../providers/registry.js';@@ -12,8 +12,10 @@ import { UserMemoryStore as UserMemoryStoreImpl } from '../memory/user-memory.jsimport { BotStore, 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';import { createBotCapabilityRegistry, filterBotTools } from './registry-factory.js';import { createBotSendTool } from './tools/bot-send.js';+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';@@ -216,6 +218,14 @@ export class BotManager {// when their run_after elapses (also covers crash-restart backoffs).this.dueTimer = setInterval(() => this.resumeDueJobs(), 30_000);this.dueTimer.unref?.();+ // Retention janitor: on boot + once a day, cool down aged files in the+ // fleet-shared folder into the archive and expire the archive (disabled+ // entirely with `sandboxJanitor.enabled: false`).+ if (this.config.bots?.retention?.sandboxJanitor?.enabled !== false) {+ const janitorTimer = setInterval(() => this.sweepRetention(), 24 * 60 * 60 * 1000);+ janitorTimer.unref?.();+ setTimeout(() => this.sweepRetention(), 15_000);+ }// Real-time activity consumer registration happens via onBotActivity();// executeTurn feeds every registered listener AND the live `activity`// map (rendered by the /bots roster and fleet_status).@@ -732,12 +742,14 @@ export class BotManager {// permissions.yaml tool gate), THEN add the bot-specific tools —// otherwise the filter would strip them again.const filtered = filterBotTools({ ...registry.getTools() }, manifest, this.store.ensurePermissions(botId));- // Fleet relations are implicit comms: a lead can message its crew and a- // crew bot its lead, without anyone hand-editing canMessage.const effectiveRoster = this.effectiveRoster(botId, manifest);if (effectiveRoster.length > 0) {filtered.bot_send = createBotSendTool(this, botId, effectiveRoster) as Tool;}+ // bot_deliver: implicit lifecycle op — every bot can move a finished+ // artifact out of its writable roots into the owner-curated outputs zone+ // (exempt from the retention janitor).+ filtered.bot_deliver = createBotDeliverTool(this, botId) as Tool;// Fleet tools for leads: monitor the crew, spawn/retire within caps.if (manifest.fleetRole === 'lead') {filtered.fleet_status = createFleetStatusTool(this, botId);@@ -1236,6 +1248,75 @@ export class BotManager {}this.queue.close();}++ /**+ * 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).+ */+ deliver(botId: string, filePath: string, rename?: string): { accepted: boolean; path?: string; reasonCode?: string } {+ if (!this.store.get(botId)) return { accepted: false, reasonCode: 'target_unknown' };+ const candidate = resolve(filePath.replace(/^~(?=$|\/|\\)/, process.env.HOME || '~'));+ const allowedBases = [this.store.sharedSandboxDir(), this.store.sandboxDir(botId)];+ const inside = allowedBases.some((base) => {+ const rel = relative(resolve(base), candidate);+ return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);+ });+ if (!inside || !existsSync(candidate) || !statSync(candidate).isFile()) {+ return { accepted: false, reasonCode: 'outside_sandbox' };+ }+ const outputsDir = join(this.store.outputsDir(), botId);+ mkdirSync(outputsDir, { recursive: true });+ const stem = basename(candidate, extname(candidate));+ const extMatch = extname(candidate);+ const requested = (rename || stem)+ .replace(/[ <>:"/\\|?*]/g, '-')+ .replace(/-+/g, '-')+ .replace(/^-|-$/g, '')+ .slice(0, 120) || 'output';+ let dest = join(outputsDir, requested);+ for (let i = 2; existsSync(dest); i++) {+ dest = join(outputsDir, `${requested}-${i}${extMatch}`);+ }+ try {+ renameSync(candidate, dest);+ } catch {+ // Cross-device fallback: copy then remove the source.+ try {+ copyFileSync(candidate, dest);+ unlinkSync(candidate);+ } catch {+ return { accepted: false, reasonCode: 'move_failed' };+ }+ }+ logger.info({ botId, dest }, 'Bot delivered a final artifact');+ return { accepted: true, path: dest };+ }++ /**+ * Retention janitor sweep: files in the fleet-shared folder cool down into+ * `_shared/.archive/<yyyy-mm>/` past the hot window, and the archive+ * expires after the archive window — the working surface stays small while+ * an incorrectly aged-out file stays recoverable for a month.+ */+ sweepRetention(): void {+ const sandbox = this.config.bots?.retention?.sandboxJanitor;+ if (sandbox?.enabled === false) return;+ const result = sweepSharedSandbox(this.store.botsRoot, {+ hotDays: sandbox?.hotDays ?? 7,+ archiveDays: sandbox?.archiveDays ?? 30,+ });+ const touched = result.moved.length + result.deleted.length;+ if (touched > 0 || result.errors.length > 0) {+ logger.info(+ { moved: result.moved.length, deleted: result.deleted.length, kept: result.kept, errors: result.errors },+ 'Sandbox retention sweep',+ );+ }+ }}function resolveProvider(providers: ProviderRegistry, manifest: BotManifest) {diff --git a/src/bots/retention.test.ts b/src/bots/retention.test.tsnew file mode 100644index 00000000..d2429397--- /dev/null+++ b/src/bots/retention.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { sweepSharedSandbox } from './retention.js';+import { BOT_SHARED_SANDBOX_DIRNAME, BotStore } from './store.js';++const NOW = new Date('2026-09-30T12:00:00Z').getTime();+const DAYS = 24 * 60 * 60 * 1000;++function makeFleetRoot(): string {+ const root = mkdtempSync(join(tmpdir(), 'mercury-retention-'));+ new BotStore(join(root, 'bots')); // materializes the bots root layout+ const shared = join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME);+ mkdirSync(shared, { recursive: true });+ return root;+}++function seed(root: string, name: string, ageDays: number): string {+ const file = join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, name);+ writeFileSync(file, `payload ${name}`);+ const mtime = new Date(NOW - ageDays * DAYS); // fs.utimes accepts Date — a bare number is SECONDS+ utimesSync(file, mtime, mtime);+ return file;+}++describe('shared-sandbox retention janitor', () => {+ it('cools down files past the hot window into the month-stamped archive', () => {+ const root = makeFleetRoot();+ seed(root, 'old-report.md', 12); // 12 days old — past the 7-day hot window+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.moved.map((m) => m.file)).toContain('old-report.md');+ expect(result.moved[0].ageDays).toBe(12);+ expect(existsSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, 'old-report.md'))).toBe(false);+ expect(existsSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, '.archive', '2026-09', 'old-report.md'))).toBe(true);+ });++ it('keeps recent files in the working surface', () => {+ const root = makeFleetRoot();+ seed(root, 'fresh-dashboard.md', 1); // inside BOTH the 24h safety net and the hot window+ seed(root, 'three-days-old.md', 3); // inside neither+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.moved).toHaveLength(0);+ expect(existsSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, 'fresh-dashboard.md'))).toBe(true);+ expect(existsSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, 'three-days-old.md'))).toBe(true);+ });++ it('never sweeps younger than 24h even with an aggressive hot window', () => {+ const root = makeFleetRoot();+ seed(root, 'hours-old.md', 0.5);+ const result = sweepSharedSandbox(root, { hotDays: 0.1, archiveDays: 30, now: NOW });+ expect(result.moved).toHaveLength(0);+ });++ it('expires archived files past the archive window', () => {+ const root = makeFleetRoot();+ seed(root, 'ancient-sweep.md', 12); // moved to archive (12 > 7 hot days)+ sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ const archived = join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, '.archive', '2026-09', 'ancient-sweep.md');+ expect(existsSync(archived)).toBe(true);+ // Backdate the ARCHIVE copy by 45 days — past the 30-day archive window+ const archiveMtime = new Date(NOW - 31 * DAYS);+ utimesSync(archived, archiveMtime, archiveMtime);+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.deleted.map((d) => d.file)).toContain('2026-09/ancient-sweep.md');+ expect(existsSync(archived)).toBe(false);+ });++ it('is idempotent and never overwrites an archived name on re-run', () => {+ const root = makeFleetRoot();+ seed(root, 'superseded.md', 10);+ sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ // Same filename appears again and ages out while its archived twin exists+ seed(root, 'superseded.md', 10);+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.moved).toHaveLength(1);+ expect(result.moved[0].archivedTo).toContain('superseded-2.md');+ });++ it('never sweeps reference files younger than the hot window when another bot still reads them', () => {+ const root = makeFleetRoot();+ seed(root, 'account-personas-roster-2026-09-24.md', 6); // 6 days old, < 7+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.moved).toHaveLength(0);+ expect(existsSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, 'account-personas-roster-2026-09-24.md'))).toBe(true);+ });++ it('leaves dotfiles, directories and non-shared trees untouched', () => {+ const root = makeFleetRoot();+ const shared = join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME);+ writeFileSync(join(shared, '.DS_Store'), 'junk');+ writeFileSync(join(shared, '.env'), 'SECRET=1');+ mkdirSync(join(shared, 'subfolder'));+ writeFileSync(join(shared, 'subfolder', 'nested.md'), 'x');+ const privateSandbox = join(root, 'bots', 'researcher');+ mkdirSync(privateSandbox, { recursive: true });+ writeFileSync(join(privateSandbox, 'private-artifact.md'), 'x');+ for (const f of ['.DS_Store', join('subfolder', 'nested.md'), join('..', 'researcher', 'private-artifact.md')]) {+ const p = join(shared, f);+ const mtime = NOW - 20 * DAYS;+ utimesSync(join(shared, f), mtime, mtime);+ }+ utimesSync(join(privateSandbox, 'private-artifact.md'), NOW - 20 * DAYS, NOW - 20 * DAYS);+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.moved).toHaveLength(0);+ expect(existsSync(join(shared, '.DS_Store'))).toBe(true);+ expect(existsSync(join(shared, 'subfolder', 'nested.md'))).toBe(true);+ expect(existsSync(join(privateSandbox, 'private-artifact.md'))).toBe(true);+ });++ it('sweeps the real shared folder path of a live fleet', () => {+ const root = makeFleetRoot();+ expect(readdirSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME)).length).toBe(0);+ seed(root, 'agentbeat-refused-void-slot-1400-2026-09-22.md', 9);+ seed(root, 'account-health-dashboard-2026-09-30-resume.md', 0);+ const result = sweepSharedSandbox(join(root, 'bots'), { hotDays: 7, archiveDays: 30, now: NOW });+ expect(result.moved.map((m) => m.file)).toEqual(['agentbeat-refused-void-slot-1400-2026-09-22.md']);+ expect(existsSync(join(root, 'bots', BOT_SHARED_SANDBOX_DIRNAME, 'account-health-dashboard-2026-09-30-resume.md'))).toBe(true);+ });+});\ No newline at end of filediff --git a/src/bots/retention.ts b/src/bots/retention.tsnew file mode 100644index 00000000..202f0cab--- /dev/null+++ b/src/bots/retention.ts@@ -0,0 +1,149 @@+import { existsSync, mkdirSync, readdirSync, renameSync, statSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';+import { BOT_SHARED_SANDBOX_DIRNAME } from './store.js';++/**+ * Sandbox retention janitor (two-stage: cool down → expire).+ *+ * The fleet-shared folder accumulates inter-run signal — dated status+ * reports, sweep results, handoffs. It is a message surface, not storage:+ * anything that must survive is the main journal's or a deliverable's job+ * (see `BotManager.deliver` / `outputsDir`, which this janitor never+ * touches). Files cool down in place for `hotDays`, then move to+ * `_shared/.archive/<yyyy-mm>/` (bots no longer need them in the working+ * surface, but recovery is possible), then are hard-deleted after+ * `archiveDays` in the archive.+ *+ * Safety rails:+ * - never touches anything modified in the last 24h (clock skew, in-flight+ * turns),+ * - never touches dotfiles (metadata like .DS_Store) or anything other+ * than top-level REGULAR FILES of the shared folder,+ * - idempotent: re-running on the same state moves/deletes nothing more,+ * - every action journaled by the caller via the returned summary.+ */++/** Never touch anything younger than this, regardless of thresholds. */+const SAFE_MIN_AGE_MS = 24 * 60 * 60 * 1000;++export interface SandboxJanitorOptions {+ /** Files leave the working surface after this many days (default 7). */+ hotDays?: number;+ /** Archived files are deleted after this many days (default 30). */+ archiveDays?: number;+ /** Millisecond epoch for the sweep — injectable for deterministic tests. */+ now?: number;+}++export interface JanitorAction {+ /** Path relative to the bots root (never absolute — logs stay portable). */+ file: string;+ ageDays: number;+}++export interface SandboxJanitorResult {+ moved: Array<JanitorAction & { archivedTo: string }>;+ deleted: JanitorAction[];+ /** Files seen and deliberately kept (recent, or below threshold). */+ kept: number;+ errors: string[];+}++export function sweepSharedSandbox(botsRoot: string, opts: { hotDays?: number; archiveDays?: number; now?: number } = {}): SandboxJanitorResult {+ const result: SandboxJanitorResult = { moved: [], deleted: [], kept: 0, errors: [] };+ const now = opts.now ?? Date.now();+ const hotMs = (opts.hotDays ?? 7) * 24 * 60 * 60 * 1000;+ const archiveMs = (opts.archiveDays ?? 30) * 24 * 60 * 60 * 1000;++ const shared = join(botsRoot, BOT_SHARED_SANDBOX_DIRNAME);+ if (!existsSync(shared)) return result;++ // Stage 1: cool down — top-level regular files past their hot window move+ // into the month-stamped archive (mtime is what ages them; rename keeps it).+ const archiveRoot = join(shared, '.archive');+ let entries: string[];+ try {+ entries = readdirSync(shared);+ } catch (err: any) {+ result.errors.push(`readdir ${BOT_SHARED_SANDBOX_DIRNAME}: ${err?.message}`);+ return result;+ }++ for (const name of entries) {+ if (name.startsWith('.')) continue; // dotfiles (incl. .DS_Store, .archive) are never swept+ const file = join(shared, name);+ try {+ const stat = statSync(file);+ if (!stat.isFile()) continue;+ const ageMs = now - stat.mtimeMs;+ if (ageMs < SAFE_MIN_AGE_MS) {+ result.kept += 1;+ continue;+ }+ const ageDays = Math.floor(ageMs / (24 * 60 * 60 * 1000));+ if (ageMs < hotMs) {+ result.kept += 1;+ continue;+ }+ const month = new Date(now).toISOString().slice(0, 7);+ const destDir = join(archiveRoot, month);+ mkdirSync(destDir, { recursive: true });+ const archivedTo = uniquePath(join(destDir, name));+ renameSync(file, archivedTo);+ result.moved.push({ file: name, ageDays, archivedTo: archivedTo });+ } catch (err: any) {+ if (err?.code === 'EBUSY' || err?.code === 'EPERM') {+ result.kept += 1; // in use right now — a later sweep takes it+ continue;+ }+ result.errors.push(`${name}: ${err?.message}`);+ }+ }++ // Stage 2: expire — archived files past the archive window are deleted.+ if (!existsSync(archiveRoot)) return result;+ let archived: string[];+ try {+ archived = readdirSync(archiveRoot);+ } catch (err: any) {+ result.errors.push(`readdir .archive: ${err?.message}`);+ return result;+ }+ for (const month of archived) {+ const monthDir = join(archiveRoot, month);+ let files: string[];+ try {+ files = readdirSync(monthDir);+ } catch (err: any) {+ result.errors.push(`readdir .archive/${month}: ${err?.message}`);+ continue;+ }+ for (const name of files) {+ const filePath = join(monthDir, name);+ try {+ const stat = statSync(filePath);+ if (!stat.isFile()) continue;+ const ageMs = now - stat.mtimeMs;+ if (ageMs < SAFE_MIN_AGE_MS || ageMs < archiveMs) continue;+ unlinkSync(filePath);+ result.deleted.push({ file: `${month}/${name}`, ageDays: Math.floor(ageMs / (24 * 60 * 60 * 1000)) });+ } catch (err: any) {+ if (err?.code === 'EBUSY' || err?.code === 'EPERM') continue;+ result.errors.push(`.archive/${month}/${name}: ${err?.message}`);+ }+ }+ // Leave empty month dirs behind — harmless, and deleting them would race+ // a concurrent sweep on another manager instance.+ }++ return result;+}++/** First free path for an archive move — never overwrites an existing entry. */+function uniquePath(path: string): string {+ if (!existsSync(path)) return path;+ for (let i = 2; ; i++) {+ const candidate = path.replace(/(\.[^./\\]+)?$/, `-${i}$1`);+ if (!existsSync(candidate)) return candidate;+ }+}\ No newline at end of filediff --git a/src/bots/store.ts b/src/bots/store.tsindex e6e3851f..98150632 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -235,6 +235,15 @@ export class BotStore {return resolve(this.botsRoot, BOT_SHARED_SANDBOX_DIRNAME);}+ /**+ * Owner-curated final deliverables (`bot_deliver`). Sits OUTSIDE the+ * fleet-shared folder and is exempt from the retention janitor — the+ * owner deletes these when done with them.+ */+ outputsDir(): string {+ return resolve(this.botsRoot, 'outputs');+ }+/** Create both sandbox areas if missing (cheap + idempotent). */ensureSandboxes(id: string): void {mkdirSync(this.sandboxDir(id), { recursive: true });diff --git a/src/bots/tools/bot-deliver.ts b/src/bots/tools/bot-deliver.tsnew file mode 100644index 00000000..f42fa2af--- /dev/null+++ b/src/bots/tools/bot-deliver.ts@@ -0,0 +1,44 @@+import { tool, zodSchema } from 'ai';+import { z } from 'zod';+import type { BotManager } from '../bot-manager.js';++/**+ * 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. Deliverables there are exempt from the retention+ * janitor and land on the owner's machine — a bot should deliver when the+ * artifact is final, then say so in its turn summary.+ *+ * Fail-closed: only files inside the bot's own writable roots travel;+ * anything else is rejected with `outside_sandbox`.+ */+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.`,+ 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")',+ ),+ saveAs: z.string().max(120).optional().describe(+ 'Optional filename to store it as (extension auto-kept). Defaults to the current filename.',+ ),+ })),+ execute: async ({ file, saveAs }: { file: string; saveAs?: string }) => {+ const result = manager.deliver(botId, file, 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.`;+ }+ if (result.reasonCode === 'target_unknown') {+ return `Error: bot profile for "${botId}" is gone.`;+ }+ 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.`;+ },+ });+}\ No newline at end of filediff --git a/src/bots/types.ts b/src/bots/types.tsindex 754c4f25..2b173a8c 100644--- a/src/bots/types.ts+++ b/src/bots/types.ts@@ -68,6 +68,19 @@ export interface BotRetentionConfig {mailboxTtlHours?: number;dlqCap?: number;artifactQuotaBytes?: number;+ /**+ * Retention janitor for the fleet-shared folder (`_shared/`): files cool+ * down into `_shared/.archive/<yyyy-mm>/` past the hot window, and the+ * archive expires after the archive window. Deliverables moved via+ * `bot_deliver` into `outputs/` are exempt. Enabled by default.+ */+ sandboxJanitor?: {+ enabled?: boolean;+ /** Days a file stays in the working surface (default 7). */+ hotDays?: number;+ /** Days an archived file survives before deletion (default 30). */+ archiveDays?: number;+ };}/**diff --git a/src/utils/config.ts b/src/utils/config.tsindex 7424e687..0f69d872 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -224,6 +224,14 @@ export interface MercuryConfig {mailboxTtlHours: number;dlqCap: number;artifactQuotaBytes: number;+ /** Retention janitor for the fleet-shared folder (disabled = never sweep). */+ sandboxJanitor: {+ enabled: boolean;+ /** Days a file stays in the working surface. */+ hotDays: number;+ /** Days an archived file survives before deletion. */+ archiveDays: number;+ };};};spotify: {@@ -498,6 +506,11 @@ export function getDefaultConfig(): MercuryConfig {mailboxTtlHours: getEnvNum('BOTS_MAILBOX_TTL_HOURS', 72),dlqCap: getEnvNum('BOTS_DLQ_CAP', 100),artifactQuotaBytes: getEnvNum('BOTS_ARTIFACT_QUOTA_BYTES', 500 * 1024 * 1024),+ sandboxJanitor: {+ enabled: getEnvBool('BOTS_SANDBOX_JANITOR', true),+ hotDays: getEnvNum('BOTS_SANDBOX_HOT_DAYS', 7),+ archiveDays: getEnvNum('BOTS_SANDBOX_ARCHIVE_DAYS', 30),+ },},},spotify: {