Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(ruflo-console): skills view uses, previews, targets, maintains, scans and authors skills

ruva3738e95c843
diff --git a/plugins/ruflo-console/hooks/bindings.ts b/plugins/ruflo-console/hooks/bindings.ts
index a52ccfc673..e8fbc4d39a 100644
--- a/plugins/ruflo-console/hooks/bindings.ts
+++ b/plugins/ruflo-console/hooks/bindings.ts
@@ -10,6 +10,7 @@ import type { Host } from './host'
import { filterPalette, paletteEntries } from './palette'
import type { Runner } from './runner'
import { skillActions } from './skills'
+import { moreSkillActions } from './skills-lab'
import { PANE_ID, viewOf, type State } from './state'
import type { Actions } from './views/common'
import { openTasks, selection } from './views/select'
@@ -249,7 +250,7 @@ export function actionsOf(state: State, host: Host, runner: Runner, steps: Steps
},
},
// ▸ edit hands the skill to the AI terminal, as x.ruv.io's ▸ open does: typed, not run.
- skills: skillActions(state, host, runner, text => actions.term.load('claude', text)),
+ skills: { ...skillActions(state, host, runner, text => actions.term.load('claude', text)), ...moreSkillActions(state, host, runner, text => actions.term.load('claude', text)) },
}
return actions
diff --git a/plugins/ruflo-console/hooks/data/skill-md.ts b/plugins/ruflo-console/hooks/data/skill-md.ts
new file mode 100644
index 0000000000..500685bcf2
--- /dev/null
+++ b/plugins/ruflo-console/hooks/data/skill-md.ts
@@ -0,0 +1,198 @@
+/**
+ * Pure readers for a project's skills, run on text the console has already read (bounded): a SKILL.md's frontmatter
+ * checked against what the `skills` CLI and the Agent Skills format require, the project's stack from its manifests
+ * (as searches to offer, never the dependency names themselves), and which agent files name which local skill.
+ * Nothing here reads a file, runs a program or reaches the network.
+ */
+import { plain } from './parse'
+import { typedOf } from './skills'
+
+/** A SKILL.md larger than this is refused (the format asks for a short entry file with details in other files). */
+export const SKILL_MD_MAX = 100_000
+/** Past this many lines the check warns: the format suggests keeping SKILL.md under 500 lines. */
+export const SKILL_MD_LINES = 500
+const NAME_MAX = 64
+const DESCRIPTION_MAX = 1024
+const SPEC_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
+
+export type SkillCheck = { ok: boolean; name?: string; description?: string; problems: string[]; warnings: string[] }
+
+/** A frontmatter value: unquoted, or one pair of quotes taken off; a folded (`>`) or literal (`|`) block joined. */
+function valueOf(lines: readonly string[], key: string): string | undefined {
+ const at = lines.findIndex(line => new RegExp(`^${key}\\s*:`).test(line))
+
+ if (at < 0) return undefined
+
+ const first = (lines[at] ?? '').replace(new RegExp(`^${key}\\s*:\\s*`), '').trim()
+
+ if (/^[>|][+-]?$/.test(first)) {
+ const block: string[] = []
+
+ for (const line of lines.slice(at + 1)) {
+ if (!/^\s+\S/.test(line) && line.trim() !== '') break
+ block.push(line.trim())
+ }
+
+ return block.join(' ').trim()
+ }
+
+ return /^(["']).*\1$/.test(first) ? first.slice(1, -1) : first
+}
+
+/**
+ * Checks a SKILL.md: a `---` frontmatter block at the top, a `name` (lowercase letters, digits and single hyphens, at
+ * most 64, and the folder's name when one is given) and a non-empty `description` (at most 1024), within the size cap.
+ * Problems fail the check; warnings (a long body, no body) do not.
+ */
+export function checkSkillMd(text: string, folder?: string): SkillCheck {
+ const problems: string[] = []
+ const warnings: string[] = []
+
+ if (text.length > SKILL_MD_MAX) return { ok: false, problems: [`${text.length} characters: over the ${SKILL_MD_MAX} cap`], warnings }
+
+ const lines = text.replace(/^/, '').replace(/\r\n/g, '\n').split('\n')
+
+ if (lines[0]?.trim() !== '---') return { ok: false, problems: ['no frontmatter: the file must start with a --- line'], warnings }
+
+ const end = lines.findIndex((line, i) => i > 0 && line.trim() === '---')
+
+ if (end < 0) return { ok: false, problems: ['the frontmatter is never closed with a --- line'], warnings }
+
+ const head = lines.slice(1, end)
+ const name = valueOf(head, 'name')
+ const description = valueOf(head, 'description')
+
+ if (name === undefined || name === '') problems.push('name: missing')
+ else if (name.length > NAME_MAX) problems.push(`name: ${name.length} characters, at most ${NAME_MAX}`)
+ else if (!SPEC_NAME.test(name)) problems.push('name: lowercase letters, digits and single hyphens only')
+ else if (folder !== undefined && folder.toLowerCase() !== name) warnings.push(`name "${name}" differs from its folder "${plain(folder, 64)}"`)
+
+ if (description === undefined || description === '') problems.push('description: missing (the CLI skips a skill without one)')
+ else if (description.length > DESCRIPTION_MAX) problems.push(`description: ${description.length} characters, at most ${DESCRIPTION_MAX}`)
+
+ if (lines.slice(end + 1).every(line => line.trim() === '')) warnings.push('no instructions after the frontmatter')
+ if (lines.length > SKILL_MD_LINES) warnings.push(`${lines.length} lines: keep SKILL.md under ${SKILL_MD_LINES} and move detail to other files`)
+
+ return {
+ ok: problems.length === 0,
+ ...(name !== undefined && name !== '' && { name: plain(name, NAME_MAX) }),
+ ...(description !== undefined && description !== '' && { description: plain(description, 300) }),
+ problems,
+ warnings,
+ }
+}
+
+/** The check as lines for the view and the outcome. */
+export const checkLines = (check: SkillCheck): string[] => [
+ check.ok ? `✓ valid: ${check.name ?? ''}` : '✗ not valid',
+ ...(check.description !== undefined ? [`description: ${check.description}`] : []),
+ ...check.problems.map(problem => `✗ ${problem}`),
+ ...check.warnings.map(warning => `! ${warning}`),
+]
+
+/** The manifests a stack is read from, as text (null when missing or unread). */
+export type Manifests = { packageJson?: string | null; cargoToml?: string | null; pyproject?: string | null; goMod?: string | null }
+
+/** A known dependency and the search it suggests: chips come from this table only, never from a dependency's own name. */
+const NODE: readonly [string, string][] = [
+ ['next', 'nextjs'],
+ ['react', 'react'],
+ ['vue', 'vue'],
+ ['svelte', 'svelte'],
+ ['@angular/core', 'angular'],
+ ['express', 'express'],
+ ['tailwindcss', 'tailwind'],
+ ['prisma', 'prisma'],
+ ['@prisma/client', 'prisma'],
+ ['vitest', 'vitest'],
+ ['jest', 'jest'],
+ ['@playwright/test', 'playwright'],
+ ['electron', 'electron'],
+ ['typescript', 'typescript'],
+]
+const RUST: readonly [string, string][] = [['tokio', 'tokio'], ['axum', 'axum'], ['wasm-bindgen', 'wasm'], ['bevy', 'bevy']]
+const PYTHON: readonly [string, string][] = [['django', 'django'], ['fastapi', 'fastapi'], ['flask', 'flask'], ['pytest', 'pytest'], ['pandas', 'pandas'], ['torch', 'pytorch']]
+const GO: readonly [string, string][] = [['github.com/gin-gonic/gin', 'gin'], ['google.golang.org/grpc', 'grpc']]
+
+const CHIPS_MAX = 8
+
+const escape = (text: string): string => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
+
+/** package.json's dependency names, or none when it is not a JSON object. */
+function nodeDeps(text: string): Set<string> {
+ try {
+ const json = JSON.parse(text.slice(0, 500_000)) as Record<string, unknown>
+ const names = ['dependencies', 'devDependencies', 'peerDependencies'].flatMap(key => {
+ const deps = json?.[key]
+
+ return deps !== null && typeof deps === 'object' && !Array.isArray(deps) ? Object.keys(deps) : []
+ })
+
+ return new Set(names)
+ } catch {
+ return new Set()
+ }
+}
+
+/**
+ * The project's stack, from the manifests at its root: each language present, and up to eight searches to offer
+ * (react → `react`). A dependency counts only when named as one (a key in package.json, `name =` or `name = {` in
+ * Cargo.toml, a requirement string in pyproject.toml, a `require` path in go.mod).
+ */
+export function inferStack(manifests: Manifests): { stack: string[]; chips: string[] } {
+ const stack: string[] = []
+ const chips: string[] = []
+ const add = (chip: string) => {
+ if (!chips.includes(chip) && chips.length < CHIPS_MAX && typedOf(chip) !== null) chips.push(chip)
+ }
+
+ if (typeof manifests.packageJson === 'string') {
+ const deps = nodeDeps(manifests.packageJson)
+
+ stack.push(deps.has('typescript') ? 'TypeScript' : 'JavaScript')
+ for (const [dep, chip] of NODE) if (deps.has(dep)) add(chip)
+ }
+
+ if (typeof manifests.cargoToml === 'string') {
+ const text = manifests.cargoToml.slice(0, 500_000)
+
+ stack.push('Rust')
+ add('rust')
+ for (const [dep, chip] of RUST) if (new RegExp(`^\\s*${escape(dep)}\\s*=`, 'm').test(text)) add(chip)
+ }
+
+ if (typeof manifests.pyproject === 'string') {
+ const text = manifests.pyproject.slice(0, 500_000).toLowerCase()
+
+ stack.push('Python')
+ add('python')
+ for (const [dep, chip] of PYTHON) if (new RegExp(`["'\\s]${escape(dep)}\\s*(?:[<>=~!\\[;"']|$)`, 'm').test(text)) add(chip)
+ }
+
+ if (typeof manifests.goMod === 'string') {
+ const text = manifests.goMod.slice(0, 500_000)
+
+ stack.push('Go')
+ add('golang')
+ for (const [dep, chip] of GO) if (new RegExp(`^\\s*(?:require\\s+)?${escape(dep)}\\s+v`, 'm').test(text)) add(chip)
+ }
+
+ return { stack, chips }
+}
+
+/** A short path for the view: the file's name under its agents folder. */
+const shortOf = (path: string): string => path.replace(/^.*?\/(agents|commands)\//, '$1/')
+
+/**
+ * Which agent files name each local skill: a whole-word, case-insensitive match of the skill's name (at least three
+ * characters, so `go` or `ui` never matches everywhere), at most eight files per skill.
+ */
+export function skillRefs(skills: readonly { name: string; where: string }[], docs: readonly { path: string; text: string }[]): { name: string; where: string; refs: string[] }[] {
+ return skills.map(skill => {
+ const isMatchable = skill.name.length >= 3
+ const pattern = new RegExp(`(^|[^A-Za-z0-9_-])${escape(skill.name)}($|[^A-Za-z0-9_-])`, 'i')
+ const refs = isMatchable ? docs.filter(doc => pattern.test(doc.text)).map(doc => shortOf(doc.path)).slice(0, 8) : []
+
+ return { name: skill.name, where: skill.where, refs }
+ })
+}
diff --git a/plugins/ruflo-console/hooks/data/skills.ts b/plugins/ruflo-console/hooks/data/skills.ts
index d619703e3f..e5a5b4a26d 100644
--- a/plugins/ruflo-console/hooks/data/skills.ts
+++ b/plugins/ruflo-console/hooks/data/skills.ts
@@ -35,8 +35,32 @@ export type SkillsState = {
asked: { key: string; label: string } | null
/** How the last change went, kept for the view after the footer lets it go. */
last: Outcome | null
+ /** Where ▸ add and ▸ update all go: the scope, and the agents named to `--agent` (none: the CLI's own pick). */
+ scope: Scope
+ agents: string[]
+ /** How results are ordered: as skills.sh answered, or by install count. */
+ sort: 'relevance' | 'installs'
+ /** When the shown results arrived: a headless `skills-find` answers with them. */
+ foundAtMs: number
+ /** The preview panel: a skill's SKILL.md (installed) or its repository's skill list (a result), and what is loading. */
+ preview: Preview | null
+ previewing: string | null
+ /** A ▸ use run in flight (its id). */
+ using: string | null
+ /** The last ▸ scan: the stack the project's manifests show, and the skills its ruflo agents name. */
+ scan: Scan | null
+ isScanning: boolean
+ /** The skill the person last created or named for authoring, and its check. */
+ authored: string | null
+ check: { name: string; ok: boolean; lines: string[]; atMs: number } | null
}
+export type Preview = { title: string; kind: 'installed' | 'repo'; lines: string[]; ok: boolean; atMs: number }
+
+/** One local skill (under .claude/skills or .agents/skills) and the agent files that name it. */
+export type LocalSkill = { name: string; where: string; refs: string[] }
+export type Scan = { stack: string[]; chips: string[]; local: LocalSkill[]; agentFiles: number; atMs: number; notes: string[] }
+
export const emptySkills = (): SkillsState => ({
installed: null,
listErrors: {},
@@ -51,8 +75,37 @@ export const emptySkills = (): SkillsState => ({
busy: null,
asked: null,
last: null,
+ scope: 'project',
+ agents: [],
+ sort: 'relevance',
+ foundAtMs: 0,
+ preview: null,
+ previewing: null,
+ using: null,
+ scan: null,
+ isScanning: false,
+ authored: null,
+ check: null,
})
+/**
+ * The agents ▸ add can name to `--agent`, by the CLI's own ids (skills 1.7.0 `agents` table; it knows ~75, these are
+ * the common ones). A fixed list: nothing typed ever reaches `--agent`.
+ */
+export const AGENT_TARGETS: readonly { id: string; label: string }[] = [
+ { id: 'claude-code', label: 'Claude Code' },
+ { id: 'codex', label: 'Codex' },
+ { id: 'cursor', label: 'Cursor' },
+ { id: 'gemini-cli', label: 'Gemini CLI' },
+ { id: 'github-copilot', label: 'Copilot' },
+ { id: 'opencode', label: 'OpenCode' },
+ { id: 'windsurf', label: 'Windsurf' },
+ { id: 'cline', label: 'Cline' },
+]
+
+/** The agent ids that may become argv: known targets only, in the list's order, each once. */
+export const agentsOf = (picked: readonly string[]): string[] => AGENT_TARGETS.map(agent => agent.id).filter(id => picked.includes(id))
+
const TYPED = /^[A-Za-z0-9@/._ -]+$/
const SKILL_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*(\/[A-Za-z0-9._-]+)*@[A-Za-z0-9][A-Za-z0-9._:-]*$/
const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/
@@ -96,7 +149,24 @@ export function findArgv(value: string): readonly string[] | null {
}
export const listArgv = (scope: Scope): readonly string[] => [...SKILLS, 'ls', ...(scope === 'global' ? ['-g'] : []), '--json']
-export const addArgv = (id: string, scope: Scope): readonly string[] => [...SKILLS, 'add', id, ...(scope === 'global' ? ['-g'] : []), '-y']
+/** `--agent` takes every word up to the next one starting with -, so the agents come last, before `-y`. */
+const agentFlag = (agents: readonly string[]): string[] => {
+ const ids = agentsOf(agents)
+
+ return ids.length === 0 ? [] : ['--agent', ...ids]
+}
+
+export const addArgv = (id: string, scope: Scope, agents: readonly string[] = []): readonly string[] => [...SKILLS, 'add', id, ...(scope === 'global' ? ['-g'] : []), ...agentFlag(agents), '-y']
+/** `use <id>` prints a prompt that carries the skill's SKILL.md; it copies the skill to a temp dir, installs nothing. */
+export const useArgv = (id: string): readonly string[] => [...SKILLS, 'use', id]
+/** `add <id> --list` lists the repository's skills and exits before installing (never with --json: the CLI refuses it). */
+export const listRepoArgv = (id: string): readonly string[] => [...SKILLS, 'add', id, '--list']
+/** `update` with no names updates every skill of the scope. */
+export const updateAllArgv = (scope: Scope): readonly string[] => [...SKILLS, 'update', scope === 'global' ? '-g' : '-p', '-y']
+/** Restores the project's skills from skills-lock.json: takes no flags. */
+export const restoreArgv = (): readonly string[] => [...SKILLS, 'experimental_install']
+/** Links skills found in node_modules into the agents' folders. */
+export const syncArgv = (agents: readonly string[] = []): readonly string[] => [...SKILLS, 'experimental_sync', ...agentFlag(agents), '-y']
export const removeArgv = (name: string, scope: Scope): readonly string[] => [...SKILLS, 'remove', name, ...(scope === 'global' ? ['-g'] : []), '-y']
/** With the scope named, so `update` never stops at its project-or-global prompt. */
export const updateArgv = (name: string, scope: Scope): readonly string[] => [...SKILLS, 'update', name, scope === 'global' ? '-g' : '-p', '-y']
@@ -146,3 +216,66 @@ export function parseFind(stdout: string): FoundSkill[] {
/** The skill's own name in an `owner/repo@skill` id: what `ls` lists once it is added. */
export const nameInId = (id: string): string => id.slice(id.lastIndexOf('@') + 1)
+
+/** An install count as skills.sh prints it (`1M`, `764.8K`, `42`), or -1 when there is none. */
+export function installsOf(text: string | undefined): number {
+ const match = /^([\d.]+)([KM]?)$/.exec(text ?? '')
+ const n = match === null ? NaN : Number(match[1])
+
+ return Number.isFinite(n) && match !== null ? n * (match[2] === 'M' ? 1_000_000 : match[2] === 'K' ? 1000 : 1) : -1
+}
+
+/** The results in the order asked for: as found, or most installed first (results without a count last). */
+export const sortedFound = (found: readonly FoundSkill[], sort: SkillsState['sort']): FoundSkill[] =>
+ sort === 'installs' ? [...found].sort((a, b) => installsOf(b.installs) - installsOf(a.installs)) : [...found]
+
+/** A line with its colour gone but its indent kept (`plain` folds whitespace, and the indent is what tells names from text). */
+const bare = (line: string): string => line.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').replace(/\s+$/, '')
+
+export type RepoSkill = { name: string; description: string; group?: string }
+
+/**
+ * `skills add <id> --list`: after the `Available Skills` step, each skill is a `│ name` line then a `│ text`
+ * line (deeper); a line with no bar is a group's title. Everything before that step (spinners, the source) is passed over.
+ */
+export function parseRepoList(stdout: string): RepoSkill[] {
+ const lines = stdout.slice(0, 200_000).split('\n').map(bare)
+ const start = lines.findIndex(line => /Available Skills\s*$/.test(line))
+ const out: RepoSkill[] = []
+ let group: string | undefined
+
+ if (start < 0) return out
+
+ for (const line of lines.slice(start + 1)) {
+ if (out.length >= 60) break
+ if (/^[└]/.test(line)) break
+
+ const body = /^│(\s*)(.*)$/.exec(line)
+
+ if (body === null) {
+ if (line.trim() !== '') group = plain(line, 60)
+ continue
+ }
+
+ const [, indent = '', words = ''] = body
+
+ if (words.trim() === '') continue
+
+ const last = out[out.length - 1]
+
+ if (indent.length <= 4) out.push({ name: plain(words, 80), description: '', ...(group !== undefined && { group }) })
+ else if (last !== undefined) last.description = plain(`${last.description} ${words}`, 300)
+ }
+
+ return out
+}
+
+/** The terminal sends at most this much of a prompt; a longer one is cut here, and the outcome says so. */
+export const USE_MAX = 8_000
+
+/** What `use` printed, as the prompt the terminal is loaded with: trimmed, capped, empty when there is none. */
+export function usePromptOf(stdout: string): { prompt: string; isCut: boolean } {
+ const text = stdout.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/\r/g, '').trim()
+
+ return { prompt: text.slice(0, USE_MAX), isCut: text.length > USE_MAX }
+}
diff --git a/plugins/ruflo-console/hooks/dispatch.ts b/plugins/ruflo-console/hooks/dispatch.ts
index 52f917f9b2..f0c2829dbf 100644
--- a/plugins/ruflo-console/hooks/dispatch.ts
+++ b/plugins/ruflo-console/hooks/dispatch.ts
@@ -9,6 +9,7 @@ import type { Controller } from './controller'
import { median, p95 } from './controller'
import { plain } from './data/parse'
import { labAnswer } from './mh-lab'
+import { skillsAnswer } from './skills-lab'
import { VIEWS, type State } from './state'
import { barText } from './views/bar'
import { viewText } from './views/pane'
@@ -114,7 +115,7 @@ export async function dispatch(control: Controller, state: State, args: string,
// A lab read answers with what it printed, so `/ruflo run mh-genome` works headless.
if (state.pending === null) await control.runner.settled()
- return { text: state.pending !== null ? `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.` : (labAnswer(state, intent.paletteId, askedAtMs) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done'))) }
+ return { text: state.pending !== null ? `Asked: ${state.pending.label}. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.` : (labAnswer(state, intent.paletteId, askedAtMs) ?? skillsAnswer(state, intent.paletteId, askedAtMs) ?? (state.outcome !== null && !state.outcome.ok ? `${state.outcome.label}: ${state.outcome.detail}` : (state.outcome?.label ?? 'done'))) }
}
case 'confirm':
if (state.pending === null) return { text: 'Nothing is waiting for a confirm.' }
diff --git a/plugins/ruflo-console/hooks/palette.ts b/plugins/ruflo-console/hooks/palette.ts
index 320a67f328..98b3ea55b2 100644
--- a/plugins/ruflo-console/hooks/palette.ts
+++ b/plugins/ruflo-console/hooks/palette.ts
@@ -7,6 +7,7 @@ import { HIVE_ROLES, pickedProposal } from './data/hive'
import { hiveBroadcast, hivePropose, hiveSpawn, hiveVote } from './hive'
import { claimTask, handoffClaim, releaseClaim, stealClaim, type ActionSpec } from './actions'
import { LAB, labSpec, labWhy } from './mh-lab'
+import { skillPaletteEntries } from './skills-lab'
import { AGENT_TYPES, agentLogs, dispatchWorker, memorySearch, memoryStore, reroute, setClaimStatus, spawnAgent, stopAgent, swarmInit, swarmStop, vote, WORKERS } from './ops'
import { VIEWS, type State, type ViewId } from './state'
import { selection } from './views/select'
@@ -49,7 +50,7 @@ export function fuzzy(query: string, label: string): number | null {
return whole < 0 ? score : score + 5 + (whole === 0 || text[whole - 1] === ' ' ? 3 : 0)
}
-const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast'] as const
+const TEXT_KEYWORDS = ['route', 'store', 'search', 'propose', 'broadcast', 'skills-find'] as const
/** Every entry for the state as it is, before filtering. */
export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
@@ -116,6 +117,9 @@ export function paletteEntries(state: State, nowMs: number): PaletteEntry[] {
// The MetaHarness lab: reads run at once, the rest ask first; promotion is never an entry (see mh-lab.ts).
for (const entry of LAB) add(entry.id, 'metaharness', entry.label, { kind: 'spec', spec: labSpec(entry, state), why: labWhy(entry) })
+ // The skills view's search, update-all, restore and sync, so /ruflo run skills-update works headless.
+ out.push(...skillPaletteEntries(state))
+
for (const worker of WORKERS) add(`worker-${worker}`, 'workers', `dispatch the ${worker} background worker`, { kind: 'spec', spec: dispatchWorker(worker), why: 'unknown worker' })
add('route', 'learning', 'route <task words>: ask the router for a pick', { kind: 'text', keyword: 'route', make: reroute })
diff --git a/plugins/ruflo-console/hooks/runner.ts b/plugins/ruflo-console/hooks/runner.ts
index 6a61fe2313..c7778aceb7 100644
--- a/plugins/ruflo-console/hooks/runner.ts
+++ b/plugins/ruflo-console/hooks/runner.ts
@@ -43,7 +43,10 @@ export function createRunner(state: State, host: Host, deps: RunnerDeps): Runner
async function execute(spec: ActionSpec): Promise<void> {
// A harness run reports into the terminal and may take minutes: it does not hold the other buttons.
if (spec.run !== undefined) {
- void spec.run()
+ const running = spec.run()
+
+ // A read that runs its own command (a skills search) is waited on, so `/ruflo run` answers with what it found.
+ if (spec.isReadOnly === true) await running
return
}
diff --git a/plugins/ruflo-console/hooks/skills-lab.ts b/plugins/ruflo-console/hooks/skills-lab.ts
new file mode 100644
index 0000000000..70966d5dca
--- /dev/null
+++ b/plugins/ruflo-console/hooks/skills-lab.ts
@@ -0,0 +1,361 @@
+/**
+ * The rest of the skills view's work, beside the list/search/add/remove of skills.ts: ▸ use a skill without installing
+ * it (its prompt goes to the AI terminal, typed, never sent), previews (an installed SKILL.md read from disk, bounded; a
+ * result's repository listed by `add <id> --list`, which installs nothing), update-all / restore / sync behind a confirm,
+ * the scope and agents ▸ add installs to, a scan of this project (its stack as searches, and which agent files name its
+ * skills), and authoring (claude writes the SKILL.md, the console checks its frontmatter). Network reads run only on a
+ * click; every change is one fixed argv on the confirm row, its cost in words beside it.
+ */
+import type { ActionSpec } from './actions'
+import { readBounded, textOf, under, type ReaderFs } from './data/files'
+import { plain } from './data/parse'
+import { checkLines, checkSkillMd, inferStack, skillRefs } from './data/skill-md'
+import { AGENT_TARGETS, agentsOf, findArgv, listRepoArgv, nameInId, newNameOf, parseRepoList, restoreArgv, skillIdOf, skillNameOf, sortedFound, syncArgv, updateAllArgv, useArgv, usePromptOf, type FoundSkill, type InstalledSkill, type Scope } from './data/skills'
+import type { Host } from './host'
+import type { PaletteEntry } from './palette'
+import type { Runner } from './runner'
+import { change, findSettled, findSkills } from './skills'
+import type { State } from './state'
+
+const NET_TIMEOUT_MS = 90_000
+/** Lines of a SKILL.md the preview shows under its check. */
+export const PREVIEW_LINES = 40
+/** Agent files read by ▸ scan, at most, and the largest one read. */
+const DOCS_MAX = 200
+const DOC_BYTES = 200_000
+
+export const NOTES = {
+ use: 'network: downloads the skill to a temp dir (skills-use-*); installs nothing; the prompt is typed into the AI terminal, not sent',
+ list: 'network: clones the repository to a temp dir to list it; installs nothing',
+ update: 'network: fetches each skill from its source and rewrites its folder',
+ restore: 'experimental · network: clones every source in skills-lock.json and writes the agents’ skill folders',
+ sync: 'experimental: links skills found in node_modules into the agents’ skill folders (writes)',
+} as const
+
+const hosts = new WeakMap<State, { host: Host; load: (text: string) => void }>()
+
+const errorOf = (error: unknown): string => plain(error instanceof Error ? error.message : String(error), 160) || 'refused'
+
+function say(state: State, host: Host, label: string, ok: boolean, detail: string, lines?: string[]): void {
+ state.outcome = { label, ok, verified: 'n/a', detail, atMs: Date.now(), ...(lines !== undefined && { lines }) }
+ state.skills.last = state.outcome
+ host.invalidate()
+}
+
+/** ▸ use: runs `use <id>` at once (a click is the ask) and loads its prompt into the claude terminal for review. */
+export function useSpec(state: State, host: Host, found: FoundSkill, load: (text: string) => void): ActionSpec | null {
+ const id = skillIdOf(found.id)
+
+ if (id === null) return null
+
+ const argv = useArgv(id)
+ const label = `use ${id} without installing it`
+
+ return {
+ label,
+ args: argv,
+ shows: argv.join(' '),
+ expect: 'the skill’s prompt typed into the AI terminal',
+ isReadOnly: true,
+ note: NOTES.use,
+ run: async () => {
+ const skills = state.skills
+
+ if (skills.using !== null) return say(state, host, label, false, `${skills.using} is still being fetched`)
+
+ skills.using = id
+ host.invalidate()
+
+ try {
+ const result = await host.run(argv, NET_TIMEOUT_MS)
+ const { prompt, isCut } = usePromptOf(result.stdout)
+
+ if (result.exitCode !== 0 || prompt === '') return say(state, host, label, false, `exit ${result.exitCode}: ${plain(result.stderr, 160) || 'no prompt printed'}`)
+
+ load(prompt)
+ say(state, host, label, true, `its prompt is in the AI terminal${isCut ? ' (cut to 8,000 characters)' : ''}: read it, then Enter twice sends it to claude`)
+ } catch (error) {
+ say(state, host, label, false, errorOf(error))
+ } finally {
+ skills.using = null
+ host.invalidate()
+ }
+ },
+ }
+}
+
+/** ▸ preview of a result: `add <id> --list` (lists, installs nothing), its skills shown, the picked one marked. */
+export function previewFoundSpec(state: State, host: Host, found: FoundSkill): ActionSpec | null {
+ const id = skillIdOf(found.id)
+
+ if (id === null) return null
+
+ const argv = listRepoArgv(id)
+ const label = `preview ${id}`
+
+ return {
+ label,
+ args: argv,
+ shows: argv.join(' '),
+ expect: 'the repository’s skills in the preview panel',
+ isReadOnly: true,
+ note: NOTES.list,
+ run: async () => {
+ const skills = state.skills
+
+ skills.previewing = id
+ host.invalidate()
+
+ try {
+ const result = await host.run(argv, NET_TIMEOUT_MS)
+ const listed = parseRepoList(result.stdout)
+ const want = nameInId(id).toLowerCase()
+ const lines = listed.flatMap(skill => [`${skill.name.toLowerCase() === want ? '▸' : ' '} ${skill.name}${skill.group !== undefined ? ` (${skill.group})` : ''}`, ` ${skill.description}`])
+ const ok = result.exitCode === 0 && listed.length > 0
+
+ skills.preview = { title: `${id} · ${listed.length} skill${listed.length === 1 ? '' : 's'} in its repository`, kind: 'repo', lines: ok ? lines : [`exit ${result.exitCode}: ${plain(result.stderr, 160) || 'no skills listed'}`], ok, atMs: Date.now() }
+ say(state, host, label, ok, ok ? `${listed.length} listed; nothing installed` : 'nothing listed')
+ } catch (error) {
+ skills.preview = { title: id, kind: 'repo', lines: [errorOf(error)], ok: false, atMs: Date.now() }
+ say(state, host, label, false, errorOf(error))
+ } finally {
+ skills.previewing = null
+ host.invalidate()
+ }
+ },
+ }
+}
+
+/** A path the CLI listed, accepted only when absolute and free of `..` segments. */
+export const isSafeDir = (path: string): boolean => path.startsWith('/') && !path.split('/').includes('..') && !/[\u0000-\u001f]/.test(path)
+
+/** Reads a SKILL.md (bounded), checks it and keeps the result as the preview; never runs it. */
+async function previewFile(state: State, fs: ReaderFs, title: string, path: string, folder: string): Promise<void> {
+ const read = await readBounded(fs, state.cache, path)
+ const text = textOf(read)
+
+ if (text === null) {
+ state.skills.preview = { title, kind: 'installed', lines: [`${path}: ${'reason' in read ? read.reason : 'unread'}`], ok: false, atMs: Date.now() }
+
+ return
+ }
+
+ const check = checkSkillMd(text, folder)
+
+ state.skills.preview = { title, kind: 'installed', lines: [...checkLines(check), '', ...text.split('\n').slice(0, PREVIEW_LINES).map(line => plain(line, 160))], ok: check.ok, atMs: Date.now() }
+}
+
+/** The person's own skills in this project, and every agent file that names one, all from disk (bounded). */
+export async function scanProject(state: State, fs: ReaderFs): Promise<void> {
+ const read = (path: string) => readBounded(fs, state.cache, under(state.cwd, path)).then(textOf)
+ const [packageJson, cargoToml, pyproject, goMod] = await Promise.all(['package.json', 'Cargo.toml', 'pyproject.toml', 'go.mod'].map(read))
+ const { stack, chips } = inferStack({ packageJson, cargoToml, pyproject, goMod })
+ const notes: string[] = []
+ const local: { name: string; where: string }[] = []
+
+ for (const where of ['.claude/skills', '.agents/skills']) {
+ const entries = await fs.list(under(state.cwd, where)).catch(() => [])
+
+ for (const entry of entries.slice(0, 100)) {
+ const name = skillNameOf(entry.name)
+
+ if (name === null || entry.kind === 'file' || local.some(skill => skill.name === name)) continue
+ if (await fs.stat(under(state.cwd, `${where}/${name}/SKILL.md`)).then(() => true, () => false)) local.push({ name, where })
+ }
+ }
+
+ const docs: { path: string; text: string }[] = []
+ const walk = async (dir: string, depth: number): Promise<void> => {
+ const entries = await fs.list(dir).catch(() => [])
+
+ for (const entry of entries) {
+ if (docs.length >= DOCS_MAX || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(entry.name)) continue
+
+ const path = `${dir}/${entry.name}`
+
+ if (entry.kind === 'dir' && depth > 0) await walk(path, depth - 1)
+ else if (entry.kind !== 'dir' && entry.name.endsWith('.md') && (entry.size ?? 0) <= DOC_BYTES) {
+ const text = textOf(await readBounded(fs, state.cache, path))
+
+ if (text !== null) docs.push({ path, text: text.slice(0, DOC_BYTES) })
+ }
+ }
+ }
+
+ await walk(under(state.cwd, '.claude/agents'), 2)
+ if (docs.length >= DOCS_MAX) notes.push(`read the first ${DOCS_MAX} agent files only`)
+
+ state.skills.scan = { stack, chips, local: skillRefs(local, docs), agentFiles: docs.length, atMs: Date.now(), notes }
+}
+
+/** What the AI terminal is loaded with for ▸ write: the skill's file, the rules its check holds it to. */
+export const authorPrompt = (cwd: string, name: string): string =>
+ `Write the agent skill at ${plain(cwd, 300)}/${name}/SKILL.md. Keep its YAML frontmatter at the top with name: ${name} (lowercase letters, digits and hyphens) and a one-sentence description: of what it does and when to use it (at most 1024 characters), then concise instructions under 500 lines; put long reference material in separate files beside it. The skill is for: `
+
+export type MoreSkillActions = {
+ use: (found: FoundSkill) => void
+ previewFound: (found: FoundSkill) => void
+ previewInstalled: (skill: InstalledSkill) => void
+ closePreview: () => void
+ updateAll: () => void
+ restore: () => void
+ sync: () => void
+ scope: (scope: Scope) => void
+ toggleAgent: (id: string) => void
+ sortBy: () => void
+ scan: () => void
+ /** A recommended search: fills the field and asks skills.sh. */
+ chip: (query: string) => void
+ /** ▸ write: the AI terminal, loaded with a prompt to write the skill named in the create field. */
+ author: () => void
+ validate: () => void
+}
+
+/** The skill being authored: the create field's name, else the one created last. */
+const authoredOf = (state: State): string | null => newNameOf(state.skills.createDraft) ?? state.skills.authored
+
+export const updateAllSpec = (state: State, host: Host): ActionSpec => ({
+ ...change(state, host, `update every ${state.skills.scope} skill`, updateAllArgv(state.skills.scope), 'each skill at the newest version of its source'),
+ note: NOTES.update,
+})
+
+export const restoreSpec = (state: State, host: Host): ActionSpec => ({
+ ...change(state, host, 'restore the project’s skills from skills-lock.json', restoreArgv(), 'every skill in skills-lock.json installed'),
+ note: NOTES.restore,
+})
+
+export const syncSpec = (state: State, host: Host): ActionSpec => ({
+ ...change(state, host, `sync skills from node_modules${state.skills.agents.length > 0 ? ` for ${agentsOf(state.skills.agents).join(', ')}` : ''}`, syncArgv(state.skills.agents), 'node_modules skills linked into the agents’ folders'),
+ note: NOTES.sync,
+})
+
+export function moreSkillActions(state: State, host: Host, runner: Runner, load: (text: string) => void): MoreSkillActions {
+ const skills = state.skills
+ const notAnId = 'that result is not an owner/repo@skill id'
+
+ hosts.set(state, { host, load })
+
+ return {
+ use: found => runner.ask(useSpec(state, host, found, load), notAnId),
+ previewFound: found => runner.ask(previewFoundSpec(state, host, found), notAnId),
+ previewInstalled: skill => {
+ if (!isSafeDir(skill.path)) return runner.ask(null, 'that skill’s path is not an absolute path the console will read')
+
+ skills.previewing = skill.name
+ host.invalidate()
+ void previewFile(state, host.fs, `${skill.name} · ${skill.scope} · SKILL.md`, `${skill.path.replace(/\/+$/, '')}/SKILL.md`, skill.path.split('/').pop() ?? '').finally(() => {
+ skills.previewing = null
+ host.invalidate()
+ })
+ },
+ closePreview: () => {
+ skills.preview = null
+ host.invalidate()
+ },
+ updateAll: () => runner.ask(updateAllSpec(state, host), ''),
+ restore: () => runner.ask(restoreSpec(state, host), ''),
+ sync: () => runner.ask(syncSpec(state, host), ''),
+ scope: scope => {
+ skills.scope = scope
+ host.invalidate()
+ },
+ toggleAgent: id => {
+ if (!AGENT_TARGETS.some(agent => agent.id === id)) return
+
+ skills.agents = skills.agents.includes(id) ? skills.agents.filter(agent => agent !== id) : agentsOf([...skills.agents, id])
+ host.invalidate()
+ },
+ sortBy: () => {
+ skills.sort = skills.sort === 'installs' ? 'relevance' : 'installs'
+ if (skills.found !== null) skills.found = sortedFound(skills.found, skills.sort)
+ host.invalidate()
+ },
+ scan: () => {
+ if (skills.isScanning) return
+
+ skills.isScanning = true
+ host.invalidate()
+ void scanProject(state, host.fs)
+ .catch(error => say(state, host, 'scan this project', false, errorOf(error)))
+ .finally(() => {
+ skills.isScanning = false
+ host.invalidate()
+ })
+ },
+ chip: query => {
+ skills.searchDraft = query
+ const why = findSkills(state, host, query)
+
+ if (why !== null) runner.ask(null, why)
+ },
+ author: () => {
+ const name = authoredOf(state)
+
+ if (name === null) return runner.ask(null, 'type the new skill’s name in the create field first')
+
+ skills.authored = name
+ load(authorPrompt(state.cwd, name))
+ },
+ validate: () => {
+ const name = authoredOf(state)
+
+ if (name === null) return runner.ask(null, 'type the skill’s name in the create field first')
+
+ skills.authored = name
+ void readBounded(host.fs, state.cache, under(state.cwd, `${name}/SKILL.md`)).then(read => {
+ const text = textOf(read)
+ const lines = text === null ? [`${name}/SKILL.md: ${'reason' in read ? read.reason : 'unread'} (▸ create makes it)`] : checkLines(checkSkillMd(text, name))
+
+ skills.check = { name, ok: text !== null && lines[0]?.startsWith('✓') === true, lines, atMs: Date.now() }
+ host.invalidate()
+ })
+ },
+ }
+}
+
+/**
+ * The skills entries of the palette, so `/ruflo run skills-update` works headless: a search (`skills-find <words>`),
+ * update-all, restore and sync. Without the view's wiring (no host yet) each says so instead of running.
+ */
+export function skillPaletteEntries(state: State): PaletteEntry[] {
+ const wired = hosts.get(state)
+ const why = 'the skills view is not wired yet'
+ const spec = (make: (host: Host) => ActionSpec): { kind: 'spec'; spec: ActionSpec | null; why: string } => ({ kind: 'spec', spec: wired === undefined ? null : make(wired.host), why })
+ const find = (text: string): ActionSpec | null => {
+ const argv = findArgv(text)
+
+ if (wired === undefined || argv === null) return null
+
+ return {
+ label: `skills find ${plain(text, 64)}`,
+ args: argv,
+ shows: argv.join(' '),
+ expect: 'the results in the skills view',
+ isReadOnly: true,
+ note: 'network: asks skills.sh',
+ run: async () => {
+ state.skills.searchDraft = text
+ if (findSkills(state, wired.host, text) === null) await findSettled(state)
+ },
+ }
+ }
+
+ return [
+ { id: 'skills-find', group: 'skills', label: 'skills-find <words>: search skills.sh (owner:<name> narrows it)', run: { kind: 'text', keyword: 'skills-find', make: find } },
+ { id: 'skills-update', group: 'skills', label: `update every ${state.skills.scope} skill (npx skills update)`, run: spec(host => updateAllSpec(state, host)) },
+ { id: 'skills-restore', group: 'skills', label: 'restore the project’s skills from skills-lock.json', run: spec(host => restoreSpec(state, host)) },
+ { id: 'skills-sync', group: 'skills', label: 'sync skills from node_modules into the agents’ folders', run: spec(host => syncSpec(state, host)) },
+ ]
+}
+
+/** The headless answer for `skills-find`: the results that arrived since the ask, most installed first when sorted so. */
+export function skillsAnswer(state: State, id: string, sinceMs: number): string | null {
+ const skills = state.skills
+
+ if (id !== 'skills-find' || skills.foundAtMs < sinceMs) return null
+ if (skills.findError !== null) return `✗ skills find: ${skills.findError}`
+
+ const found = skills.found ?? []
+
+ return [`skills find "${skills.query}": ${found.length} found`, ...found.slice(0, 15).map(skill => ` ${skill.id}${skill.installs !== undefined ? ` · ${skill.installs} installs` : ''}`)].join('\n')
+}
diff --git a/plugins/ruflo-console/hooks/skills.ts b/plugins/ruflo-console/hooks/skills.ts
index 43bb7ac27b..f980470dcc 100644
--- a/plugins/ruflo-console/hooks/skills.ts
+++ b/plugins/ruflo-console/hooks/skills.ts
@@ -6,7 +6,7 @@
* installed lists are read again to say whether it took. Every argv is fixed, with no shell; nothing here writes a file.
*/
import type { ActionSpec } from './actions'
-import { addArgv, findArgv, initArgv, listArgv, nameInId, newNameOf, parseFind, parseInstalled, removeArgv, skillIdOf, skillNameOf, updateArgv, type FoundSkill, type InstalledSkill, type Scope } from './data/skills'
+import { addArgv, agentsOf, findArgv, initArgv, listArgv, nameInId, newNameOf, parseFind, parseInstalled, removeArgv, skillIdOf, skillNameOf, sortedFound, updateArgv, type FoundSkill, type InstalledSkill, type Scope } from './data/skills'
import { plain } from './data/parse'
import type { Host } from './host'
import { outputLines } from './ops'
@@ -20,6 +20,7 @@ const CHANGE_TIMEOUT_MS = 180_000
const firstLine = (text: string): string => plain(text.split('\n').find(line => line.trim() !== '') ?? '', 120)
const listing = new WeakMap<State, Promise<void>>()
+const finding = new WeakMap<State, Promise<void>>()
async function listOnce(state: State, host: Host): Promise<void> {
const skills = state.skills
@@ -82,10 +83,11 @@ export function findSkills(state: State, host: Host, text: string): string | nul
skills.findError = null
host.invalidate()
- void host
+ const run = host
.run(argv, READ_TIMEOUT_MS)
.then(result => {
- skills.found = parseFind(result.stdout)
+ skills.found = sortedFound(parseFind(result.stdout), skills.sort)
+ skills.foundAtMs = Date.now()
skills.findError = result.exitCode !== 0 ? `exit ${result.exitCode}: ${firstLine(result.stderr) || firstLine(result.stdout) || 'no message'}` : null
})
.catch((error: unknown) => {
@@ -97,14 +99,19 @@ export function findSkills(state: State, host: Host, text: string): string | nul
host.invalidate()
})
+ finding.set(state, run)
+
return null
}
+/** Resolves when the search started last has answered (a headless `skills-find` waits on it). */
+export const findSettled = (state: State): Promise<void> => finding.get(state) ?? Promise.resolve()
+
/**
* One confirm-gated change: `shows` puts its argv on the confirm row; once confirmed, `run` runs it, reads the lists
* again, and says how it went (on disk: the lists show the change).
*/
-function change(state: State, host: Host, label: string, argv: readonly string[], expect: string, verify?: (installed: InstalledSkill[]) => boolean): ActionSpec {
+export function change(state: State, host: Host, label: string, argv: readonly string[], expect: string, verify?: (installed: InstalledSkill[]) => boolean): ActionSpec {
return {
label,
args: argv,
@@ -156,7 +163,10 @@ const isIn = (name: string, scope: Scope) => (installed: InstalledSkill[]) => in
export function addSpec(state: State, host: Host, found: FoundSkill, scope: Scope): ActionSpec | null {
const id = skillIdOf(found.id)
- return id === null ? null : change(state, host, `add skill ${id}${scope === 'global' ? ' globally' : ' to this project'}`, addArgv(id, scope), `${nameInId(id)} listed as ${scope}`, isIn(nameInId(id), scope))
+ const agents = agentsOf(state.skills.agents)
+ const where = `${scope === 'global' ? ' globally' : ' to this project'}${agents.length > 0 ? ` for ${agents.join(', ')}` : ''}`
+
+ return id === null ? null : change(state, host, `add skill ${id}${where}`, addArgv(id, scope, agents), `${nameInId(id)} listed as ${scope}`, isIn(nameInId(id), scope))
}
export function removeSpec(state: State, host: Host, skill: InstalledSkill): ActionSpec | null {
@@ -229,6 +239,7 @@ export function skillActions(state: State, host: Host, runner: Runner, load: (te
const spec = name === null ? null : initSpec(state, host, name)
skills.createDraft = text
+ if (name !== null) skills.authored = name
runner.ask(spec, NAME_RULE)
skills.asked = spec !== null && name !== null ? { key: name, label: spec.label } : null
},
diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts
index 4270e97672..e996935dd8 100644
--- a/plugins/ruflo-console/hooks/state.ts
+++ b/plugins/ruflo-console/hooks/state.ts
@@ -41,7 +41,7 @@ export const VIEWS: readonly { id: ViewId; key: string; label: string; short: st
{ id: 'xruv', key: 'w', label: 'x.ruv.io', short: 'XRV', icon: '🛸', blurb: 'the open agent federation: what it offers, how to join, its channels and who is on', rows: 34 },
{ id: 'terminal', key: 'i', label: 'Terminal', short: 'Trm', icon: '💻', blurb: 'an AI terminal: codex, claude or both, each a session that remembers the conversation, streamed live', rows: 32 },
// No hotkey: every digit and letter is taken. The tab, the menu prompt and /ruflo skills reach it by name.
- { id: 'skills', key: '', label: 'Skills', short: 'Skl', icon: '🧰', blurb: 'agent skills (npx skills, skills.sh): what is installed here and globally, search, add, update, remove, create', rows: 34 },
+ { id: 'skills', key: '', label: 'Skills', short: 'Skl', icon: '🧰', blurb: 'agent skills (npx skills, skills.sh): installed, search, use without installing, preview, add to chosen agents, update, create', rows: 60 },
]
export const AGENT_VIEW = { id: 'agent' as const, rows: 28 }
diff --git a/plugins/ruflo-console/hooks/views/common.ts b/plugins/ruflo-console/hooks/views/common.ts
index 482d9f5b70..c698f5d734 100644
--- a/plugins/ruflo-console/hooks/views/common.ts
+++ b/plugins/ruflo-console/hooks/views/common.ts
@@ -8,6 +8,7 @@ import type { Elements, RenderChildren, RenderElement } from 'claude-code'
import type { ProbeResult } from '../data/cli'
import type { Grid } from '../gfx/raster'
import type { SkillActions } from '../skills'
+import type { MoreSkillActions } from '../skills-lab'
import type { HarnessId, State, ViewId } from '../state'
export type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button'> & { Raster?: Elements['terminal']['Raster']; Input?: Elements['terminal']['Input'] }
@@ -43,7 +44,7 @@ export type Actions = {
menu: (text: string) => void
term: { harness: (id: HarnessId) => void; draft: (text: string) => void; submit: (text: string) => void; stop: () => void; fresh: () => void; clear: () => void; load: (id: HarnessId, text: string) => void; /** Moves the window up (positive) or down by screen rows. */ scroll: (by: number) => void; /** Puts an earlier question back in the field. */ reuse: (text: string) => void }
/** The skills view: list, search, and the confirm-gated add, remove, update and create; edit loads the terminal. */
- skills: SkillActions
+ skills: SkillActions & MoreSkillActions
}
export type Ctx = {
diff --git a/plugins/ruflo-console/hooks/views/skills-more.ts b/plugins/ruflo-console/hooks/views/skills-more.ts
new file mode 100644
index 0000000000..1af2852acc
--- /dev/null
+++ b/plugins/ruflo-console/hooks/views/skills-more.ts
@@ -0,0 +1,136 @@
+import type { RenderElement } from 'claude-code'
+
+import { AGENT_TARGETS, agentsOf } from '../data/skills'
+import { ago, button, clip, row, rule, text, THEME, type Ctx } from './common'
+
+/** Preview lines in view at once. */
+export const PREVIEW_ROWS = 14
+
+const plainButton = (ctx: Ctx, key: string, label: string, onPress: () => void, isOn = false): RenderElement => ctx.kit.Button({ key, label, plain: true, dimColor: !isOn, onPress })
+
+/** Where ▸ add installs: the scope (one of two, clearly marked) and the agents named to `--agent`. */
+export function targetRows(ctx: Ctx): RenderElement[] {
+ const skills = ctx.state.skills
+ const agents = agentsOf(skills.agents)
+ const rows: RenderElement[] = [rule(ctx, 'Install to', `▸ add → ${skills.scope} · ${agents.length > 0 ? agents.join(' ') : 'the CLI’s default agents'}`)]
+
+ rows.push(
+ row(ctx, [
+ text(ctx, ' scope ', { dimColor: true }),
+ plainButton(ctx, 'sk-scope-project', skills.scope === 'project' ? ' (●) project: this repo ' : ' ( ) project: this repo ', () => ctx.act.skills.scope('project'), skills.scope === 'project'),
+ plainButton(ctx, 'sk-scope-global', skills.scope === 'global' ? ' (●) global: every project ' : ' ( ) global: every project ', () => ctx.act.skills.scope('global'), skills.scope === 'global'),
+ ]),
+ )
+ rows.push(
+ row(ctx, [
+ text(ctx, ' agents ', { dimColor: true }),
+ ...AGENT_TARGETS.map(agent => {
+ const isOn = skills.agents.includes(agent.id)
+
+ return plainButton(ctx, `sk-agent-${agent.id}`, ` [${isOn ? 'x' : ' '}] ${agent.label}`, () => ctx.act.skills.toggleAgent(agent.id), isOn)
+ }),
+ ]),
+ )
+ rows.push(text(ctx, ' none ticked: the CLI picks the agents it detects · update all and sync use the same choice', { dimColor: true }))
+
+ return rows
+}
+
+/** The preview panel: an installed SKILL.md with its check, or a result's repository list. */
+export function previewRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const { preview, previewing, using } = state.skills
+ const rows: RenderElement[] = []
+
+ if (preview === null && previewing === null && using === null) return rows
+
+ rows.push(rule(ctx, 'Preview', previewing !== null ? `reading ${clip(previewing, 40)}…` : preview === null ? '' : `${preview.kind === 'installed' ? 'local read' : 'add --list · nothing installed'} · ${ago(preview.atMs, nowMs)}`))
+
+ if (using !== null) rows.push(text(ctx, ` ▸ fetching ${using} for the AI terminal (npx -y skills use)…`, { color: THEME.warn }))
+ if (preview === null) return rows
+
+ rows.push(
+ row(ctx, [
+ text(ctx, ` ${clip(preview.title, Math.max(10, ctx.columns - 12))} `, { bold: true, color: preview.ok ? THEME.ok : THEME.warn }),
+ plainButton(ctx, 'sk-preview-close', ' ▸ close', () => ctx.act.skills.closePreview()),
+ ]),
+ )
+
+ for (const line of preview.lines.slice(0, PREVIEW_ROWS)) {
+ rows.push(text(ctx, ` ${line}`, line.startsWith('✗') ? { color: THEME.bad } : line.startsWith('!') ? { color: THEME.warn } : line.startsWith('✓') || line.startsWith('▸') ? { color: THEME.ok } : {}))
+ }
+
+ if (preview.lines.length > PREVIEW_ROWS) rows.push(text(ctx, ` … ${preview.lines.length - PREVIEW_ROWS} more lines`, { dimColor: true }))
+
+ return rows
+}
+
+/** Searches matching this project's stack, and the skills its ruflo agents name: on ▸ scan only (local reads). */
+export function projectRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const { scan, isScanning } = state.skills
+ const rows: RenderElement[] = [rule(ctx, 'For this project', isScanning ? 'scanning…' : scan === null ? 'not scanned · local reads only' : `scanned ${ago(scan.atMs, nowMs)}`)]
+
+ rows.push(
+ row(ctx, [
+ plainButton(ctx, 'sk-scan', ' ▸ scan', () => ctx.act.skills.scan()),
+ text(ctx, ' package.json, Cargo.toml, pyproject.toml, go.mod, .claude/skills, .agents/skills and .claude/agents: read here, nothing sent', { dimColor: true }),
+ ]),
+ )
+
+ if (scan === null) return rows
+
+ rows.push(
+ row(ctx, [
+ text(ctx, ` stack ${scan.stack.length > 0 ? scan.stack.join(', ') : 'n/a (no manifest at the root)'} `, { color: THEME.info }),
+ ...scan.chips.map((chip, i) => plainButton(ctx, `sk-chip-${i}`, ` ▸ find ${chip}`, () => ctx.act.skills.chip(chip))),
+ ]),
+ )
+
+ if (scan.local.length === 0) rows.push(text(ctx, ` no skills under .claude/skills or .agents/skills · ${scan.agentFiles} agent files read`, { dimColor: true }))
+ else rows.push(text(ctx, ` skills your ruflo agents use · ${scan.local.length} local · ${scan.agentFiles} agent files read`, { bold: true }))
+
+ for (const skill of scan.local.slice(0, 8)) {
+ rows.push(text(ctx, ` ${skill.name} (${skill.where}) ← ${skill.refs.length > 0 ? skill.refs.join(', ') : 'no agent names it'}`, skill.refs.length > 0 ? { color: THEME.ok } : { dimColor: true }))
+ }
+
+ if (scan.local.length > 8) rows.push(text(ctx, ` +${scan.local.length - 8} more`, { dimColor: true }))
+ for (const note of scan.notes) rows.push(text(ctx, ` ${note}`, { color: THEME.warn }))
+
+ return rows
+}
+
+/** After ▸ create: claude writes it, the console checks its frontmatter. */
+export function authorRows(ctx: Ctx): RenderElement[] {
+ const { state, nowMs } = ctx
+ const { check, authored } = state.skills
+ const rows: RenderElement[] = [
+ row(ctx, [
+ text(ctx, ` ${authored !== null ? `${authored}/SKILL.md` : 'the named skill'} `, { dimColor: true }),
+ plainButton(ctx, 'sk-author', ' ▸ write with claude', () => ctx.act.skills.author()),
+ plainButton(ctx, 'sk-validate', ' ▸ validate', () => ctx.act.skills.validate()),
+ ]),
+ ]
+
+ if (check !== null) {
+ rows.push(text(ctx, ` ${check.name}/SKILL.md · checked ${ago(check.atMs, nowMs)}`, { dimColor: true }))
+ for (const line of check.lines.slice(0, 6)) rows.push(text(ctx, ` ${line}`, line.startsWith('✓') ? { color: THEME.ok } : line.startsWith('✗') ? { color: THEME.bad } : line.startsWith('!') ? { color: THEME.warn } : {}))
+ }
+
+ return rows
+}
+
+/** Changes to many skills at once, each asked first with its argv and what it costs. */
+export function maintainRows(ctx: Ctx): RenderElement[] {
+ const skills = ctx.state.skills
+
+ return [
+ rule(ctx, 'Maintain', 'each asks first · network and writes named on the confirm row'),
+ row(ctx, [
+ button(ctx, 'sk-update-all', `update all (${skills.scope})`, () => ctx.act.skills.updateAll()),
+ button(ctx, 'sk-restore', 'restore from skills-lock.json', () => ctx.act.skills.restore()),
+ button(ctx, 'sk-sync', 'sync from node_modules', () => ctx.act.skills.sync()),
+ ]),
+ text(ctx, ' restore and sync are the CLI’s experimental_install and experimental_sync', { dimColor: true }),
+ ]
+}
diff --git a/plugins/ruflo-console/hooks/views/skills.ts b/plugins/ruflo-console/hooks/views/skills.ts
index 278c03b60b..3a5dd0ccc0 100644
--- a/plugins/ruflo-console/hooks/views/skills.ts
+++ b/plugins/ruflo-console/hooks/views/skills.ts
@@ -2,6 +2,7 @@ import type { RenderElement } from 'claude-code'
import type { FoundSkill, InstalledSkill } from '../data/skills'
import { ago, clip, col, row, rule, text, THEME, type Ctx } from './common'
+import { authorRows, maintainRows, previewRows, projectRows, targetRows } from './skills-more'
const SHOWN = 10
@@ -42,6 +43,7 @@ function installedRows(ctx: Ctx): RenderElement[] {
{ key: `sk-update-${i}`, label: 'update', onPress: () => ctx.act.skills.update(skill) },
{ key: `sk-remove-${i}`, label: 'remove', onPress: () => ctx.act.skills.remove(skill) },
{ key: `sk-edit-${i}`, label: 'edit', onPress: () => ctx.act.skills.edit(skill) },
+ { key: `sk-view-${i}`, label: 'view', onPress: () => ctx.act.skills.previewInstalled(skill) },
], skill.scope === 'global' ? THEME.ok : THEME.head),
)
rows.push(text(ctx, ` ${skill.path}${skill.source !== undefined ? ` · from ${skill.source}` : ''}`, { dimColor: true }))
@@ -54,14 +56,14 @@ function installedRows(ctx: Ctx): RenderElement[] {
function searchRows(ctx: Ctx): RenderElement[] {
const skills = ctx.state.skills
- const rows: RenderElement[] = [rule(ctx, 'Search', 'skills.sh · npx skills find')]
+ const rows: RenderElement[] = [rule(ctx, 'Search', `skills.sh · npx skills find · ${skills.sort === 'installs' ? 'most installed first' : 'as found'}`)]
if (ctx.kit.Input !== undefined) {
rows.push(
ctx.kit.Input({
key: 'skills-search',
label: 'find',
- placeholder: 'a word or two: react, testing, owner:vercel-labs deploy …',
+ placeholder: 'a word or two: react, testing · owner:vercel-labs deploy narrows to one GitHub owner',
value: skills.searchDraft,
submitLabel: 'search',
onInput: value => ctx.act.skills.searchDraft(value),
@@ -80,13 +82,21 @@ function searchRows(ctx: Ctx): RenderElement[] {
;(skills.found ?? []).slice(0, SHOWN).forEach((found: FoundSkill, i) => {
rows.push(
leader(ctx, `sk-found-${i}`, found.id, found.installs !== undefined ? `${found.installs} installs` : 'installs n/a', [
- { key: `sk-add-${i}`, label: 'add', onPress: () => ctx.act.skills.add(found, 'project') },
- { key: `sk-addg-${i}`, label: 'add -g', onPress: () => ctx.act.skills.add(found, 'global') },
+ { key: `sk-use-${i}`, label: 'use', onPress: () => ctx.act.skills.use(found) },
+ { key: `sk-preview-${i}`, label: 'preview', onPress: () => ctx.act.skills.previewFound(found) },
+ { key: `sk-add-${i}`, label: 'add', onPress: () => ctx.act.skills.add(found, skills.scope) },
]),
)
})
- if ((skills.found?.length ?? 0) > 0) rows.push(text(ctx, ' ▸ add installs into this project, ▸ add -g for every project; each asks first (y/n)', { dimColor: true }))
+ if ((skills.found?.length ?? 0) > 0) {
+ rows.push(
+ row(ctx, [
+ ctx.kit.Button({ key: 'sk-sort', label: skills.sort === 'installs' ? ' ▸ sort: as found' : ' ▸ sort: most installed', plain: true, dimColor: true, onPress: () => ctx.act.skills.sortBy() }),
+ text(ctx, ` · ▸ use hands the skill to claude without installing · ▸ preview lists its repo · ▸ add installs to ${skills.scope} (asks first)`, { dimColor: true }),
+ ]),
+ )
+ }
return rows
}
@@ -110,6 +120,7 @@ function createRows(ctx: Ctx): RenderElement[] {
}
rows.push(text(ctx, ' Enter shows the command, Enter again (or y) runs it · ▸ edit opens a skill in the AI terminal with claude', { dimColor: true }))
+ rows.push(...authorRows(ctx))
return rows
}
@@ -129,5 +140,5 @@ export function skillsView(ctx: Ctx): RenderElement {
status.push(text(ctx, ` ${skills.last.ok ? '✓' : '✗'} ${skills.last.label}${skills.last.verified === 'yes' ? ' · listed' : skills.last.verified === 'no' ? ' · not listed' : ''}: ${skills.last.detail} (${ago(skills.last.atMs, nowMs)})`, { color: skills.last.ok ? THEME.ok : THEME.bad }))
}
- return col(ctx, [...status, ...installedRows(ctx), ...searchRows(ctx), ...createRows(ctx)], 'skills')
+ return col(ctx, [...status, ...targetRows(ctx), ...installedRows(ctx), ...searchRows(ctx), ...previewRows(ctx), ...projectRows(ctx), ...createRows(ctx), ...maintainRows(ctx)], 'skills')
}
diff --git a/plugins/ruflo-console/tests/fixtures/skills.ts b/plugins/ruflo-console/tests/fixtures/skills.ts
index 346336e54f..2595818e5e 100644
--- a/plugins/ruflo-console/tests/fixtures/skills.ts
+++ b/plugins/ruflo-console/tests/fixtures/skills.ts
@@ -30,3 +30,43 @@ export const LS_GLOBAL = JSON.stringify([
},
{ name: 'tdd', path: '/home/dev/.agents/skills/tdd', scope: 'global', agents: [], source: null, sourceUrl: null, sourceType: null },
])
+
+/**
+ * `npx skills add vercel-labs/agent-skills@vercel-react-best-practices --list` as skills 1.7.0 printed it on this
+ * machine (clack's │ gutter, a name at four spaces, its description at six), spinner frames cut to one.
+ */
+export const LIST_OUT = [
+ '',
+ '\u001b[90m│\u001b[39m',
+ '\u001b[32m◇\u001b[39m Source: https://github.com/vercel-labs/agent-skills.git \u001b[2m@\u001b[22m\u001b[36mvercel-react-best-practices\u001b[39m',
+ '\u001b[?25l\u001b[90m│\u001b[39m',
+ '\u001b[35m◒\u001b[39m Fetching skills…\u001b[1G\u001b[J\u001b[32m◇\u001b[39m Found \u001b[32m1\u001b[39m skill',
+ '\u001b[?25h',
+ '\u001b[90m│\u001b[39m',
+ '\u001b[32m◇\u001b[39m \u001b[1mAvailable Skills\u001b[22m',
+ '\u001b[90m│\u001b[39m',
+ '\u001b[90m│\u001b[39m \u001b[36mvercel-react-best-practices\u001b[39m',
+ '\u001b[90m│\u001b[39m',
+ '\u001b[90m│\u001b[39m \u001b[2mReact and Next.js performance optimization guidelines from Vercel Engineering.\u001b[22m',
+ '',
+ '\u001b[90m│\u001b[39m',
+ '\u001b[90m└\u001b[39m Use --skill <name> to install specific skills',
+ '',
+].join('\n')
+
+/** The head of what `npx skills use vercel-labs/agent-skills@vercel-react-best-practices` printed: the prompt only. */
+export const USE_OUT = [
+ "You are being given a Skill to execute for the user's next request.",
+ '',
+ 'Use the following SKILL.md as your instructions:',
+ '',
+ '<SKILL.md>',
+ '---',
+ 'name: vercel-react-best-practices',
+ 'description: React and Next.js performance optimization guidelines from Vercel Engineering.',
+ '---',
+ '',
+ '# Vercel React Best Practices',
+ '</SKILL.md>',
+ '',
+].join('\n')
diff --git a/plugins/ruflo-console/tests/palette.test.ts b/plugins/ruflo-console/tests/palette.test.ts
index bf0366f178..6a76e0691f 100644
--- a/plugins/ruflo-console/tests/palette.test.ts
+++ b/plugins/ruflo-console/tests/palette.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, mock, test } from 'claude-code/testing'
import { HIVE_FILES, WORKERS } from './fixtures/hive'
import { RUFLO_FILES } from './fixtures/ruflo-run'
-import { command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'
+import { FIND_OUT } from './fixtures/skills'
+import { cliAnswer, command, elementsOf, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'
const runsOf = (runs: readonly string[][], word: string) => runs.filter(argv => argv.includes(word))
@@ -170,6 +171,25 @@ describe('palette and /ruflo', () => {
expect((await $.command.run(command('run mh-learn-run'))).text).toBe('nothing to do: type it in the terminal (i): ruflo metaharness learn --run --format json --host claude-code --model haiku --slice <path>')
})
+ test('skills headless: /ruflo run skills-find answers with what skills.sh found; skills-update asks first', { options: { boot: false } }, async ($, on) => {
+ const world = worldOf(on, RUFLO_FILES)
+
+ world.respond = argv => (argv[2] !== 'skills' ? cliAnswer(argv) : { exitCode: 0, stdout: argv[3] === 'find' ? FIND_OUT : argv[3] === 'ls' ? '[]' : 'done\n', stderr: '' })
+ mock.clock(on)
+ await $.session.start({ ...SESSION, isInteractive: false })
+
+ const found = (await $.command.run(command('run skills-find react'))).text ?? ''
+
+ expect(found).toMatch(/^skills find "react": 4 found\n {2}mattpocock\/skills@tdd · 1M installs/)
+ expect(runsOf(world.runs, 'find')).toEqual([['npx', '-y', 'skills', 'find', 'react']])
+ expect((await $.command.run(command('run skills-update'))).text).toBe('Asked: update every project skill. Confirm with /ruflo yes (or y in the pane), cancel with /ruflo no.')
+ expect(runsOf(world.runs, 'update')).toEqual([])
+ // A skills change runs its own command and reports into the skills view, so the confirm answers before it ends.
+ expect((await $.command.run(command('yes'))).text).toBe('Ran.')
+ await $.command.run(command('status'))
+ expect(runsOf(world.runs, 'update')).toEqual([['npx', '-y', 'skills', 'update', '-p', '-y']])
+ })
+
test('/ruflo help, an unknown word, and the hints when ruflo-mods or ruflo-swarm are not loaded', { options: { boot: false } }, async ($, on) => {
worldOf(on, RUFLO_FILES)
mock.clock(on)
diff --git a/plugins/ruflo-console/tests/skills-lab.spec.ts b/plugins/ruflo-console/tests/skills-lab.spec.ts
new file mode 100644
index 0000000000..360c8c6d55
--- /dev/null
+++ b/plugins/ruflo-console/tests/skills-lab.spec.ts
@@ -0,0 +1,337 @@
+/**
+ * The skills view's second half under vitest: the argv for use / preview / update-all / restore / sync and ▸ add to
+ * chosen agents, reading `add --list` and `use`, the install-count sort, the SKILL.md check, the stack a project's
+ * manifests show, which agent files name a skill, and each action on a fake Host (reads at once, changes asked first,
+ * the palette's headless entries). Nothing here runs the real CLI or reads the real disk.
+ */
+import { describe, expect, it } from 'vitest'
+
+import type { ReaderFs } from '../hooks/data/files'
+import { checkLines, checkSkillMd, inferStack, SKILL_MD_MAX, skillRefs } from '../hooks/data/skill-md'
+import { addArgv, agentsOf, installsOf, listRepoArgv, parseRepoList, restoreArgv, sortedFound, syncArgv, updateAllArgv, USE_MAX, useArgv, usePromptOf } from '../hooks/data/skills'
+import type { Host } from '../hooks/host'
+import { createRunner } from '../hooks/runner'
+import { addSpec } from '../hooks/skills'
+import { authorPrompt, isSafeDir, moreSkillActions, scanProject, skillPaletteEntries, skillsAnswer } from '../hooks/skills-lab'
+import { newState } from '../hooks/state'
+import { FIND_OUT, LIST_OUT, USE_OUT } from './fixtures/skills'
+
+const GOOD = ['---', 'name: my-skill', 'description: Does one thing well. Use when asked to do it.', '---', '', '# My skill', 'Steps.'].join('\n')
+
+describe('argv for the new actions', () => {
+ it('add names only known agents, after the scope and before -y; use, --list, update-all, restore and sync are fixed', () => {
+ expect(addArgv('o/r@s', 'project', ['codex', 'claude-code'])).toEqual(['npx', '-y', 'skills', 'add', 'o/r@s', '--agent', 'claude-code', 'codex', '-y'])
+ expect(addArgv('o/r@s', 'global', ['cursor', '-y', '*', 'evil;rm'])).toEqual(['npx', '-y', 'skills', 'add', 'o/r@s', '-g', '--agent', 'cursor', '-y'])
+ expect(addArgv('o/r@s', 'global', [])).toEqual(['npx', '-y', 'skills', 'add', 'o/r@s', '-g', '-y'])
+ expect(agentsOf(['codex', 'codex', 'nope'])).toEqual(['codex'])
+ expect(useArgv('o/r@s')).toEqual(['npx', '-y', 'skills', 'use', 'o/r@s'])
+ expect(listRepoArgv('o/r@s')).toEqual(['npx', '-y', 'skills', 'add', 'o/r@s', '--list'])
+ expect(listRepoArgv('o/r@s')).not.toContain('--json')
+ expect(updateAllArgv('project')).toEqual(['npx', '-y', 'skills', 'update', '-p', '-y'])
+ expect(updateAllArgv('global')).toEqual(['npx', '-y', 'skills', 'update', '-g', '-y'])
+ expect(restoreArgv()).toEqual(['npx', '-y', 'skills', 'experimental_install'])
+ expect(syncArgv()).toEqual(['npx', '-y', 'skills', 'experimental_sync', '-y'])
+ expect(syncArgv(['claude-code'])).toEqual(['npx', '-y', 'skills', 'experimental_sync', '--agent', 'claude-code', '-y'])
+ })
+})
+
+describe('reading what the CLI prints', () => {
+ it('add --list: each skill and its description, colour and the │ gutter gone; group titles kept', () => {
+ expect(parseRepoList(LIST_OUT)).toEqual([{ name: 'vercel-react-best-practices', description: 'React and Next.js performance optimization guidelines from Vercel Engineering.' }])
+
+ const grouped = ['◇ Available Skills', 'Web Design', '│ web-design', '│ Layouts.', '', 'General', '│ tdd', '│ Tests first.', '└ done'].join('\n')
+
+ expect(parseRepoList(grouped)).toEqual([
+ { name: 'web-design', description: 'Layouts.', group: 'Web Design' },
+ { name: 'tdd', description: 'Tests first.', group: 'General' },
+ ])
+ expect(parseRepoList('No valid skills found.')).toEqual([])
+ })
+
+ it('use: the prompt as printed, capped where the terminal caps it, and says when it was cut', () => {
+ expect(usePromptOf(USE_OUT).prompt.startsWith("You are being given a Skill")).toBe(true)
+ expect(usePromptOf(USE_OUT).isCut).toBe(false)
+ expect(usePromptOf('x'.repeat(USE_MAX + 5))).toEqual({ prompt: 'x'.repeat(USE_MAX), isCut: true })
+ expect(usePromptOf('\u001b[31m\n').prompt).toBe('')
+ })
+
+ it('install counts sort most first, results without one last; relevance keeps the order found', () => {
+ expect([installsOf('1M'), installsOf('764.8K'), installsOf('42'), installsOf(undefined), installsOf('lots')]).toEqual([1_000_000, 764_800, 42, -1, -1])
+
+ const found = [{ id: 'a/b@none' }, { id: 'a/b@k', installs: '900K' }, { id: 'a/b@m', installs: '1.2M' }]
+
+ expect(sortedFound(found, 'installs').map(skill => skill.id)).toEqual(['a/b@m', 'a/b@k', 'a/b@none'])
+ expect(sortedFound(found, 'relevance')).toEqual(found)
+ })
+})
+
+describe('the SKILL.md check', () => {
+ it('passes a well-formed file and names it', () => {
+ const check = checkSkillMd(GOOD, 'my-skill')
+
+ expect(check).toMatchObject({ ok: true, name: 'my-skill', problems: [], warnings: [] })
+ expect(checkLines(check)[0]).toBe('✓ valid: my-skill')
+ })
+
+ it('refuses a file without frontmatter, an unclosed one, a missing or malformed name, a missing description, an oversize file', () => {
+ expect(checkSkillMd('# just text').problems).toEqual(['no frontmatter: the file must start with a --- line'])
+ expect(checkSkillMd('---\nname: a\n').problems).toEqual(['the frontmatter is never closed with a --- line'])
+ expect(checkSkillMd('---\ndescription: x\n---\nbody').problems).toEqual(['name: missing'])
+ expect(checkSkillMd('---\nname: My_Skill\ndescription: x\n---\nbody').problems).toEqual(['name: lowercase letters, digits and single hyphens only'])
+ expect(checkSkillMd(`---\nname: ${'a'.repeat(65)}\ndescription: x\n---\nb`).problems[0]).toMatch(/at most 64/)
+ expect(checkSkillMd('---\nname: a\n---\nbody').problems).toEqual(['description: missing (the CLI skips a skill without one)'])
+ expect(checkSkillMd(`---\nname: a\ndescription: ${'d'.repeat(1025)}\n---\nb`).problems[0]).toMatch(/at most 1024/)
+ expect(checkSkillMd('x'.repeat(SKILL_MD_MAX + 1)).ok).toBe(false)
+ })
+
+ it('reads quoted and block descriptions; warns (without failing) on a folder mismatch, an empty body or a long file', () => {
+ expect(checkSkillMd('---\nname: "a-b"\ndescription: >\n Folded\n text.\n---\nbody').description).toBe('Folded text.')
+ expect(checkSkillMd("---\nname: 'a'\ndescription: 'quoted'\n---\nbody")).toMatchObject({ ok: true, name: 'a', description: 'quoted' })
+
+ const warned = checkSkillMd('---\nname: a\ndescription: x\n---\n', 'b')
+
+ expect(warned.ok).toBe(true)
+ expect(warned.warnings).toEqual(['name "a" differs from its folder "b"', 'no instructions after the frontmatter'])
+ expect(checkSkillMd(`${GOOD}\n${'line\n'.repeat(600)}`).warnings[0]).toMatch(/lines: keep SKILL.md under 500/)
+ })
+})
+
+describe('the project scan', () => {
+ it('reads the stack from each manifest as searches from a fixed table, never a dependency’s own name', () => {
+ const pkg = JSON.stringify({ dependencies: { react: '^19', next: '15', 'evil; rm -rf': '1' }, devDependencies: { typescript: '5', vitest: '3' } })
+
+ expect(inferStack({ packageJson: pkg })).toEqual({ stack: ['TypeScript'], chips: ['nextjs', 'react', 'vitest', 'typescript'] })
+ expect(inferStack({ cargoToml: '[dependencies]\ntokio = { version = "1" }\nserde = "1"\n# axum = "0.7"\n' })).toEqual({ stack: ['Rust'], chips: ['rust', 'tokio'] })
+ expect(inferStack({ pyproject: '[project]\ndependencies = ["FastAPI>=0.110", "pytest"]\n' })).toEqual({ stack: ['Python'], chips: ['python', 'fastapi', 'pytest'] })
+ expect(inferStack({ goMod: 'module x\nrequire github.com/gin-gonic/gin v1.9.1\n' })).toEqual({ stack: ['Go'], chips: ['golang', 'gin'] })
+ expect(inferStack({ packageJson: 'not json' })).toEqual({ stack: ['JavaScript'], chips: [] })
+ expect(inferStack({})).toEqual({ stack: [], chips: [] })
+ })
+
+ it('caps the searches at eight', () => {
+ const deps = Object.fromEntries(['next', 'react', 'vue', 'svelte', 'express', 'tailwindcss', 'prisma', 'vitest', 'jest', 'electron'].map(name => [name, '1']))
+
+ expect(inferStack({ packageJson: JSON.stringify({ dependencies: deps }) }).chips).toHaveLength(8)
+ })
+
+ it('names the agent files that mention a skill, by whole word; a two-letter name matches nothing', () => {
+ const docs = [
+ { path: '/w/.claude/agents/core/coder.md', text: 'Use the tdd skill, then sparc-methodology.' },
+ { path: '/w/.claude/agents/tester.md', text: 'TDD always. Not tdd-ish.' },
+ { path: '/w/.claude/agents/go.md', text: 'go go go' },
+ ]
+
+ expect(skillRefs([{ name: 'tdd', where: '.claude/skills' }, { name: 'go', where: '.agents/skills' }, { name: 'sparc', where: '.claude/skills' }], docs)).toEqual([
+ { name: 'tdd', where: '.claude/skills', refs: ['agents/core/coder.md', 'agents/tester.md'] },
+ { name: 'go', where: '.agents/skills', refs: [] },
+ { name: 'sparc', where: '.claude/skills', refs: [] },
+ ])
+ })
+})
+
+/** A ReaderFs over a map of absolute paths; folders are the prefixes of the files. */
+function memFs(files: Record<string, string>): ReaderFs {
+ return {
+ read: async path => {
+ if (!(path in files)) throw new Error('ENOENT')
+
+ return files[path] as string
+ },
+ stat: async path => {
+ if (!(path in files)) throw new Error('ENOENT')
+
+ return { size: (files[path] as string).length, mtimeMs: 1 }
+ },
+ list: async dir => {
+ const names = new Map<string, 'file' | 'dir'>()
+
+ for (const path of Object.keys(files)) {
+ if (!path.startsWith(`${dir}/`)) continue
+
+ const rest = path.slice(dir.length + 1).split('/')
+
+ names.set(rest[0] as string, rest.length > 1 ? 'dir' : 'file')
+ }
+
+ if (names.size === 0) throw new Error('ENOENT')
+
+ return [...names].map(([name, kind]) => ({ name, kind, size: 10 }))
+ },
+ }
+}
+
+function fake(answer: (argv: readonly string[]) => { exitCode: number; stdout: string; stderr: string }, files: Record<string, string> = {}) {
+ const runs: string[][] = []
+ const host = {
+ fs: memFs(files),
+ run: async (argv: readonly string[]) => {
+ runs.push([...argv])
+
+ return { ...answer(argv), isStdoutTruncated: false, isStderrTruncated: false }
+ },
+ invalidate: () => undefined,
+ } as unknown as Host
+ const state = newState({})
+
+ state.cwd = '/w'
+
+ const runner = createRunner(state, host, { freshRead: async () => undefined, setView: () => undefined, drill: () => undefined, command: () => undefined })
+ const loaded: string[] = []
+ const act = moreSkillActions(state, host, runner, text => void loaded.push(text))
+
+ return { host, state, runner, runs, act, loaded }
+}
+
+const settle = () => new Promise(resolve => setTimeout(resolve, 5))
+const until = async (done: () => boolean) => {
+ for (let i = 0; i < 40 && !done(); i++) await settle()
+}
+
+describe('the new skills actions', () => {
+ it('▸ use runs `use <id>` at once and types its prompt into the AI terminal; nothing is asked or sent', async () => {
+ const { state, runs, act, loaded } = fake(() => ({ exitCode: 0, stdout: USE_OUT, stderr: '' }))
+
+ act.use({ id: 'vercel-labs/agent-skills@vercel-react-best-practices' })
+ await until(() => loaded.length > 0)
+
+ expect(runs).toEqual([['npx', '-y', 'skills', 'use', 'vercel-labs/agent-skills@vercel-react-best-practices']])
+ expect(state.pending).toBeNull()
+ expect(loaded[0]).toContain('<SKILL.md>')
+ expect(state.outcome).toMatchObject({ ok: true })
+ expect(state.outcome?.detail).toMatch(/Enter twice sends it to claude/)
+
+ act.use({ id: '-g@x' })
+ expect(runs).toHaveLength(1)
+ })
+
+ it('▸ preview of a result lists its repository with add --list; of an installed skill reads and checks its SKILL.md', async () => {
+ const { state, runs, act } = fake(() => ({ exitCode: 0, stdout: LIST_OUT, stderr: '' }), { '/home/dev/.agents/skills/my-skill/SKILL.md': GOOD })
+
+ act.previewFound({ id: 'vercel-labs/agent-skills@vercel-react-best-practices' })
+ await until(() => state.skills.preview !== null)
+ expect(runs).toEqual([['npx', '-y', 'skills', 'add', 'vercel-labs/agent-skills@vercel-react-best-practices', '--list']])
+ expect(state.skills.preview?.lines[0]).toBe('▸ vercel-react-best-practices')
+
+ act.previewInstalled({ name: 'my-skill', path: '/home/dev/.agents/skills/my-skill', scope: 'global', agents: [] })
+ await until(() => state.skills.preview?.kind === 'installed')
+ expect(state.skills.preview?.lines.slice(0, 2)).toEqual(['✓ valid: my-skill', 'description: Does one thing well. Use when asked to do it.'])
+ expect(runs).toHaveLength(1)
+
+ expect(isSafeDir('relative/x')).toBe(false)
+ expect(isSafeDir('/a/../etc')).toBe(false)
+ act.previewInstalled({ name: 'x', path: '../x', scope: 'project', agents: [] })
+ expect(state.outcome?.detail).toMatch(/not an absolute path/)
+ })
+
+ it('update all, restore and sync ask first with their exact argv and cost, and run one fixed argv on yes', async () => {
+ const { state, runner, runs, act } = fake(argv => ({ exitCode: 0, stdout: argv[3] === 'ls' ? '[]' : 'ok', stderr: '' }))
+
+ act.updateAll()
+ expect(state.pending).toMatchObject({ shows: 'npx -y skills update -p -y', note: expect.stringMatching(/network/) })
+ expect(runs).toEqual([])
+ await runner.confirm()
+ await until(() => state.skills.busy === null && runs.length >= 3)
+ expect(runs[0]).toEqual(['npx', '-y', 'skills', 'update', '-p', '-y'])
+
+ act.restore()
+ expect(state.pending).toMatchObject({ shows: 'npx -y skills experimental_install', note: expect.stringMatching(/experimental · network/) })
+ runner.cancel()
+
+ act.scope('global')
+ act.toggleAgent('claude-code')
+ act.toggleAgent('not-an-agent')
+ act.sync()
+ expect(state.pending?.shows).toBe('npx -y skills experimental_sync --agent claude-code -y')
+ runner.cancel()
+ act.updateAll()
+ expect(state.pending?.shows).toBe('npx -y skills update -g -y')
+ runner.cancel()
+ expect(runs).toHaveLength(3)
+ })
+
+ it('▸ add installs to the chosen scope and agents', () => {
+ const { state, host, act } = fake(() => ({ exitCode: 0, stdout: '', stderr: '' }))
+
+ act.toggleAgent('codex')
+ act.toggleAgent('claude-code')
+ expect(state.skills.agents).toEqual(['claude-code', 'codex'])
+ act.toggleAgent('codex')
+ expect(addSpec(state, host, { id: 'o/r@s' }, 'global')?.shows).toBe('npx -y skills add o/r@s -g --agent claude-code -y')
+ expect(addSpec(state, host, { id: 'o/r@s' }, 'global')?.label).toBe('add skill o/r@s globally for claude-code')
+ })
+
+ it('▸ scan reads the manifests, the local skills and the agent files that name them; it runs nothing', async () => {
+ const files = {
+ '/w/package.json': JSON.stringify({ dependencies: { react: '1' } }),
+ '/w/.claude/skills/tdd/SKILL.md': GOOD,
+ '/w/.claude/skills/notes.txt': 'not a skill',
+ '/w/.agents/skills/sparc-flow/SKILL.md': GOOD,
+ '/w/.claude/agents/core/coder.md': 'Apply the tdd skill.',
+ '/w/.claude/agents/readme.txt': 'tdd',
+ }
+ const { state, runs } = fake(() => ({ exitCode: 0, stdout: '', stderr: '' }), files)
+ const fs = memFs(files)
+
+ await scanProject(state, fs)
+
+ expect(state.skills.scan).toMatchObject({ stack: ['JavaScript'], chips: ['react'], agentFiles: 1 })
+ expect(state.skills.scan?.local).toEqual([
+ { name: 'tdd', where: '.claude/skills', refs: ['agents/core/coder.md'] },
+ { name: 'sparc-flow', where: '.agents/skills', refs: [] },
+ ])
+ expect(runs).toEqual([])
+ })
+
+ it('authoring: ▸ write loads claude with the file and its rules; ▸ validate checks it from disk', async () => {
+ const { state, act, loaded } = fake(() => ({ exitCode: 0, stdout: '', stderr: '' }), { '/w/my-skill/SKILL.md': GOOD, '/w/bad/SKILL.md': '# no frontmatter' })
+
+ act.author()
+ expect(state.outcome?.detail).toMatch(/create field first/)
+
+ state.skills.createDraft = 'my-skill'
+ act.author()
+ expect(loaded).toEqual([authorPrompt('/w', 'my-skill')])
+ expect(loaded[0]).toMatch(/^Write the agent skill at \/w\/my-skill\/SKILL\.md/)
+
+ act.validate()
+ await until(() => state.skills.check !== null)
+ expect(state.skills.check).toMatchObject({ name: 'my-skill', ok: true })
+
+ state.skills.createDraft = 'bad'
+ act.validate()
+ await until(() => state.skills.check?.name === 'bad')
+ expect(state.skills.check).toMatchObject({ ok: false, lines: ['✗ not valid', '✗ no frontmatter: the file must start with a --- line'] })
+
+ state.skills.createDraft = 'missing'
+ act.validate()
+ await until(() => state.skills.check?.name === 'missing')
+ expect(state.skills.check?.lines[0]).toMatch(/missing/)
+ })
+
+ it('the palette: skills-find runs headless and answers with what it found; update/restore/sync ask first', async () => {
+ const { state, runner, runs } = fake(() => ({ exitCode: 0, stdout: FIND_OUT, stderr: '' }))
+ const ids = skillPaletteEntries(state).map(entry => entry.id)
+
+ expect(ids).toEqual(['skills-find', 'skills-update', 'skills-restore', 'skills-sync'])
+
+ const askedAtMs = Date.now()
+
+ expect(runner.runById('skills-find', 'react')).toBe(true)
+ await runner.settled()
+ expect(runs).toEqual([['npx', '-y', 'skills', 'find', 'react']])
+ expect(skillsAnswer(state, 'skills-find', askedAtMs)).toMatch(/^skills find "react": 4 found\n {2}mattpocock\/skills@tdd · 1M installs/)
+
+ expect(runner.runById('skills-update', '')).toBe(true)
+ expect(state.pending?.shows).toBe('npx -y skills update -p -y')
+ runner.cancel()
+ expect(runner.runById('skills-find', '-rf')).toBe(true)
+ expect(runs).toHaveLength(1)
+ })
+
+ it('without the view wired, the palette entries say so instead of running', () => {
+ const state = newState({})
+ const update = skillPaletteEntries(state).find(entry => entry.id === 'skills-update')
+
+ expect(update?.run).toEqual({ kind: 'spec', spec: null, why: 'the skills view is not wired yet' })
+ })
+})
diff --git a/plugins/ruflo-console/tests/views.test.ts b/plugins/ruflo-console/tests/views.test.ts
index 39a1187e2b..5b784b226a 100644
--- a/plugins/ruflo-console/tests/views.test.ts
+++ b/plugins/ruflo-console/tests/views.test.ts
@@ -4,7 +4,7 @@ import { describe, expect, mock, test } from 'claude-code/testing'
import { HIVE_FILES, RAFT_ID, WORKERS } from './fixtures/hive'
import { MISSION_OBSERVATION } from './fixtures/missions'
import { HIVE_TOKEN, RUFLO_FILES } from './fixtures/ruflo-run'
-import { FIND_OUT, LS_GLOBAL } from './fixtures/skills'
+import { FIND_OUT, LIST_OUT, LS_GLOBAL, USE_OUT } from './fixtures/skills'
import { cliAnswer, command, elementsOf, fakeRuflo, keyOf, paneAt, PLUGIN, SESSION, textOf, worldOf } from './fixtures/world'
const HOME_FILES = {
@@ -335,7 +335,9 @@ describe('views', () => {
expect(found).toContain('1M installs')
expect(skillRuns()).toEqual(['ls --json', 'ls -g --json', 'find react'])
- await pane.press({ key: 'sk-addg-0' })
+ // The scope is chosen once, above the lists; ▸ add then installs there.
+ await pane.press({ key: 'sk-scope-global' })
+ await pane.press({ key: 'sk-add-0' })
expect(textOf(await pane.drawn())).toContain('runs: npx -y skills add mattpocock/skills@tdd -g -y')
expect(skillRuns().some(line => line.startsWith('add'))).toBe(false)
@@ -345,6 +347,76 @@ describe('views', () => {
await pane.unmount()
})
+ test('skills: use, preview, targets, maintain and scan; reads run on a click, every change asks with its argv and cost', { options: { boot: false } }, async ($, on) => {
+ const files = { ...RUFLO_FILES, 'package.json': JSON.stringify({ dependencies: { react: '19' } }), '.claude/agents/coder.md': 'Use the tdd skill.' }
+ const world = worldOf(on, files)
+ const skillRuns = () => world.runs.filter(argv => argv[2] === 'skills').map(argv => argv.slice(3).join(' '))
+ const answer = (argv: readonly string[]) => (argv[3] === 'ls' ? (argv.includes('-g') ? LS_GLOBAL : '[]') : argv[3] === 'find' ? FIND_OUT : argv[3] === 'use' ? USE_OUT : argv.includes('--list') ? LIST_OUT : 'done\n')
+
+ world.respond = argv => (argv[2] !== 'skills' ? cliAnswer(argv) : { exitCode: 0, stdout: answer(argv), stderr: '' })
+ mock.clock(on)
+ await $.session.start(SESSION)
+
+ const { text, tree } = await drawn($, 'skills')
+ const keys = elementsOf(tree, 'Button').map(keyOf)
+
+ for (const section of ['INSTALL TO', 'INSTALLED', 'SEARCH', 'FOR THIS PROJECT', 'CREATE', 'MAINTAIN']) expect(text).toContain(section)
+ expect(keys).toEqual(expect.arrayContaining(['sk-scope-project', 'sk-scope-global', 'sk-agent-claude-code', 'sk-agent-codex', 'sk-update-all', 'sk-restore', 'sk-sync', 'sk-scan', 'sk-author', 'sk-validate', 'sk-view-0']))
+ expect(text).toContain('(●) project')
+ // Opening lists what is installed; nothing else (no search, no scan, no use) runs unasked.
+ expect(skillRuns()).toEqual(['ls --json', 'ls -g --json'])
+
+ const pane = await $.ui.mount({ ...paneAt(110), surface: 'terminal' as const, plugin: PLUGIN })
+
+ // ▸ update all asks first, its argv and its network note on the confirm row; it runs one fixed argv on yes.
+ await pane.press({ key: 'sk-update-all' })
+ const asked = textOf(await pane.drawn())
+
+ expect(asked).toContain('runs: npx -y skills update -p -y')
+ expect(asked).toMatch(/network: fetches each skill/)
+ expect(skillRuns()).toEqual(['ls --json', 'ls -g --json'])
+ await pane.press({ key: 'confirm' })
+ await pane.drawn()
+ expect(skillRuns()).toContain('update -p -y')
+
+ // ▸ restore asks, and is not run when cancelled.
+ await pane.press({ key: 'sk-restore' })
+ expect(textOf(await pane.drawn())).toContain('runs: npx -y skills experimental_install')
+ await pane.press({ key: 'cancel' })
+ expect(skillRuns()).not.toContain('experimental_install')
+
+ // ▸ scan reads the project's own files: a react chip, and the agent file that names a skill; it runs nothing.
+ const before = world.runs.length
+
+ await pane.press({ key: 'sk-scan' })
+ const scanned = textOf(await pane.drawn())
+
+ expect(scanned).toContain('stack JavaScript')
+ expect(elementsOf(await pane.drawn(), 'Button').map(keyOf)).toContain('sk-chip-0')
+ expect(world.runs.length).toBe(before)
+
+ // A chip is a search; a result's ▸ preview runs add --list at once and shows its repository.
+ await pane.press({ key: 'sk-chip-0' })
+ await pane.drawn()
+ expect(skillRuns()).toContain('find react')
+ await pane.press({ key: 'sk-preview-0' })
+ const preview = textOf(await pane.drawn())
+
+ expect(skillRuns()).toContain('add mattpocock/skills@tdd --list')
+ expect(preview).toContain('PREVIEW')
+ expect(preview).toContain('vercel-react-best-practices')
+
+ // ▸ use runs `use <id>` at once and opens the AI terminal with the prompt typed, not sent.
+ await pane.press({ key: 'sk-use-0' })
+ const term = await pane.drawn()
+ const field = elementsOf(term, 'Input').find(input => keyOf(input) === 'term-input') as { props?: { value?: string } } | undefined
+
+ expect(skillRuns()).toContain('use mattpocock/skills@tdd')
+ expect(field?.props?.value).toContain('<SKILL.md>')
+ expect(world.runs.some(argv => argv[0] === 'claude')).toBe(false)
+ await pane.unmount()
+ })
+
test('main menu: bare /ruflo lands on it in the BBS look; its prompt takes a key or a name', { options: { boot: false } }, async ($, on) => {
worldOf(on, RUFLO_FILES)
mock.clock(on)