UNPKG

akm-cli

Version:

akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur

293 lines (292 loc) • 12.4 kB
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. /** * Built-in asset matchers for the akm file classification system. * * Each private `classifyBy*` function encapsulates the classification logic for * one heuristic. The public `*Matcher` exports compose those facts into the * `MatchResult` shape expected by the rest of the indexer. */ import { isSecretSidecar } from "../../asset/asset-placement.js"; import { SCRIPT_EXTENSIONS } from "../../recognition-util.js"; import { presentationFor } from "../../type-presentation.js"; // --------------------------------------------------------------------------- // Private data // --------------------------------------------------------------------------- const DIR_TYPE_MAP = [ { dir: "scripts", type: "script", test: (ext) => SCRIPT_EXTENSIONS.has(ext), }, { dir: "commands", type: "command", test: (ext) => ext === ".md", }, { dir: "agents", type: "agent", test: (ext) => ext === ".md", }, { dir: "knowledge", type: "knowledge", test: (ext) => ext === ".md", }, { // Stash-resident `instruction` // assets live under `instructions/`, mirroring the `knowledge` rule. This // is a walker discovery rule for FILES ON DISK under a stash's // `instructions/` dir; it is unrelated to the adapter-emitted root // CLAUDE.md/AGENTS.md instruction docs (`tool-dir-shared.ts`), which are // synthesized by format-family adapters, carry `ownsPresentation: true`, // and never pass through this matcher at all. dir: "instructions", type: "instruction", test: (ext) => ext === ".md", }, { dir: "rules", type: "rule", test: (ext) => ext === ".md", }, { dir: "workflows", type: "workflow", test: (ext) => ext === ".md" || ext === ".yml", }, { dir: "memories", type: "memory", test: (ext) => ext === ".md", }, { dir: "lessons", type: "lesson", test: (ext) => ext === ".md", }, { dir: "env", type: "env", test: (_, fileName) => fileName === ".env" || fileName.endsWith(".env"), }, { dir: "secrets", type: "secret", // Any regular file under secrets/ is a secret value, except the lock and // sensitive-marker sidecars. The whole file is the value (no extension or // body parsing — see the secret-file renderer + indexer guards). test: (_, fileName) => !isSecretSidecar(fileName), }, { dir: "tasks", type: "task", // Tasks migrated from `.md` to `.yml` in 0.8.0 (commit 031c659f updated // the placement specs, renderers, and the task-linter, but missed this // matcher — tasks/*.yml were unrecognized until this fix). test: (ext) => ext === ".yml", }, { // #561 — agent session assets live under `sessions/<harness>/<id>.md`. // classifyByDirectory walks every ancestor dir, so a nested file still // matches the `sessions` rule. Without this entry the file falls through // to classifyByLooseMarkdown and is typed `knowledge`. dir: "sessions", type: "session", test: (ext) => ext === ".md", }, { // Durable stash-level facts live under `facts/<category>/<name>.md`. // classifyByDirectory walks every ancestor dir, so nested category // subdirs still match. Without this entry a fact file would fall through // to classifyByLooseMarkdown and be typed `knowledge`. dir: "facts", type: "fact", test: (ext) => ext === ".md", }, ]; /** Body placeholders can discover loose commands, but also occur in documentation. */ const ARGUMENTS_PLACEHOLDER_RE = /\$ARGUMENTS/; /** * `$1` / `$2` / `$3` — AMBIGUOUS, because ordinary prose writes money the same * way. The old combined pattern used `\$[123]\b`, and `\b` sits between the * `2` and the comma in `$2,000`, so every note quoting a price read as a * command (#824). Excluding a following digit, or a `.`/`,` that is itself * followed by a digit, rules out `$1,200` / `$2,000` / `$2.50` / `$12` while * still matching `$1.` at the end of a sentence — a period with no digit after * it is not part of a number. */ const NUMERIC_PLACEHOLDER_RE = /\$[123](?!\d|[.,]\d)/; const SMART_MD_FACTS = { workflow: { type: "workflow", specificity: 19 }, command: { type: "command", specificity: 18 }, modelAgent: { type: "agent", specificity: 8 }, knowledge: { type: "knowledge", specificity: 5 }, }; // Files that should never be treated as the typed asset for the surrounding // directory (e.g. `workflows/README.md` is documentation, not a workflow). // Lower-cased and matched case-insensitively against `ctx.fileName`. They are // still indexable — falling through to `classifyByLooseMarkdown` routes // them to the generic `knowledge` type. const TYPED_DIR_DOC_FILES = new Set(["readme.md"]); function isTypedDirDocFile(fileName) { return TYPED_DIR_DOC_FILES.has(fileName.toLowerCase()); } function isNestedSkillResource(ctx) { return ctx.ancestorDirs[0] === "skills" && ctx.ancestorDirs.length > 1 && ctx.fileName !== "SKILL.md"; } // --------------------------------------------------------------------------- // Private helpers // --------------------------------------------------------------------------- function matchDirectoryHint(dirName, ctx, specificity) { if (dirName === "skills" && ctx.fileName === "SKILL.md") { return { type: "skill", specificity }; } for (const rule of DIR_TYPE_MAP) { // `rules/` is the bundle's top-level folder only; a `rules` folder deeper down is whatever its parent says. if (rule.dir === "rules" && ctx.ancestorDirs[0] !== "rules") continue; if (rule.dir === dirName && rule.test(ctx.ext, ctx.fileName)) { // Skip `README.md` (case-insensitive) so `workflows/README.md`, // `agents/README.md`, etc. are not parsed as the typed asset and don't // trip the workflow/agent metadata validators. They still get indexed // as `knowledge` via the loose-Markdown matcher. if (isTypedDirDocFile(ctx.fileName)) return null; return { type: rule.type, specificity }; } } return null; } function classifyByExtension(ctx) { if (ctx.fileName === "SKILL.md") { return { type: "skill", specificity: 25 }; } if (SCRIPT_EXTENSIONS.has(ctx.ext)) { return { type: "script", specificity: 3 }; } return null; } function classifyByDirectory(ctx) { if (isNestedSkillResource(ctx)) return null; for (const dir of ctx.ancestorDirs) { const result = matchDirectoryHint(dir, ctx, 10); if (result) return result; } return null; } function classifyByParentDirHint(ctx) { const { parentDir, ext, fileName } = ctx; if (isNestedSkillResource(ctx)) return null; if (parentDir === "skills" && (fileName === "SKILL.md" || ext === ".md")) { return { type: "skill", specificity: 15 }; } return matchDirectoryHint(parentDir, ctx, 15); } /** * The type a file's location declares, from the same directory rules the * indexer applies: parent-directory hint (specificity 15) over the outermost * typed ancestor (10), each honouring the rule's extension predicate, the * `README.md` documentation exception and nested skill resources. `undefined` * when no directory rule claims the file. Path fields only; no bytes are read. */ export function declaredTypeForPath(ctx) { // In the skills tree, a package name is not a competing type declaration. if (ctx.ancestorDirs[0] === "skills" && ctx.ancestorDirs.length > 1 && ctx.fileName === "SKILL.md") { return "skill"; } return (classifyByParentDirHint(ctx) ?? classifyByDirectory(ctx))?.type; } /** * True when some ancestor directory already DECLARES this file's type via * `DIR_TYPE_MAP` — the same walk `classifyByDirectory` performs. Derived from * path fields alone, so the content rules below can apply it without reading * bytes. A skill's folder is a declared context too: a file in it is a skill * resource, so a shell `$1` in one of its snippets must not retype it (#1063). */ function hasDeclaredDirType(ctx) { if (isNestedSkillResource(ctx)) return true; return ctx.ancestorDirs.some((dir) => matchDirectoryHint(dir, ctx, 0) !== null); } /** What a Markdown file is when nothing but its path is known: knowledge. */ function classifyByLooseMarkdown(ctx) { if (ctx.ext !== ".md") return null; // A file under secrets/ is a secret value, whatever its extension: the directory matcher types it. if (ctx.ancestorDirs.includes("secrets")) return null; return SMART_MD_FACTS.knowledge; } /** A loose Markdown file's type by its content; the path's answer ({@link classifyByLooseMarkdown}) when nothing in it says more. */ function classifyBySmartMd(ctx) { const byPath = classifyByLooseMarkdown(ctx); // README.md is documentation, never a workflow/agent/command even when the body shape would otherwise classify. if (byPath === null || isTypedDirDocFile(ctx.fileName)) return byPath; const body = ctx.content(); const fm = ctx.frontmatter(); // A workflow living OUTSIDE `workflows/` that still declares its type explicitly. Residence under `workflows/` is // the directory rule's. if (fm && fm.type === "workflow") return SMART_MD_FACTS.workflow; if (fm && "agent" in fm) return SMART_MD_FACTS.command; // Mentioning a placeholder is not explicit command intent. Directory // declarations and skill-resource context win over body-text guesses. if (!hasDeclaredDirType(ctx) && (ARGUMENTS_PLACEHOLDER_RE.test(body) || NUMERIC_PLACEHOLDER_RE.test(body))) { return SMART_MD_FACTS.command; } if (fm && "model" in fm) return SMART_MD_FACTS.modelAgent; return byPath; } // --------------------------------------------------------------------------- // Adapter: MatchFact → MatchResult // --------------------------------------------------------------------------- function toMatchResult(ctx, classify) { const fact = classify(ctx); return fact ? matchResultForFact(fact) : null; } function matchResultForFact(fact) { // Renderer name resolved via TYPE_PRESENTATION (core leaf), so matchers.ts // carries no edge into the taxonomy SCC. // TYPE_PRESENTATION.renderer is the single source of truth for renderer names. const renderer = presentationFor(fact.type).renderer; if (!renderer) return null; return { type: fact.type, specificity: fact.specificity, renderer, ...(fact.meta ? { meta: fact.meta } : {}), }; } // --------------------------------------------------------------------------- // Public matchers (API unchanged) // --------------------------------------------------------------------------- export function extensionMatcher(ctx) { return toMatchResult(ctx, classifyByExtension); } export function directoryMatcher(ctx) { return toMatchResult(ctx, classifyByDirectory); } export function parentDirHintMatcher(ctx) { return toMatchResult(ctx, classifyByParentDirHint); } /** Markdown by its path alone: knowledge. This is what identity and the write gates see. */ export function looseMarkdownMatcher(ctx) { return toMatchResult(ctx, classifyByLooseMarkdown); } /** Markdown by its content (`type: workflow`, `agent:`, `$ARGUMENTS`, `model:`), else as {@link looseMarkdownMatcher}. */ export function smartMdMatcher(ctx) { return toMatchResult(ctx, classifyBySmartMd); } // The matcher functions above are consumed directly by `recognizeMatch()` and `recognizeMatchByPath()` // (`core/adapter/recognize-match.ts`, which hold the same registration-order arrays for tie-breaking). There is no // file-context matcher registry or `registerBuiltinMatchers` glue — recognition is adapter-driven, not registry-driven.