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
296 lines (295 loc) • 13.5 kB
JavaScript
// 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/.
/**
* Authoritative workflow-source ownership.
*
* One canonical workflow ref must have exactly one source file. This module
* is the shared filesystem arbitration point used before indexing, cache
* reuse, lookup/show, and runtime load/start.
*/
import fs from "node:fs";
import path from "node:path";
// asset-io: deprecated
import { buildFileContext } from "../core/adapter/directory/file-context.js";
// asset-io: deprecated
import { declaredTypeForPath } from "../core/adapter/directory/matchers.js";
import { compareCodePoints, toPosix } from "../core/common.js";
import { UsageError } from "../core/errors.js";
import { canonicalizeWorkflowName, WORKFLOW_EXTENSIONS } from "../core/recognition-util.js";
import { warnOnce } from "../core/warn.js";
export class WorkflowSourceRejectionError extends UsageError {
sourcePaths;
constructor(message, code, sourcePaths) {
super(message, code);
this.sourcePaths = [...sourcePaths].sort(compareCodePoints);
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class WorkflowSourceCollisionError extends WorkflowSourceRejectionError {
canonicalName;
constructor(canonicalName, sourcePaths) {
const sorted = [...sourcePaths].sort(compareCodePoints);
super(`Workflow "${canonicalName}" resolves to multiple workflow source files: ${sorted.join(", ")}. ` +
"A canonical workflow ref must be owned by exactly one recognized .md source; remove or rename the duplicate.", "RESOURCE_ALREADY_EXISTS", sorted);
this.name = "WorkflowSourceCollisionError";
this.canonicalName = canonicalName;
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class WorkflowSourceIdentityError extends UsageError {
constructor(ref, indexedPath, authoritativePath) {
super(`Indexed workflow source identity for "${ref}" points to ${indexedPath}, but the authoritative source is ${authoritativePath}. ` +
"Refusing the stale index/cache identity; run `akm index --full` to reconcile it.", "WORKFLOW_SOURCE_INVALID");
this.name = "WorkflowSourceIdentityError";
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class WorkflowSourceNameError extends WorkflowSourceRejectionError {
constructor(sourcePath, nestedSuffix) {
super(`Workflow source filename ${sourcePath} has an extensionless stem ending in recognized workflow suffix "${nestedSuffix}". ` +
"Nested workflow suffixes are invalid; remove the inner .md suffix instead of relying on repeated stripping.", "WORKFLOW_SOURCE_INVALID", [sourcePath]);
this.name = "WorkflowSourceNameError";
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class WorkflowSourceLinkIdentityError extends WorkflowSourceRejectionError {
constructor(sourcePath, targetPath) {
super(`Workflow source ${sourcePath} resolves through a symlink to ${targetPath} with a different extension. ` +
"The authored workflow path and resolved source must both be .md.", "WORKFLOW_SOURCE_INVALID", [sourcePath]);
this.name = "WorkflowSourceLinkIdentityError";
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class WorkflowSourceLinkResolutionError extends WorkflowSourceRejectionError {
constructor(sourcePath) {
super(`Workflow source symlink ${sourcePath} cannot be resolved to a regular file.`, "WORKFLOW_SOURCE_INVALID", [
sourcePath,
]);
this.name = "WorkflowSourceLinkResolutionError";
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Does `absPath` belong to the workflow domain of `adapterId`? An `akm-workflow`
* bundle is all workflows; in an `akm` bundle a file is a workflow when its
* location declares it (the same directory rule the indexer applies), wherever
* in the bundle it sits.
*/
function ownsWorkflowFile(sourceRoot, adapterId, absPath) {
// asset-io: deprecated workflows are not read through the adapters
if (adapterId === "akm-workflow")
return true;
// asset-io: deprecated
return adapterId === "akm" && declaredTypeForPath(buildFileContext(sourceRoot, absPath)) === "workflow";
}
/** Derive the once-canonicalizable workflow name from an adapter-owned authored path. */
export function workflowNameForSourcePath(sourceRoot, adapterId, sourcePath) {
// asset-io: deprecated workflows are not read through the adapters
if (adapterId !== "akm" && adapterId !== "akm-workflow")
return undefined;
const relativePath = toPosix(path.relative(path.resolve(sourceRoot), path.resolve(sourcePath)));
if (!isSafeRelativeName(relativePath))
return undefined;
const extension = path.posix.extname(relativePath);
if (!WORKFLOW_EXTENSIONS.includes(extension.toLowerCase()))
return undefined;
return ownsWorkflowFile(sourceRoot, adapterId, path.resolve(sourcePath)) ? relativePath : undefined;
}
/** Whether `sourcePath` is a workflow source of the bundle: a loose `.md` typed workflow by its content is none. */
export function isWorkflowSource(sourceRoot, adapterId, sourcePath) {
return workflowNameForSourcePath(sourceRoot, adapterId, sourcePath) !== undefined;
}
/**
* Resolve a pre-enumerated set of authored workflow candidates in one batch.
*
* Callers that already walked a bundle (for example full lint/index scans)
* must use this surface instead of point-resolving every canonical ref and
* re-reading the same parent directory once per workflow. Candidate
* inspection, symlink containment/format rules, nested-suffix rejection, and
* collision construction are shared by every resolution of a workflow source.
*/
export function resolveWorkflowSourceDomains(sourceRoot, adapterId, sourcePaths) {
// asset-io: deprecated workflows are not read through the adapters
if (adapterId !== "akm" && adapterId !== "akm-workflow")
return [];
const authoredRoot = path.resolve(sourceRoot);
let realRoot;
try {
realRoot = fs.realpathSync(authoredRoot);
}
catch {
return [];
}
const candidatesByName = new Map();
const seenAuthoredPaths = new Set();
for (const sourcePath of sourcePaths) {
// A full walk can legitimately feed the same authored file through more
// than one lexical spelling (or a caller may repeat it verbatim). Collapse
// only the normalized AUTHORED path here: distinct symlink/case-variant
// paths must remain separate ownership candidates even when they resolve to
// the same physical inode.
const normalizedSourcePath = path.resolve(sourcePath);
if (seenAuthoredPaths.has(normalizedSourcePath))
continue;
seenAuthoredPaths.add(normalizedSourcePath);
const authoredName = workflowNameForSourcePath(authoredRoot, adapterId, normalizedSourcePath);
if (authoredName === undefined)
continue;
const canonicalName = canonicalizeWorkflowName(authoredName);
if (!isSafeRelativeName(canonicalName))
continue;
const extension = path.extname(normalizedSourcePath);
const lowerExtension = extension.toLowerCase();
if (!WORKFLOW_EXTENSIONS.includes(lowerExtension))
continue;
const candidate = {
path: normalizedSourcePath,
relativePath: toPosix(path.relative(authoredRoot, normalizedSourcePath)),
lowerExtension,
extensionlessStem: path.basename(normalizedSourcePath).slice(0, -extension.length),
};
const domain = candidatesByName.get(canonicalName) ?? [];
domain.push(candidate);
candidatesByName.set(canonicalName, domain);
}
const resolutions = [];
for (const canonicalName of [...candidatesByName.keys()].sort(compareCodePoints)) {
const candidates = candidatesByName.get(canonicalName) ?? [];
candidates.sort((left, right) => compareCodePoints(left.relativePath, right.relativePath));
const sources = inspectWorkflowSourceDomain(candidates, canonicalName, realRoot);
const sourcePaths = candidates.map((candidate) => candidate.relativePath);
resolutions.push({
canonicalName,
sourcePaths,
source: pickWorkflowSource(canonicalName, sources),
});
}
return resolutions;
}
/**
* Whether the workflow source `file` of the bundle at `sourceRoot` may run: a symlink may not change the source's
* format or lead to no file. A source that may not is warned about once, as the index and lint do.
*/
export function isUsableWorkflowSource(sourceRoot, file) {
const authoredRoot = path.resolve(sourceRoot);
let realRoot;
try {
realRoot = fs.realpathSync(authoredRoot);
}
catch {
return false;
}
const authored = path.resolve(file);
const extension = path.extname(authored);
const inspection = inspectWorkflowSourceCandidate({
path: authored,
relativePath: toPosix(path.relative(authoredRoot, authored)),
lowerExtension: extension.toLowerCase(),
extensionlessStem: path.basename(authored).slice(0, -extension.length),
}, "", realRoot);
for (const issue of inspection.issues) {
warnOnce(`workflow-source-invalid:${issue.sourcePaths.join(",")}`, issue.message);
}
return inspection.source !== undefined;
}
function inspectWorkflowSourceDomain(candidates, canonicalName, realRoot) {
const sources = [];
for (const candidate of candidates) {
const inspection = inspectWorkflowSourceCandidate(candidate, canonicalName, realRoot);
if (inspection.source) {
sources.push(inspection.source);
continue;
}
for (const issue of inspection.issues) {
warnOnce(`workflow-source-invalid:${issue.sourcePaths.join(",")}`, issue.message);
}
}
return sources;
}
function pickWorkflowSource(canonicalName, sources) {
if (sources.length <= 1)
return sources[0];
const winner = sources[0];
const shadowed = sources.filter((source) => source !== winner);
warnOnce(`workflow-source-collision:${canonicalName}`, `Workflow "${canonicalName}" has several sources (${shadowed
.map((source) => source.relativePath)
.join(", ")} shadowed by ${winner?.relativePath}); using ${winner?.relativePath}. Remove the shadowed ` +
"sibling to silence this warning.");
return winner;
}
function inspectWorkflowSourceCandidate(candidate, canonicalName, realRoot) {
const issues = [];
let authoredStat;
try {
// asset-io: deprecated
authoredStat = fs.lstatSync(candidate.path);
}
catch {
issues.push(new WorkflowSourceLinkResolutionError(candidate.relativePath));
return { issues };
}
const isLink = authoredStat.isSymbolicLink();
if (!isLink && !authoredStat.isFile()) {
issues.push(new WorkflowSourceLinkResolutionError(candidate.relativePath));
return { issues };
}
let realPath;
try {
realPath = fs.realpathSync(candidate.path);
}
catch {
issues.push(new WorkflowSourceLinkResolutionError(candidate.relativePath));
return { issues };
}
// A symlink may point anywhere (installing a bundle is the trust decision),
// but it may not change the source's format.
const targetPath = toPosix(path.relative(realRoot, realPath));
if (isLink && path.extname(realPath).toLowerCase() !== candidate.lowerExtension) {
issues.push(new WorkflowSourceLinkIdentityError(candidate.relativePath, targetPath));
}
try {
// asset-io: deprecated
if (!fs.statSync(realPath).isFile())
issues.push(new WorkflowSourceLinkResolutionError(candidate.relativePath));
}
catch {
issues.push(new WorkflowSourceLinkResolutionError(candidate.relativePath));
}
if (issues.length > 0)
return { issues };
return {
issues,
source: {
path: candidate.path,
realPath,
relativePath: candidate.relativePath,
canonicalName,
},
};
}
/** Compare an indexed path with the single authoritative on-disk source. */
export function assertIndexedWorkflowSourceIdentity(ref, indexedPath, authoritative) {
let indexedRealPath;
try {
indexedRealPath = fs.realpathSync(indexedPath);
}
catch {
throw new WorkflowSourceIdentityError(ref, indexedPath, authoritative.path);
}
if (path.resolve(indexedPath) !== path.resolve(authoritative.path) ||
path.resolve(indexedRealPath) !== path.resolve(authoritative.realPath)) {
throw new WorkflowSourceIdentityError(ref, indexedPath, authoritative.path);
}
const indexedExtension = path.extname(indexedPath).toLowerCase();
if (indexedExtension !== ".md") {
throw new WorkflowSourceIdentityError(ref, indexedPath, authoritative.path);
}
}
function isSafeRelativeName(name) {
return (name.length > 0 &&
!path.posix.isAbsolute(name) &&
name !== ".." &&
!name.startsWith("../") &&
path.posix.normalize(name) === name);
}