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

203 lines (202 loc) • 9.75 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/. /** * Window handling for `akm health`: `--window-compare` / `--windows` parsing, * per-window metric assembly, and delta computation between two windows. */ import { UsageError } from "../../core/errors.js"; import { readEvents } from "../../core/events.js"; import { DURATION_UNITS, parseDuration } from "../../core/time.js"; import { queryTaskHistory } from "../../storage/repositories/task-history-repository.js"; import { classifyAttempt, hereNow } from "../../tasks/run/attempt-liveness.js"; import { agentDispatches, buildImproveSkipSummary, computeWallTimeStats, computeWindowProposalCoverage, countAgentFailureReasons, countTaskRuns, decodeTaskRows, readImproveRows, roundOrNull, summarizeImproveRuns, } from "./improve-metrics.js"; import { readLlmUsageAggregate } from "./llm-usage.js"; import { buildPerRunSummaries } from "./task-runs.js"; import { IMPROVE_COMPLETED_EVENT, } from "./types.js"; /** * Parse a `--window-compare <duration>` shorthand into two adjacent windows * (current, prior). Duration syntax matches {@link parseHealthSince}. */ export function resolveWindowCompare(duration, now = () => Date.now()) { const trimmed = duration.trim(); // Canonical CLI unit grammar: `m` = minutes, `M` = months. Not lower-cased, // so case distinguishes the two. See core/time.ts DURATION_UNITS. const ms = parseDuration(trimmed, DURATION_UNITS); if (ms === null) { throw new UsageError("--window-compare must be a duration like '24h', '7d', or '30m'.", "INVALID_FLAG_VALUE"); } if (ms <= 0) { throw new UsageError("--window-compare must be a positive duration.", "INVALID_FLAG_VALUE"); } const nowMs = now(); const currentSince = new Date(nowMs - ms).toISOString(); const currentUntil = new Date(nowMs).toISOString(); const priorSince = new Date(nowMs - 2 * ms).toISOString(); const priorUntil = currentSince; return [ { name: "current", since: currentSince, until: currentUntil }, { name: "prior", since: priorSince, until: priorUntil }, ]; } /** * Parse a single repeatable `--windows` value of the form * `name=...,since=...,until=...`. All keys are optional EXCEPT name and since. */ export function parseWindowSpec(raw) { const fields = {}; for (const part of raw.split(",")) { const trimmed = part.trim(); if (!trimmed) continue; const eq = trimmed.indexOf("="); if (eq < 0) { throw new UsageError(`--windows entry must be a comma-separated list of key=value pairs: ${raw}`, "INVALID_FLAG_VALUE"); } const key = trimmed.slice(0, eq).trim(); const value = trimmed.slice(eq + 1).trim(); fields[key] = value; } if (!fields.name) { throw new UsageError(`--windows entry is missing required 'name': ${raw}`, "INVALID_FLAG_VALUE"); } if (!fields.since) { throw new UsageError(`--windows entry is missing required 'since': ${raw}`, "INVALID_FLAG_VALUE"); } return { name: fields.name, since: fields.since, ...(fields.until ? { until: fields.until } : {}), }; } /** * Metric paths diffed between the earliest and latest window (`deltas` in the * JSON result; the delta column of `--format md`). Paths are relative to a * {@link WindowResult}. */ export const INTERESTING_DELTA_PATHS = [ "improve.actions.reflect.failed", "improve.actions.distill.queued", "improve.actions.distill.llmFailed", "improve.consolidation.promoted", "improve.memoryInference.written", "improve.memoryInference.yieldRate", "improve.memoryInference.skippedNoFacts", "improve.autoAccept.promoted", "improve.autoAccept.validationFailed", "improve.coverage.acceptedProposals", "improve.coverage.distinctRefs", "improve.wallTime.medianMs", "improve.wallTime.p95Ms", "metrics.llmUsage.calls", "metrics.llmUsage.totalTokens", "metrics.llmUsage.totalDurationMs", "metrics.llmUsage.failures", ]; /** The number at `path`; `null` when the value, or a parent on the way to it, is unknown (null). A missing key is 0. */ export function readNumericPath(obj, path) { let cursor = obj; for (const part of path.split(".")) { if (cursor === null) return null; if (typeof cursor !== "object") return 0; cursor = cursor[part]; } if (cursor === null) return null; return typeof cursor === "number" && Number.isFinite(cursor) ? cursor : 0; } /** The change of each listed metric between two windows; a metric unknown in either window has an `unknown` change. */ export function computeDeltas(first, last) { const out = {}; for (const path of INTERESTING_DELTA_PATHS) { const from = readNumericPath(first, path); const to = readNumericPath(last, path); if (from === null || to === null) { out[path] = { from, to, pctChange: "unknown" }; continue; } if (from === 0 && to === 0) continue; let pctChange; if (from === 0) { pctChange = to === 0 ? 0 : "+inf"; } else { pctChange = Number((((to - from) / from) * 100).toFixed(2)); } out[path] = { from, to, pctChange }; } return out; } /** * Task-history-derived rates, shared by the main health path * (`health.ts`'s `gatherTaskHistoryPhase`) and {@link buildWindowMetrics} * below — the only difference is whether the caller has already bounded * `taskRows` by an `until`. Pure projection of * already-queried rows; callers own the `since`/`until` query. The main health * check supplies all still-active rows independently of its history window. Whether an active row's run is still * there is `classifyAttempt`'s answer, never its age. */ export function computeTaskWindowRates(taskRows, activeTaskRows = taskRows) { const failedTaskRows = taskRows.filter((row) => row.status === "failed"); const activeRows = activeTaskRows.filter((row) => row.status === "active" && row.completed_at === null); const here = hereNow(); const liveness = activeRows.map((row) => ({ row, state: classifyAttempt(row, here) })); const stuckActiveRows = liveness.filter(({ state }) => state === "interrupted").map(({ row }) => row); const unverifiedActiveRows = liveness.filter(({ state }) => state === "indeterminate").map(({ row }) => row); const decoded = decodeTaskRows(taskRows); const dispatches = agentDispatches(decoded); const failedDispatches = dispatches.filter((reason) => reason !== undefined); return { taskRuns: countTaskRuns(decoded), taskFailRate: taskRows.length === 0 ? null : failedTaskRows.length / taskRows.length, agentFailureRate: dispatches.length === 0 ? null : failedDispatches.length / dispatches.length, agentFailureReasonCounts: countAgentFailureReasons(dispatches), stuckActiveRuns: stuckActiveRows.length, stuckActiveRows, unverifiedActiveRows, }; } /** * Improve-pipeline window summary, shared by the main health path * (`health.ts`) and {@link buildWindowMetrics} below: events-derived * invoked/completed/skipped counts, the `result_json` aggregate, wall-time * stats from the same per-run rows, and accepted-proposal coverage, all over * one `[since, until)`. */ export function buildImproveWindowSummary(db, stateDbPath, since, until, readOnly = false) { const untilMs = new Date(until).getTime(); const eventsBeforeUntil = (type) => readEvents({ since, type }, { dbPath: stateDbPath, readOnly }).events.filter((event) => new Date(event.ts ?? since).getTime() < untilMs); const improveRows = readImproveRows(db, since, until); const { metrics: improve, runCount, outcomes } = summarizeImproveRuns(improveRows); improve.invoked = eventsBeforeUntil("improve_invoked").length; improve.completed = eventsBeforeUntil(IMPROVE_COMPLETED_EVENT).length; const skipSummary = buildImproveSkipSummary(eventsBeforeUntil("improve_skipped")); improve.skipped = skipSummary.skipped; improve.skipReasons = skipSummary.skipReasons; // Wall times come from the same improve-runs window as the per-run // reporting so counts and percentiles stay aligned with it. const perRunSummaries = buildPerRunSummaries(db, improveRows, since, until); improve.wallTime = computeWallTimeStats(perRunSummaries.map((run) => run.wallTimeMs).filter((ms) => Number.isFinite(ms) && ms > 0)); improve.coverage = computeWindowProposalCoverage(db, since, until); return { improve, runCount, perRunSummaries, outcomes }; } export function buildWindowMetrics(db, stateDbPath, since, until, readOnly = false) { const untilMs = new Date(until).getTime(); const taskRows = queryTaskHistory(db, { since }).filter((row) => { const startMs = new Date(row.started_at).getTime(); return !Number.isFinite(untilMs) || startMs < untilMs; }); const rates = computeTaskWindowRates(taskRows); const { improve, runCount } = buildImproveWindowSummary(db, stateDbPath, since, until, readOnly); const metrics = { taskFailRate: roundOrNull(rates.taskFailRate), agentFailureRate: roundOrNull(rates.agentFailureRate), agentFailureReasonCounts: rates.agentFailureReasonCounts, stuckActiveRuns: rates.stuckActiveRuns, llmUsage: readLlmUsageAggregate(stateDbPath, since, until, readOnly), }; return { improve, metrics, runs: runCount }; }