Skip to content

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

feat(skills): generic built-in skills; no fuzzy routing; retire one-owner defaults (ADR-040)

Salman Qureshi234b4ab02412
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1df2bcc6..8a28cb64 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,12 @@
## Unreleased
+### Skills
+- **Six useful built-in skills.** Alongside `web-search`: `computer-health` (why the computer is slow or full, what's running, why a container is down), `tidy-files` (clean up and sort folders safely), `data-analysis` (spreadsheets and CSVs, computed and checked), `long-documents` (long PDFs and logs, with page references) and `documents` (make or convert Word, PDF and slides). None of them can act without asking. Each is installed once: delete one and it stays deleted.
+- **`tweet-notifier` and `screenshot` are no longer installed or reinstalled on start.** If your copy is exactly as Mercury installed it, it's moved to `~/.mercury/skills/_retired-<name>/` (nothing is deleted). A copy you edited stays as it is.
+- **No more guessing which skill you meant.** Mercury no longer matches your message to skills by similar words. The model picks a skill when its description fits, or you pick one with `#skill-name`.
+- **No default skill can run commands without asking.** The old `screenshot` skill let shell commands and file writes skip approval while it was in use.
+
### Token usage
- **Token usage is now counted correctly** (#296, thanks @parz1val-t). Mercury used to record only the last model call of each turn, under-reporting usage by about 6–12×. Every call is now counted, including the steps of a turn that ended early (a failed provider, a pause), so `dailyBudget` fills up and Token Saver kicks in much sooner than before. If you hit the budget earlier than expected, raise `tokens.dailyBudget`, or set `tokens.cachedWeight` (0–1, e.g. `0.1`) to count prompt-cache hits at a discount. `/budget` now shows today's cached, uncached and output split. Usage from past days is not recalculated.
- **Each provider is billed for its own steps** when a turn moves from one provider to another.
diff --git a/DECISIONS.md b/DECISIONS.md
index 234c3aab..ad94ff55 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -433,3 +433,21 @@
- **First-response window.** With no chunk of any kind within 150 s (`MERCURY_FIRST_RESPONSE_TIMEOUT_MS`, 0 = off), the attempt is treated as stalled and the next provider in the chain takes over.
- **draw.io tools** join Spotify as a niche group, sent only when the turn is about diagrams.
- **Consequence**: A new turn's request is mostly cache reads on every provider, a multi-step Anthropic turn is billed close to linearly instead of quadratically, and nothing waits on a picker before the model runs. On a model that ignores suggestions, a skill that the old forced routing would have run now has to be picked by the model. Hidden-reasoning models that think for over 150 s before their first token fall back to the next provider unless the window is raised.
+
+## ADR-040: Generic built-in skills; skills are chosen by the model or the user, never by a fuzzy matcher
+
+- **Context**:
+ - **Three defaults were reseeded on every start.** A deleted copy came back:
+ - `web-search`
+ - `tweet-notifier`: one owner's tweet-approval workflow, naming "Optimus Prime" as the founder and Telegram supporters. Wrong for everyone else.
+ - `screenshot`: assumed Playwright and Chromium were "installed globally on this system", and its `allowed-tools` (`run_command`, `create_file`, `write_file`, `send_file`, …) made shell commands and file writes prompt-free for the turn through `elevateForSkill`.
+ - **The intent router scored messages fuzzily.** It counted single shared keywords, word-pair similarity and words from skill descriptions. After ADR-039 its only use was a suggestion in the per-turn context, which duplicated the skill list the model already reads in the system prompt.
+- **Decision**:
+ - **Built-in skills are generic procedures only.** Alongside `web-search`, there are five more: `computer-health` (read-only diagnostics per OS), `tidy-files` (plan → yes → move to `_to-delete`, never delete), `data-analysis` (compute with code, check totals), `long-documents` (read in sections, cite pages or lines) and `documents` (pandoc or a script, verify the file opens). To qualify, a default uses only tools Mercury has, lists no `allowed-tools` that could make actions prompt-free, works on macOS, Linux, Windows and Termux, and doesn't duplicate a built-in mode. Each default is installed once (`.seeded-defaults.json`): an edit is kept and a deletion is respected.
+ - **The old defaults are retired.** `tweet-notifier` and `screenshot` are no longer seeded. A user copy whose SHA-256 matches a version Mercury ever seeded (`RETIRED_SEEDS`, taken from git history) was never edited, and moves to `_retired-<name>`, which isn't loaded and isn't deleted. An edited copy is the owner's skill and stays.
+ - **No automatic skill routing.** `#skill-name` is the user's explicit pick. Otherwise the model chooses from the skill list and descriptions in the system prompt. The pre-model batch executor is gone from the agent.
+ - **The router keeps exact matching only:** whole-phrase intents and whole-word tags. The keyword-overlap, word-pair and description layers are removed.
+- **Consequence**:
+ - Fresh installs carry six general-purpose skills, and nothing reinstalls a skill the owner removed.
+ - No default skill can make shell commands prompt-free.
+ - A skill gets used when its description fits or when the user names it. Skill authors should write descriptions that say plainly when to use the skill.
diff --git a/src/core/agent.ts b/src/core/agent.ts
index ff77a35e..1ec13f1f 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -35,7 +35,6 @@ import { ProgrammingMode, scopedProgrammingState, type ProgrammingSnapshot } fro
import { ResearchMode } from './research-mode.js';
import { SaverMode, NORMAL_HISTORY_WINDOW } from './saver-mode.js';
import { BackgroundTaskManager } from './background-tasks.js';
-import { SkillBatcher } from '../skills/batcher.js';
import type { SkillLoader } from '../skills/loader.js';
import { logger } from '../utils/logger.js';
import { refinePersona } from '../bots/persona-template.js';
@@ -637,20 +636,6 @@ export function laneKeyFor(msg: ChannelMessage): string {
return `${msg.channelType}:${conversation}`;
}
-/**
- * The owner's own words, for skill routing: what a channel says they said
- * (`metadata.routingText`), else the message without a leading `[...]`
- * channel note (voice wrappers carry Mercury's own instructions, which named
- * web_search and made every voice question "match" the web-search skill).
- */
-export function routingTextOf(msg: ChannelMessage): string {
- const given = msg.metadata?.routingText;
- if (typeof given === 'string') return given.trim();
- const text = msg.content.trim();
- const note = /^\[[^\]]*\][^\n]*\n/.exec(text);
- return (note ? text.slice(note[0].length) : text).trim();
-}
-
export class Agent {
private readonly globalLifecycle: Lifecycle;
readonly scheduler: Scheduler;
@@ -828,7 +813,6 @@ export class Agent {
readonly researchMode: ResearchMode;
readonly saverMode: SaverMode;
spotifyClient?: SpotifyClient;
- private skillBatcher: SkillBatcher | null = null;
private skillLoader?: SkillLoader;
readonly backgroundTasks: BackgroundTaskManager;
private titleGenerationInFlight = new Set<string>();
@@ -908,9 +892,6 @@ export class Agent {
setSkillLoader(skillLoader: SkillLoader): void {
this.skillLoader = skillLoader;
- if (this.supervisor) {
- this.skillBatcher = new SkillBatcher(this.supervisor, this.backgroundTasks);
- }
}
/** Wire the Mercury Bots runtime (see bots/bot-manager.ts, BOTS-ARCHITECTURE.md). */
@@ -1012,9 +993,6 @@ export class Agent {
setSupervisor(supervisor: import('../core/supervisor.js').SubAgentSupervisor): void {
this.supervisor = supervisor;
- if (this.skillLoader) {
- this.skillBatcher = new SkillBatcher(supervisor, this.backgroundTasks);
- }
supervisor.setSaverMode(this.saverMode);
supervisor.setNotifyCallback(async (channelType, channelId, message) => {
const channel = this.channels.get(channelType as any);
@@ -3247,67 +3225,36 @@ export class Agent {
}
/**
- * Skill intent routing and batch execution (see the strategy note at the
- * call site): an explicit `#skill` pick, a clear multi-skill batch, or an
- * ambiguous match the user disambiguates. May rewrite or append to
- * `messages`; never ends the turn on its own.
- */
- /**
- * Skill routing (ADR-039). Two things only, and nothing blocks the turn:
- * - `#skill-name …` is the user's explicit pick: the model is told to use it.
- * - otherwise the router may *suggest* skills in the per-turn context; the
- * model decides. It used to stop the turn on a skill picker before the
- * first model call (2 minutes on the desktop, then the first option), to
- * answer that picker itself on voice channels, and to tell the model
- * "User clarified: use X" although nobody had — and to run whole skill
- * batches as sub-agents before the model was even asked.
- * Routing reads the owner's own words (`metadata.routingText`, or the
- * message without a leading channel note), never Mercury's own wrapper text.
- * Returns the hint for the per-turn context, or '' for none.
+ * The user's explicit skill pick (ADR-039, ADR-040): `#skill-name …` tells
+ * the model to use that skill; an unknown `#tag` is stripped. Nothing else
+ * is routed — the model sees every installed skill and its description in
+ * the system prompt and picks itself. Mercury used to stop the turn on a
+ * skill picker before the first model call, answer that picker itself on
+ * voice channels, tell the model "User clarified: use X" although nobody
+ * had, run skill batches as sub-agents up front, and later suggest skills
+ * from a fuzzy match.
*/
- private async routeSkillIntent(msg: ChannelMessage, trimmed: string, messages: Array<{ role: string; content: unknown }>): Promise<string> {
- if (!this.skillLoader || msg.channelType === 'internal') return '';
+ private applyExplicitSkillPick(msg: ChannelMessage, trimmed: string, messages: Array<{ role: string; content: unknown }>): void {
+ if (!this.skillLoader || msg.channelType === 'internal') return;
+ const hashMatch = trimmed.match(/^#([a-z0-9_:.-]+)\b\s*(.*)$/i);
+ if (!hashMatch) return;
try {
- const intentRouter = this.skillLoader.intentRouter;
- if (!intentRouter || !intentRouter.isInitialized()) return '';
-
- // (1) Explicit `#skill-name <rest>` shortcut from the # picker.
- const hashMatch = trimmed.match(/^#([a-z0-9_:.-]+)\b\s*(.*)$/i);
- if (hashMatch) {
- const skillName = hashMatch[1];
- const rest = hashMatch[2].trim();
- const knownSkills = this.skillLoader.getDiscovered?.() || [];
- if (knownSkills.some((s: any) => s.name === skillName)) {
- messages[messages.length - 1] = { role: 'user', content: rest || trimmed };
- messages.push({
- role: 'user',
- content: `[Routing] The user explicitly selected the \`${skillName}\` skill via #-prefix. Invoke it via \`use_skill\` with name="${skillName}" before doing anything else, then act on the result.`,
- });
- } else {
- // Unknown #tag: just strip it.
- const stripped = rest || trimmed.replace(/^#\S+\s*/, '');
- if (stripped) messages[messages.length - 1] = { role: 'user', content: stripped };
- }
- return '';
- }
-
- // (2) A suggestion, never a gate.
- const text = routingTextOf(msg);
- if (!text) return '';
- const analysis = intentRouter.analyzeMatch(text, { clearThreshold: 0.85, gap: 0.15 });
- const candidates = analysis.clearWinner && analysis.top
- ? [analysis.top]
- : analysis.ambiguous ? analysis.closeContenders.slice(0, 3) : [];
- if (candidates.length === 0) return '';
- this.markProgress(`Possible skills: ${candidates.map((c) => c.name).join(', ')}`);
- const lines = candidates.map((c) => {
- const desc = intentRouter.getSkillDescription?.(c.name) || '';
- return `- ${c.name}${desc ? ` — ${desc.slice(0, 160)}` : ''}`;
- });
- return `Skills that may fit this message (use one with use_skill only if it actually fits; otherwise answer directly):\n${lines.join('\n')}`;
+ const skillName = hashMatch[1];
+ const rest = hashMatch[2].trim();
+ const knownSkills = this.skillLoader.getDiscovered?.() || [];
+ if (knownSkills.some((s: any) => s.name === skillName)) {
+ messages[messages.length - 1] = { role: 'user', content: rest || trimmed };
+ messages.push({
+ role: 'user',
+ content: `[Routing] The user explicitly selected the \`${skillName}\` skill via #-prefix. Invoke it via \`use_skill\` with name="${skillName}" before doing anything else, then act on the result.`,
+ });
+ } else {
+ // Unknown #tag: just strip it.
+ const stripped = rest || trimmed.replace(/^#\S+\s*/, '');
+ if (stripped) messages[messages.length - 1] = { role: 'user', content: stripped };
+ }
} catch (err) {
- logger.warn({ err }, 'Intent routing failed — continuing without it');
- return '';
+ logger.warn({ err }, 'Explicit skill pick failed — continuing without it');
}
}
@@ -3711,7 +3658,7 @@ export class Agent {
if (!canonicalSessionId) messages.push({ role: 'user', content: msg.content });
- let volatileSystem = [
+ const volatileSystem = [
promptParts.dynamic,
contextBlocks.length > 0 ? `## Context for this turn\n\n${contextBlocks.join('\n\n')}` : '',
].filter(Boolean).join('\n\n');
@@ -3724,22 +3671,11 @@ export class Agent {
recentMemory.map((m) => m.content),
);
- // ── Skill Intent Routing & Batch Execution ──
- //
- // Routing strategy:
- // 1. Explicit pick via `#skill-name` prefix → run that skill directly,
- // no ambiguity resolution needed.
- // 2. Otherwise consult the intent router:
- // - Clear winner (high confidence + clear gap) → let the LLM invoke
- // it normally via use_skill (single skill) OR batch-execute when
- // the top batch is multi-skill in the same category.
- // - Ambiguous (multiple contenders bunched near the top) → ask the
- // user to disambiguate before doing anything.
- // - No usable match → fall through to the normal LLM loop.
// A command that reached the model is a real turn after all.
raiseTurnIndicator();
- const routingHint = await this.routeSkillIntent(msg, trimmed, messages);
- if (routingHint) volatileSystem = volatileSystem ? `${volatileSystem}\n\n${routingHint}` : routingHint;
+ // `#skill-name` is the user's explicit pick; any other skill choice is
+ // the model's (ADR-040).
+ this.applyExplicitSkillPick(msg, trimmed, messages);
this.lifecycle.transition('responding');
diff --git a/src/core/skill-routing.test.ts b/src/core/skill-routing.test.ts
index 0d5ce233..9ed51453 100644
--- a/src/core/skill-routing.test.ts
+++ b/src/core/skill-routing.test.ts
@@ -1,29 +1,11 @@
import { describe, expect, it } from 'vitest';
-import type { ChannelMessage } from '../types/channel.js';
-import { routingTextOf } from './agent.js';
import { IntentRouter } from '../skills/intent-router.js';
-/** ADR-039: skills are routed on the owner's own words, whole words only, and only ever suggested. */
-
-const msg = (content: string, metadata: Record<string, unknown> = {}): ChannelMessage =>
- ({ id: 'm', channelId: 'c', channelType: 'web', senderId: 'u', content, timestamp: 0, metadata });
-
-describe('routing text', () => {
- it("uses the channel's own record of what the owner said", () => {
- expect(routingTextOf(msg('[Voice …web_search for anything current…]\nwhat is running?', { routingText: 'what is running?' }))).toBe('what is running?');
- });
-
- it('drops a leading [channel note] line, never the owner text', () => {
- expect(routingTextOf(msg('[Voice, on the owner\'s computer: use web_search, skills…]\nWhat containers are up?'))).toBe('What containers are up?');
- expect(routingTextOf(msg('search for [brackets] in my notes'))).toBe('search for [brackets] in my notes');
- expect(routingTextOf(msg(' hi '))).toBe('hi');
- });
-});
-
+/** ADR-039/040: skill intents match exactly — whole phrases and whole words, never a fuzzy guess. */
describe('intent matching', () => {
const router = new IntentRouter();
- router.buildIndex([{ name: 'web-search', description: 'Search the web' }, { name: 'history', description: 'Browser history' }] as never);
- router.registerSkillMeta({ name: 'web-search', description: 'Search the web', intents: ['search for', 'look this up'] } as never);
+ router.buildIndex([{ name: 'web-search', description: 'Search the web for current news' }, { name: 'history', description: 'Browser history' }] as never);
+ router.registerSkillMeta({ name: 'web-search', description: 'Search the web for current news', intents: ['search for', 'look this up'], tags: ['websearch'] } as never);
router.registerSkillMeta({ name: 'history', description: 'Browser history', intents: ['show this history'] } as never);
it('a greeting matches nothing (it used to match inside "this" and "history")', () => {
@@ -31,9 +13,15 @@ describe('intent matching', () => {
expect(router.analyzeMatch('Hi').clearWinner).toBe(false);
});
- it('real requests still match on whole words', () => {
+ it('real requests still match on whole phrases and tags', () => {
expect(router.match('search for flights to Lisbon')[0]?.name).toBe('web-search');
expect(router.match('please look this up')[0]?.name).toBe('web-search');
- expect(router.match('research for my thesis').some((m) => m.name === 'web-search' && m.confidence >= 0.95)).toBe(false);
+ expect(router.match('use websearch please')[0]?.name).toBe('web-search');
+ });
+
+ it('no fuzzy matches: a shared word, a similar word or a description word is not a match', () => {
+ expect(router.match('research for my thesis')).toEqual([]);
+ expect(router.match('what is the current status of my history homework')).toEqual([]);
+ expect(router.match('searching news for things')).toEqual([]);
});
});
diff --git a/src/core/slash-command-indicator.test.ts b/src/core/slash-command-indicator.test.ts
index 6a33142f..f8a878aa 100644
--- a/src/core/slash-command-indicator.test.ts
+++ b/src/core/slash-command-indicator.test.ts
@@ -21,7 +21,7 @@ describe('slash commands do not show the processing indicator', () => {
});
it('raises the indicator again right before a fallen-through command reaches the model', () => {
- const idx = agent.indexOf('await this.routeSkillIntent(msg, trimmed, messages);');
+ const idx = agent.indexOf('this.applyExplicitSkillPick(msg, trimmed, messages);');
expect(idx).toBeGreaterThan(0);
expect(agent.slice(idx - 200, idx)).toContain('raiseTurnIndicator();');
});
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 0e33d3ac..a723ad0a 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -409,7 +409,7 @@ export class PluginChannel extends BaseChannel {
senderRole: 'admin',
content: this.desktop ? `${DESKTOP_VOICE_NOTE}\n${question}` : `[Voice call: the owner asked this out loud. Use your tools to get the real answer: web_search for news and anything current, fetch_url, memory, skills. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Go ahead and do what they ask, including saving files or running things: if an action needs approval, Mercury asks the owner on the call and in the chat, and continues once they say yes. Don't ask them to confirm by message yourself. Links, lists, prices, addresses and other details worth keeping: never read them out. If they asked for them, send them with whatsapp__send_to_chat and say you've sent them to the chat. If you found something useful they didn't ask to receive, end your answer by offering to send it ("Want me to send the links to your chat?") and only send once they say yes. Whenever your answer involves links or details, add them after a final line "For the chat:" (that part isn't spoken, and lets you send them later without searching again).]${sentNote}\n${question}`,
timestamp: Date.now(),
- metadata: { pluginId: this.manifest.id, voiceCall: true, callId, routingText: question, attachments: files.slice(-4), channelAccess: this.accessFor('admin'), channelGuidance: this.guidance('admin', false, true) },
+ metadata: { pluginId: this.manifest.id, voiceCall: true, callId, attachments: files.slice(-4), channelAccess: this.accessFor('admin'), channelGuidance: this.guidance('admin', false, true) },
});
});
}
diff --git a/src/skills/default-skills-retire.test.ts b/src/skills/default-skills-retire.test.ts
new file mode 100644
index 00000000..1c59a174
--- /dev/null
+++ b/src/skills/default-skills-retire.test.ts
@@ -0,0 +1,121 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { SkillLoader } from './loader.js';
+import { DEFAULT_SKILL_SEEDS, RETIRED_SEEDS } from './default-skills.js';
+
+/**
+ * ADR-040: Mercury ships one default skill (web-search). Copies of the old
+ * defaults it seeded (tweet-notifier, screenshot) that the owner never
+ * edited are moved aside — not deleted — and never come back; edited copies
+ * are the owner's and stay.
+ */
+describe('default skills', () => {
+ let root: string;
+ const sha = (s: string) => createHash('sha256').update(s).digest('hex');
+ const original = structuredClone(RETIRED_SEEDS);
+
+ beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'mercury-default-skills-')); });
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+ for (const k of Object.keys(RETIRED_SEEDS)) delete RETIRED_SEEDS[k];
+ Object.assign(RETIRED_SEEDS, original);
+ });
+
+ const DEFAULTS = ['web-search', 'computer-health', 'tidy-files', 'data-analysis', 'long-documents', 'documents'];
+
+ it('ships the generic defaults, and a fresh install gets exactly those', () => {
+ expect(DEFAULT_SKILL_SEEDS.map((s) => s.dirName)).toEqual(DEFAULTS);
+ const names = new SkillLoader(join(root, 'skills')).discover().map((s) => s.name).sort();
+ expect(names).toEqual([...DEFAULTS].sort());
+ });
+
+ it('every default parses, says when to use it, and grants nothing (approval stays on)', () => {
+ const loader = new SkillLoader(join(root, 'skills'));
+ loader.discover();
+ for (const name of DEFAULTS) {
+ const skill = loader.load(name);
+ expect(skill, name).toBeTruthy();
+ expect(skill!.description.length, name).toBeGreaterThan(60);
+ expect(skill!.instructions.length, name).toBeGreaterThan(200);
+ if (name !== 'web-search') {
+ // Only web-search lists tools, and only ones that need no elevation.
+ expect(skill!['allowed-tools'] ?? [], name).toEqual([]);
+ }
+ }
+ expect(loader.load('web-search')!['allowed-tools']).toEqual(['web_search', 'fetch_url']);
+ });
+
+ it('installs a default once: a deleted one stays deleted', () => {
+ const dir = join(root, 'skills');
+ new SkillLoader(dir).discover();
+ rmSync(join(dir, 'tidy-files'), { recursive: true });
+ const names = new SkillLoader(dir).discover().map((s) => s.name);
+ expect(names).not.toContain('tidy-files');
+ expect(existsSync(join(dir, 'tidy-files'))).toBe(false);
+ });
+
+ it('an existing install gets defaults added later, once', () => {
+ const dir = join(root, 'skills');
+ mkdirSync(dir, { recursive: true });
+ // An install from before: web-search on disk, recorded as installed.
+ const web = DEFAULT_SKILL_SEEDS.find((s) => s.dirName === 'web-search')!;
+ mkdirSync(join(dir, 'web-search'));
+ writeFileSync(join(dir, 'web-search', 'SKILL.md'), web.content);
+ writeFileSync(join(dir, '.seeded-defaults.json'), JSON.stringify({ seeded: ['web-search'] }));
+ const names = new SkillLoader(dir).discover().map((s) => s.name).sort();
+ expect(names).toEqual([...DEFAULTS].sort());
+ expect(JSON.parse(readFileSync(join(dir, '.seeded-defaults.json'), 'utf8')).seeded).toEqual([...DEFAULTS].sort());
+ });
+
+ it('the old defaults are listed for retirement with the hashes of what was seeded', () => {
+ expect(Object.keys(RETIRED_SEEDS).sort()).toEqual(['screenshot', 'tweet-notifier']);
+ for (const hashes of Object.values(RETIRED_SEEDS)) for (const h of hashes) expect(h).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it('moves an untouched old default aside and does not reseed it', () => {
+ const untouched = '---\nname: tweet-notifier\ndescription: seeded\n---\n\nBody\n';
+ RETIRED_SEEDS['tweet-notifier'] = [sha(untouched)];
+ mkdirSync(join(root, 'tweet-notifier'), { recursive: true });
+ writeFileSync(join(root, 'tweet-notifier', 'SKILL.md'), untouched);
+
+ const names = new SkillLoader(root).discover().map((s) => s.name);
+ expect(names).not.toContain('tweet-notifier');
+ expect(names).toContain('web-search');
+ expect(existsSync(join(root, 'tweet-notifier'))).toBe(false);
+ // Kept, not deleted, in a folder the loader skips.
+ expect(readFileSync(join(root, '_retired-tweet-notifier', 'SKILL.md'), 'utf8')).toBe(untouched);
+ // A second start leaves everything as it is.
+ expect(new SkillLoader(root).discover().map((s) => s.name)).not.toContain('tweet-notifier');
+ expect(readdirSync(root).filter((d) => d.startsWith('_retired-'))).toEqual(['_retired-tweet-notifier']);
+ });
+
+ it("keeps an old default the owner edited — it's their skill now", () => {
+ RETIRED_SEEDS.screenshot = [sha('the seeded version')];
+ mkdirSync(join(root, 'screenshot'), { recursive: true });
+ const edited = '---\nname: screenshot\ndescription: my own screenshot flow\n---\n\nMine.\n';
+ writeFileSync(join(root, 'screenshot', 'SKILL.md'), edited);
+
+ expect(new SkillLoader(root).discover().map((s) => s.name)).toContain('screenshot');
+ expect(readFileSync(join(root, 'screenshot', 'SKILL.md'), 'utf8')).toBe(edited);
+ });
+});
+
+describe('skill list in the system prompt', () => {
+ it('lists every skill once, even one in several categories', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'mercury-skill-list-'));
+ try {
+ const loader = new SkillLoader(join(dir, 'skills'));
+ loader.discover();
+ const text = loader.getSkillSummariesText();
+ expect(text.split('- web-search:').length - 1).toBe(1);
+ for (const name of ['computer-health', 'tidy-files', 'data-analysis', 'long-documents', 'documents']) {
+ expect(text.split(`- ${name}:`).length - 1, name).toBe(1);
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/src/skills/default-skills.ts b/src/skills/default-skills.ts
index 9efea155..4928d3f5 100644
--- a/src/skills/default-skills.ts
+++ b/src/skills/default-skills.ts
@@ -249,259 +249,225 @@ then try one shorter or rephrased query.
`,
},
{
- dirName: 'tweet-notifier',
+ dirName: 'computer-health',
fileName: 'SKILL.md',
content: `---
-name: tweet-notifier
-description: Schedule tweets with notifications to founders and supporters. Alerts founders when tweets are scheduled, and notifies supporters (approved Telegram users) when tweets are pending approval.
+name: computer-health
+description: Check what's wrong with this computer or a service on it — disk space, memory, CPU, processes, open ports, Docker containers and their logs, battery — with read-only commands, then explain what was found before suggesting any fix.
version: 1.0.0
-category: social
-categories:
- - social
- - communication
-intents:
- - schedule tweet
- - approve tweet
- - post tweet
- - reject tweet
- - pending tweets
- - show tweets
- - notify supporters
- - cancel tweet
- - tweet approval
- - schedule a tweet
+category: system
tags:
- - twitter
- - tweet
- - scheduling
- - notification
- - social media
-allowed-tools:
- - schedule_task
- - send_message
- - save_memory
- - search_memory
- - fetch_url
- - github_api
+ - diagnostics
+ - disk
+ - memory
+ - processes
+ - docker
+ - ports
---
-# Tweet Notifier
+# Computer health
-Notification system for tweet scheduling and approval workflows. Alerts the founder (Optimus Prime) and supporters (approved Telegram users) at key states of the tweet lifecycle.
+Use this when the owner asks why the computer is slow, full, hot or noisy, what is running, what uses a port, or why a container or service is down.
-## States
+## Rules
-| State | Description | Notification Sent To |
-|---|---|---|
-| \`draft\` | Tweet is being composed | None (internal) |
-| \`scheduled\` | Tweet is queued with a time | Founder (send_message) |
-| \`pending_approval\` | Tweet needs review before posting | Founder + Supporters (send_message) |
-| \`approved\` | Tweet is cleared to post | Founder + Supporters |
-| \`posted\` | Tweet has been published | Supporters |
-| \`cancelled\` | Tweet was cancelled | Founder |
+- Look first, change nothing. Every command in "Checks" only reads. Anything that stops, deletes, restarts or installs is a separate step the owner agrees to.
+- Find the platform once (\`uname -s\`; on Windows the shell is PowerShell; on Android/Termux \`$PREFIX\` contains \`com.termux\`) and use the matching commands below.
+- Keep output small: sort, then \`head\` (PowerShell: \`Select-Object -First 15\`). Never dump a whole process list or log.
+- Report in plain words with the numbers that matter ("the disk is 94% full; 41 GB of it is ~/Library/Caches"), then the likely cause, then one or two fixes to choose from.
-## Workflow
+## Checks
-When the user wants to schedule or approve a tweet:
+| What | macOS | Linux / Termux | Windows (PowerShell) |
+|---|---|---|---|
+| Disk free | \`df -h /\` | \`df -h /\` (Termux: \`df -h $HOME\`) | \`Get-PSDrive -PSProvider FileSystem\` |
+| Biggest folders | \`du -sh ~/* 2>/dev/null \\| sort -rh \\| head -15\` | same | \`Get-ChildItem $HOME -Directory \\| ForEach-Object { [pscustomobject]@{Name=$_.Name; GB=[math]::Round((Get-ChildItem $_.FullName -Recurse -File -ErrorAction SilentlyContinue \\| Measure-Object Length -Sum).Sum/1GB,2)} } \\| Sort-Object GB -Descending \\| Select-Object -First 15\` |
+| Memory | \`vm_stat\`, \`memory_pressure\` | \`free -h\` | \`Get-CimInstance Win32_OperatingSystem \\| Select-Object FreePhysicalMemory,TotalVisibleMemorySize\` |
+| Top CPU / memory | \`ps -Ao pid,pcpu,pmem,comm -r \\| head -15\` | \`ps -eo pid,pcpu,pmem,comm --sort=-pcpu \\| head -15\` | \`Get-Process \\| Sort-Object CPU -Descending \\| Select-Object -First 15 Id,CPU,WS,ProcessName\` |
+| Who uses a port | \`lsof -nP -iTCP:PORT -sTCP:LISTEN\` | \`ss -ltnp \\| grep :PORT\` | \`Get-NetTCPConnection -LocalPort PORT -State Listen\` |
+| Uptime / load | \`uptime\` | \`uptime\` | \`(Get-CimInstance Win32_OperatingSystem).LastBootUpTime\` |
+| Battery | \`pmset -g batt\` | \`upower -i $(upower -e \\| grep BAT)\` (Termux: \`termux-battery-status\`) | \`Get-CimInstance Win32_Battery\` |
+
+## Docker and services
+
+1. \`docker ps -a --format '{{.Names}}\\t{{.Status}}\\t{{.Image}}'\` — what runs, what exited, what is unhealthy.
+2. For one container: \`docker logs --tail 80 NAME\` and, when it reports a health status, \`docker inspect --format '{{json .State.Health}}' NAME\`.
+3. Resource use: \`docker stats --no-stream\`.
+4. Services (Linux): \`systemctl --failed\` and \`journalctl -u NAME -n 80 --no-pager\`. macOS: \`launchctl list | grep -i NAME\`.
+
+Explain the error from the logs in one or two sentences and quote the decisive line. Restarting or rebuilding is the owner's call.
+`,
+ },
+ {
+ dirName: 'tidy-files',
+ fileName: 'SKILL.md',
+ content: `---
+name: tidy-files
+description: Organize, clean up or bulk-rename files and folders (Downloads, Desktop, photos, duplicates) safely — show the plan first, move instead of delete, and report exactly what changed.
+version: 1.0.0
+category: productivity
+tags:
+ - files
+ - cleanup
+ - organize
+ - rename
+ - duplicates
+---
-### 1. Schedule a Tweet
+# Tidy files
-1. Ask for the tweet content and desired posting time
-2. Use \`save_memory\` to store the tweet as a memory with type \`project\`:
- - Summary: "Tweet: [content preview] scheduled for [time]"
- - Include detail with full tweet content, scheduled time, status
-3. Use \`send_message\` to alert the founder:
- - \`📅 **Tweet Scheduled** — @[time]: "[content preview]"\\nStatus: pending_approval — needs review before posting.\`
-4. Use \`schedule_task\` to set a delayed task:
- - \`delay_seconds\`: seconds until posting time
- - \`description\`: "Post scheduled tweet: [content preview]"
- - \`prompt\`: "The following tweet is scheduled to post now. Check memory for full content and status. If approved, post it. If pending_approval, remind the user first."
+Use this when the owner asks to clean up, sort, deduplicate or rename many files.
-### 2. Tweet Requires Approval (Pending)
+## Workflow
-When a tweet is in \`pending_approval\` state:
+1. **Look.** \`list_dir\` the folder, then measure with \`run_command\`: how many files, how much space, which types (\`find DIR -type f | sed 's/.*\\.//' | sort | uniq -c | sort -rn | head\`). On Windows use PowerShell \`Get-ChildItem -Recurse -File | Group-Object Extension\`.
+2. **Plan.** Propose the rule in one or two sentences ("images into Pictures/2026, installers older than 30 days into _to-delete") and show a sample of what moves where with the total count.
+3. **Ask.** Get a clear yes (ask_user) before touching anything. A change of plan means a new plan and a new yes.
+4. **Move, don't delete.** Do it with one script or command for all files, not one call per file. Anything to remove goes into a dated folder such as \`_to-delete-2026-11-10\` inside the same folder, never straight to deletion. Never overwrite: add a suffix when a name already exists.
+5. **Report.** How many files moved, where to, how much space the \`_to-delete\` folder holds, and how to undo it (move the folder back). Deleting \`_to-delete\` for real is a separate yes.
-1. Use \`send_message\` to notify the founder:
- - \`✋ **Tweet Pending Approval** — "[content preview]"\\nPlease review and approve or reject this tweet.\\nTo approve, say: approve tweet [id]\\nTo reject, say: reject tweet [id]\`
-2. Use \`send_message\` to notify supporters (approved Telegram users):
- - \`📢 **New Tweet for Review** — A new tweet is pending approval:\\n> "[content preview]"\\nThe founder will review it shortly.\`
+## Duplicates
-### 3. Approve or Reject a Tweet
+Find them by content, not by name: group same-size files first, then hash only those (\`shasum -a 256\`, Linux \`sha256sum\`, PowerShell \`Get-FileHash\`). Keep the oldest copy, or the one in the better-named folder, and list the rest for \`_to-delete\`.
-When the user approves:
+## Never
-1. Use \`save_memory\` to update the tweet status to \`approved\`
-2. Use \`send_message\` to alert supporters:
- - \`✅ **Tweet Approved** — "[content preview]"\\nThis tweet has been approved and will be posted at [time].\`
-3. If immediate posting, use \`fetch_url\` or \`github_api\` as appropriate for the posting platform
-4. Use \`send_message\` to notify supporters after posting:
- - \`🐦 **Tweet Posted** — "[content preview]"\\nView it at: [url]\`
+- Touch system folders, app bundles, \`.git\` folders, or anything outside the folder the owner named.
+- Rename files a program depends on (projects, photo libraries, music libraries) without saying so first.
+`,
+ },
+ {
+ dirName: 'data-analysis',
+ fileName: 'SKILL.md',
+ content: `---
+name: data-analysis
+description: Analyse CSV, Excel or JSON data — look at the columns first, compute every number with a script instead of by eye, check the result, then summarize and chart it.
+version: 1.0.0
+category: productivity
+tags:
+ - data
+ - csv
+ - excel
+ - spreadsheet
+ - chart
+ - statistics
+---
-When the user rejects:
+# Data analysis
-1. Use \`save_memory\` to update the tweet status to \`cancelled\`
-2. Use \`send_message\` to notify supporters:
- - \`🚫 **Tweet Cancelled** — "[content preview]" was not approved for posting.\`
+Use this when the owner shares a spreadsheet, CSV or JSON file, or asks for totals, trends, comparisons or a chart from data.
-### 4. Check Scheduled Tweets
+## Workflow
-When asked "what tweets are scheduled" or "show pending tweets":
+1. **Inspect before computing.** Row count, column names and types, a few sample rows, empty values. For a small file \`read_file\` is enough; for a large one use \`run_command\` (\`head -5 file.csv\`, \`wc -l file.csv\`) or a short script.
+2. **Compute with code, never by reading numbers.** Write one short script (Python with pandas or the csv module; \`python3 -c "import pandas"\` tells you which is available) and run it with \`run_command\`. Print only the results, not whole tables.
+3. **Check.** Totals add up, row counts match, no column was parsed as text by mistake (currency signs, thousands separators, dates). Say what you cleaned and how.
+4. **Answer the question first**, with the key numbers, then the detail. State the time range and any rows you excluded.
+5. **Chart when it helps.** Save a PNG next to the data (matplotlib), name it after what it shows, and send it with \`send_file\` on chat channels. Label axes and units.
-1. Use \`search_memory\` with query "tweet" and type filter for \`project\`
-2. Summarize all tweets with their status, content preview, and scheduled time
-3. Present them grouped by status (pending_approval, approved, scheduled)
+## Rules
-## Notification Flow Examples
+- Never invent or round numbers you didn't compute.
+- Leave the original file unchanged; write results to a new file (\`name-summary.csv\`).
+- Excel: read with pandas (\`openpyxl\` engine). Say which sheet you used if there are several.
+- Money and percentages: keep the source's currency and say how you rounded.
+`,
+ },
+ {
+ dirName: 'long-documents',
+ fileName: 'SKILL.md',
+ content: `---
+name: long-documents
+description: Read and answer questions about long PDFs, logs, transcripts, books or code files — read them in sections, take notes as you go, and answer with page or line references instead of guessing from the first part.
+version: 1.0.0
+category: productivity
+tags:
+ - pdf
+ - documents
+ - logs
+ - summarize
+ - transcript
+---
+
+# Long documents
-### Founder Notification (via send_message)
-\`\`\`
-📅 Tweet Scheduled — @2:30 PM PST: "Exciting new features coming soon..."
-Status: pending_approval — needs review before posting.
-To approve, say: approve tweet t1
-To reject, say: reject tweet t1
-\`\`\`
+read_file returns at most 64 KB. Use this skill whenever a file is bigger than that, or the owner wants a summary, a specific detail or a comparison from a long file.
-### Supporter Notification (via send_message)
-\`\`\`
-📢 New Tweet for Review
+## Workflow
-A new tweet is pending approval:
+1. **Size it up.** \`wc -l FILE\` and \`ls -lh FILE\`. A PDF: \`pdfinfo FILE\` for pages, then \`pdftotext -layout FILE out.txt\` (if pdftotext is missing, use Python \`pypdf\`). Word files: \`pandoc FILE -t plain -o out.txt\`.
+2. **Find before you read.** For a specific question, search first: \`grep -n -i "term" FILE | head -30\`, then read just around the hits (\`sed -n '120,180p' FILE\`).
+3. **For a summary, read in sections** of about 300–500 lines (\`sed -n 'START,ENDp'\`), and keep short notes per section: what it covers and anything the owner is likely to ask about. Use the document's own headings or pages as section boundaries when it has them.
+4. **Answer from the notes**, citing where each point is (page, section heading or line numbers). Say if you only read part of the document and which part.
-> "Exciting new features coming soon..."
+## Logs
-The founder will review it shortly. Stay tuned!
-\`\`\`
+Start from the end (\`tail -200\`) and from errors (\`grep -n -iE "error|fail|exception|fatal" FILE | tail -40\`). Report the first error of a failure, not only the last one, with its timestamp.
-## Memory Schema
+## Rules
-Store each tweet as a memory with:
-- Type: \`project\`
-- Summary: \`Tweet: [preview] scheduled for [time] — status: [state]\`
-- Detail: \`{"content": "full tweet text", "scheduledAt": "ISO time", "status": "draft|scheduled|pending_approval|approved|posted|cancelled", "id": "unique-id"}\`
-- Confidence: 0.95
-- Importance: 0.8
+- Never claim the document says something you didn't read.
+- Quote exactly when the wording matters (contracts, specs, error messages).
`,
},
{
- dirName: 'screenshot',
+ dirName: 'documents',
fileName: 'SKILL.md',
content: `---
-name: screenshot
-description: Take full-page screenshots of any website with configurable viewport and color scheme (dark/light mode).
+name: documents
+description: Create or convert real files — Word, PDF, slides, spreadsheets, Markdown, HTML — with pandoc or a short script, check the result opens, and send it back.
version: 1.0.0
-category: media
-categories:
- - media
- - web
- - productivity
-intents:
- - take a screenshot
- - screenshot
- - capture website
- - screenshot website
- - web screenshot
- - capture page
- - screenshot of
- - take screenshot of
- - mobile screenshot
- - desktop screenshot
- - dark mode screenshot
- - light mode screenshot
+category: productivity
tags:
- - screenshot
- - website
- - capture
- - playwright
- - browser
- - viewport
- - dark mode
- - light mode
-allowed-tools:
- - run_command
- - create_file
- - write_file
- - send_file
- - cd
- - send_message
+ - documents
+ - pdf
+ - docx
+ - convert
+ - pandoc
+ - slides
---
-# Screenshot
-
-Take full-page screenshots of any website with Playwright. Supports configurable viewport dimensions and dark/light display modes.
+# Documents
-## Prerequisites
-
-Playwright and Chromium are already installed globally on this system. The skill will create and run a temporary Node.js script to handle each screenshot request.
+Use this when the owner wants a file they can open or share (a report, letter, CV, slide deck, spreadsheet), or a file converted from one format to another.
## Workflow
-When the user asks for a screenshot:
-
-1. **Ask for the URL** if not provided — ensure it includes the protocol (https://).
-2. **Ask for viewport / dimensions** if not specified:
- - \`mobile\` — iPhone-like viewport (375 × 812)
- - \`desktop\` — Standard desktop viewport (1280 × 800)
- - \`custom\` — Ask for specific width × height in pixels
- - Default: desktop (1280 × 800)
-3. **Ask for display mode** if not specified:
- - \`light\` — Light color scheme
- - \`dark\` — Dark color scheme (emulates prefers-color-scheme: dark)
- - Default: light
-4. **Generate a unique filename** — use the domain and a timestamp (e.g., \`example.com-2025-05-30-14-30-00.png\`). Store in \`~/Desktop/\` for easy access.
-5. **Create a temporary Playwright script** using \`create_file\` or \`write_file\`, then execute it with \`run_command\`.
-
-## Playwright Script Template
-
-Use this exact template, substituting the user's parameters:
-
-\`\`\`javascript
-import { chromium } from 'playwright';
-
-const url = '{{URL}}';
-const outputPath = '{{OUTPUT_PATH}}';
-const width = {{WIDTH}};
-const height = {{HEIGHT}};
-const colorScheme = '{{COLOR_SCHEME}}'; // 'light' or 'dark'
-
-const browser = await chromium.launch({ headless: true });
-const context = await browser.newContext({
- viewport: { width, height },
- colorScheme,
-});
-const page = await context.newPage();
-await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 });
-await page.screenshot({ path: outputPath, fullPage: true });
-await browser.close();
-console.log('Screenshot saved to:', outputPath);
-\`\`\`
-
-### Dark Mode Details
-
-To emulate dark mode, set \`colorScheme: 'dark'\` in the browser context options. This triggers \`prefers-color-scheme: dark\` media queries on the target website.
-
-## Preset Viewport Dimensions
-
-| Preset | Width | Height | Notes |
-|---|---|---|---|
-| Mobile | 375 | 812 | iPhone X/11/12/13/14 proportions |
-| Mobile Small | 320 | 568 | iPhone SE |
-| Mobile Large | 414 | 896 | iPhone Plus/Pro Max |
-| Tablet | 768 | 1024 | iPad portrait |
-| Desktop (default) | 1280 | 800 | Standard laptop |
-| Desktop Wide | 1440 | 900 | Standard desktop |
-| Desktop HD | 1920 | 1080 | Full HD |
-
-## Output
+1. **Agree on the content first** when it is new writing: a short outline, then the full text in Markdown.
+2. **Pick the tool.** Check what is installed (\`command -v pandoc\`, \`python3 -c "import docx"\`):
+ - Markdown → Word / HTML / EPUB: \`pandoc in.md -o out.docx\`.
+ - Markdown → PDF: \`pandoc in.md -o out.pdf\` (needs a PDF engine; if none, make HTML and print it to PDF with the browser, or use Python \`reportlab\`).
+ - Slides: \`pandoc in.md -o out.pptx\` (headings become slides; put each slide under its own heading).
+ - Spreadsheets: Python \`openpyxl\` or pandas \`to_excel\`.
+ - Anything → Markdown or text: \`pandoc FILE -t gfm\`; PDFs with \`pdftotext\`.
+ If the tool is missing, say which one and offer to install it, or use the next option.
+3. **One command for many files.** Converting a folder is one loop or one script, not one call per file.
+4. **Check the result.** The file exists, has a sensible size, and opens: convert it back to text and look at the start (\`pandoc out.docx -t plain | head -20\`, \`pdftotext out.pdf - | head -20\`).
+5. **Deliver.** Save it where the owner asked, otherwise in the working directory, with a clear name. On chat channels send it with \`send_file\`. Say where it is.
-- Screenshots are saved as PNG files to \`~/Desktop/\` with the naming pattern: \`<domain>-<YYYY-MM-DD-HH-MM-SS>.png\`
-- After the screenshot is taken, use \`send_file\` to deliver the image to the user.
-- If the user is on Telegram, the image will be sent as a photo attachment.
-
-## Error Handling
+## Rules
-- If the page fails to load (timeout, DNS error, etc.), retry once with \`waitUntil: 'domcontentloaded'\` instead of \`networkidle\`.
-- If Playwright encounters an installation issue, run \`npx playwright install chromium\` and retry.
-- Inform the user if a site blocks automated screenshots (e.g., CAPTCHA, bot detection).
+- Never overwrite the source file; write to a new name.
+- Keep the owner's wording in conversions; don't "improve" text you were asked to convert.
+- Fonts, logos and page size follow what the owner asked; otherwise use the tool's defaults.
`,
},
];
+
+/**
+ * Skills Mercury used to install on every start and no longer ships
+ * (ADR-040): `tweet-notifier` (one owner's workflow, wrong for everyone else)
+ * and `screenshot` (assumed a global Playwright install, and its
+ * allowed-tools elevated run_command and file writes to prompt-free for the
+ * turn). By SHA-256 of every version ever seeded: a copy that matches was
+ * never edited and is moved aside; an edited copy is the owner's and stays.
+ */
+export const RETIRED_SEEDS: Record<string, string[]> = {
+ 'tweet-notifier': [
+ '0b777896e3b28d6568d35b01e1ea92de6ae3c4b51098fb9f3192d74b138f3b89',
+ '39624176a81dcedc554b548aa04b43e82a48c0952ee46b529554c7e155f5ba07',
+ ],
+ screenshot: [
+ 'fcc32bf6b26b05353c7c9779a21980ba9968d7f95730827e0345aefb1a555c8b',
+ ],
+};
diff --git a/src/skills/intent-router.ts b/src/skills/intent-router.ts
index 95b33260..71693da9 100644
--- a/src/skills/intent-router.ts
+++ b/src/skills/intent-router.ts
@@ -2,21 +2,12 @@ import type { SkillDiscovery, SkillMeta, MatchedSkill } from './types.js';
import { logger } from '../utils/logger.js';
/**
- * IntentRouter — matches user input against skill intents to route requests
- * to the right skill(s) automatically.
+ * IntentRouter — the skill index: categories for the skill list, and an
+ * exact match of a message against declared intents (whole phrases) and tags
+ * (whole words). No fuzzy scoring (ADR-040): shared single words, word-pair
+ * similarity and description guessing matched unrelated requests, and Mercury
+ * no longer routes automatically anyway — the model picks skills itself.
*/
-/**
- * Generic verbs / nouns that appear in many skill intents and would otherwise
- * drag in unrelated skills on a single shared word. Indexed intents still keep
- * these words (for exact-intent matching), but the per-word keyword index skips
- * them so they cannot single-handedly score a skill at 0.70.
- */
-const KEYWORD_STOPLIST = new Set([
- 'download', 'send', 'get', 'find', 'show', 'make', 'use', 'open', 'run',
- 'start', 'stop', 'create', 'fetch', 'list', 'add', 'remove', 'update',
- 'check', 'search', 'this', 'that', 'with', 'from', 'into', 'about',
- 'http', 'https', 'www', 'com', 'org', 'net',
-]);
/** `phrase` occurs in `text` as whole words. */
function containsPhrase(text: string, phrase: string): boolean {
@@ -28,7 +19,6 @@ function containsPhrase(text: string, phrase: string): boolean {
export class IntentRouter {
private intentIndex: Map<string, Array<{ skillName: string; intent: string }>> = new Map();
private tagIndex: Map<string, string[]> = new Map(); // tag -> skill names
- private keywordIndex: Map<string, string[]> = new Map(); // keyword -> skill names
private skillMap: Map<string, { name: string; description: string; category?: string; categories?: string[]; intents?: string[]; tags?: string[] }> = new Map();
private initialized = false;
@@ -39,7 +29,6 @@ export class IntentRouter {
buildIndex(skills: SkillDiscovery[]): void {
this.intentIndex.clear();
this.tagIndex.clear();
- this.keywordIndex.clear();
this.skillMap.clear();
for (const skill of skills) {
@@ -75,21 +64,6 @@ export class IntentRouter {
this.intentIndex.set(normalized, []);
}
this.intentIndex.get(normalized)!.push({ skillName: meta.name, intent: normalized });
-
- // Also index individual words from the intent for fuzzy matching.
- // Stoplist generic verbs (download, send, get, …) so a single shared
- // word can't pull in 10 unrelated skills.
- const words = normalized
- .split(/\s+/)
- .filter(w => w.length > 3 && !KEYWORD_STOPLIST.has(w));
- for (const word of words) {
- if (!this.keywordIndex.has(word)) {
- this.keywordIndex.set(word, []);
- }
- if (!this.keywordIndex.get(word)!.includes(meta.name)) {
- this.keywordIndex.get(word)!.push(meta.name);
- }
- }
}
}
@@ -132,46 +106,7 @@ export class IntentRouter {
}
}
- // 2. Word overlap match — count how many indexed keywords are shared.
- // Single shared word = weak signal (0.55); ≥2 shared = strong (0.75).
- const inputWords = input.split(/\s+/).filter(w => w.length > 3 && !KEYWORD_STOPLIST.has(w));
- const inputBigrams = this.getBigrams(input);
- const overlapCount: Map<string, number> = new Map();
-
- for (const [word, skillNames] of this.keywordIndex.entries()) {
- if (inputWords.includes(word)) {
- for (const name of skillNames) {
- overlapCount.set(name, (overlapCount.get(name) ?? 0) + 1);
- }
- }
- }
- for (const [name, count] of overlapCount.entries()) {
- // Single shared content word is a weak signal. We deliberately keep it
- // below the default ambiguity floor (0.75) so it can never be a sole
- // contender on its own — it only helps boost an already-matched skill.
- const conf = count >= 3 ? 0.85 : count >= 2 ? 0.75 : 0.45;
- const current = matches.get(name);
- const currentConf = current?.confidence ?? 0;
- this.addOrUpdateMatch(matches, name, Math.max(currentConf, conf), undefined);
- }
-
- // 3. Bigram similarity — paraphrase catch. Tightened: word must be ≥4
- // chars and overlap ratio > 0.6 (was 0.3). Kills "research" → "NousResearch".
- for (const [word, skillNames] of this.keywordIndex.entries()) {
- if (word.length < 4) continue;
- const wordBigrams = this.getBigrams(word);
- const overlap = inputBigrams.filter(b => wordBigrams.includes(b)).length;
- const maxLen = Math.max(inputBigrams.length, wordBigrams.length);
- if (maxLen > 0 && overlap / maxLen > 0.6) {
- for (const name of skillNames) {
- const current = matches.get(name);
- const currentConf = current?.confidence ?? 0;
- this.addOrUpdateMatch(matches, name, Math.max(currentConf, 0.5), undefined);
- }
- }
- }
-
- // 4. Tag match — require tag ≥4 chars and matched as a whole word
+ // 2. Tag match — require tag ≥4 chars and matched as a whole word
// (not just substring) so short tags like "cli" don't match "clip".
for (const [tag, skillNames] of this.tagIndex.entries()) {
if (tag.length < 4) continue;
@@ -185,16 +120,6 @@ export class IntentRouter {
}
}
- // 5. Description keyword match (lowest confidence)
- for (const [name, info] of this.skillMap.entries()) {
- if (matches.has(name)) continue; // already matched
- const desc = info.description.toLowerCase();
- const matchCount = inputWords.filter(w => desc.includes(w)).length;
- if (matchCount >= 2) {
- this.addOrUpdateMatch(matches, name, Math.min(0.5, 0.15 * matchCount), undefined);
- }
- }
-
// Sort by confidence descending
return [...matches.values()]
.sort((a, b) => b.confidence - a.confidence)
@@ -388,13 +313,4 @@ export class IntentRouter {
});
}
}
-
- private getBigrams(text: string): string[] {
- const words = text.split(/\s+/).filter(w => w.length > 0);
- const bigrams: string[] = [];
- for (let i = 0; i < words.length - 1; i++) {
- bigrams.push(`${words[i]} ${words[i + 1]}`);
- }
- return bigrams;
- }
}
diff --git a/src/skills/loader.ts b/src/skills/loader.ts
index 4db2b074..91d66e6a 100644
--- a/src/skills/loader.ts
+++ b/src/skills/loader.ts
@@ -1,4 +1,5 @@
-import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync, rmSync, unlinkSync } from 'node:fs';
+import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync, rmSync, unlinkSync, renameSync } from 'node:fs';
+import { createHash } from 'node:crypto';
import { join, resolve, sep } from 'node:path';
import { parse as parseYaml } from 'yaml';
import { getMercuryHome } from '../utils/config.js';
@@ -6,7 +7,7 @@ import type { SkillDiscovery, Skill, SkillMeta } from './types.js';
import { recordSelfMadeUse, SELF_MADE_CATEGORY, SELF_MADE_LABEL } from './self-made.js';
import { IntentRouter } from './intent-router.js';
import { logger } from '../utils/logger.js';
-import { DEFAULT_SKILL_SEEDS, PREVIOUS_SEED_CONTENTS, getCategoryLabel } from './default-skills.js';
+import { DEFAULT_SKILL_SEEDS, PREVIOUS_SEED_CONTENTS, RETIRED_SEEDS, getCategoryLabel } from './default-skills.js';
/**
* The web-search skill dir holds a skill that tells the model to fetch a
@@ -21,6 +22,8 @@ export function isBrokenSearchSkill(dirName: string, content: string): boolean {
}
const SKILL_FILE = 'SKILL.md';
+/** Which built-in skills were installed once (see ensureDefaultSkills). */
+const SEEDED_FILE = '.seeded-defaults.json';
const DISABLED_FILE = '.disabled';
function parseSkillMd(content: string): { meta: SkillMeta; instructions: string } | null {
@@ -67,6 +70,7 @@ export class SkillLoader {
}
if (this.seedDefaults) {
+ this.retireOldDefaults();
this.ensureDefaultSkills();
}
@@ -204,11 +208,16 @@ export class SkillLoader {
let text = '**Available Skills** (invoke with the `use_skill` tool):\n';
if (hasCategories && categories.size > 1) {
- // Group by category
+ // Group by category. A skill in several categories is listed once,
+ // under the first (every line here is re-sent with each request).
+ const listed = new Set<string>();
for (const [category, catSkills] of categories) {
+ const fresh = catSkills.filter((s) => !listed.has(s.name));
+ if (fresh.length === 0) continue;
const label = category === SELF_MADE_CATEGORY ? SELF_MADE_LABEL : getCategoryLabel(category);
text += `\n**${label}:**\n`;
- for (const s of catSkills) {
+ for (const s of fresh) {
+ listed.add(s.name);
const discovered = this.discovered.get(s.name);
const desc = discovered?.description || s.description;
text += `- ${s.name}: ${desc}\n`;
@@ -231,12 +240,6 @@ export class SkillLoader {
+ 'Questions about this computer, its files or programs are not web questions.';
}
- const hasTweetNotifier = skills.some(s => s.name === 'tweet-notifier');
- if (hasTweetNotifier) {
- text += '\n\n**Tweets:** for scheduling, approving or posting tweets, the `tweet-notifier` skill has the templates, '
- + 'workflow and memory schema; load it with `use_skill` before starting that work.';
- }
-
text += '\n\n**Using skills** — When a request clearly matches a skill, invoke it via `use_skill`. '
+ 'A skill is optional help, not a requirement: if none fits, just do the task. '
+ 'If the request could match several skills equally, pick the best fit or ask with `ask_user`. '
@@ -420,18 +423,68 @@ Describe what this skill enables Mercury to do. When invoked via the use_skill t
- Keep instructions concise to save tokens
- List only the tools you need in allowed-tools
- The skill name must be unique among installed skills
-- Add \`category\`, \`categories\`, \`intents\`, and \`tags\` in frontmatter for automatic intent routing
+- Add \`category\` and \`tags\` in frontmatter to group the skill in lists; the description is what Mercury reads to decide when to use it
`;
writeFileSync(join(templateDir, SKILL_FILE), content, 'utf-8');
logger.info('Seeded template skill');
}
+ /**
+ * Built-in skills Mercury no longer ships (ADR-040). A copy that is byte
+ * for byte one Mercury seeded was never touched by the owner: it moves to
+ * `_retired-<name>` (underscore folders are not loaded, nothing is
+ * deleted). An edited copy is the owner's own skill and stays where it is.
+ */
+ private retireOldDefaults(): void {
+ for (const [dirName, hashes] of Object.entries(RETIRED_SEEDS)) {
+ const skillDir = join(this.skillsDir, dirName);
+ const skillFile = join(skillDir, SKILL_FILE);
+ if (!existsSync(skillFile)) continue;
+ try {
+ const hash = createHash('sha256').update(readFileSync(skillFile)).digest('hex');
+ if (!hashes.includes(hash)) continue;
+ let target = join(this.skillsDir, `_retired-${dirName}`);
+ if (existsSync(target)) target = `${target}-${Date.now()}`;
+ renameSync(skillDir, target);
+ logger.info({ skill: dirName, movedTo: target }, 'Retired a built-in skill Mercury no longer ships');
+ } catch (err) {
+ logger.warn({ err, skill: dirName }, 'Could not retire an old built-in skill');
+ }
+ }
+ }
+
+ /**
+ * Defaults are installed once (ADR-040). Which ones were installed is kept
+ * in `.seeded-defaults.json`, so a default the owner deletes stays deleted
+ * instead of coming back on the next start; a new default Mercury adds
+ * later is still installed once.
+ */
+ private readSeededDefaults(): Set<string> {
+ try {
+ const parsed = JSON.parse(readFileSync(join(this.skillsDir, SEEDED_FILE), 'utf-8')) as { seeded?: unknown };
+ return new Set(Array.isArray(parsed.seeded) ? parsed.seeded.filter((n): n is string => typeof n === 'string') : []);
+ } catch {
+ return new Set();
+ }
+ }
+
+ private writeSeededDefaults(seeded: Set<string>): void {
+ try {
+ writeFileSync(join(this.skillsDir, SEEDED_FILE), JSON.stringify({ seeded: [...seeded].sort() }, null, 2) + '\n', 'utf-8');
+ } catch (err) {
+ logger.warn({ err }, 'Could not record installed default skills');
+ }
+ }
+
private ensureDefaultSkills(): void {
+ const seeded = this.readSeededDefaults();
+ const before = seeded.size;
for (const seed of DEFAULT_SKILL_SEEDS) {
const skillDir = join(this.skillsDir, seed.dirName);
const skillFile = join(skillDir, seed.fileName);
if (existsSync(skillFile)) {
+ seeded.add(seed.dirName);
// Upgrade an untouched copy of an older built-in version; never overwrite edits.
try {
const current = readFileSync(skillFile, 'utf-8');
@@ -451,9 +504,13 @@ Describe what this skill enables Mercury to do. When invoked via the use_skill t
continue;
}
+ // Installed before and gone now: the owner removed it. Leave it removed.
+ if (seeded.has(seed.dirName)) continue;
mkdirSync(skillDir, { recursive: true });
writeFileSync(skillFile, seed.content, 'utf-8');
+ seeded.add(seed.dirName);
logger.info({ skill: seed.dirName }, 'Seeded default skill');
}
+ if (seeded.size !== before) this.writeSeededDefaults(seeded);
}
}
diff --git a/website/docs/reference/skills.mdx b/website/docs/reference/skills.mdx
index 7f148572..b531b281 100644
--- a/website/docs/reference/skills.mdx
+++ b/website/docs/reference/skills.mdx
@@ -23,19 +23,22 @@ A skill bundles:
└── references/ # optional
```
-On first run, Mercury seeds a `_template` directory and a curated set of built-in skills. If a seeded `SKILL.md` already exists, it is left alone — your customizations are never overwritten.
+On first run, Mercury seeds a `_template` directory and its built-in skills. Each built-in skill is installed once: if you edit it, your version is kept; if you delete it, it stays deleted (`~/.mercury/skills/.seeded-defaults.json` records what was installed).
-### Bundled default skills
+### Built-in skills
-As of `v1.1.11`, fresh installs (or `mercury doctor --seed-skills`) come with three built-in skills:
+| Skill | Use it for |
+|---|---|
+| `web-search` | Current events and anything on the web: focused searches, the best sources, answers with links. |
+| `computer-health` | Why the computer is slow or full, what's running, what uses a port, why a Docker container or service is down. It only reads until you agree to a fix. |
+| `tidy-files` | Cleaning up, sorting, deduplicating or renaming many files. It shows the plan, asks, moves files into a dated `_to-delete` folder instead of deleting, and tells you how to undo. |
+| `data-analysis` | CSV, Excel and JSON: it inspects the columns, computes every number with a script, checks the totals, then summarizes and charts. |
+| `long-documents` | Long PDFs, logs, transcripts and books: it reads in sections and answers with page or line references. |
+| `documents` | Making or converting Word, PDF, slides, spreadsheets and Markdown with pandoc or a script, checking the file opens, and sending it back. |
-| Skill | What it does | Tools used |
-|---|---|---|
-| `web-search` | DuckDuckGo HTML search + summarized sources with cross-referencing. | `fetch_url` |
-| `tweet-notifier` | Schedule tweets with founder approval and supporter notifications. | `schedule_task`, `send_message`, `save_memory`, `search_memory`, `fetch_url`, `github_api` |
-| `screenshot` | Full-page website screenshots via Playwright with configurable viewport (mobile/desktop/HD/custom) and dark/light color scheme. Output goes to `~/Desktop/<domain>-<timestamp>.png`. | `run_command`, `create_file`, `write_file`, `send_file`, `cd`, `send_message` |
+None of them can run commands or change files without asking: they don't list `allowed-tools` (`web-search` lists only `web_search` and `fetch_url`).
-The `screenshot` skill requires Playwright/Chromium (`npx playwright install chromium`). On Telegram, the captured image is sent as a photo attachment.
+Earlier versions also installed `tweet-notifier` and `screenshot`. If your copy of either is exactly as Mercury installed it, Mercury moves it to `~/.mercury/skills/_retired-<name>/` on start. Nothing is deleted, and folders starting with `_` aren't loaded. If you edited it, it's yours and stays where it is.
Browse and install community skills at **[skills.mercuryagent.sh](https://skills.mercuryagent.sh)**.
@@ -78,13 +81,13 @@ Generates a structured summary of the user's day from chat history and memory.
### Required frontmatter
- `name` — unique slug across installed skills
-- `description` — one-line summary used in listings and intent routing
+- `description` — one-line summary; it's what Mercury reads to decide when the skill fits
### Optional frontmatter
- `version` — semver string
- `category` / `categories` — used for grouping in the UI
-- `intents` — natural-language hints used for automatic routing
+- `intents` — example requests the skill is for (shown with the skill; Mercury doesn't route on them automatically)
- `tags` — arbitrary labels
- `allowed-tools` — the only tool names this skill may call when invoked (elevated permissions are granted from this list)
@@ -182,7 +185,8 @@ Drop a directory containing a valid `SKILL.md` into `~/.mercury/skills/` and Mer
## Invoking a skill
-- Ask in natural language: "Use the daily-digest skill" — intent routing matches against the skill's `intents`, `categories`, and `tags`.
+- Ask in natural language: "Use the daily-digest skill", or just describe the task. Mercury sees every installed skill with its description and picks one when it fits.
+- Pick it yourself: start your message with `#daily-digest`.
- Schedule it: "Remind me daily at 9am to run the daily-digest skill" — see the [Schedules](../integrations/web-dashboard) page.
When invoked, Mercury injects the skill's Markdown body into context as guidance, and the tools listed in `allowed-tools` are granted elevated permissions for the duration of that turn.
@@ -240,5 +244,5 @@ Edit the frontmatter (especially `name`, `description`, `intents`, and `allowed-
- Keep instructions concise — every token in the body is loaded when the skill is invoked.
- Only list the tools you actually need in `allowed-tools` (least-privilege).
-- Use `intents` to make the skill discoverable from natural language without the user having to remember the exact name.
+- Write a `description` that says plainly when the skill should be used — that's what Mercury reads to decide.
- Use `scripts/` for reusable shell snippets and `references/` for data files the skill can read.