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
191 lines (190 loc) • 9.52 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/.
/**
* Single-file authoring for the owner: read a document's source, save it over the revision they read, create knowledge,
* copy an asset, retire one. Every write checks the `revision` (the sha256 of the raw bytes) the owner last saw inside
* the asset-mutation lease, and fails fast when another akm process holds the lease.
*/
import { createHash } from "node:crypto";
import path from "node:path";
import { akmProposalAccept } from "../commands/proposal/proposal.js";
import { createRetireProposal, recordGateDecision, rejectProposalDurably } from "../commands/proposal/repository.js";
import { writeMarkdownAsset } from "../commands/read/knowledge.js";
import { akmShowUnified } from "../commands/read/show.js";
import { akmClone } from "../commands/sources/source-clone.js";
import { assertFlatAssetName, normalizeCreateSubPath } from "../core/asset/asset-create.js";
import { stashDirFor } from "../core/asset/asset-placement.js";
import { parseBundleRef } from "../core/asset/asset-ref.js";
import { conceptIdFromTypeName } from "../core/asset/resolve-ref.js";
import { assertAdapterWrites } from "../core/assets/gate.js";
import { findAsset } from "../core/assets/read.js";
import { addressOf } from "../core/assets/write.js";
import { resolveStashDir, toErrorMessage } from "../core/common.js";
import { loadConfig } from "../core/config/config.js";
import { UsageError } from "../core/errors.js";
import { appendEvent } from "../core/events.js";
import { resolveBundleWriteTarget } from "../core/mutation-target.js";
import { warn } from "../core/warn.js";
import { requireWriteTargetPath } from "../core/write-source.js";
import { readUsableIndex } from "../indexer/index-readiness.js";
import { noIndexError } from "../storage/repositories/index-connection.js";
import { getEntryIdByFilePath, getItemRefById } from "../storage/repositories/index-entries-repository.js";
import { retireBlocker } from "./file-actions.js";
import { interactive } from "./lease.js";
import { createFile } from "./new-file.js";
import { redactUrlsInText } from "./redact.js";
export { check } from "./check-text.js";
export { applyFrontmatter, frontmatter } from "./frontmatter.js";
export { createFile };
/** An indexed asset file whose bundle accepts AKM writes, found the way the UI reads it. */
async function resolveWritableIndexedAsset(ref) {
const { fragment } = parseBundleRef(ref);
if (fragment !== undefined) {
throw new UsageError(`Export fragment "#${fragment}" is not accepted here — drop it from "${ref.trim()}".`, "INVALID_FLAG_VALUE");
}
const shown = await akmShowUnified({ ref, readOnly: true });
if (!shown.path)
throw new UsageError("The document has no local source file.");
const canonical = readUsableIndex((db) => {
const id = getEntryIdByFilePath(db, shown.path);
return id === undefined ? undefined : (getItemRefById(db, id) ?? undefined);
}, null);
if (canonical === null)
throw noIndexError();
if (!canonical)
throw new UsageError("Only indexed documents can be edited.");
const target = resolveBundleWriteTarget(loadConfig(), parseBundleRef(canonical).bundle);
assertAdapterWrites(target.source);
return { canonical, target, path: shown.path, type: shown.type, name: shown.name };
}
/** Source reads are limited to indexed, writable AKM knowledge/memory files, never arbitrary paths. */
export async function readSource(input) {
const { name: _name, ...source } = await loadSource(input.ref);
return source;
}
async function loadSource(ref) {
const found = await resolveWritableIndexedAsset(ref);
if (found.type !== "knowledge" && found.type !== "memory")
throw new UsageError("Only knowledge and memory support source editing in this UI.");
// The writers place a document by its type and name, so a document sitting
// anywhere else cannot be saved through them.
const typeDir = stashDirFor(found.type);
if (!typeDir)
throw new UsageError("Only indexed documents can be edited.");
// The document is the one asset the target's adapter places under that type and name.
const asset = findAsset(found.canonical);
const placed = addressOf(found.target.source, conceptIdFromTypeName(found.type, found.name));
// The writers keep a document at the file they place it in: one held in another spelling of it cannot be saved.
if (asset === undefined || asset.conceptId !== placed.conceptId || placed.heldElsewhere === true)
throw new UsageError("The indexed source no longer matches the writable document target. Refresh the index before editing.");
const raw = asset.entry.bytes();
const content = raw.toString("utf8");
if (!Buffer.from(content, "utf8").equals(raw))
throw new UsageError("This source is not valid UTF-8; edit it outside the UI.");
if (redactUrlsInText(content) !== content)
throw new UsageError("This document contains URL credentials hidden by the UI. Edit it outside the UI to preserve those values.");
return {
ref: found.canonical,
type: found.type,
name: found.name,
content,
revision: createHash("sha256").update(raw).digest("hex"),
};
}
/**
* Save `content` over the knowledge or memory document at `ref` if its raw SHA-256 is still `revision`, through the
* shared Markdown writer (and record its event).
*/
async function saveLocked(ref, content, revision) {
const source = await loadSource(ref);
const result = await writeMarkdownAsset({
type: source.type,
content,
name: source.name,
fallbackPrefix: source.type,
target: parseBundleRef(source.ref).bundle,
force: true,
expectedContentHash: revision,
});
if (!result.unchanged)
appendEvent({
eventType: source.type === "knowledge" ? "import" : "remember",
ref: result.ref,
metadata: { source: "ui", path: result.path, force: true },
});
return result;
}
export async function save(input) {
if (typeof input.content !== "string")
throw new UsageError("Markdown content is required.");
const ref = required(input.ref, "ref");
const revision = required(input.revision, "revision");
return interactive("ui-document-save", () => saveLocked(ref, input.content, revision));
}
function required(value, key) {
if (typeof value !== "string" || !value.trim())
throw new UsageError(`${key} is required.`);
return value.trim();
}
/** A new knowledge document, placed and indexed as `akm import -` does. An existing document is refused. */
export async function createKnowledge(input) {
if (typeof input.content !== "string" || !input.content.trim())
throw new UsageError("Document content is required.");
const name = required(input.name, "name");
assertFlatAssetName(name);
const folder = path.posix.join("knowledge", normalizeCreateSubPath(input.path));
return createFile({ bundle: input.bundle, folder, name, content: input.content });
}
/** Copy an asset to a bundle. Overwriting an existing asset is never done here. */
export async function copy(input) {
return interactive("ui-asset-copy", () => akmClone({
sourceRef: required(input.sourceRef, "sourceRef"),
target: input.target,
newName: input.newName,
force: false,
}));
}
/**
* A person retires an asset: the ordinary retire proposal, minted and accepted at once the way `akm feedback`'s typed fix
* is. The proposal captures exactly the bytes whose `revision` the person saw (checked where they are read, inside the
* lease). Undo is reverting that proposal.
*/
export async function retire(input) {
const ref = required(input.ref, "ref");
const revision = required(input.revision, "revision");
return interactive("manual-retire", async () => {
const { canonical, target, type } = await resolveWritableIndexedAsset(ref);
const blocker = retireBlocker(type);
if (blocker !== undefined)
throw new UsageError(blocker);
const stashDir = resolveStashDir();
const minted = createRetireProposal(stashDir, {
ref: canonical,
source: "propose",
target: { source: target.source.name, root: requireWriteTargetPath(target.source) },
expectedRevision: revision,
});
let result;
try {
recordGateDecision(stashDir, minted.id, { outcome: "auto-accepted", reason: "manual-retire", gate: "workspace" });
result = await akmProposalAccept({ stashDir, id: minted.id });
}
catch (error) {
try {
rejectProposalDurably(stashDir, minted.id, `manual retire not applied: ${toErrorMessage(error)}`);
}
catch (rejectError) {
warn(`[retire] could not reject proposal ${minted.id}: ${toErrorMessage(rejectError)}`);
}
throw error;
}
return {
proposalId: result.proposal.id,
ref: canonical,
bundle: target.source.name,
archiveDirs: result.proposal.retiredArchive?.retired.map(({ handle }) => handle) ?? [],
warnings: result.warnings ?? [],
};
});
}