Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
chore(bots): type the governed turn and its tests; lock the improved lint baseline
Salman Qureshi4a0c63af985c
diff --git a/.lint-baseline.json b/.lint-baseline.jsonindex 2f5446f8..14e9d7c8 100644--- a/.lint-baseline.json+++ b/.lint-baseline.json@@ -1,11 +1,11 @@{"$comment": "ESLint ratchet baseline. Per-rule counts (errors + warnings) may only go down. Refresh with `npm run lint:ratchet -- --update` after a clean-up.","provisional": false,- "generatedAt": "2026-10-10T07:52:30.812Z",+ "generatedAt": "2026-10-10T14:37:25.243Z","target": "src","rules": {"(unknown)": 1,- "@typescript-eslint/no-explicit-any": 1145,+ "@typescript-eslint/no-explicit-any": 1138,"@typescript-eslint/no-require-imports": 6,"@typescript-eslint/no-this-alias": 5,"@typescript-eslint/no-unused-expressions": 100,diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.tsindex 431a40d8..2fc841c4 100644--- a/src/bots/bot-manager.test.ts+++ b/src/bots/bot-manager.test.ts@@ -1114,10 +1114,12 @@ describe('bot governance (ADR-020)', () => {rmSync(root, { recursive: true, force: true });});- const ok = (text = 'done') => ({ text, finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 5 } } as any);+ type StepOpts = { onStepFinish?: (step: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[] }) => void };+ const ok = (text = 'done') => ({ text, finishReason: 'stop', usage: { inputTokens: 10, outputTokens: 5 } }) as never;const completes = () => mockedGenerateText.mockImplementation(async () => ok());+ const stateOf = (botId: string) => manager.getStatusSummaries().find(s => s.id === botId)?.state;const waitIdle = (botId: string) => vi.waitFor(() => {- expect((manager as any).running.get(botId)?.size ?? 0).toBe(0);+ expect(stateOf(botId)).not.toBe('running');expect(manager.getQueuedCount(botId)).toBe(0);});@@ -1127,7 +1129,7 @@ describe('bot governance (ADR-020)', () => {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));+ await vi.waitFor(() => expect(stateOf('ticker')).toBe('running'));// 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.@@ -1151,7 +1153,7 @@ describe('bot governance (ADR-020)', () => {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(); });+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => { opts.onStepFinish?.({ usage: { inputTokens: 800, outputTokens: 50 }, toolCalls: [], toolResults: [] }); return ok(); }) as never);manager.enqueue('spender', { trigger: 'chat', prompt: 'a' });await waitIdle('spender');expect(alerts.some(a => a.includes('85% of today'))).toBe(true);@@ -1166,10 +1168,10 @@ describe('bot governance (ADR-020)', () => {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) => {+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => {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.');- });+ }) as never);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' });@@ -1199,10 +1201,10 @@ describe('bot governance (ADR-020)', () => {seedBot(store, 'big', { autonomy: { maxTokensPerTurn: 100 } });const alerts: string[] = [];manager.setAlert(async (m) => { alerts.push(m); });- mockedGenerateText.mockImplementation(async (opts: any) => {+ mockedGenerateText.mockImplementation((async (opts: StepOpts) => {opts.onStepFinish?.({ usage: { inputTokens: 500, outputTokens: 5 }, toolCalls: [], toolResults: [] });return ok('partial');- });+ }) as never);manager.enqueue('big', { trigger: 'chat', prompt: 'huge task' });await waitIdle('big');const [row] = manager.getJournal('big', 1);@@ -1215,7 +1217,7 @@ describe('bot governance (ADR-020)', () => {});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);+ seedBot(store, 'lead', { fleetRole: 'lead' });store.update('lead', m => { m.name = 'Article Writer'; });manager.addCrew('lead', { id: 'fact-checker', name: 'Fact Checker' });const shared = store.sharedSandboxDir();diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 3d5aacf2..5db3d8f8 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1627,8 +1627,8 @@ export class BotManager {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');+ } catch (err) {+ logger.warn({ botId: entry.name, file: file.name, err: (err as Error)?.message }, 'Legacy deliverable could not be moved');}}try { if (readdirSync(from).length === 0) rmSync(from, { recursive: true }); } catch { /* keep */ }diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.tsindex 7d8a843a..9a2b92d7 100644--- a/src/bots/bot-turn.test.ts+++ b/src/bots/bot-turn.test.ts@@ -250,6 +250,16 @@ describe('runBotTurn live thinking events', () => {import { compactMessages, computeOutcome, wrapBotTools, isReadOnlyCommand, isTransientFailure, DEFAULT_TURN_LIMITS } from './bot-turn.js';+/** The streamText options the turn loop passes, as the mocks see them. */+type MockOpts = {+ messages: Array<{ role: string; content: string }>;+ tools: Record<string, { execute?: (args: unknown, options: unknown) => Promise<unknown> }>;+ abortSignal?: AbortSignal;+ onStepFinish?: (step: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[] }) => void;+};+const impl = (fn: (opts: MockOpts) => unknown) => fn as never;+const finished = (text: string, finishReason = 'stop') => streamedResult({ text, finishReason });+describe('classifyFailure (ADR-020)', () => {it('treats network cuts and empty streams as transient, unwrapping retry wrappers', () => {expect(classifyFailure(new Error('terminated'))).toBe('provider_timeout');@@ -264,12 +274,12 @@ describe('classifyFailure (ADR-020)', () => {});it('surfaces the stream error instead of the generic "No output generated"', async () => {- mockedStreamText.mockImplementationOnce(() => ({+ mockedStreamText.mockImplementationOnce(impl(() => ({fullStream: (async function* () { yield { type: 'error', error: new Error('invalid_api_key: 401') }; })(),text: Promise.reject(new Error('No output generated. Check the stream for errors.')),finishReason: Promise.reject(new Error('No output generated. Check the stream for errors.')),usage: Promise.resolve({}),- }) as any);+ })));const out = await runBotTurn(turnInput());expect(out.status).toBe('failed');expect(out.error).toContain('invalid_api_key');@@ -287,7 +297,7 @@ describe('compactMessages', () => {toolMsg('b', big),toolMsg('c', 'recent'),];- const out: any[] = compactMessages(msgs, { keepRecentToolResults: 2, maxToolResultChars: 1000 });+ const out = compactMessages(msgs as never, { keepRecentToolResults: 2, maxToolResultChars: 1000 }) as unknown as Array<{ content: Array<{ output: { value: string } }> }>;expect(out[0]).toBe(msgs[0]);expect(out[1].content[0].output.value).toContain('more chars trimmed from an earlier step');expect(out[1].content[0].output.value.length).toBeLessThan(600);@@ -295,25 +305,25 @@ describe('compactMessages', () => {expect(out[2].content[0].output.value.length).toBeLessThan(1100);expect(out[3].content[0].output.value).toBe('recent');// Never mutates the originals.- expect((msgs[2] as any).content[0].output.value).toBe(big);+ expect((msgs[2] as { content: Array<{ output: { value: string } }> }).content[0].output.value).toBe(big);});it('is a no-op without tool results', () => {const msgs = [{ role: 'user', content: 'hi' }];- expect(compactMessages(msgs, DEFAULT_TURN_LIMITS)).toBe(msgs);+ expect(compactMessages(msgs as never, DEFAULT_TURN_LIMITS)).toBe(msgs);});});describe('turn governor', () => {it('stops a turn that exceeds the per-turn token cap and reports it as turn_budget, not an escalation', async () => {let rounds = 0;- mockedStreamText.mockImplementation((opts: any) => {+ mockedStreamText.mockImplementation(impl((opts) => {rounds++;// Each step burns 200k tokens; the cap is 300k.opts.onStepFinish?.({ usage: { inputTokens: 200_000, outputTokens: 10 }, toolCalls: [{ toolName: 'read_file', toolCallId: 't1', input: { path: 'a' } }], toolResults: [{ toolCallId: 't1', output: { type: 'text', value: 'ok' } }] });opts.onStepFinish?.({ usage: { inputTokens: 200_000, outputTokens: 10 }, toolCalls: [], toolResults: [] });const aborted = opts.abortSignal?.aborted;- return streamedResult({ text: aborted ? '' : 'still going', finishReason: aborted ? 'other' : 'tool-calls' } as any);- });+ return finished(aborted ? '' : 'still going', aborted ? 'other' : 'tool-calls');+ }));const out = await runBotTurn(turnInput({ trigger: 'cron', manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 2 } } }));expect(out.status).toBe('failed');expect(out.reasonCode).toBe('turn_budget');@@ -323,10 +333,10 @@ describe('turn governor', () => {});it('honours a per-bot maxTokensPerTurn override', async () => {- mockedStreamText.mockImplementation((opts: any) => {+ mockedStreamText.mockImplementation(impl((opts) => {opts.onStepFinish?.({ usage: { inputTokens: 900, outputTokens: 10 }, toolCalls: [], toolResults: [] });- return streamedResult({ text: 'done', finishReason: 'stop' } as any);- });+ return finished('done');+ }));const out = await runBotTurn(turnInput({ manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 3, maxTokensPerTurn: 500 } } }));expect(out.reasonCode).toBe('turn_budget');});@@ -351,11 +361,11 @@ describe('outcome gate', () => {it('nudges a work run that only wrote notes exactly once, then journals none + the false claim', async () => {const prompts: string[] = [];- mockedStreamText.mockImplementation((opts: any) => {- prompts.push(opts.messages.at(-1).content);+ mockedStreamText.mockImplementation(impl((opts) => {+ prompts.push(opts.messages.at(-1)?.content ?? '');opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 }, toolCalls: [{ toolName: 'write_file', toolCallId: 'w', input: { path: '/tmp/shared/cycle-record.md', content: 'x' } }], toolResults: [{ toolCallId: 'w', output: { type: 'text', value: 'Wrote file' } }] });- return streamedResult({ text: 'Record filed and delivered.', finishReason: 'stop' } as any);- });+ return finished('Record filed and delivered.');+ }));const out = await runBotTurn(turnInput({ trigger: 'cron', manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 3 } } }));expect(out.status).toBe('completed');expect(out.outcome).toBe('none');@@ -368,7 +378,7 @@ describe('outcome gate', () => {});it('does not nudge a check routine or a reply-contract run', async () => {- mockedStreamText.mockImplementation(() => streamedResult({ text: 'All quiet.', finishReason: 'stop' } as any));+ mockedStreamText.mockImplementation(impl(() => finished('All quiet.')));const check = await runBotTurn(turnInput({ trigger: 'cron', expects: 'check' }));expect(check.outcome).toBe('none');expect(check.outcomeNudged).toBe(false);@@ -378,19 +388,19 @@ describe('outcome gate', () => {});it('a delivery during the turn makes the outcome deliverable with the path recorded', async () => {- const deliver = { execute: async () => 'Delivered to /home/u/Documents/Mercury/T/2026-10-10 Piece.md — the owner\'s outputs zone.' } as any;+ const deliver = { execute: async () => 'Delivered to /home/u/Documents/Mercury/T/2026-10-10 Piece.md — the owner\'s outputs zone.' } as never;// The tool runs inside the stream (as the SDK would run it), so the// wrapper's capture lands before the turn computes its outcome.- mockedStreamText.mockImplementation(((opts: any) => ({+ mockedStreamText.mockImplementation(impl((opts) => ({fullStream: (async function* () {- const r = await opts.tools.bot_deliver.execute({ file: 'x.md' }, {});+ const r = await opts.tools.bot_deliver.execute!({ file: 'x.md' }, {} as never);opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 }, toolCalls: [{ toolName: 'bot_deliver', toolCallId: 'd', input: { file: 'x.md' } }], toolResults: [{ toolCallId: 'd', output: { type: 'text', value: r } }] });yield { type: 'text-delta', text: 'Delivered.' };})(),text: Promise.resolve('Delivered.'),finishReason: Promise.resolve('stop'),usage: Promise.resolve({}),- })) as any);+ })));const out = await runBotTurn(turnInput({ trigger: 'cron', tools: { bot_deliver: deliver } }));expect(out.outcome).toBe('deliverable');expect(out.deliverables).toEqual(['/home/u/Documents/Mercury/T/2026-10-10 Piece.md']);@@ -401,21 +411,21 @@ describe('outcome gate', () => {describe('shared-folder write budget', () => {const sandbox = { workspace: '/tmp/ws', shared: '/tmp/shared' };const writes: string[] = [];- const write = { execute: async (args: any) => { writes.push(args.path); return `Wrote ${args.path}`; } } as any;+ const write = { execute: async (args: { path: string }) => { writes.push(args.path); return `Wrote ${args.path}`; } } as never;it('warns past the soft limit and refuses past the hard limit, but never limits the private workspace', async () => {writes.length = 0;- const tools = wrapBotTools({ write_file: write }, { sandbox, limits: { ...DEFAULT_TURN_LIMITS, sharedWrites: { softFiles: 1, softBytes: 100, hardFiles: 2, hardBytes: 1000 } }, onDelivered: () => {} });- const a = await tools.write_file.execute!({ path: '/tmp/shared/a.md', content: 'x'.repeat(50) }, {} as any);+ const tools = wrapBotTools({ write_file: write as never }, { sandbox, limits: { ...DEFAULT_TURN_LIMITS, sharedWrites: { softFiles: 1, softBytes: 100, hardFiles: 2, hardBytes: 1000 } }, onDelivered: () => {} });+ const a = await tools.write_file.execute!({ path: '/tmp/shared/a.md', content: 'x'.repeat(50) }, {} as never);expect(String(a)).toBe('Wrote /tmp/shared/a.md');- const b = await tools.write_file.execute!({ path: '/tmp/shared/b.md', content: 'x'.repeat(60) }, {} as any);+ const b = await tools.write_file.execute!({ path: '/tmp/shared/b.md', content: 'x'.repeat(60) }, {} as never);expect(String(b)).toContain('[Note: this run has written 2 files');- const c = await tools.write_file.execute!({ path: '/tmp/shared/c.md', content: 'x' }, {} as any);+ const c = await tools.write_file.execute!({ path: '/tmp/shared/c.md', content: 'x' }, {} as never);expect(String(c)).toMatch(/^Error: shared-folder write budget/);expect(writes).toEqual(['/tmp/shared/a.md', '/tmp/shared/b.md']);- const p = await tools.write_file.execute!({ path: '/tmp/ws/notes.md', content: 'x'.repeat(5000) }, {} as any);+ const p = await tools.write_file.execute!({ path: '/tmp/ws/notes.md', content: 'x'.repeat(5000) }, {} as never);expect(String(p)).toBe('Wrote /tmp/ws/notes.md');// Relative paths resolve against the private workspace, not the shared folder.- const r = await tools.write_file.execute!({ path: 'draft.md', content: 'x' }, {} as any);+ const r = await tools.write_file.execute!({ path: 'draft.md', content: 'x' }, {} as never);expect(String(r)).toBe('Wrote draft.md');});});diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.tsindex a3371b0a..112f186f 100644--- a/src/bots/bot-turn.ts+++ b/src/bots/bot-turn.ts@@ -1,5 +1,5 @@import { streamText, stepCountIs } from 'ai';-import type { Tool } from 'ai';+import type { ModelMessage, Tool } from 'ai';import { isAbsolute, relative, resolve } from 'node:path';import type { CapabilityRegistry } from '../capabilities/registry.js';import type { UserMemoryStore } from '../memory/user-memory.js';@@ -191,7 +191,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {const startedAt = Date.now();const system = buildBotSystemPrompt(input);- const messages: any[] = [];+ const messages: ModelMessage[] = [];for (const m of input.mail) {messages.push({ role: 'user', content: `Message from 🤖 ${m.from}:\n\n${m.content}` });@@ -206,7 +206,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {let tokensIn = 0;let tokensOut = 0;let peakInputTokens = 0;- let lastResult: any = null;+ let lastResult: { text: string; finishReason: unknown } | null = null;let stepsRemaining = maxSteps;let budgetContinuations = 0;let stepIndex = 0;@@ -280,7 +280,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {// Context compaction: every step re-sends the whole conversation, so// 25 steps of 60KB tool results is a multi-megatoken prompt. Keep// the newest results verbatim (capped), stub the rest.- prepareStep: ({ messages: stepMessages }: any) => ({ messages: compactMessages(stepMessages, limits) }),+ prepareStep: ({ messages: stepMessages }: { messages: ModelMessage[] }) => ({ messages: compactMessages(stepMessages, limits) }),experimental_onStepStart: () => {stepIndex++;emit({ kind: 'step', stepIndex, label: `step ${stepIndex}` });@@ -300,7 +300,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {elapsedMs: typeof durationMs === 'number' ? durationMs : undefined,});},- onStepFinish: ({ usage, toolCalls, toolResults }: any) => {+ onStepFinish: ({ usage, toolCalls, toolResults }: { usage?: { inputTokens?: number; outputTokens?: number }; toolCalls?: unknown[]; toolResults?: unknown[] }) => {if (governor.signal.aborted) return;stepsRemaining--;if (usage) {@@ -308,9 +308,9 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {tokensOut += usage.outputTokens ?? 0;peakInputTokens = Math.max(peakInputTokens, usage.inputTokens ?? 0);}- for (const tc of toolCalls ?? []) {+ for (const tc of (toolCalls ?? []) as Array<{ toolName?: string; toolCallId?: string }>) {if (tc?.toolName) toolsUsed.add(String(tc.toolName));- trace.push(traceEntry(tc, (toolResults ?? []).find((r: any) => r?.toolCallId && r.toolCallId === tc?.toolCallId)));+ trace.push(traceEntry(tc, ((toolResults ?? []) as Array<{ toolCallId?: string; output?: ToolOutput }>).find((r) => r?.toolCallId !== undefined && r.toolCallId === tc?.toolCallId)));}const kIn = Math.round(tokensIn / 100) / 10;emit({ kind: 'step', stepIndex, label: `step ${stepIndex} · ${kIn}k tok in` });@@ -345,7 +345,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {// The provider's real error. Without this, `stream.text` below// throws the generic "No output generated" and the journal never// learns it was an invalid key or a 429.- streamError = (part as any).error ?? streamError;+ streamError = (part as { error?: unknown }).error ?? streamError;}if (Date.now() - lastEmit >= THINKING_EMIT_INTERVAL_MS) flushThinking();}@@ -362,7 +362,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {lastResult = result;const completion = classifyStreamCompletion({- finishReason: (result as any)?.finishReason,+ finishReason: result.finishReason as never,hasText: Boolean(result?.text),hasToolCalls: true,});@@ -382,7 +382,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {// the budget redoing the first 25 steps. The per-turn token cap is the// runaway guard; past the continuation bound the paused return below// still applies.- if (stepsRemaining <= 0 && (lastResult as any)?.finishReason === 'tool-calls') {+ if (stepsRemaining <= 0 && lastResult?.finishReason === 'tool-calls') {if (!governor.signal.aborted && budgetContinuations < MAX_AUTOMATIC_CONTINUATIONS) {budgetContinuations++;logger.warn(@@ -433,7 +433,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {// Step budget exhausted with tool calls still pending — pause, never// report success on half-done work (sub-agent completion contract).// Last resort only: reached past the in-process continuation bound.- if (stepsRemaining <= 0 && (lastResult as any)?.finishReason === 'tool-calls') {+ if (stepsRemaining <= 0 && lastResult?.finishReason === 'tool-calls') {emit({ kind: 'turn-end', stepIndex, label: 'paused — step budget', status: 'done' });return {status: 'paused',@@ -460,7 +460,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {emit({ kind: 'turn-end', stepIndex, label: outcome === 'none' && expects === 'work' ? 'completed — no deliverable' : 'completed', status: 'done' });return { status: 'completed', output, outcome, claimedWithoutAction, ...baseOutput() };- } catch (err: any) {+ } catch (err) {if (halted()) {emit({ kind: 'turn-end', stepIndex, label: 'halted', status: 'done' });return { status: 'halted', output: 'Turn was halted.', outcome: 'none', claimedWithoutAction: false, ...baseOutput() };@@ -468,11 +468,12 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {if (governorReason) {return governedFailure(governorReason, lastResult?.text, limits, baseOutput(), input, trace, deliveries, expects, emit, stepIndex);}- emit({ kind: 'turn-end', stepIndex, label: `failed: ${String(err?.message ?? err).slice(0, 80)}`, status: 'error' });+ const message = err instanceof Error ? err.message : String(err);+ emit({ kind: 'turn-end', stepIndex, label: `failed: ${message.slice(0, 80)}`, status: 'error' });return {status: 'failed',- output: `Turn failed: ${err?.message ?? String(err)}`,- error: err?.message ?? String(err),+ output: `Turn failed: ${message}`,+ error: message,reasonCode: classifyFailure(err),outcome: computeOutcome({ trace, deliveries, expects, text: '', sandbox: input.sandbox }),claimedWithoutAction: false,@@ -542,8 +543,8 @@ export function resolveTurnLimits(manifest: BotManifest, overrides?: Partial<Bot}/** Map a provider/tool error to a typed reason code (retry vs permanent). */-export function classifyFailure(err: any): string {- let msg = String(err?.message ?? err ?? '').toLowerCase();+export function classifyFailure(err: unknown): string {+ let msg = String((err as { message?: unknown })?.message ?? err ?? '').toLowerCase();// Retry wrappers ("Failed after 3 attempts. Last error: …") carry the// real cause after the colon — classify that, not the wrapper.const inner = /last error:\s*(.+)$/s.exec(msg);@@ -584,11 +585,14 @@ export function isTurnLimitFailure(reasonCode: string | undefined): boolean {// ---- outcome verdict -------------------------------------------------------function traceEntry(toolCall: any, toolResult: any): BotToolTraceEntry {+type ToolOutput = { type?: string; value?: unknown } | string | undefined;++function traceEntry(toolCall: { toolName?: string; input?: unknown } | undefined, toolResult: { output?: ToolOutput } | undefined): BotToolTraceEntry {const name = String(toolCall?.toolName ?? 'tool');const inputArgs = (toolCall?.input ?? {}) as Record<string, unknown>;- const text = toolResultText(toolResult?.output);- const failedOutput = toolResult?.output?.type === 'error-text' || toolResult?.output?.type === 'error-json';+ const output = toolResult?.output;+ const text = toolResultText(output);+ const failedOutput = typeof output === 'object' && (output?.type === 'error-text' || output?.type === 'error-json');const ok = toolResult !== undefined && !failedOutput && !isFailedToolResult(text);const arg = typeof inputArgs.path === 'string' ? inputArgs.path: typeof inputArgs.command === 'string' ? inputArgs.command@@ -598,13 +602,13 @@ function traceEntry(toolCall: any, toolResult: any): BotToolTraceEntry {return { name, ok, arg, ...(inputArgs.task === true ? { task: true } : {}) };}-function toolResultText(output: any): string {+function toolResultText(output: ToolOutput): string {if (!output) return '';+ if (typeof output === 'string') return output;if (output.type === 'text' || output.type === 'error-text') return String(output.value ?? '');if (output.type === 'json' || output.type === 'error-json') {try { return JSON.stringify(output.value ?? ''); } catch { return ''; }}- if (typeof output === 'string') return output;return '';}@@ -664,11 +668,13 @@ function noOutcomePrompt(input: BotTurnInput): string {* with a short stub. The model can re-run a tool it still needs; it cannot* afford to re-send 60KB of every file it ever read on every step.*/-export function compactMessages(messages: any[], limits: Pick<BotTurnLimits, 'keepRecentToolResults' | 'maxToolResultChars'>): any[] {+type ToolResultPart = { type: 'tool-result'; toolName?: string; output?: ToolOutput };++export function compactMessages(messages: ModelMessage[], limits: Pick<BotTurnLimits, 'keepRecentToolResults' | 'maxToolResultChars'>): ModelMessage[] {const resultRefs: Array<{ mi: number; pi: number }> = [];messages.forEach((m, mi) => {if (m?.role !== 'tool' || !Array.isArray(m.content)) return;- m.content.forEach((p: any, pi: number) => {+ (m.content as unknown as Array<{ type?: string }>).forEach((p, pi) => {if (p?.type === 'tool-result') resultRefs.push({ mi, pi });});});@@ -676,9 +682,11 @@ export function compactMessages(messages: any[], limits: Pick<BotTurnLimits, 'keconst stubBefore = Math.max(0, resultRefs.length - limits.keepRecentToolResults);const out = messages.slice();resultRefs.forEach(({ mi, pi }, idx) => {- const part = out[mi].content[pi];- const text = toolResultText(part.output);- if (part.output?.type === 'content') return; // media parts: leave alone+ const content = out[mi].content as unknown as ToolResultPart[];+ const part = content[pi];+ const output = part.output;+ const text = toolResultText(output);+ if (typeof output === 'object' && output?.type === 'content') return; // media parts: leave alonelet next: string | null = null;if (idx < stubBefore) {if (text.length > 400) {@@ -688,8 +696,8 @@ export function compactMessages(messages: any[], limits: Pick<BotTurnLimits, 'kenext = `${text.slice(0, limits.maxToolResultChars)}\n[…truncated ${text.length - limits.maxToolResultChars} chars]`;}if (next === null) return;- if (out[mi] === messages[mi]) out[mi] = { ...messages[mi], content: messages[mi].content.slice() };- out[mi].content[pi] = { ...part, output: { type: 'text', value: next } };+ if (out[mi] === messages[mi]) out[mi] = { ...messages[mi], content: (messages[mi].content as unknown as ToolResultPart[]).slice() } as ModelMessage;+ (out[mi].content as unknown as ToolResultPart[])[pi] = { ...part, output: { type: 'text', value: next } };});return out;}@@ -709,12 +717,13 @@ export function wrapBotTools(const out: Record<string, Tool> = { ...tools };const shared = { files: new Set<string>(), bytes: 0 };const { sharedWrites } = ctx.limits;- type Exec = (args: any, options: any) => Promise<unknown>;- const wrap = (name: string, fn: (original: Exec, args: any, options: any) => Promise<unknown>): void => {+ type ToolArgs = Record<string, unknown>;+ type Exec = (args: ToolArgs, options: unknown) => Promise<unknown>;+ const wrap = (name: string, fn: (original: Exec, args: ToolArgs, options: unknown) => Promise<unknown>): void => {const original = tools[name];if (!original || typeof original.execute !== 'function') return;const exec = original.execute.bind(original) as Exec;- out[name] = { ...original, execute: (args: any, options: any) => fn(exec, args, options) } as Tool;+ out[name] = { ...original, execute: (args: ToolArgs, options: unknown) => fn(exec, args, options) } as Tool;};wrap('bot_deliver', async (exec, args, options) => {diff --git a/src/bots/journal.ts b/src/bots/journal.tsindex c2100993..733ca3c1 100644--- a/src/bots/journal.ts+++ b/src/bots/journal.ts@@ -1,6 +1,7 @@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, BOT_TRANSCRIPTS_DIRNAME, assertValidBotId } from './store.js';+import { logger } from '../utils/logger.js';import type { BotRunRecord } from './types.js';/**@@ -41,8 +42,8 @@ export class BotJournal {try { rmSync(join(dir, stale)); } catch { /* best effort */ }}return file;- } catch (err: any) {- console.error(`[bots] transcript write failed for ${record.botId}: ${err?.message}`);+ } catch (err) {+ logger.warn({ botId: record.botId, err: (err as Error)?.message }, 'Bot transcript write failed');return null;}}diff --git a/src/bots/store.ts b/src/bots/store.tsindex 2eed0846..a312e9df 100644--- a/src/bots/store.ts+++ b/src/bots/store.ts@@ -57,17 +57,20 @@ export function defaultDeliverablesRoot(): string {}/** A folder name a person recognises: the bot's display name, filesystem-safe. */+/** Drop filesystem-hostile characters: the reserved set plus ASCII control codes. */+function stripUnsafeChars(text: string): string {+ return [...text].filter((ch) => ch.charCodeAt(0) >= 32 && !'<>:"/\\|?*'.includes(ch)).join('');+}+export function deliverablesFolderName(name: string, id: string): string {- const clean = name.replace(/[<>:"/\\|?*\x00-\x1f]/g, '').replace(/\s+/g, ' ').trim().slice(0, 60);+ const clean = stripUnsafeChars(name).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, '')+ const title = stripUnsafeChars(stemOrTitle.replace(/^\d{4}-\d{2}-\d{2}[ _-]*/, '')).replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim()@@ -275,8 +278,8 @@ export class BotStore {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');+ } catch (err) {+ logger.warn({ botId: id, err: (err as Error)?.message }, 'Could not persist routine state');}}