@blockrun/franklin 3.28.5 → 3.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -219,7 +219,7 @@ const DIRECT_COMMANDS = {
219
219
  if (ctx.skillRegistry) {
220
220
  const visible = ctx.skillRegistry
221
221
  .list()
222
- .filter((l) => !l.skill.disableModelInvocation);
222
+ .filter((l) => !l.skill.disableModelInvocation && !l.skill.hidden);
223
223
  if (visible.length > 0) {
224
224
  skillsBlock =
225
225
  `\n **Skills:**\n` +
@@ -318,20 +318,48 @@ const DIRECT_COMMANDS = {
318
318
  emitDone(ctx);
319
319
  },
320
320
  '/mcp': async (ctx) => {
321
- const { listMcpServers } = await import('../mcp/client.js');
321
+ const { listMcpServers, listMcpFailures, getMcpStderrTail } = await import('../mcp/client.js');
322
322
  const servers = listMcpServers();
323
- if (servers.length === 0) {
324
- ctx.onEvent({ kind: 'text_delta', text: 'No MCP servers connected.\nAdd servers to `~/.blockrun/mcp.json` or `.mcp.json` in your project.\n' });
323
+ const failures = listMcpFailures();
324
+ let text = '';
325
+ if (servers.length === 0 && failures.length === 0) {
326
+ text = 'No MCP servers connected.\nAdd servers to `~/.blockrun/mcp.json` or `.mcp.json` in your project.\n';
325
327
  }
326
328
  else {
327
- let text = `**${servers.length} MCP server(s) connected:**\n\n`;
329
+ if (servers.length > 0) {
330
+ text += `**${servers.length} MCP server(s) connected:**\n\n`;
331
+ for (const s of servers) {
332
+ const oauthFlag = s.hasOAuth ? (s.oauthAuthorized ? ' · oauth ✓' : ' · oauth ✗') : '';
333
+ const filterNote = s.filtered > 0 ? ` (+${s.filtered} hidden by enabled_tools/disabled_tools)` : '';
334
+ text += ` **${s.name}** [${s.transport}] — ${s.toolCount} tools${filterNote}${oauthFlag}\n`;
335
+ for (const t of s.tools)
336
+ text += ` · ${t}\n`;
337
+ }
338
+ }
339
+ if (failures.length > 0) {
340
+ text += `\n**${failures.length} MCP server(s) failed to connect:**\n\n`;
341
+ for (const f of failures) {
342
+ text += ` **${f.name}** [${f.transport}] — ${f.reason}\n`;
343
+ if (f.stderrTail.length > 0) {
344
+ text += ` stderr (last ${f.stderrTail.length} lines):\n`;
345
+ for (const line of f.stderrTail.slice(-10)) {
346
+ text += ` | ${line.slice(0, 200)}\n`;
347
+ }
348
+ }
349
+ }
350
+ }
351
+ // Surface live stderr from running stdio servers (debug helper).
328
352
  for (const s of servers) {
329
- text += ` **${s.name}** — ${s.toolCount} tools\n`;
330
- for (const t of s.tools)
331
- text += ` · ${t}\n`;
353
+ const tail = getMcpStderrTail(s.name);
354
+ if (tail.length > 0 && s.transport === 'stdio') {
355
+ text += `\n ${s.name} recent stderr (${tail.length} lines):\n`;
356
+ for (const line of tail.slice(-5)) {
357
+ text += ` | ${line.slice(0, 200)}\n`;
358
+ }
359
+ }
332
360
  }
333
- ctx.onEvent({ kind: 'text_delta', text });
334
361
  }
362
+ ctx.onEvent({ kind: 'text_delta', text });
335
363
  emitDone(ctx);
336
364
  },
337
365
  '/context': async (ctx) => {
@@ -9,7 +9,7 @@ import { BLOCKRUN_DIR } from '../config.js';
9
9
  import { getWalletAddress as getBaseWalletAddress } from '@blockrun/llm';
10
10
  import { Keypair } from '@solana/web3.js';
11
11
  import bs58 from 'bs58';
12
- import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt, loadSkills, formatSkillsForPrompt } from '../learnings/store.js';
12
+ import { loadLearnings, decayLearnings, saveLearnings, formatForPrompt } from '../learnings/store.js';
13
13
  // ─── System Instructions Assembly ──────────────────────────────────────────
14
14
  // Composable prompt sections — each independently maintainable and conditionally includable.
15
15
  function getCoreInstructions() {
@@ -505,18 +505,12 @@ export function assembleInstructions(workingDir, model) {
505
505
  }
506
506
  }
507
507
  catch { /* learnings are optional — never block startup */ }
508
- // Inject relevant skills (procedural memory from past complex tasks)
509
- try {
510
- const allSkills = loadSkills();
511
- if (allSkills.length > 0) {
512
- // Skills are matched lazily on first user message — for now inject top skills by use count
513
- const topSkills = allSkills.sort((a, b) => b.uses - a.uses).slice(0, 5);
514
- const skillsSection = formatSkillsForPrompt(topSkills);
515
- if (skillsSection)
516
- parts.push(skillsSection);
517
- }
518
- }
519
- catch { /* skills are optional */ }
508
+ // Procedural skills (bundled + learned + user + project) used to be
509
+ // injected here at session boot. They now flow through the unified
510
+ // src/skills/ Registry and are matched per-turn against the user's
511
+ // message in src/skills/triggers.ts, so we no longer pre-inject all
512
+ // top-by-use skills into every system prompt — the per-turn hint is both
513
+ // more relevant and cheaper.
520
514
  // Model-specific execution guidance
521
515
  if (model) {
522
516
  parts.push(getModelGuidance(model));
@@ -6,7 +6,8 @@ import { ModelClient } from './llm.js';
6
6
  import { autoCompactIfNeeded, forceCompact, microCompact, projectCompactionSavings } from './compact.js';
7
7
  import { estimateHistoryTokens, updateActualTokens, resetTokenAnchor, getAnchoredTokenCount, getContextWindow, setEstimationModel } from './tokens.js';
8
8
  import { handleSlashCommand } from './commands.js';
9
- import { loadBundledSkills, getSkillVars } from '../skills/bootstrap.js';
9
+ import { loadAllSkills, getSkillVars } from '../skills/bootstrap.js';
10
+ import { matchSkillTriggers, formatSkillHints } from '../skills/triggers.js';
10
11
  import { reduceTokens } from './reduce.js';
11
12
  import { redactSecrets, stashSecretsToEnv, formatRedactionWarning } from './secret-redact.js';
12
13
  import { PermissionManager } from './permissions.js';
@@ -543,10 +544,12 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
543
544
  config.baseModel = config.model; // User's intended model — /model command updates this
544
545
  let turnFailedModels = new Set(); // Models that failed this turn (cleared each new turn)
545
546
  // ── Skills (file-loaded SKILL.md prompt-rewrite slash commands) ──
546
- // Bundled-only in Phase 1 of the skills MVP. User-global and project-local
547
- // discovery + the budget-cap-usd / cost-receipt enforcement contract land
548
- // in Phase 2 — see docs/plans/2026-04-29-franklin-skills-mvp-design.md.
549
- const skillBoot = loadBundledSkills();
547
+ // Loaded from four sources, precedence project > user > learned > bundled,
548
+ // in a single Registry that handles name conflicts. Learned skills are
549
+ // written by the learnings extractor under ~/.blockrun/skills/learned/
550
+ // and join the same Registry — they show up via trigger matching but are
551
+ // hidden from /help unless the user explicitly lists them.
552
+ const skillBoot = loadAllSkills(workDir);
550
553
  if (skillBoot.errors.length > 0 && config.debug) {
551
554
  for (const err of skillBoot.errors) {
552
555
  onEvent({ kind: 'text_delta', text: `[skills] ${err.path}: ${err.error}\n` });
@@ -724,6 +727,26 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
724
727
  input = redactedText;
725
728
  }
726
729
  lastUserInput = input;
730
+ // ── Skill trigger auto-invoke ──
731
+ // Match the user message against every skill's `triggers:` list. Strong
732
+ // matches surface as a soft hint appended to this turn's system prompt
733
+ // so the model treats the skill's procedure as guidance rather than
734
+ // mandatory rewriting (which would surprise the user). The skill body
735
+ // is NEVER substituted into the visible user message — that breaks the
736
+ // session transcript and the user's intent representation. See
737
+ // src/skills/triggers.ts for the matching algorithm.
738
+ let turnSkillHints = '';
739
+ try {
740
+ const matches = matchSkillTriggers(input, skillRegistry.list());
741
+ if (matches.length > 0) {
742
+ turnSkillHints = formatSkillHints(matches);
743
+ if (config.debug && matches.length > 0) {
744
+ const summary = matches.map(m => `${m.skill.skill.name}(${m.score.toFixed(1)})`).join(', ');
745
+ onEvent({ kind: 'text_delta', text: `*[skill triggers] ${summary}*\n` });
746
+ }
747
+ }
748
+ }
749
+ catch { /* trigger matching is best-effort */ }
727
750
  // Push the user's clean message; any harness-injected annotations
728
751
  // (pushback SYSTEM NOTE, prefetch context block) are applied AFTER
729
752
  // the turn analyzer runs so they get driven by model-decided flags
@@ -1257,6 +1280,11 @@ export async function interactiveSession(config, getUserInput, onEvent, onAbortR
1257
1280
  callMaxTokens = 2048; // Short plan output
1258
1281
  callSystemPrompt = systemPrompt + '\n\n' + getPlanningPrompt();
1259
1282
  }
1283
+ // Skill-trigger hints from this turn — see the trigger-match block
1284
+ // above, computed once per user message.
1285
+ if (turnSkillHints) {
1286
+ callSystemPrompt = callSystemPrompt + '\n\n' + turnSkillHints;
1287
+ }
1260
1288
  // ── Hallucination guard for weak models ──
1261
1289
  // Weak / free models (nemotron-ultra, GLM-4, qwen coder, free-profile
1262
1290
  // resolves) have been observed inventing tool names (e.g. MixtureOfAgents)
@@ -37,10 +37,11 @@ export function scavengeToolCalls(text, opts) {
37
37
  for (const invoke of iterateDsmlInvokes(text)) {
38
38
  if (out.length >= max)
39
39
  break;
40
- if (!opts.allowedNames.has(invoke.name))
40
+ const resolved = resolveAllowedName(invoke.name, opts.allowedNames);
41
+ if (!resolved)
41
42
  continue;
42
- out.push(makeInvocation(invoke.name, invoke.args));
43
- notes.push(`scavenged DSML call: ${invoke.name}`);
43
+ out.push(makeInvocation(resolved, invoke.args));
44
+ notes.push(`scavenged DSML call: ${resolved}`);
44
45
  }
45
46
  // Pattern B — raw JSON objects in the three canonical shapes. Strip
46
47
  // DSML blocks first so their parameter payloads don't get re-scavenged
@@ -144,22 +145,53 @@ function coerceToInvocation(candidateJson, allowedNames) {
144
145
  if (!parsed || typeof parsed !== 'object')
145
146
  return null;
146
147
  const obj = parsed;
147
- // Pattern 1 — { name, arguments } (Anthropic-ish flat form).
148
- if (typeof obj.name === 'string' && allowedNames.has(obj.name)) {
149
- return makeInvocation(obj.name, normalizeArgs(obj.arguments));
148
+ // Pattern 1 — { name, arguments } (Anthropic-ish flat form) AND the flat
149
+ // OpenAI leak { type: "function", name, parameters } emitted by the free
150
+ // DeepSeek model — both carry the name at the top level. Args land under
151
+ // `arguments` or `parameters` depending on the model's chat template.
152
+ if (typeof obj.name === 'string') {
153
+ const resolved = resolveAllowedName(obj.name, allowedNames);
154
+ if (resolved) {
155
+ return makeInvocation(resolved, normalizeArgs(obj.arguments ?? obj.parameters));
156
+ }
150
157
  }
151
158
  // Pattern 2 — OpenAI-style { type: "function", function: { name, arguments } }.
152
159
  if (obj.type === 'function' &&
153
160
  obj.function &&
154
161
  typeof obj.function === 'object') {
155
162
  const fn = obj.function;
156
- if (typeof fn.name === 'string' && allowedNames.has(fn.name)) {
157
- return makeInvocation(fn.name, normalizeArgs(fn.arguments));
163
+ const resolved = typeof fn.name === 'string' ? resolveAllowedName(fn.name, allowedNames) : null;
164
+ if (resolved) {
165
+ return makeInvocation(resolved, normalizeArgs(fn.arguments ?? fn.parameters));
158
166
  }
159
167
  }
160
168
  // Pattern 3 — { tool_name, tool_args } (R1 free-form variant).
161
- if (typeof obj.tool_name === 'string' && allowedNames.has(obj.tool_name)) {
162
- return makeInvocation(obj.tool_name, normalizeArgs(obj.tool_args));
169
+ if (typeof obj.tool_name === 'string') {
170
+ const resolved = resolveAllowedName(obj.tool_name, allowedNames);
171
+ if (resolved) {
172
+ return makeInvocation(resolved, normalizeArgs(obj.tool_args ?? obj.tool_parameters));
173
+ }
174
+ }
175
+ return null;
176
+ }
177
+ /** Collapse a tool name to a comparison key: lowercase, drop separators.
178
+ * `activate_tool` / `web_search` → `activatetool` / `websearch`. */
179
+ function normalizeName(name) {
180
+ return name.toLowerCase().replace(/[_\-\s]/g, '');
181
+ }
182
+ /** Resolve a leaked tool name to its canonical registry spelling. Exact
183
+ * match wins; otherwise a separator/case-insensitive match lets models
184
+ * that rewrite names to OpenAI snake_case (`web_search` → `WebSearch`)
185
+ * still be recovered. Returns null if no allowed tool matches. */
186
+ function resolveAllowedName(name, allowedNames) {
187
+ if (!name || typeof name !== 'string')
188
+ return null;
189
+ if (allowedNames.has(name))
190
+ return name;
191
+ const target = normalizeName(name);
192
+ for (const allowed of allowedNames) {
193
+ if (normalizeName(allowed) === target)
194
+ return allowed;
163
195
  }
164
196
  return null;
165
197
  }
@@ -4,5 +4,6 @@
4
4
  */
5
5
  export interface SkillsCommandOptions {
6
6
  json?: boolean;
7
+ all?: boolean;
7
8
  }
8
9
  export declare function skillsCommand(action: string | undefined, arg: string | undefined, opts?: SkillsCommandOptions): Promise<void>;
@@ -3,7 +3,7 @@
3
3
  * during a session. Phase 1 of the skills MVP — bundled only.
4
4
  */
5
5
  import chalk from 'chalk';
6
- import { loadBundledSkills } from '../skills/bootstrap.js';
6
+ import { loadAllSkills } from '../skills/bootstrap.js';
7
7
  export async function skillsCommand(action, arg, opts = {}) {
8
8
  const sub = action ?? 'list';
9
9
  if (sub === 'list') {
@@ -19,8 +19,13 @@ export async function skillsCommand(action, arg, opts = {}) {
19
19
  process.exit(1);
20
20
  }
21
21
  function runList(opts) {
22
- const { registry, errors } = loadBundledSkills();
23
- const skills = registry.list();
22
+ const { registry, errors } = loadAllSkills(process.cwd());
23
+ const all = registry.list();
24
+ // Hidden skills (e.g. auto-generated learned skills) stay active for trigger
25
+ // matching and explicit `which` lookup, but are kept out of the default list.
26
+ // `--all` reveals them; `--json` always includes everything for tooling.
27
+ const skills = opts.json || opts.all ? all : all.filter((l) => !l.skill.hidden);
28
+ const hiddenCount = all.length - skills.length;
24
29
  if (opts.json) {
25
30
  process.stdout.write(JSON.stringify({
26
31
  skills: skills.map((l) => ({
@@ -32,6 +37,8 @@ function runList(opts) {
32
37
  costReceipt: l.skill.costReceipt ?? false,
33
38
  budgetCapUsd: l.skill.budgetCapUsd ?? null,
34
39
  disableModelInvocation: l.skill.disableModelInvocation ?? false,
40
+ hidden: l.skill.hidden ?? false,
41
+ autoGenerated: l.skill.autoGenerated ?? false,
35
42
  })),
36
43
  errors,
37
44
  shadowed: registry.shadowed().map((s) => ({
@@ -41,9 +48,12 @@ function runList(opts) {
41
48
  }, null, 2) + '\n');
42
49
  return;
43
50
  }
44
- if (skills.length === 0) {
51
+ if (skills.length === 0 && hiddenCount === 0) {
45
52
  console.log(chalk.dim('No skills loaded.'));
46
53
  }
54
+ else if (skills.length === 0) {
55
+ console.log(chalk.dim(`No visible skills. ${hiddenCount} hidden — run with --all to show.`));
56
+ }
47
57
  else {
48
58
  console.log(chalk.bold(`Skills (${skills.length})`));
49
59
  console.log('');
@@ -56,10 +66,16 @@ function runList(opts) {
56
66
  flags.push(`cap $${l.skill.budgetCapUsd.toFixed(2)}`);
57
67
  if (l.skill.disableModelInvocation)
58
68
  flags.push('manual-only');
69
+ if (l.skill.hidden)
70
+ flags.push('hidden');
59
71
  const flagStr = flags.length > 0 ? chalk.dim(` [${flags.join(', ')}]`) : '';
60
72
  const sourceTag = chalk.dim(`(${l.source})`);
61
73
  console.log(` ${chalk.cyan('/' + l.skill.name.padEnd(nameWidth))} ${l.skill.description}${flagStr} ${sourceTag}`);
62
74
  }
75
+ if (hiddenCount > 0) {
76
+ console.log('');
77
+ console.log(chalk.dim(` +${hiddenCount} hidden — run with --all to show.`));
78
+ }
63
79
  }
64
80
  const shadowed = registry.shadowed();
65
81
  if (shadowed.length > 0) {
@@ -83,7 +99,7 @@ function runWhich(name) {
83
99
  console.log(chalk.red('Usage: franklin skills which <name>'));
84
100
  process.exit(1);
85
101
  }
86
- const { registry } = loadBundledSkills();
102
+ const { registry } = loadAllSkills(process.cwd());
87
103
  const skill = registry.lookup(name);
88
104
  if (!skill) {
89
105
  console.log(chalk.red(`Skill not found: ${name}`));
package/dist/index.js CHANGED
@@ -158,6 +158,7 @@ program
158
158
  .command('skills [action] [arg]')
159
159
  .description('Manage Franklin skills — list | which <name>')
160
160
  .option('--json', 'Output the skill list as JSON')
161
+ .option('--all', 'Include hidden (auto-generated) skills in the list')
161
162
  .action(async (action, arg, opts) => {
162
163
  const { skillsCommand } = await import('./commands/skills.js');
163
164
  await skillsCommand(action, arg, opts);
@@ -13,13 +13,34 @@ export declare function mergeLearning(existing: Learning[], newEntry: {
13
13
  }): Learning[];
14
14
  export declare function decayLearnings(learnings: Learning[]): Learning[];
15
15
  export declare function formatForPrompt(learnings: Learning[]): string;
16
- /** Load all skills from disk. */
16
+ /**
17
+ * One-time migration of legacy auto-extracted skills.
18
+ *
19
+ * Before the unified registry, learned skills were flat markdown files at
20
+ * `~/.blockrun/skills/<name>.md`. The new layout expects
21
+ * `~/.blockrun/skills/learned/<name>/SKILL.md`, and the user-source loader
22
+ * only reads `<dir>/SKILL.md` — so the old flat files would be silently
23
+ * orphaned on upgrade. This moves each one into the new layout (normalizing
24
+ * it through `saveSkill`, which adds `hidden`/`auto-generated`) and deletes
25
+ * the old file. Idempotent and cheap: returns immediately when there are no
26
+ * flat `.md` files left to migrate.
27
+ */
28
+ export declare function migrateLegacyLearnedSkills(): number;
29
+ /** Load all learned skills from `~/.blockrun/skills/learned/`. */
17
30
  export declare function loadSkills(): Skill[];
18
- /** Save a new skill to disk. */
31
+ /** Save a new auto-extracted skill to disk in unified SKILL.md format. */
19
32
  export declare function saveSkill(skill: Skill): void;
20
33
  /** Bump use count for a skill. */
21
34
  export declare function bumpSkillUse(skill: Skill): void;
22
- /** Find skills relevant to a user message, by trigger matching. */
35
+ /**
36
+ * Compat shim retained so older callers keep working while the rest of the
37
+ * codebase migrates to `src/skills/triggers.ts`. New code should NOT depend
38
+ * on this — it ignores `hidden` and `disableModelInvocation` flags.
39
+ */
23
40
  export declare function matchSkills(input: string, skills: Skill[]): Skill[];
24
- /** Format matched skills for system prompt injection. */
41
+ /**
42
+ * Compat shim. The new code path injects skills per-turn via
43
+ * `formatSkillHints` rather than baking them into the boot-time system
44
+ * prompt, so callers should not need this any more.
45
+ */
25
46
  export declare function formatSkillsForPrompt(skills: Skill[]): string;
@@ -158,25 +158,99 @@ export function formatForPrompt(learnings) {
158
158
  return '# Personal Context\nLearned from previous sessions:\n\n' + sections.join('\n\n');
159
159
  }
160
160
  // ─── Skills (procedural memory) ──────────────────────────────────────────
161
- // Stored as individual markdown files in ~/.blockrun/skills/
162
- // Larger than learnings, conditionally injected based on trigger matching.
161
+ //
162
+ // Auto-extracted "skills" from sessions are now stored under
163
+ // `~/.blockrun/skills/learned/<name>/SKILL.md` in the unified Anthropic
164
+ // SKILL.md format. The skills/ directory layout looks like:
165
+ //
166
+ // ~/.blockrun/skills/
167
+ // ├── my-handwritten/SKILL.md (user-authored)
168
+ // └── learned/
169
+ // ├── refactor-step-flow/SKILL.md (extracted by Franklin)
170
+ // └── pricing-quote-flow/SKILL.md
171
+ //
172
+ // The runtime registry (src/skills/bootstrap.loadAllSkills) discovers all
173
+ // three sources (bundled / learned / user / project) in one pass and
174
+ // trigger matching (src/skills/triggers.matchSkillTriggers) handles
175
+ // auto-invoke. The legacy `loadSkills`/`matchSkills`/`formatSkillsForPrompt`
176
+ // exports below are kept as compat shims (delegating to the new disk layout)
177
+ // so older callers don't break; new code should import from src/skills/.
163
178
  const SKILLS_DIR = path.join(BLOCKRUN_DIR, 'skills');
164
- const MAX_SKILLS_IN_PROMPT = 5;
165
- const MAX_SKILL_CHARS = 1500;
166
- function ensureSkillsDir() {
167
- if (!fs.existsSync(SKILLS_DIR)) {
168
- fs.mkdirSync(SKILLS_DIR, { recursive: true });
179
+ const LEARNED_SKILLS_DIR = path.join(SKILLS_DIR, 'learned');
180
+ function ensureLearnedSkillsDir() {
181
+ if (!fs.existsSync(LEARNED_SKILLS_DIR)) {
182
+ fs.mkdirSync(LEARNED_SKILLS_DIR, { recursive: true });
169
183
  }
170
184
  }
171
- /** Load all skills from disk. */
185
+ /**
186
+ * One-time migration of legacy auto-extracted skills.
187
+ *
188
+ * Before the unified registry, learned skills were flat markdown files at
189
+ * `~/.blockrun/skills/<name>.md`. The new layout expects
190
+ * `~/.blockrun/skills/learned/<name>/SKILL.md`, and the user-source loader
191
+ * only reads `<dir>/SKILL.md` — so the old flat files would be silently
192
+ * orphaned on upgrade. This moves each one into the new layout (normalizing
193
+ * it through `saveSkill`, which adds `hidden`/`auto-generated`) and deletes
194
+ * the old file. Idempotent and cheap: returns immediately when there are no
195
+ * flat `.md` files left to migrate.
196
+ */
197
+ export function migrateLegacyLearnedSkills() {
198
+ let entries;
199
+ try {
200
+ entries = fs.readdirSync(SKILLS_DIR);
201
+ }
202
+ catch {
203
+ return 0; // no skills dir yet — nothing to migrate
204
+ }
205
+ const flatFiles = entries.filter((f) => f.endsWith('.md'));
206
+ if (flatFiles.length === 0)
207
+ return 0;
208
+ let migrated = 0;
209
+ for (const file of flatFiles) {
210
+ const oldPath = path.join(SKILLS_DIR, file);
211
+ try {
212
+ if (!fs.statSync(oldPath).isFile())
213
+ continue;
214
+ const raw = fs.readFileSync(oldPath, 'utf-8');
215
+ const skill = parseSkillFile(raw, file.replace(/\.md$/, ''));
216
+ if (!skill)
217
+ continue;
218
+ const destDir = path.join(LEARNED_SKILLS_DIR, safeDirName(skill.name));
219
+ // Don't clobber a skill already present in the new layout.
220
+ if (!fs.existsSync(path.join(destDir, 'SKILL.md'))) {
221
+ saveSkill(skill);
222
+ }
223
+ fs.rmSync(oldPath);
224
+ migrated++;
225
+ }
226
+ catch { /* skip unreadable/locked file */ }
227
+ }
228
+ return migrated;
229
+ }
230
+ function safeDirName(name) {
231
+ return name.replace(/[^a-z0-9-]/gi, '-').toLowerCase() || 'skill';
232
+ }
233
+ function escapeYamlValue(v) {
234
+ if (/[:#'"\n]/.test(v)) {
235
+ return JSON.stringify(v);
236
+ }
237
+ return v;
238
+ }
239
+ /** Load all learned skills from `~/.blockrun/skills/learned/`. */
172
240
  export function loadSkills() {
173
- ensureSkillsDir();
241
+ ensureLearnedSkillsDir();
174
242
  const skills = [];
175
243
  try {
176
- for (const file of fs.readdirSync(SKILLS_DIR).filter(f => f.endsWith('.md'))) {
244
+ for (const entry of fs.readdirSync(LEARNED_SKILLS_DIR)) {
245
+ const dirPath = path.join(LEARNED_SKILLS_DIR, entry);
177
246
  try {
178
- const raw = fs.readFileSync(path.join(SKILLS_DIR, file), 'utf-8');
179
- const skill = parseSkillFile(raw);
247
+ if (!fs.statSync(dirPath).isDirectory())
248
+ continue;
249
+ const filePath = path.join(dirPath, 'SKILL.md');
250
+ if (!fs.existsSync(filePath))
251
+ continue;
252
+ const raw = fs.readFileSync(filePath, 'utf-8');
253
+ const skill = parseSkillFile(raw, entry);
180
254
  if (skill)
181
255
  skills.push(skill);
182
256
  }
@@ -186,49 +260,79 @@ export function loadSkills() {
186
260
  catch { /* dir doesn't exist yet */ }
187
261
  return skills;
188
262
  }
189
- function parseSkillFile(raw) {
190
- const m = raw.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
263
+ function parseSkillFile(raw, fallbackName) {
264
+ const m = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
191
265
  if (!m)
192
266
  return null;
193
267
  const fm = m[1];
194
- const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim() || '';
268
+ const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim() || fallbackName;
195
269
  const description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim() || '';
196
- const triggersRaw = fm.match(/^triggers:\s*\[([^\]]*)\]/m)?.[1] || '';
197
- const triggers = triggersRaw.split(',').map(t => t.trim()).filter(Boolean);
270
+ // Triggers may be a YAML list (- "foo") OR a legacy inline form ([a, b]).
271
+ let triggers = [];
272
+ const inline = fm.match(/^triggers:\s*\[([^\]]*)\]/m)?.[1];
273
+ if (inline !== undefined) {
274
+ triggers = inline.split(',').map(t => t.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
275
+ }
276
+ else {
277
+ const lines = fm.split('\n');
278
+ const triggersIdx = lines.findIndex(l => /^triggers:\s*$/.test(l));
279
+ if (triggersIdx >= 0) {
280
+ for (let i = triggersIdx + 1; i < lines.length; i++) {
281
+ const m = lines[i].match(/^\s+-\s+(.+)$/);
282
+ if (!m)
283
+ break;
284
+ triggers.push(m[1].trim().replace(/^["']|["']$/g, ''));
285
+ }
286
+ }
287
+ }
198
288
  const created = fm.match(/^created:\s*(.+)$/m)?.[1]?.trim() || '';
199
289
  const uses = parseInt(fm.match(/^uses:\s*(\d+)$/m)?.[1] || '0');
200
- const source = fm.match(/^source_session:\s*(.+)$/m)?.[1]?.trim() || '';
290
+ const source = fm.match(/^source(?:[-_]session):\s*(.+)$/m)?.[1]?.trim() || '';
201
291
  if (!name)
202
292
  return null;
203
293
  return { name, description, triggers, steps: m[2].trim(), created, uses, source_session: source };
204
294
  }
205
- /** Save a new skill to disk. */
295
+ /** Save a new auto-extracted skill to disk in unified SKILL.md format. */
206
296
  export function saveSkill(skill) {
207
- ensureSkillsDir();
208
- const filename = skill.name.replace(/[^a-z0-9-]/gi, '-').toLowerCase() + '.md';
209
- const fm = [
210
- '---',
211
- `name: ${skill.name}`,
212
- `description: ${skill.description}`,
213
- `triggers: [${skill.triggers.join(', ')}]`,
214
- `created: ${skill.created}`,
215
- `uses: ${skill.uses}`,
216
- `source_session: ${skill.source_session}`,
217
- '---',
218
- ].join('\n');
219
- fs.writeFileSync(path.join(SKILLS_DIR, filename), `${fm}\n${skill.steps}\n`);
297
+ ensureLearnedSkillsDir();
298
+ const dir = path.join(LEARNED_SKILLS_DIR, safeDirName(skill.name));
299
+ fs.mkdirSync(dir, { recursive: true });
300
+ const fmLines = ['---'];
301
+ fmLines.push(`name: ${escapeYamlValue(skill.name)}`);
302
+ fmLines.push(`description: ${escapeYamlValue(skill.description)}`);
303
+ if (skill.triggers.length > 0) {
304
+ fmLines.push(`triggers:`);
305
+ for (const t of skill.triggers) {
306
+ fmLines.push(` - ${escapeYamlValue(t)}`);
307
+ }
308
+ }
309
+ fmLines.push(`hidden: true`);
310
+ fmLines.push(`auto-generated: true`);
311
+ if (skill.created)
312
+ fmLines.push(`created: ${skill.created}`);
313
+ fmLines.push(`uses: ${skill.uses}`);
314
+ if (skill.source_session) {
315
+ fmLines.push(`source-session: ${escapeYamlValue(skill.source_session)}`);
316
+ }
317
+ fmLines.push('---');
318
+ fmLines.push('');
319
+ fmLines.push(skill.steps);
320
+ fs.writeFileSync(path.join(dir, 'SKILL.md'), fmLines.join('\n') + '\n');
220
321
  }
221
322
  /** Bump use count for a skill. */
222
323
  export function bumpSkillUse(skill) {
223
- const filename = skill.name.replace(/[^a-z0-9-]/gi, '-').toLowerCase() + '.md';
224
- const fp = path.join(SKILLS_DIR, filename);
324
+ const filePath = path.join(LEARNED_SKILLS_DIR, safeDirName(skill.name), 'SKILL.md');
225
325
  try {
226
- const raw = fs.readFileSync(fp, 'utf-8');
227
- fs.writeFileSync(fp, raw.replace(/^uses:\s*\d+$/m, `uses: ${skill.uses + 1}`));
326
+ const raw = fs.readFileSync(filePath, 'utf-8');
327
+ fs.writeFileSync(filePath, raw.replace(/^uses:\s*\d+$/m, `uses: ${skill.uses + 1}`));
228
328
  }
229
329
  catch { /* non-critical */ }
230
330
  }
231
- /** Find skills relevant to a user message, by trigger matching. */
331
+ /**
332
+ * Compat shim retained so older callers keep working while the rest of the
333
+ * codebase migrates to `src/skills/triggers.ts`. New code should NOT depend
334
+ * on this — it ignores `hidden` and `disableModelInvocation` flags.
335
+ */
232
336
  export function matchSkills(input, skills) {
233
337
  const lower = input.toLowerCase();
234
338
  const scored = [];
@@ -244,12 +348,17 @@ export function matchSkills(input, skills) {
244
348
  if (score > 0)
245
349
  scored.push({ skill: s, score });
246
350
  }
247
- return scored.sort((a, b) => b.score - a.score).slice(0, MAX_SKILLS_IN_PROMPT).map(m => m.skill);
351
+ return scored.sort((a, b) => b.score - a.score).slice(0, 5).map(m => m.skill);
248
352
  }
249
- /** Format matched skills for system prompt injection. */
353
+ /**
354
+ * Compat shim. The new code path injects skills per-turn via
355
+ * `formatSkillHints` rather than baking them into the boot-time system
356
+ * prompt, so callers should not need this any more.
357
+ */
250
358
  export function formatSkillsForPrompt(skills) {
251
359
  if (skills.length === 0)
252
360
  return '';
361
+ const MAX_SKILL_CHARS = 1500;
253
362
  const parts = ['# Learned Skills\nProcedures from previous experience — use when relevant:\n'];
254
363
  for (const s of skills) {
255
364
  const body = s.steps.length > MAX_SKILL_CHARS ? s.steps.slice(0, MAX_SKILL_CHARS) + '\n…' : s.steps;