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
252 lines (251 loc) • 11.7 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/.
/**
* What improve proposed and changed in the environment, week by week, and what went wrong.
* One response feeds every section of the page; each store read degrades on its own, so one unreadable table leaves
* the cards that do not depend on it. Nothing here writes.
*/
import { metricsWindow, readLlmRows, readUsageRows } from "../commands/metrics/metrics-cli.js";
import { isRetireProposal } from "../commands/proposal/proposal-types.js";
import { stateBundleId } from "../core/bundle-at-dir.js";
import { resolveStashDir } from "../core/common.js";
import { USAGE_EVENT_RETENTION_DAYS } from "../indexer/usage/usage-events.js";
import { readStateEvents } from "../storage/repositories/events-repository.js";
import { listIndexCompletedEvents } from "../storage/repositories/metrics-repository.js";
import { listStateProposals } from "../storage/repositories/proposals-repository.js";
import { classifyOutcome, decidedAt, deciderOf, weekOf, weekRange } from "./derive.js";
import { attempt, withReadonlyStateDb } from "./readers.js";
const DAY = 86_400_000;
const FLAG_DAYS = 14;
const COMPARE_DAYS = 28;
const blank = () => ({ judge: 0, you: 0, unknown: 0, rejected: 0, reverted: 0 });
function outcomesByProcess(proposals, weeks) {
const byProcess = new Map();
for (const proposal of proposals) {
const outcome = classifyOutcome(proposal);
if (outcome === "pending")
continue;
const week = weekOf(decidedAt(proposal));
if (!weeks.includes(week))
continue;
const process = byProcess.get(proposal.source) ?? new Map();
const counts = process.get(week) ?? blank();
counts[outcome] += 1;
process.set(week, counts);
byProcess.set(proposal.source, process);
}
return [...byProcess]
.map(([source, perWeek]) => ({
source,
weeks: weeks.map((week) => ({ week, ...(perWeek.get(week) ?? blank()) })),
}))
.sort((a, b) => a.source.localeCompare(b.source));
}
/** Waiting for review at the end of each week: made by then and not yet decided by then. */
function reviewFlow(proposals, weeks) {
// One pass buckets each proposal's week once; "waiting" needs the end of each week, so it compares strings.
const created = new Map();
const decided = new Map();
for (const p of proposals) {
const madeIn = weekOf(p.createdAt);
created.set(madeIn, (created.get(madeIn) ?? 0) + 1);
if (p.status !== "pending") {
const decidedIn = weekOf(decidedAt(p));
decided.set(decidedIn, (decided.get(decidedIn) ?? 0) + 1);
}
}
return weeks.map((week) => {
const end = new Date(Date.parse(`${week}T00:00:00Z`) + 7 * DAY).toISOString();
const waiting = proposals.filter((p) => p.createdAt < end && (p.status === "pending" || decidedAt(p) >= end)).length;
return { week, created: created.get(week) ?? 0, decided: decided.get(week) ?? 0, waiting };
});
}
/** Usage rows grouped by asset ref, so a per-asset lookup does not rescan every row. */
function rowsByRef(rows) {
const byRef = new Map();
for (const row of rows) {
if (!row.ref)
continue;
const list = byRef.get(row.ref);
if (list)
list.push(row);
else
byRef.set(row.ref, [row]);
}
return byRef;
}
function harmLog(proposals, usage, reopened, sinceIso) {
const items = [];
for (const p of proposals) {
if (p.status === "reverted" && p.updatedAt >= sinceIso)
items.push({
kind: "reverted",
ref: p.ref,
at: p.updatedAt,
detail: `${p.source} change undone`,
proposalId: p.id,
});
if (p.status === "accepted" && isRetireProposal(p) && p.retirement?.continuityRisk && decidedAt(p) >= sinceIso)
items.push({
kind: "risky-retirement",
ref: p.retirement.retiredRef,
at: decidedAt(p),
detail: "retired with a continuity risk flagged",
proposalId: p.id,
});
}
for (const event of reopened) {
if (event.ts >= sinceIso && event.ref)
items.push({ kind: "reopened", ref: event.ref, at: event.ts, detail: "a rejection was reopened" });
}
// A flag after a change: negative feedback on an asset within two weeks after improve changed it.
const negative = rowsByRef(usage.filter((row) => row.eventType === "feedback" && row.signal === "negative"));
for (const p of proposals) {
if (p.status !== "accepted" && p.status !== "reverted")
continue;
const at = decidedAt(p);
if (at < sinceIso)
continue;
const end = new Date(Date.parse(at) + FLAG_DAYS * DAY).toISOString();
const flags = (negative.get(p.ref) ?? []).filter((row) => row.at > at && row.at <= end);
for (const flag of flags)
items.push({
kind: "flag-after-change",
ref: p.ref,
at: flag.at,
detail: flag.reason ? `negative feedback: ${flag.reason}` : "negative feedback after a change",
proposalId: p.id,
});
}
return items.sort((a, b) => b.at.localeCompare(a.at));
}
/** Before and after counts of how an asset was found and rated, around the day improve changed it. */
function changedAssets(proposals, usage, now, usageSince) {
const byRef = rowsByRef(usage);
return proposals
.filter((p) => (p.status === "accepted" || p.status === "reverted") && !isRetireProposal(p))
.sort((a, b) => decidedAt(b).localeCompare(decidedAt(a)))
.slice(0, 50)
.map((p) => {
const at = Date.parse(decidedAt(p));
const count = (from, to) => {
const fromIso = new Date(from).toISOString();
const toIso = new Date(to).toISOString();
const mine = (byRef.get(p.ref) ?? []).filter((row) => row.at >= fromIso && row.at < toIso);
return {
hits: mine.filter((row) => row.eventType === "search" || row.eventType === "show").length,
negative: mine.filter((row) => row.signal === "negative").length,
};
};
const afterDays = Math.min(COMPARE_DAYS, Math.floor((now - at) / DAY));
return {
ref: p.ref,
source: p.source,
outcome: classifyOutcome(p),
decidedAt: decidedAt(p),
before: count(at - COMPARE_DAYS * DAY, at),
after: count(at, at + COMPARE_DAYS * DAY),
afterDays,
// Fewer than four weeks since the change: the "after" side is still filling.
complete: afterDays >= COMPARE_DAYS,
// The "before" side starts earlier than the usage rows read (the window or the retention): it is not recorded.
beforeComplete: at - COMPARE_DAYS * DAY >= Date.parse(usageSince),
};
});
}
function judgeAndYou(proposals) {
const table = {};
for (const p of proposals) {
const outcome = classifyOutcome(p);
if (outcome === "pending")
continue;
const who = deciderOf(p);
const row = table[who] ?? { accepted: 0, rejected: 0, reverted: 0 };
table[who] = row;
if (outcome === "rejected")
row.rejected += 1;
else if (outcome === "reverted")
row.reverted += 1;
else
row.accepted += 1;
}
return table;
}
export function improveImpact(input = {}) {
const since = input.since === "365d" ? "365d" : "90d";
const now = Date.now();
const window = metricsWindow(since, now);
const errors = {};
// The store reads are what can fail (one malformed proposal row throws), so each degrades on its own; the
// derivations below are pure functions of what was read.
const state = withReadonlyStateDb((db) => ({
proposals: attempt(errors, "proposals", () => listStateProposals(db, { bundleId: stateBundleId(resolveStashDir()), withContent: false }), []),
reopened: attempt(errors, "reopened", () => readStateEvents(db, { type: "proposal_reopened", since: window.since }).events, []),
library: attempt(errors, "library", () => listIndexCompletedEvents(db, window.since, new Date(now + DAY).toISOString()), []),
usage: attempt(errors, "usage", () => readUsageRows(db, window), []),
llm: attempt(errors, "cost", () => readLlmRows(db, window), []),
}), null);
if (!state)
return { available: false, since, errors };
const { proposals, usage } = state;
// Usage rows older than their retention are purged on every index: the figures from them start no earlier.
const retainedFrom = new Date(now - USAGE_EVENT_RETENTION_DAYS * DAY).toISOString();
const usageSince = retainedFrom > window.since ? retainedFrom : window.since;
const weeks = weekRange(window.since.slice(0, 10), new Date(now).toISOString().slice(0, 10));
const lastPerWeek = new Map();
for (const event of state.library) {
try {
const total = JSON.parse(event.metadata_json).totalEntries;
if (typeof total === "number")
lastPerWeek.set(weekOf(event.ts), total);
}
catch {
// A row that is not JSON has no size to read.
}
}
const library = weeks.map((week) => ({ week, entries: lastPerWeek.get(week) ?? null }));
const costByWeek = new Map();
for (const row of state.llm) {
const week = weekOf(row.day);
const entry = costByWeek.get(week) ?? { calls: 0, tokens: 0, usageCalls: 0, byProcess: {} };
entry.calls += row.calls;
entry.tokens += row.totalTokens;
entry.usageCalls += row.usageCalls;
const process = row.process ?? "other";
entry.byProcess[process] = (entry.byProcess[process] ?? 0) + row.calls;
costByWeek.set(week, entry);
}
const cost = weeks.map((week) => ({
week,
...(costByWeek.get(week) ?? { calls: 0, tokens: 0, usageCalls: 0, byProcess: {} }),
}));
const harm = harmLog(proposals, usage, state.reopened, window.since);
const decided = proposals.filter((p) => p.status !== "pending" && decidedAt(p) >= window.since);
const calls = cost.reduce((sum, w) => sum + w.calls, 0);
const usageCalls = cost.reduce((sum, w) => sum + w.usageCalls, 0);
return {
available: true,
since,
/** Where the usage figures (flags, found and negative counts) start: the window, or later where retention cut them. */
usageSince,
usageComplete: retainedFrom <= window.since,
weeks,
summary: {
kept: decided.filter((p) => p.status === "accepted").length,
reverted: harm.filter((item) => item.kind === "reverted").length,
flags: harm.filter((item) => item.kind === "flag-after-change").length,
tokens: cost.reduce((sum, w) => sum + w.tokens, 0),
tokenCoverage: calls > 0 ? usageCalls / calls : null,
checked: decided.length,
},
outcomes: outcomesByProcess(proposals, weeks),
reviewFlow: reviewFlow(proposals, weeks),
library,
harm,
cost,
changedAssets: changedAssets(proposals, usage, now, usageSince),
judgeAndYou: judgeAndYou(proposals),
...(Object.keys(errors).length > 0 ? { errors } : {}),
};
}