// NOTE: no import from "@opencode/plugin". A local plugin loaded by path cannot // resolve that bare specifier — identical code without the import loads, with // it the plugin fails with "Plugin failed to load" (see knox.claims). import { execFile } from "node:child_process" import { existsSync } from "node:fs" /** * knox.maintenance — rolling housekeeping for the knowledge index. * * Curation has to happen on a schedule, but knox is not a daemon for it: the * watcher owns ingestion, not retention. Rather than a systemd timer, this * rides the same `prompt` hook knox.claims uses, so the sweep happens while the * machine is actually in use and nothing has to be installed alongside it. * * The schedule itself lives in the index (`settings['snippets_expire_last_run']`, * enforced by `knox snippets expire --every`). That matters: this plugin is one * caller among several — a cron job or a human running the same command shares * one clock, and restarting OpenCode (which reloads this module) cannot cause a * burst of sweeps. The in-process guard below only avoids spawning a CLI that * would immediately decide it is not due. */ // The OpenCode server does not inherit the service's PATH, so prefer the // checkout binary when it exists and fall back to PATH lookup. const DEFAULT_BIN = `${process.env.HOME ?? ""}/assistant/knox/knox` const BIN = process.env.KNOX_BIN ?? (existsSync(DEFAULT_BIN) ? DEFAULT_BIN : "knox") /** How long an uncurated snippet candidate stays reviewable. */ const RETENTION_DAYS = process.env.KNOX_SNIPPET_RETENTION_DAYS ?? "7" /** Minimum gap between sweeps; knox enforces the same value authoritatively. */ const EVERY = "24h" const EVERY_MS = 24 * 60 * 60 * 1000 const EXPIRE_TIMEOUT_MS = 120_000 let lastAttempt = 0 /** * Expire candidates that fell out of the review window, and quiet the log while * doing it: this runs in the background of a user prompt, not as a report. */ function maintain(): void { const now = Date.now() if (now - lastAttempt < EVERY_MS) return lastAttempt = now execFile( BIN, ["snippets", "expire", "--days", RETENTION_DAYS, "--every", EVERY], { timeout: EXPIRE_TIMEOUT_MS }, () => {}, ) } export default { id: "knox.maintenance", async setup(ctx: any) { // Prompt admission is the natural place: the index is already being // refreshed here by knox.claims, and the sweep is fire-and-forget. await ctx.session.hook("prompt", () => { maintain() }) }, }