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
118 lines (117 loc) • 4.93 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/.
import { makeBundleRef, parseBundleRef } from "../../core/asset/asset-ref.js";
import { rethrowIfTestIsolationError } from "../../core/errors.js";
import { appendEvent, readEvents } from "../../core/events.js";
import { withStateDbTelemetry } from "../../core/state-db.js";
import { TELEMETRY_BUSY_TIMEOUT_MS, withIndexDb } from "../../storage/repositories/index-db.js";
import { findEntryIdByRef, getEntryById, getEntryIdByFilePath, getItemRefById, } from "../../storage/repositories/index-entries-repository.js";
import { usageEventAttributionMetadata } from "../search/search-attribution.js";
import { insertUsageEvent } from "./usage-events.js";
/** Count prior show events in the current one-hour loop-detection window. */
export function recentShowCount(ref) {
try {
return readEvents({
type: "show",
ref,
since: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
}).events.length;
}
catch {
return 0;
}
}
/** Compare search/display selectors by their durable parent asset identity. */
function traceParentRef(ref) {
try {
const parsed = parseBundleRef(ref);
return makeBundleRef(parsed.bundle, parsed.conceptId);
}
catch {
// Registry result refs are not local bundle refs and cannot have a local
// selector. Keep their existing exact comparison behavior.
return ref;
}
}
function appendShowTrace(ref, type, name) {
appendEvent({ eventType: "show", ref, metadata: { type, name } });
try {
const { events: recentSearches } = readEvents({
type: "search",
since: new Date(Date.now() - 60_000).toISOString(),
});
const cutoffMs = Date.now() - 60_000;
const matchingSearch = [...recentSearches].reverse().find((event) => {
if (!event.ts || new Date(event.ts).getTime() < cutoffMs)
return false;
const refs = event.metadata?.resultRefs ?? [];
return refs.some((candidate) => traceParentRef(candidate) === ref);
});
if (!matchingSearch)
return;
const resultRefs = matchingSearch.metadata?.resultRefs ?? [];
appendEvent({
eventType: "select",
ref,
metadata: {
query: matchingSearch.metadata?.query,
searchTs: matchingSearch.ts,
rankPosition: resultRefs.findIndex((candidate) => traceParentRef(candidate) === ref),
},
});
}
catch {
// Selection attribution is best-effort.
}
}
function insertShowUsage(entryId, entryRef, derivedFrom, eventSource) {
withStateDbTelemetry((stateDb) => {
insertUsageEvent(stateDb, {
event_type: "show",
entry_ref: entryRef,
entry_id: entryId,
metadata: usageEventAttributionMetadata(derivedFrom ? { memoryInference: { exposure: "direct" } } : undefined, entryRef),
source: eventSource,
});
}, TELEMETRY_BUSY_TIMEOUT_MS);
}
/** Record a successful show using the already-rendered response identity. */
export function recordShowUsage(ref, type, name, eventSource = "user", filePath) {
const parsed = parseBundleRef(ref);
const eventRef = makeBundleRef(parsed.bundle, parsed.conceptId);
appendShowTrace(eventRef, type, name);
try {
withIndexDb((db) => {
const entryId = filePath ? getEntryIdByFilePath(db, filePath) : findEntryIdByRef(db, eventRef);
if (entryId === undefined)
return;
const entryRef = getItemRefById(db, entryId);
if (!entryRef)
return;
insertShowUsage(entryId, entryRef, getEntryById(db, entryId)?.entry.derivedFrom, eventSource);
}, { busyTimeoutMs: TELEMETRY_BUSY_TIMEOUT_MS });
}
catch (error) {
rethrowIfTestIsolationError(error);
}
}
/** Record a nested execution-source read only after dispatch has crossed preflight. */
export function recordIndexedShowUsage(ref, eventSource = "user") {
try {
withIndexDb((db) => {
const entryId = findEntryIdByRef(db, ref);
if (entryId === undefined)
return;
const indexed = getEntryById(db, entryId);
const entryRef = getItemRefById(db, entryId);
if (!indexed || !entryRef)
return;
appendShowTrace(entryRef, indexed.entry.type, indexed.entry.name);
insertShowUsage(entryId, entryRef, indexed.entry.derivedFrom, eventSource);
}, { busyTimeoutMs: TELEMETRY_BUSY_TIMEOUT_MS });
}
catch (error) {
rethrowIfTestIsolationError(error);
}
}