feat: the / menu reads the sources of the agent's profile and its history

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-20 08:57:24 +01:00
1 parent 0263eca263
commit 1b12550d04
3 files changed
+297 -160

No files matched your search

@@ -6,13 +6,12 @@
// reads the person's snippets and passes them in, and it schedules the retry // reads the person's snippets and passes them in, and it schedules the retry
// and the debounce with the numbers exported here. // and the debounce with the numbers exported here.
// //
// Sources for `/` (the design's §5.3): the built-in commands of the agent, // Sources for `/`: the profile of the agent (profiles.js) says which are
// the person's saved snippets and - for Claude Code only (`isClaudeCode`) - // read - its built-in commands, the folders of the project and of the home
// the project's own `.claude/commands/*.md` and `.claude/skills/*/SKILL.md` // folder with its own commands, the plugins - and the person's snippets and
// and the global commands of `~/.claude` and its plugins. Another agent does // the commands sent to this agent before (the history) come on top. An agent
// not understand the `.claude` files, so it gets its built-ins and snippets, // with no profile gets only the snippets and the history, and nothing is
// and nothing is read for it. One source for `@`: the files git tracks in the // read for it. One source for `@`: the files git tracks in the pane's folder.
// pane's folder.
// //
// A read that fails is not an empty list: the failure is reported through // A read that fails is not an empty list: the failure is reported through
// `onReadError` and the menu keeps what it knows. A caller with no handler // `onReadError` and the menu keeps what it knows. A caller with no handler
@@ -20,7 +19,14 @@
// with nothing to show. An empty list without a failure means the catalog // with nothing to show. An empty list without a failure means the catalog
// was read and nothing fit. // was read and nothing fit.
import { GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_PLUGIN, rank } from "./suggest.js"; import {
GROUP_BUILTIN,
GROUP_PROJECT,
GROUP_USER,
GROUP_PLUGIN,
GROUP_HISTORY,
rank,
} from "./suggest.js";
import { decode } from "./powershell.js"; import { decode } from "./powershell.js";
/** /**
@@ -51,30 +57,30 @@ export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo p
export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej."; export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej.";
export { BUILTINS } from "./profiles.js"; export { BUILTINS } from "./profiles.js";
import { BUILTINS as PROFILE_BUILTINS } from "./profiles.js";
/** The same agent under the name the program's table gives it. */
const AGENT_ALIASES = { claude: "claude-code" };
/** How many files the `@` menu shows at most. */ /** How many files the `@` menu shows at most. */
const FILE_LIMIT = 20; const FILE_LIMIT = 20;
/** The project's command files, as a shell finds them. */ /** One command: a `/` and a name that holds no space and no path separator. */
const LIST_SH = const HISTORY_COMMAND = /^\/[A-Za-z0-9][\w:.-]*$/;
'for f in .claude/commands/*.md .claude/skills/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\n\' "$f"; done; exit 0';
/** The same in PowerShell, for a machine without a POSIX shell. */ /** The message of a pane whose agent has no profile. */
const LIST_PS = export function unknownAgentMessage(agent) {
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " + return `Nieznany agent \`${agent}\` – dodaj profil w ~/.config/herdr-app/composer-agents.json`;
"@(Get-ChildItem -Path '.claude/commands/*.md','.claude/skills/*/SKILL.md' -File -ErrorAction SilentlyContinue) " + }
"| ForEach-Object { Resolve-Path -Relative -LiteralPath $_.FullName }";
/** The message about a `composer-agents.json` that could not be read whole. */
export function profileProblemMessage(problem) {
return `\`composer-agents.json\`: ${problem}`;
}
/** /**
* The global listing with a POSIX shell: the arguments come in threes - the * The listing with a POSIX shell, for the project and for the home folder:
* index of the spec, its kind (`file`, `md` or `skills`) and its path - and * the arguments come in threes - the index of the spec, its kind (`file`,
* every file found is written as `index<TAB>path`. * `md` or `skills`) and its path - and every file found is written as
* `index<TAB>path`.
*/ */
const GLOBAL_SH = const LIST_SH =
'while [ $# -ge 3 ]; do i=$1; k=$2; p=$3; shift 3; case "$k" in ' + 'while [ $# -ge 3 ]; do i=$1; k=$2; p=$3; shift 3; case "$k" in ' +
'file) [ -f "$p" ] && printf \'%s\\t%s\\n\' "$i" "$p";; ' + 'file) [ -f "$p" ] && printf \'%s\\t%s\\n\' "$i" "$p";; ' +
'md) for f in "$p"/*.md; do [ -f "$f" ] && printf \'%s\\t%s\\n\' "$i" "$f"; done;; ' + 'md) for f in "$p"/*.md; do [ -f "$f" ] && printf \'%s\\t%s\\n\' "$i" "$f"; done;; ' +
@@ -97,22 +103,12 @@ export function retryDelay(attempt) {
} }
/** /**
* Is this agent Claude Code (under its name or its alias)? Only its commands * The commands the `/` menu offers, in this order: the built-ins of the
* live in `.claude` files. * profile, the project sources of the profile (read with `exec` in `cwd`),
* * the global ones (`options.global`, read by `globalCommands`), the snippets
* @param {string|undefined} agent * and the history (`historyCommands`). A name is offered once: the first
* @returns {boolean} * source that has it wins. Without a profile only the snippets and the
*/ * history are offered, and nothing is read (no `exec`).
export function isClaudeCode(agent) {
const name = String(agent ?? "");
return (AGENT_ALIASES[name] ?? name) === "claude-code";
}
/**
* The commands the `/` menu offers: the agent's built-ins and the person's
* snippets - and, for Claude Code only, the project's own commands and the
* global ones (`options.global`). For another agent the project is not read
* (no `exec`) and `options.global` is ignored.
* *
* A source that cannot be read does not take the others with it: the menu * A source that cannot be read does not take the others with it: the menu
* shows what is known and the failure goes to `onReadError`, so the caller * shows what is known and the failure goes to `onReadError`, so the caller
@@ -121,20 +117,22 @@ export function isClaudeCode(agent) {
* *
* @param {string} cwd - the folder of the pane * @param {string} cwd - the folder of the pane
* @param {Exec} exec * @param {Exec} exec
* @param {{agent?:string, snippets?:object[], global?:Item[], onReadError?:(error:Error) => void}} [options] * @param {{profile?:object|null, snippets?:object[], global?:Item[], history?:Item[], onReadError?:(error:Error) => void}} [options]
* `global`: the person's and the plugins' commands, read by `globalCommands`
* @returns {Promise<Item[]>} * @returns {Promise<Item[]>}
*/ */
export async function commands(cwd, exec, options = {}) { export async function commands(cwd, exec, options = {}) {
const builtins = builtinItems(options.agent); const profile = options.profile ?? null;
const snippets = snippetItems(options.snippets); const snippets = snippetItems(options.snippets);
const history = Array.isArray(options.history) ? options.history : [];
// The `.claude` files mean something to Claude Code alone. // An agent we know nothing about: nothing to read.
if (!isClaudeCode(options.agent)) return [...builtins, ...snippets]; if (!profile) return dedupe([...snippets, ...history]);
const builtins = builtinItems(profile);
let project = []; let project = [];
try { try {
project = await projectItems(cwd, exec); project = await projectItems(cwd, exec, profile.sources);
} catch (err) { } catch (err) {
// Nobody to tell: the caller gets the failure instead of a list that // Nobody to tell: the caller gets the failure instead of a list that
// looks empty - an empty list would say "nothing fits" and the caller // looks empty - an empty list would say "nothing fits" and the caller
@@ -145,10 +143,14 @@ export async function commands(cwd, exec, options = {}) {
const global = Array.isArray(options.global) ? options.global : []; const global = Array.isArray(options.global) ? options.global : [];
// A name is offered once: the first source that has it wins. return dedupe([...builtins, ...project, ...global, ...snippets, ...history]);
}
/** A name is offered once: the first source that has it wins. */
function dedupe(items) {
const seen = new Set(); const seen = new Set();
const out = []; const out = [];
for (const item of [...builtins, ...project, ...global, ...snippets]) { for (const item of items) {
if (seen.has(item.key)) continue; if (seen.has(item.key)) continue;
seen.add(item.key); seen.add(item.key);
out.push(item); out.push(item);
@@ -156,6 +158,36 @@ export async function commands(cwd, exec, options = {}) {
return out; return out;
} }
/**
* The commands that were sent to this agent before: the first word of every
* message of the history that starts with a `/` and is a command name (not a
* path such as /c/Users/x). The newest come first.
*
* @param {{text?:string, agentName?:string, sentAt?:number}[]} history
* @param {string} agent - `agentName()` of the pane
* @returns {Item[]}
*/
export function historyCommands(history, agent) {
const name = String(agent ?? "").trim().toLowerCase();
if (!Array.isArray(history)) return [];
const entries = history
.filter((entry) => String(entry?.agentName ?? "").trim().toLowerCase() === name)
.sort((a, b) => (Number(b.sentAt) || 0) - (Number(a.sentAt) || 0));
const seen = new Set();
const items = [];
for (const entry of entries) {
const token = String(entry.text ?? "").trimStart().split(/\s/, 1)[0];
if (!HISTORY_COMMAND.test(token)) continue;
const key = token.slice(1);
if (seen.has(key)) continue;
seen.add(key);
items.push({ key, desc: "", group: GROUP_HISTORY, insert: `/${key} ` });
}
return items;
}
/** /**
* The commands that live in the person's `~/.claude`: their own commands and * The commands that live in the person's `~/.claude`: their own commands and
* skills, and those of the plugins that `settings.json` switches on. * skills, and those of the plugins that `settings.json` switches on.
@@ -168,22 +200,27 @@ export async function commands(cwd, exec, options = {}) {
* @param {string} home - the person's home folder * @param {string} home - the person's home folder
* @param {Exec} exec * @param {Exec} exec
* @param {(path:string) => Promise<string|null>} readText * @param {(path:string) => Promise<string|null>} readText
* @param {{onReadError?:(error:Error) => void}} [options] * @param {{sources?:object[], onReadError?:(error:Error) => void}} [options]
* `sources`: the sources of the profile; only the ones of the `home` scope
* are read, and none of them means nothing is read
* @returns {Promise<Item[]>} * @returns {Promise<Item[]>}
*/ */
export async function globalCommands(home, exec, readText, options = {}) { export async function globalCommands(home, exec, readText, options = {}) {
const root = slashes(home).replace(/\/+$/, ""); const root = slashes(home).replace(/\/+$/, "");
const claude = `${root}/.claude`; const claude = `${root}/.claude`;
const sources = (Array.isArray(options.sources) ? options.sources : []).filter(
(source) => source?.scope === "home",
);
/** @type {{kind:"file"|"md"|"skills", path:string, plugin:string|null}[]} */ /** @type {{kind:"file"|"md"|"skills", path:string, plugin:string|null, prefix:string}[]} */
const specs = [ const specs = [];
{ kind: "md", path: `${claude}/commands`, plugin: null },
{ kind: "skills", path: `${claude}/skills`, plugin: null },
];
for (const source of sources) {
if (source.kind === "claude-plugins") {
const settings = await readJson(readText, `${claude}/settings.json`); const settings = await readJson(readText, `${claude}/settings.json`);
const installed = await readJson(readText, `${claude}/plugins/installed_plugins.json`); const installed = await readJson(readText, `${claude}/plugins/installed_plugins.json`);
const enabled = settings && typeof settings.enabledPlugins === "object" ? settings.enabledPlugins : {}; const enabled =
settings && typeof settings.enabledPlugins === "object" ? settings.enabledPlugins : {};
for (const [id, on] of Object.entries(enabled ?? {})) { for (const [id, on] of Object.entries(enabled ?? {})) {
if (on !== true) continue; if (on !== true) continue;
@@ -194,12 +231,24 @@ export async function globalCommands(home, exec, readText, options = {}) {
const base = slashes(installPath).replace(/\/+$/, ""); const base = slashes(installPath).replace(/\/+$/, "");
const name = id.split("@")[0]; const name = id.split("@")[0];
const manifest = await readJson(readText, `${base}/.claude-plugin/plugin.json`); const manifest = await readJson(readText, `${base}/.claude-plugin/plugin.json`);
specs.push(...pluginSpecs(base, name, manifest)); specs.push(...pluginSpecs(base, name, manifest).map((spec) => ({ ...spec, prefix: "/" })));
} }
} else {
specs.push({
kind: source.pattern === "*/SKILL.md" ? "skills" : "md",
path: `${root}/${source.path}`,
plugin: null,
prefix: source.prefix ?? "/",
});
}
}
// Nothing to look at: no `exec` either.
if (specs.length === 0) return [];
let listed = []; let listed = [];
try { try {
listed = await listFiles(exec, specs); listed = (await listFiles(exec, specs)).found;
} catch (err) { } catch (err) {
if (options.onReadError) options.onReadError(err); if (options.onReadError) options.onReadError(err);
else throw err; else throw err;
@@ -226,7 +275,7 @@ export async function globalCommands(home, exec, readText, options = {}) {
key, key,
desc: describe(text), desc: describe(text),
group: spec.plugin ? GROUP_PLUGIN : GROUP_USER, group: spec.plugin ? GROUP_PLUGIN : GROUP_USER,
insert: `/${key} `, insert: `${spec.prefix}${key} `,
}); });
} }
return items; return items;
@@ -316,30 +365,44 @@ export async function files(cwd, exec, options = {}) {
return rank(items, needle, { atLineStart: true }).slice(0, limit); return rank(items, needle, { atLineStart: true }).slice(0, limit);
} }
/** The built-in commands of one agent - an agent we do not know has none. */ /** The built-in commands of a profile. */
function builtinItems(agent) { function builtinItems(profile) {
const name = String(agent ?? ""); return (profile.builtins ?? []).map((item) => ({
const list = PROFILE_BUILTINS[name] ?? PROFILE_BUILTINS[AGENT_ALIASES[name]];
if (!list) return [];
return list.map((item) => ({
key: item.key, key: item.key,
desc: item.desc, desc: item.desc ?? "",
group: GROUP_BUILTIN, group: GROUP_BUILTIN,
insert: `/${item.key} `, insert: `/${item.key} `,
})); }));
} }
/** The commands the project has: its command files and its skills. */ /** The commands the project has, as the project sources of the profile say. */
async function projectItems(cwd, exec) { async function projectItems(cwd, exec, sources) {
const { kind, paths } = await listProjectFiles(cwd, exec); const specs = (Array.isArray(sources) ? sources : [])
.filter((source) => source?.scope === "project" && !source.kind)
.map((source) => ({
kind: source.pattern === "*/SKILL.md" ? "skills" : "md",
path: source.path,
prefix: source.prefix ?? "/",
}));
// Nothing to look at: no `exec` either.
if (specs.length === 0) return [];
const { shell, found } = await listFiles(exec, specs, { cwd, shellFirst: true, relative: true });
const items = []; const items = [];
for (const path of paths) { for (const { index, path } of found) {
const spec = specs[index];
if (!spec) continue;
const name = commandName(path); const name = commandName(path);
if (!name) continue; if (!name) continue;
const text = await readFile(cwd, exec, path, kind); const text = await readFile(cwd, exec, path, shell);
if (text === null) continue; if (text === null) continue;
items.push({ key: name, desc: describe(text), group: GROUP_PROJECT, insert: `/${name} ` }); items.push({
key: name,
desc: describe(text),
group: GROUP_PROJECT,
insert: `${spec.prefix}${name} `,
});
} }
return items; return items;
} }
@@ -365,54 +428,43 @@ function snippetItems(snippets) {
} }
/** /**
* The project's command files. A POSIX shell is asked first - it is what a * The files of the specs, listed by one `exec`. For the home folder it is
* Linux or macOS machine has - and PowerShell after it, for a Windows machine * PowerShell first (the machine this mod is made for) and a POSIX shell after
* without one. Neither is there: the catalog could not be read. * it; for the project (`options.shellFirst`) a POSIX shell first - it is what
*/ * a Linux or macOS machine has - and PowerShell after it. Neither is there:
async function listProjectFiles(cwd, exec) { * the listing could not be read. The paths of the specs reach PowerShell
const viaShell = await tryList(exec, "sh", ["-c", LIST_SH, "catalog"], cwd, false); * only as Base64 of a JSON text (`decode`). With `options.relative` the
if (viaShell) return { kind: "sh", paths: viaShell }; * paths found are relative to `options.cwd`, as the specs are.
const viaPowerShell = await tryList(
exec,
"powershell",
["-NoProfile", "-Command", LIST_PS],
cwd,
true,
);
if (viaPowerShell) return { kind: "powershell", paths: viaPowerShell };
throw new Error("nie udało się wczytać katalogu projektu");
}
/**
* The files of the global specs, listed by one `exec`: PowerShell first (the
* machine this mod is made for), a POSIX shell after it. The paths of the
* specs reach PowerShell only as Base64 of a JSON text (`decode`).
* *
* @returns {Promise<{index:number, path:string}[]>} * @returns {Promise<{shell:"sh"|"powershell", found:{index:number, path:string}[]}>}
*/ */
async function listFiles(exec, specs) { async function listFiles(exec, specs, options = {}) {
const relative = options.relative === true;
const psScript = const psScript =
"$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " + "$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
`$specs = ConvertFrom-Json (${decode(JSON.stringify(specs.map((spec, i) => ({ i, k: spec.kind, p: spec.path }))))}); ` + `$specs = ConvertFrom-Json (${decode(JSON.stringify(specs.map((spec, i) => ({ i, k: spec.kind, p: spec.path, r: relative }))))}); ` +
"foreach ($s in $specs) { $p = $s.p; " + "foreach ($s in $specs) { $p = $s.p; " +
"if ($s.k -eq 'file') { if (Test-Path -LiteralPath $p -PathType Leaf) { \"$($s.i)`t$p\" } } " + "if ($s.k -eq 'file') { if (Test-Path -LiteralPath $p -PathType Leaf) { \"$($s.i)`t$p\" } } " +
"elseif (Test-Path -LiteralPath $p -PathType Container) { " + "elseif (Test-Path -LiteralPath $p -PathType Container) { " +
"if ($s.k -eq 'md') { Get-ChildItem -LiteralPath $p -Filter '*.md' -File | ForEach-Object { \"$($s.i)`t$($_.FullName)\" } } " + "if ($s.k -eq 'md') { Get-ChildItem -LiteralPath $p -Filter '*.md' -File | ForEach-Object { " +
"$o = if ($s.r) { \"$p/$($_.Name)\" } else { $_.FullName }; \"$($s.i)`t$o\" } } " +
"else { Get-ChildItem -LiteralPath $p -Directory | ForEach-Object { $f = Join-Path $_.FullName 'SKILL.md'; " + "else { Get-ChildItem -LiteralPath $p -Directory | ForEach-Object { $f = Join-Path $_.FullName 'SKILL.md'; " +
"if (Test-Path -LiteralPath $f -PathType Leaf) { \"$($s.i)`t$f\" } } } } }"; "if (Test-Path -LiteralPath $f -PathType Leaf) { " +
"$o = if ($s.r) { \"$p/$($_.Name)/SKILL.md\" } else { $f }; \"$($s.i)`t$o\" } } } } }";
const shArgs = ["-c", GLOBAL_SH, "catalog"]; const shArgs = ["-c", LIST_SH, "catalog"];
specs.forEach((spec, i) => shArgs.push(String(i), spec.kind, spec.path)); specs.forEach((spec, i) => shArgs.push(String(i), spec.kind, spec.path));
for (const [command, args] of [ const tries = [
["powershell", ["-NoProfile", "-Command", psScript]], ["powershell", ["-NoProfile", "-Command", psScript]],
["sh", shArgs], ["sh", shArgs],
]) { ];
if (options.shellFirst) tries.reverse();
for (const [command, args] of tries) {
let result; let result;
try { try {
result = await exec(command, args, {}); result = await exec(command, args, options.cwd === undefined ? {} : { cwd: options.cwd });
} catch { } catch {
continue; continue;
} }
@@ -423,29 +475,11 @@ async function listFiles(exec, specs) {
const match = /^(\d+)\t(.+)$/.exec(line.replace(/\r$/, "")); const match = /^(\d+)\t(.+)$/.exec(line.replace(/\r$/, ""));
if (match) found.push({ index: Number(match[1]), path: slashes(match[2]).trim() }); if (match) found.push({ index: Number(match[1]), path: slashes(match[2]).trim() });
} }
return found; return { shell: command, found };
} }
throw new Error("nie udało się wczytać katalogu globalnego"); throw new Error(
} relative ? "nie udało się wczytać katalogu projektu" : "nie udało się wczytać katalogu globalnego",
);
/** One listing, or `null` when the program is not there or it failed. */
async function tryList(exec, command, args, cwd, windowsPaths) {
let result;
try {
result = await exec(command, args, { cwd });
} catch {
return null;
}
if (!result || result.code !== 0) return null;
return String(result.stdout ?? "")
.split("\n")
.map((line) => {
const path = line.trim();
// PowerShell writes the separators of its own platform.
return windowsPaths ? path.replace(/\\/g, "/") : path;
})
.filter(Boolean);
} }
/** /**
@@ -14,7 +14,7 @@
* @typedef {object} Item * @typedef {object} Item
* @property {string} key - the name the needle is matched against * @property {string} key - the name the needle is matched against
* @property {string} desc - one line about the item * @property {string} desc - one line about the item
* @property {string} [group] - Wbudowane | Projekt | Użytkownik | Pluginy | Terminal * @property {string} [group] - Wbudowane | Projekt | Użytkownik | Pluginy | Z historii | Terminal
* @property {string} insert - the text put into the field ("/review ") * @property {string} insert - the text put into the field ("/review ")
* @property {number} [uses] - how often the person picked the item * @property {number} [uses] - how often the person picked the item
*/ */
@@ -27,11 +27,20 @@ export const GROUP_PROJECT = "Projekt";
export const GROUP_USER = "Użytkownik"; export const GROUP_USER = "Użytkownik";
/** The commands of the plugins that are switched on. */ /** The commands of the plugins that are switched on. */
export const GROUP_PLUGIN = "Pluginy"; export const GROUP_PLUGIN = "Pluginy";
/** The commands that were sent to this agent before. */
export const GROUP_HISTORY = "Z historii";
/** The commands the terminal itself understands. */ /** The commands the terminal itself understands. */
export const GROUP_TERMINAL = "Terminal"; export const GROUP_TERMINAL = "Terminal";
/** The groups, in the order the menu shows them. */ /** The groups, in the order the menu shows them. */
export const GROUPS = [GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_PLUGIN, GROUP_TERMINAL]; export const GROUPS = [
GROUP_BUILTIN,
GROUP_PROJECT,
GROUP_USER,
GROUP_PLUGIN,
GROUP_HISTORY,
GROUP_TERMINAL,
];
/** A name may start a word after one of these. */ /** A name may start a word after one of these. */
const BOUNDARY = new Set([":", "-", "_", ".", "/"]); const BOUNDARY = new Set([":", "-", "_", ".", "/"]);
+126 -32
View File
@@ -3,16 +3,23 @@ import assert from "node:assert/strict";
import { import {
BUILTINS, BUILTINS,
commands, commands,
isClaudeCode,
globalCommands, globalCommands,
historyCommands,
} from "../herdr/herdr-composer/mods/herdr-composer/catalog.js"; } from "../herdr/herdr-composer/mods/herdr-composer/catalog.js";
import {
DEFAULT_PROFILES,
resolveProfile,
} from "../herdr/herdr-composer/mods/herdr-composer/profiles.js";
import { import {
GROUPS, GROUPS,
GROUP_HISTORY,
GROUP_USER, GROUP_USER,
GROUP_PLUGIN, GROUP_PLUGIN,
} from "../herdr/herdr-composer/mods/herdr-composer/suggest.js"; } from "../herdr/herdr-composer/mods/herdr-composer/suggest.js";
const HOME = "C:/Users/Test"; const HOME = "C:/Users/Test";
const CC_PROFILE = DEFAULT_PROFILES[0];
const CC = CC_PROFILE.sources;
/** /**
* A fake machine: `files` maps a path to its text. `exec` answers the POSIX * A fake machine: `files` maps a path to its text. `exec` answers the POSIX
@@ -129,7 +136,7 @@ test("globalCommands: an enabled plugin gives plugin:name (default skills dir)",
...plugins({ "superpowers@official": true }, { "superpowers@official": "C:\\p\\superpowers\\7.0.2" }), ...plugins({ "superpowers@official": true }, { "superpowers@official": "C:\\p\\superpowers\\7.0.2" }),
[`${dir}/skills/brainstorming/SKILL.md`]: skill("brainstorming"), [`${dir}/skills/brainstorming/SKILL.md`]: skill("brainstorming"),
}); });
const items = await globalCommands(HOME, exec, readText); const items = await globalCommands(HOME, exec, readText, { sources: CC });
assert.equal(items.length, 1); assert.equal(items.length, 1);
assert.equal(items[0].key, "superpowers:brainstorming"); assert.equal(items[0].key, "superpowers:brainstorming");
assert.equal(items[0].group, GROUP_PLUGIN); assert.equal(items[0].group, GROUP_PLUGIN);
@@ -144,7 +151,7 @@ test("globalCommands: disabled or unlisted plugin gives nothing", async () => {
[`${dir}/skills/x/SKILL.md`]: skill("x"), [`${dir}/skills/x/SKILL.md`]: skill("x"),
["C:/p/b/1/skills/y/SKILL.md"]: skill("y"), ["C:/p/b/1/skills/y/SKILL.md"]: skill("y"),
}); });
assert.deepEqual(await globalCommands(HOME, exec, readText), []); assert.deepEqual(await globalCommands(HOME, exec, readText, { sources: CC }), []);
}); });
test("globalCommands: plugin.json skills array takes only the named dirs", async () => { test("globalCommands: plugin.json skills array takes only the named dirs", async () => {
@@ -156,7 +163,7 @@ test("globalCommands: plugin.json skills array takes only the named dirs", async
[`${dir}/skills/eng/other/SKILL.md`]: skill("other"), [`${dir}/skills/eng/other/SKILL.md`]: skill("other"),
[`${dir}/skills/direct/SKILL.md`]: skill("direct"), [`${dir}/skills/direct/SKILL.md`]: skill("direct"),
}); });
const keys = (await globalCommands(HOME, exec, readText)).map((item) => item.key); const keys = (await globalCommands(HOME, exec, readText, { sources: CC })).map((item) => item.key);
assert.deepEqual(keys, ["mp:tdd"]); assert.deepEqual(keys, ["mp:tdd"]);
}); });
@@ -168,7 +175,7 @@ test("globalCommands: plugin commands dir and user-invocable false", async () =>
[`${dir}/skills/hidden/SKILL.md`]: skill("hidden", "user-invocable: false\n"), [`${dir}/skills/hidden/SKILL.md`]: skill("hidden", "user-invocable: false\n"),
[`${dir}/skills/shown/SKILL.md`]: skill("shown"), [`${dir}/skills/shown/SKILL.md`]: skill("shown"),
}); });
const keys = (await globalCommands(HOME, exec, readText)).map((item) => item.key).sort(); const keys = (await globalCommands(HOME, exec, readText, { sources: CC })).map((item) => item.key).sort();
assert.deepEqual(keys, ["c:ship", "c:shown"]); assert.deepEqual(keys, ["c:ship", "c:shown"]);
}); });
@@ -176,7 +183,7 @@ test("globalCommands: name: in the front matter wins over the folder name", asyn
const { exec, readText } = machine({ const { exec, readText } = machine({
[`${HOME}/.claude/skills/folder/SKILL.md`]: skill("real-name"), [`${HOME}/.claude/skills/folder/SKILL.md`]: skill("real-name"),
}); });
const items = await globalCommands(HOME, exec, readText); const items = await globalCommands(HOME, exec, readText, { sources: CC });
assert.deepEqual(items.map((item) => item.key), ["real-name"]); assert.deepEqual(items.map((item) => item.key), ["real-name"]);
}); });
@@ -184,7 +191,7 @@ test("globalCommands: a user command gives handoff in Użytkownik", async () =>
const { exec, readText } = machine({ const { exec, readText } = machine({
[`${HOME}/.claude/commands/handoff.md`]: "---\ndescription: Przekazanie\n---\n", [`${HOME}/.claude/commands/handoff.md`]: "---\ndescription: Przekazanie\n---\n",
}); });
const items = await globalCommands(HOME, exec, readText); const items = await globalCommands(HOME, exec, readText, { sources: CC });
assert.equal(items.length, 1); assert.equal(items.length, 1);
assert.equal(items[0].key, "handoff"); assert.equal(items[0].key, "handoff");
assert.equal(items[0].group, GROUP_USER); assert.equal(items[0].group, GROUP_USER);
@@ -193,23 +200,23 @@ test("globalCommands: a user command gives handoff in Użytkownik", async () =>
test("globalCommands: no settings.json, broken json: user items only, no throw", async () => { test("globalCommands: no settings.json, broken json: user items only, no throw", async () => {
const none = machine({ [`${HOME}/.claude/commands/a.md`]: "x" }); const none = machine({ [`${HOME}/.claude/commands/a.md`]: "x" });
assert.deepEqual((await globalCommands(HOME, none.exec, none.readText)).map((i) => i.key), ["a"]); assert.deepEqual((await globalCommands(HOME, none.exec, none.readText, { sources: CC })).map((i) => i.key), ["a"]);
const broken = machine({ const broken = machine({
[`${HOME}/.claude/settings.json`]: "{nope", [`${HOME}/.claude/settings.json`]: "{nope",
[`${HOME}/.claude/plugins/installed_plugins.json`]: "[[", [`${HOME}/.claude/plugins/installed_plugins.json`]: "[[",
[`${HOME}/.claude/commands/a.md`]: "x", [`${HOME}/.claude/commands/a.md`]: "x",
}); });
assert.deepEqual((await globalCommands(HOME, broken.exec, broken.readText)).map((i) => i.key), ["a"]); assert.deepEqual((await globalCommands(HOME, broken.exec, broken.readText, { sources: CC })).map((i) => i.key), ["a"]);
}); });
test("globalCommands: a listing failure goes to onReadError, or throws", async () => { test("globalCommands: a listing failure goes to onReadError, or throws", async () => {
const { exec, readText } = machine({}, { listError: true }); const { exec, readText } = machine({}, { listError: true });
const errors = []; const errors = [];
const items = await globalCommands(HOME, exec, readText, { onReadError: (err) => errors.push(err) }); const items = await globalCommands(HOME, exec, readText, { sources: CC, onReadError: (err) => errors.push(err) });
assert.deepEqual(items, []); assert.deepEqual(items, []);
assert.equal(errors.length, 1); assert.equal(errors.length, 1);
await assert.rejects(() => globalCommands(HOME, exec, readText)); await assert.rejects(() => globalCommands(HOME, exec, readText, { sources: CC }));
}); });
test("paths with spaces and Polish letters are not put in the PowerShell script as text", async () => { test("paths with spaces and Polish letters are not put in the PowerShell script as text", async () => {
@@ -222,7 +229,7 @@ test("paths with spaces and Polish letters are not put in the PowerShell script
} }
throw new Error("no"); throw new Error("no");
}; };
await globalCommands(home, exec, async () => null); await globalCommands(home, exec, async () => null, { sources: CC });
assert.ok(script.length > 0); assert.ok(script.length > 0);
assert.ok(!script.includes("Zażółć")); assert.ok(!script.includes("Zażółć"));
}); });
@@ -233,7 +240,7 @@ test("commands: options.global joins after the project, first key wins", async (
{ key: "clear", desc: "dup", group: GROUP_USER, insert: "/clear " }, { key: "clear", desc: "dup", group: GROUP_USER, insert: "/clear " },
{ key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " }, { key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " },
]; ];
const items = await commands("/x", exec, { agent: "claude-code", global }); const items = await commands("/x", exec, { profile: CC_PROFILE, global });
assert.equal(items.filter((item) => item.key === "clear").length, 1); assert.equal(items.filter((item) => item.key === "clear").length, 1);
assert.equal( assert.equal(
items.find((item) => item.key === "clear").desc, items.find((item) => item.key === "clear").desc,
@@ -242,37 +249,25 @@ test("commands: options.global joins after the project, first key wins", async (
assert.ok(items.some((item) => item.key === "handoff")); assert.ok(items.some((item) => item.key === "handoff"));
}); });
test("isClaudeCode: claude-code and its alias only", () => { test("commands: codex gets its builtins and snippets - no project sources, no exec", async () => {
assert.equal(isClaudeCode("claude-code"), true);
assert.equal(isClaudeCode("claude"), true);
for (const name of ["codex", "kiro-cli", "", undefined]) assert.equal(isClaudeCode(name), false, String(name));
});
test("commands: another agent gets its builtins and snippets - no project, no global, no exec", async () => {
let calls = 0; let calls = 0;
const exec = async () => { const exec = async () => {
calls += 1; calls += 1;
return { code: 0, stdout: "", stderr: "" }; return { code: 0, stdout: "", stderr: "" };
}; };
const global = [{ key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " }];
const items = await commands("/x", exec, { const items = await commands("/x", exec, {
agent: "codex", profile: resolveProfile([], "codex"),
global,
snippets: [{ key: "mine", desc: "s" }], snippets: [{ key: "mine", desc: "s" }],
}); });
assert.equal(calls, 0); assert.equal(calls, 0);
const keys = items.map((item) => item.key); const keys = items.map((item) => item.key);
assert.deepEqual(keys, [...BUILTINS.codex.map((item) => item.key), "mine"]); assert.deepEqual(keys, [...BUILTINS.codex.map((item) => item.key), "mine"]);
assert.ok(!keys.includes("handoff"));
}); });
test("commands: claude-code still reads the project and takes the global ones", async () => { test("commands: claude-code still reads the project and takes the global ones", async () => {
const exec = async (command) => { const { exec } = ccMachine({ ".claude/commands/p.md": "x" });
if (command === "sh") return { code: 0, stdout: ".claude/commands/p.md\n", stderr: "" };
return { code: 1, stdout: "", stderr: "" };
};
const global = [{ key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " }]; const global = [{ key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " }];
const items = await commands("/x", exec, { agent: "claude", global }); const items = await commands("/x", exec, { profile: resolveProfile([], "claude"), global });
const keys = items.map((item) => item.key); const keys = items.map((item) => item.key);
assert.ok(keys.includes("handoff")); assert.ok(keys.includes("handoff"));
assert.ok(keys.includes("clear")); assert.ok(keys.includes("clear"));
@@ -333,9 +328,108 @@ const EXPECTED_CC = [
{"key":"sp:brainstorming","group":"Pluginy","insert":"/sp:brainstorming ","desc":"Opis brainstorming"}, {"key":"sp:brainstorming","group":"Pluginy","insert":"/sp:brainstorming ","desc":"Opis brainstorming"},
]; ];
test("the / menu of Claude Code stays as it was (pinned before profiles)", async () => { test("the / menu of Claude Code stays as it was", async () => {
const { exec, readText } = ccMachine(CC_FILES); const { exec, readText } = ccMachine(CC_FILES);
const global = await globalCommands(HOME, exec, readText); const global = await globalCommands(HOME, exec, readText, { sources: CC });
const items = await commands("/proj", exec, { agent: "claude-code", global }); const items = await commands("/proj", exec, { profile: resolveProfile([], "claude-code"), global });
assert.deepEqual(items.map(ccRow), EXPECTED_CC); assert.deepEqual(items.map(ccRow), EXPECTED_CC);
}); });
test("commands: no profile gives only the history and the snippets, and no exec", async () => {
let calls = 0;
const exec = async () => {
calls += 1;
return { code: 0, stdout: "", stderr: "" };
};
const h = { key: "clear", desc: "", group: GROUP_HISTORY, insert: "/clear " };
assert.deepEqual(await commands("/x", exec, { profile: null, history: [h] }), [h]);
assert.equal(calls, 0);
});
test("commands: a profile project source with a prefix", async () => {
const profile = {
id: "kiro",
match: ["kiro-cli"],
builtins: [],
sources: [{ scope: "project", path: ".kiro/prompts", pattern: "*.md", prefix: "@" }],
};
const { exec } = ccMachine({ ".kiro/prompts/review.md": "---\ndescription: R\n---\n" });
const items = await commands("/x", exec, { profile });
assert.deepEqual(items, [
{ key: "review", desc: "R", group: "Projekt", insert: "@review " },
]);
});
test("commands: a project source path never reaches the shell as a script", async () => {
const seen = [];
const exec = async (command, args) => {
seen.push([command, args]);
return { code: 0, stdout: "", stderr: "" };
};
const profile = {
id: "x",
match: ["x"],
builtins: [],
sources: [{ scope: "project", path: ".a b/Zażółć", pattern: "*.md", prefix: "/" }],
};
await commands("/x", exec, { profile });
assert.equal(seen.length, 1);
assert.ok(!seen[0][1][1].includes("Zażółć"));
assert.ok(seen[0][1].includes(".a b/Zażółć"));
});
test("globalCommands: no sources gives [] and no exec", async () => {
let calls = 0;
const exec = async () => {
calls += 1;
return { code: 0, stdout: "", stderr: "" };
};
assert.deepEqual(await globalCommands(HOME, exec, async () => null, { sources: [] }), []);
assert.deepEqual(await globalCommands(HOME, exec, async () => null), []);
assert.equal(calls, 0);
});
test("globalCommands: a home source gives the Użytkownik group with its prefix", async () => {
const { exec, readText } = machine({ [`${HOME}/.kiro/prompts/plan.md`]: "---\ndescription: P\n---\n" });
const sources = [{ scope: "home", path: ".kiro/prompts", pattern: "*.md", prefix: "@" }];
const items = await globalCommands(HOME, exec, readText, { sources });
assert.deepEqual(items, [{ key: "plan", desc: "P", group: GROUP_USER, insert: "@plan " }]);
});
test("globalCommands: a project source is not read from home", async () => {
const { exec, readText } = machine({ [`${HOME}/.kiro/prompts/plan.md`]: "x" });
const sources = [{ scope: "project", path: ".kiro/prompts", pattern: "*.md", prefix: "/" }];
assert.deepEqual(await globalCommands(HOME, exec, readText, { sources }), []);
});
test("historyCommands: commands of this agent, newest first, no paths", () => {
const e = (text, sentAt, agentName = "claude-code") => ({ text, sentAt, agentName });
const history = [
e("/clear", 1),
e(" /superpowers:brainstorming x", 5),
e("/c/Users/x", 6),
e("/ cos", 7),
e("/", 8),
e("hej /clear", 9),
e("/other", 10, "codex"),
];
const items = historyCommands(history, "Claude-Code");
assert.deepEqual(items.map((i) => i.key), ["superpowers:brainstorming", "clear"]);
assert.ok(items.every((i) => i.group === "Z historii" && i.desc === ""));
assert.equal(items[0].insert, "/superpowers:brainstorming ");
});
test("commands: a history command that is a builtin shows once, as Wbudowane", async () => {
const exec = async () => ({ code: 0, stdout: "", stderr: "" });
const items = await commands("/x", exec, {
profile: resolveProfile([], "codex"),
history: historyCommands([{ text: "/model", sentAt: 1, agentName: "codex" }], "codex"),
});
const model = items.filter((i) => i.key === "model");
assert.equal(model.length, 1);
assert.equal(model[0].group, "Wbudowane");
});
test("GROUPS has Z historii right after Pluginy", () => {
assert.equal(GROUPS[GROUPS.indexOf("Pluginy") + 1], "Z historii");
});