repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/remember.ts

Raw
File outline
/**
 * Remember Extension
 *
 * Persistent, user-controlled memory for pi.
 * Stores facts in JSONL files, injects into system prompt via before_agent_start.
 *
 * ~/.pi/agent/remember.jsonl  - global facts (personal preferences)
 * <project>/.pi/remember.jsonl - project facts (shared with team)
 * <project>/.pi/remember.md   - rendered markdown (convenience, NOT loading mechanism)
 */

import fs from "node:fs";
import path from "node:path";
import type { ExtensionAPI, ExtensionCommandContext, Theme } from "@mariozechner/pi-coding-agent";
import { DynamicBorder, getMarkdownTheme, getAgentDir } from "@mariozechner/pi-coding-agent";
import { Container, Markdown, matchesKey, Text } from "@mariozechner/pi-tui";
import { Type } from "typebox";
import { complete } from "@mariozechner/pi-ai";
import { dbgScope } from "../lib/dbg.ts";
import { assert, assertEq, invariant, assertString, assertHasKeys } from "../lib/assert.ts";

const log = dbgScope("remember");

// ============================================================================
// Types
// ============================================================================

interface Fact {
	id: string;
	ts: string;
	tags: string[];
	fact: string;
	reason?: string;
	scope?: "global" | "project";
}

interface JsonlEntry {
	op: "add" | "delete";
	id: string;
	ts: string;
	tags?: string[];
	fact?: string;
	reason?: string;
}

// ============================================================================
// Tag Normalization
// ============================================================================

function normalizeTag(tag: string): string {
	return tag
		.toLowerCase()
		.replace(/[^a-z0-9]+/g, "-")
		.replace(/-+/g, "-")
		.replace(/^-|-$/g, "");
}

// ============================================================================
// Materialize Facts
// ============================================================================

function materializeFacts(filePath: string): Fact[] {
	if (!fs.existsSync(filePath)) {
		return [];
	}

	const content = fs.readFileSync(filePath, "utf-8");
	const lines = content.split("\n").filter((l) => l.trim());
	const facts = new Map<string, Fact>();

	for (const line of lines) {
		try {
			const raw = JSON.parse(line);
			assertHasKeys(raw, ["op", "id", "ts"], "malformed JSONL entry");

			const entry = raw as JsonlEntry;
			invariant(entry.op === "add" || entry.op === "delete", `unknown op: ${entry.op}`);

			if (entry.op === "add") {
				assertString(entry.id, "entry missing id");
				assertString(entry.ts, "entry missing ts");
				facts.set(entry.id, {
					id: entry.id,
					ts: entry.ts,
					tags: (entry.tags ?? []).map(normalizeTag),
					fact: entry.fact ?? "",
					reason: entry.reason,
				});
			} else if (entry.op === "delete") {
				facts.delete(entry.id);
			}
		} catch {
			log("materializeFacts: skipped malformed line", { line: line.slice(0, 100), filePath });
		}
	}

	return Array.from(facts.values()).sort((a, b) => a.id.localeCompare(b.id));
}

// ============================================================================
// ID Assignment & Write Queue
// ============================================================================

let nextId = 1;
let writeQueue: Promise<void> = Promise.resolve();

function initCounter(paths: string[]): void {
	let max = 0;
	for (const p of paths) {
		const facts = materializeFacts(p);
		for (const f of facts) {
			const n = parseInt(f.id.replace("RM", ""), 10);
			if (n > max) max = n;
		}
	}
	nextId = max + 1;
	log("initCounter", { nextId, files: paths.length });
}

function assignId(): string {
	return `RM${String(nextId++).padStart(3, "0")}`;
}

function queuedWrite(path: string, fn: () => void): Promise<void> {
	writeQueue = writeQueue.then(() => {
		log("queuedWrite: executing", { path });
		fn();
	}).catch(err => {
		log("queuedWrite: failed", { path, error: String(err) });
	});
	return writeQueue;
}

// ============================================================================
// Compact and Delete
// ============================================================================

async function compactAndDelete(filePath: string, id: string): Promise<Fact[]> {
	log("compactAndDelete: starting", { id, filePath });
	await queuedWrite(filePath, () => {
		const facts = materializeFacts(filePath);
		const remaining = facts.filter((f) => f.id !== id);

		if (remaining.length === facts.length) {
			log("compactAndDelete: id not found", { id, filePath });
			return;
		}

		log("compactAndDelete: rewriting", { id, before: facts.length, after: remaining.length });
		const lines = remaining.map((f) =>
			JSON.stringify({ op: "add", id: f.id, ts: f.ts, tags: f.tags, fact: f.fact, reason: f.reason })
		);
		const content = lines.join("\n") + (lines.length ? "\n" : "");
		fs.writeFileSync(filePath, content);
	});
	return materializeFacts(filePath);
}

// ============================================================================
// Render Functions
// ============================================================================

function renderSystemPromptSection(global: Fact[], project: Fact[]): string {
	if (global.length === 0 && project.length === 0) return "";
	log("renderSystemPromptSection", { global: global.length, project: project.length });
	let section = "\n\n## Remembered Facts\n";
	if (global.length > 0) {
		section += "\n### Personal Preferences (apply across projects)\n";
		section += global.map((f) => `- ${f.fact}`).join("\n");
	}
	if (project.length > 0) {
		section += "\n### Project Facts (this codebase)\n";
		section += project
			.map((f) => {
				const tagStr = f.tags.map((t) => "`" + t + "`").join(" ");
				let line = `- [${f.id}] ${tagStr} — ${f.fact}`;
				if (f.reason) line += `\n  Reason: ${f.reason}`;
				return line;
			})
			.join("\n");
	}
	section +=
		"\n\nThese are user-learned heuristics, NOT ground truth. If a source file contradicts a memory, trust the source file.";

	return section;
}

function renderMarkdownFile(facts: Fact[]): string {
	if (facts.length === 0) return "";

	const lines = [
		"# Project Facts",
		"",
		`${facts.length} remembered fact(s).`,
		"",
		"| ID | Tags | Fact | Reason |",
		"|-----|------|------|--------|",
		...facts.map(
			(f) =>
				`| ${f.id} | ${f.tags.join(", ") || "-"} | ${f.fact} | ${f.reason ?? "-"} |`
		),
	];

	return lines.join("\n");
}

function renderDashboardText(global: Fact[], project: Fact[]): string {
	const totalFacts = global.length + project.length;
	if (totalFacts === 0) {
		return "No facts remembered yet.\n\n/remember <text>       add a fact\n/remember --list       show all\n/remember --project    add project fact";
	}

	const tagCounts = new Map<string, number>();
	const globalTagCounts = new Map<string, number>();

	for (const f of global) {
		for (const t of f.tags) {
			globalTagCounts.set(t, (globalTagCounts.get(t) ?? 0) + 1);
		}
	}
	for (const f of project) {
		for (const t of f.tags) {
			tagCounts.set(t, (tagCounts.get(t) ?? 0) + 1);
		}
	}

	const allSorted = [...global, ...project].sort(
		(a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime()
	);
	const recent = allSorted.slice(0, 3);

	const staleThreshold = Date.now() - 30 * 24 * 60 * 60 * 1000;
	const stale = allSorted.filter((f) => new Date(f.ts).getTime() < staleThreshold);

	const lines: string[] = [
		`🧠 ${totalFacts} facts (${project.length} project, ${global.length} global)`,
		"",
		"Tags:",
	];

	const sortedTags = Array.from(tagCounts.entries())
		.sort((a, b) => b[1] - a[1])
		.slice(0, 5);
	for (const [tag, count] of sortedTags) {
		lines.push(`  ${tag}   ${count} facts`);
	}
	for (const [tag, count] of globalTagCounts) {
		lines.push(`  ${tag}   ${count} facts (global)`);
	}

	if (recent.length > 0) {
		lines.push("");
		lines.push("Recent:");
		for (const f of recent) {
			const date = new Date(f.ts).toISOString().slice(0, 10);
			lines.push(`  [${f.id}] ${date}  ${f.fact}`);
		}
	}

	if (stale.length > 0) {
		lines.push("");
		lines.push("Stale (>30 days):");
		for (const f of stale.slice(0, 3)) {
			const date = new Date(f.ts).toISOString().slice(0, 10);
			lines.push(`  [${f.id}] ${date}  ${f.fact}`);
		}
	}

	lines.push("");
	lines.push("/remember <text>       add a fact");
	lines.push("/remember --list       full list");
	lines.push("/remember --audit      check staleness");

	return lines.join("\n");
}

function estimateTokens(facts: Fact[]): number {
	return Math.ceil(renderSystemPromptSection(facts, []).length / 4);
}

// ============================================================================
// Path Helpers
// ============================================================================

const getGlobalJsonlPath = () => path.join(getAgentDir(), "remember.jsonl");
const getProjectJsonlPath = (cwd: string) => path.join(cwd, ".pi", "remember.jsonl");
const getProjectMdPath = (cwd: string) => path.join(cwd, ".pi", "remember.md");

// ============================================================================
// Cache Layer
// ============================================================================

let cachedGlobalFacts: Fact[] = [];
let cachedProjectFacts: Fact[] = [];

function refreshCache(cwd: string): void {
	cachedGlobalFacts = materializeFacts(getGlobalJsonlPath()).map((f) => ({ ...f, scope: "global" as const }));
	cachedProjectFacts = materializeFacts(getProjectJsonlPath(cwd)).map((f) => ({ ...f, scope: "project" as const }));
	log("refreshCache", { cwd, global: cachedGlobalFacts.length, project: cachedProjectFacts.length });
}

// ============================================================================
// Markdown Regeneration
// ============================================================================

function regenerateMarkdown(cwd: string): void {
	const mdPath = getProjectMdPath(cwd);
	const facts = materializeFacts(getProjectJsonlPath(cwd));

	if (facts.length === 0) {
		if (fs.existsSync(mdPath)) {
			fs.unlinkSync(mdPath);
			log("regenerateMarkdown: removed empty .md", { mdPath });
		}
		return;
	}

	fs.mkdirSync(path.dirname(mdPath), { recursive: true });
	fs.writeFileSync(mdPath, renderMarkdownFile(facts));
	log("regenerateMarkdown: wrote", { mdPath, facts: facts.length });
}

// ============================================================================
// Helper Functions
// ============================================================================

function parseId(args: string): string | null {
	const match = args.match(/RM(\d+)/i);
	return match ? `RM${match[1].padStart(3, "0")}` : null;
}

function appendToAgentsMd(cwd: string, fact: string): void {
	log("appendToAgentsMd", { cwd, fact: fact.slice(0, 80) });
	let agentsPath = path.join(cwd, "AGENTS.md");
	let searchDir = cwd;

	while (searchDir !== path.dirname(searchDir)) {
		const altPath = path.join(searchDir, "AGENTS.md");
		if (fs.existsSync(altPath)) {
			agentsPath = altPath;
			break;
		}
		const claudePath = path.join(searchDir, "CLAUDE.md");
		if (fs.existsSync(claudePath)) {
			agentsPath = claudePath;
			break;
		}
		searchDir = path.dirname(searchDir);
	}

	const bullet = `\n- ${fact}`;
	if (fs.existsSync(agentsPath)) {
		fs.appendFileSync(agentsPath, bullet);
	} else {
		fs.writeFileSync(agentsPath, `# Agent Instructions\n\n${bullet}\n`);
	}
}

// ============================================================================
// Module-scoped pi reference for handlers that need it
// ============================================================================
let _pi: ExtensionAPI | null = null;

// ============================================================================
// Command Handlers
// ============================================================================

async function handleHelp(ctx: ExtensionCommandContext) {
	const lines = [
		"🧠 /remember — persistent memory that survives restarts",
		"",
		"Saves facts. Surfaces them in future sessions via system prompt.",
		"JSONL-backed. No summarization. No hallucinations persist silently.",
		"(One-prompt delay before a saved fact enters the prompt — edit or delete before it bites you.)",
		"",
		"Usage:",
		"  /remember <text>                 save to global scope (personal)",
		"  /remember <text> --tags a,b       tag the fact",
		"  /remember <text> --reason why    add context",
		"",
		"  /remember --project <text>       save to project scope (shared)",
		"  /remember --project <text> --tags infra",
		"",
		"  /remember --list                 show all facts",
		"  /remember --list <tag>           filter by tag substring",
		"",
		"  /remember --delete <id>          remove a fact (compacts JSONL)",
		"  /remember --edit <id>            edit via JSON (interactive only)",
		"",
		"  /remember --promote <id>         move to AGENTS.md (interactive)",
		"  /remember --skill <tag>          bundle tagged facts into a skill",
		"  /remember --amend <text>         save + inject into current session",
		"  /remember --audit                LLM staleness check",
		"",
		"  /remember                        dashboard (TUI)",
		"  /remember --help                 this",
		"",
		"Storage:",
		"  ~/.pi/agent/remember.jsonl       global facts (you type them)",
		"  <project>/.pi/remember.jsonl    project facts (you + agent tool)",
		"",
		"Graduation: facts → AGENTS.md (--promote) or → skills (--skill). Never automatic.",
	].join("\n");
	ctx.ui.notify(lines, "info");
}

async function handleSave(args: string, ctx: ExtensionCommandContext, scope: "global" | "project") {
	log("handleSave", { scope, args: args.slice(0, 80) });
	let text = args;
	if (scope === "project" && text.startsWith("--project")) {
		text = text.slice("--project".length).trim();
	}

	let tags: string[] = [];
	let reason: string | undefined;

	const tagsMatch = text.match(/--tags\s+(\S+)/);
	if (tagsMatch) {
		tags = tagsMatch[1].split(",").map((t) => normalizeTag(t.trim())).filter(Boolean);
		text = text.replace(tagsMatch[0], "").trim();
	}

	const reasonMatch = text.match(/--reason\s+(.+)$/);
	if (reasonMatch) {
		reason = reasonMatch[1].trim();
		text = text.replace(reasonMatch[0], "").trim();
	}

	if (!text) {
		ctx.ui.notify("Usage: /remember <text> [--tags a,b] [--reason why]", "warning");
		return;
	}

	const id = assignId();
	const targetPath = scope === "global" ? getGlobalJsonlPath() : getProjectJsonlPath(ctx.cwd);

	await queuedWrite(targetPath, () => {
		fs.mkdirSync(path.dirname(targetPath), { recursive: true });
		fs.appendFileSync(
			targetPath,
			JSON.stringify({ op: "add", id, ts: new Date().toISOString(), tags, fact: text, reason }) + "\n"
		);
	});

	refreshCache(ctx.cwd);
	regenerateMarkdown(ctx.cwd);
	log("handleSave: done", { id, scope, path: targetPath });
	ctx.ui.notify(`✓ Saved as ${id} (${scope})`, "info");
}

async function handleDashboard(ctx: ExtensionCommandContext) {
	const text = renderDashboardText(cachedGlobalFacts, cachedProjectFacts);

	if (ctx.hasUI) {
		await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
			const container = new Container();
			const border = new DynamicBorder((s: string) => theme.fg("accent", s));
			const mdTheme = getMarkdownTheme();

			container.addChild(border);
			container.addChild(new Text(theme.fg("accent", theme.bold("🧠 Remembered Facts")), 1, 0));
			container.addChild(new Markdown(text, 1, 1, mdTheme));
			container.addChild(new Text(theme.fg("dim", "Press Enter or Esc to close"), 1, 0));
			container.addChild(border);

			return {
				render: (width: number) => container.render(width),
				invalidate: () => container.invalidate(),
				handleInput: (data: string) => {
					if (matchesKey(data, "enter") || matchesKey(data, "escape")) done(undefined);
				},
			};
		});
	} else {
		ctx.ui.notify(text, "info");
	}
}

async function handleList(args: string, ctx: ExtensionCommandContext) {
	const tag = args.startsWith("--list") ? args.slice(6).trim() : undefined;
	let facts = [...cachedGlobalFacts, ...cachedProjectFacts];

	if (tag) {
		const normalized = normalizeTag(tag);
		facts = facts.filter((f) => f.tags.some((t) => t.includes(normalized)));
	}

	if (facts.length === 0) {
		ctx.ui.notify(tag ? `No facts matching "${tag}"` : "No facts stored", "info");
		return;
	}

	const lines = facts.map((f) => {
		const tagStr = f.tags.length ? f.tags.map((t) => "#" + t).join(" ") + " " : "";
		const scopeStr = f.scope === "global" ? "(global) " : "";
		return `[${f.id}] ${tagStr}${scopeStr}${f.fact}`;
	});

	ctx.ui.notify(lines.join("\n"), "info");
}

async function handleDelete(args: string, ctx: ExtensionCommandContext) {
	log("handleDelete", { args: args.slice(0, 50) });
	const id = parseId(args);
	if (!id) {
		ctx.ui.notify("Usage: /remember --delete <id>\nRun /remember to see IDs.", "warning");
		return;
	}

	const allFacts = [...cachedGlobalFacts, ...cachedProjectFacts];
	const fact = allFacts.find((f) => f.id === id);
	invariant(fact, `fact ${id} should exist (already checked above)`);

	if (ctx.hasUI) {
		const ok = await ctx.ui.confirm(`Delete ${id}?`, fact.fact);
		if (!ok) return;
	}

	const targetPath = fact.scope === "global" ? getGlobalJsonlPath() : getProjectJsonlPath(ctx.cwd);
	const before = cachedGlobalFacts.length + cachedProjectFacts.length;
	await compactAndDelete(targetPath, id);
	refreshCache(ctx.cwd);
	regenerateMarkdown(ctx.cwd);

	// Verify deletion worked
	const after = cachedGlobalFacts.length + cachedProjectFacts.length;
	assertEq(after, before - 1, `delete should remove exactly 1 fact`);

	ctx.ui.notify(`✓ Deleted ${id}`, "info");
}

async function handleEdit(args: string, ctx: ExtensionCommandContext) {
	log("handleEdit", { args: args.slice(0, 50) });
	const id = parseId(args);
	if (!id) {
		ctx.ui.notify("Usage: /remember --edit <id>", "warning");
		return;
	}

	const allFacts = [...cachedGlobalFacts, ...cachedProjectFacts];
	const fact = allFacts.find((f) => f.id === id);
	if (!fact) {
		ctx.ui.notify(`${id} not found`, "warning");
		return;
	}

	if (!ctx.hasUI) {
		ctx.ui.notify("--edit requires interactive mode", "warning");
		return;
	}

	const edited = await ctx.ui.editor(
		`Edit ${id}:`,
		JSON.stringify({ fact: fact.fact, tags: fact.tags, reason: fact.reason }, null, 2)
	);

	let parsed: Partial<Fact>;
	try {
		parsed = JSON.parse(edited);
	} catch {
		ctx.ui.notify("Invalid JSON", "warning");
		return;
	}

	const targetPath = fact.scope === "global" ? getGlobalJsonlPath() : getProjectJsonlPath(ctx.cwd);
	await compactAndDelete(targetPath, id);
	await queuedWrite(targetPath, () => {
		fs.appendFileSync(
			targetPath,
			JSON.stringify({
				op: "add",
				id,
				ts: new Date().toISOString(),
				tags: (parsed.tags ?? fact.tags).map(normalizeTag),
				fact: parsed.fact ?? fact.fact,
				reason: parsed.reason ?? fact.reason,
			}) + "\n"
		);
	});

	refreshCache(ctx.cwd);
	regenerateMarkdown(ctx.cwd);
	ctx.ui.notify(`✓ Updated ${id}`, "info");
}

async function handlePromote(args: string, ctx: ExtensionCommandContext) {
	log("handlePromote", { args: args.slice(0, 50) });
	const id = parseId(args);
	if (!id) {
		ctx.ui.notify("Usage: /remember --promote <id>", "warning");
		return;
	}

	const allFacts = [...cachedGlobalFacts, ...cachedProjectFacts];
	const fact = allFacts.find((f) => f.id === id);
	if (!fact) {
		ctx.ui.notify(`${id} not found`, "warning");
		return;
	}

	let target = "AGENTS.md";
	if (ctx.hasUI) {
		const choice = await ctx.ui.select("Promote to:", ["AGENTS.md", "Cancel"]);
		if (choice === "Cancel" || !choice) return;
		target = choice;
	}

	appendToAgentsMd(ctx.cwd, fact.fact);

	const targetPath = fact.scope === "global" ? getGlobalJsonlPath() : getProjectJsonlPath(ctx.cwd);
	await compactAndDelete(targetPath, id);
	refreshCache(ctx.cwd);
	regenerateMarkdown(ctx.cwd);
	ctx.ui.notify(`✓ Promoted ${id} to ${target}`, "info");
}

async function handleSkill(args: string, ctx: ExtensionCommandContext) {
	log("handleSkill", { args: args.slice(0, 50) });
	const tagPart = args.startsWith("--skill") ? args.slice(7).trim() : "";
	if (!tagPart) {
		ctx.ui.notify("Usage: /remember --skill <tag>", "warning");
		return;
	}

	const normalized = normalizeTag(tagPart);
	const allFacts = [...cachedGlobalFacts, ...cachedProjectFacts];
	const matching = allFacts.filter((f) => f.tags.some((t) => t.includes(normalized)));

	if (matching.length === 0) {
		ctx.ui.notify(`No facts matching "${tagPart}"`, "warning");
		return;
	}

	const skillDir = path.join(ctx.cwd, ".pi", "skills", normalized);
	const content = [
		"---",
		`name: ${normalized}`,
		`description: Derived from ${matching.length} remembered facts.`,
		"---",
		"",
		`# ${normalized}`,
		"",
		"<!-- Edit this skill to turn raw facts into a reusable procedure. -->",
		"",
		...matching.map((f) => `- [${f.id}] ${f.fact}${f.reason ? ` (Reason: ${f.reason})` : ""}`),
		"",
	].join("\n");

	fs.mkdirSync(skillDir, { recursive: true });
	fs.writeFileSync(path.join(skillDir, "SKILL.md"), content);
	ctx.ui.notify(`✓ Created .pi/skills/${normalized}/SKILL.md with ${matching.length} facts`, "info");
}

async function handleAmend(args: string, ctx: ExtensionCommandContext) {
	log("handleAmend", { args: args.slice(0, 80) });
	const text = args.startsWith("--amend") ? args.slice(7).trim() : "";
	if (!text) {
		ctx.ui.notify("Usage: /remember --amend <text>", "warning");
		return;
	}

	const id = assignId();
	const targetPath = getGlobalJsonlPath();

	await queuedWrite(targetPath, () => {
		fs.mkdirSync(path.dirname(targetPath), { recursive: true });
		fs.appendFileSync(
			targetPath,
			JSON.stringify({ op: "add", id, ts: new Date().toISOString(), tags: [], fact: text }) + "\n"
		);
	});

	refreshCache(ctx.cwd);
	regenerateMarkdown(ctx.cwd);
	ctx.ui.notify(`✓ Saved as ${id} (will be injected in next turn)`, "info");

	// Inject into current session via sendUserMessage
	// This makes it appear as a user message, triggering a new agent turn
	if (_pi && ctx.isIdle()) {
		_pi.sendUserMessage(`[Remembered] ${text}`);
	} else if (_pi) {
		// Agent is streaming - steer to inject
		_pi.sendUserMessage(`[Remembered] ${text}`, { deliverAs: "steer" });
	}
}

async function handleAudit(ctx: ExtensionCommandContext) {
	log("handleAudit: starting");
	if (!ctx.model) {
		ctx.ui.notify("No model available for audit", "warning");
		return;
	}

	const auth = await ctx.modelRegistry.getApiKeyAndHeaders(ctx.model);
	if (!auth?.ok || !auth.apiKey) {
		ctx.ui.notify("No API key available", "warning");
		return;
	}

	const allFacts = [...cachedGlobalFacts, ...cachedProjectFacts];
	if (allFacts.length === 0) {
		ctx.ui.notify("No facts to audit", "info");
		return;
	}

	ctx.ui.notify("Running LLM audit...", "info");

	const factsText = allFacts
		.map((f) => {
			const savedDate = new Date(f.ts).toISOString().slice(0, 10);
			return `[${f.id}] [${f.scope ?? "unknown"}] [${f.tags.join(", ")}] ${f.fact} (saved ${savedDate})${f.reason ? ` — ${f.reason}` : ""}`;
		})
		.join("\n");

	const auditPrompt = `Review these remembered facts for staleness and accuracy.

For each fact, classify as:
- VALID: Still accurate and useful
- STALE: Outdated or no longer relevant
- PROMOTE: Looks like a standing rule that should be in AGENTS.md
- CLUSTER: Part of a pattern that suggests a skill

Facts to review:
${factsText}

Respond with a structured report:
### VALID
(list IDs)

### STALE  
(list IDs with brief reason)

### PROMOTE
(list IDs with suggested AGENTS.md wording)

### CLUSTER
(list tag clusters with suggested skill names)`;

	try {
		const response = await complete(
			ctx.model,
			{
				messages: [
					{
						role: "user" as const,
						content: [{ type: "text" as const, text: auditPrompt }],
						timestamp: Date.now(),
					},
				],
			},
			{ apiKey: auth.apiKey, headers: auth.headers }
		);

		const auditText = response.content
			.filter((c): c is { type: "text"; text: string } => c.type === "text")
			.map((c) => c.text)
			.join("\n");

		if (ctx.hasUI) {
			await ctx.ui.custom<void>((_tui, theme, _kb, done) => {
				const container = new Container();
				const border = new DynamicBorder((s: string) => theme.fg("accent", s));
				const mdTheme = getMarkdownTheme();

				container.addChild(border);
				container.addChild(new Text(theme.fg("accent", theme.bold("🧠 Audit Results")), 1, 0));
				container.addChild(new Markdown(auditText, 1, 1, mdTheme));
				container.addChild(new Text(theme.fg("dim", "Press Enter or Esc to close"), 1, 0));
				container.addChild(border);

				return {
					render: (width: number) => container.render(width),
					invalidate: () => container.invalidate(),
					handleInput: (data: string) => {
						if (matchesKey(data, "enter") || matchesKey(data, "escape")) done(undefined);
					},
				};
			});
		} else {
			ctx.ui.notify(auditText, "info");
		}
	} catch (err) {
		ctx.ui.notify(`Audit failed: ${err}`, "error");
	}
}

// ============================================================================
// Extension Entry Point
// ============================================================================

export default function (pi: ExtensionAPI) {
	log("remember: extension factory called");
	_pi = pi;

	// -------------------------------------------------------------------------
	// session_start: initialize cache and show nudges
	// -------------------------------------------------------------------------
	pi.on("session_start", async (_event, ctx) => {
		log("session_start", { cwd: ctx.cwd, hasUI: ctx.hasUI });
		try {
			initCounter([getGlobalJsonlPath(), getProjectJsonlPath(ctx.cwd)]);
			refreshCache(ctx.cwd);
			regenerateMarkdown(ctx.cwd);
		} catch(e) {
			log("session_start: init failed", { error: String(e) });
		}

		// Token warning
		const tokens = estimateTokens([...cachedGlobalFacts, ...cachedProjectFacts]);
		if (tokens > 2000 && ctx.hasUI) {
			ctx.ui.notify(`🧠 Remembered facts use ~${tokens} tokens. Consider /remember --audit.`, "info");
		}

		// Tag cluster nudge
		const tagCounts = new Map<string, number>();
		for (const f of [...cachedGlobalFacts, ...cachedProjectFacts]) {
			for (const t of f.tags) {
				tagCounts.set(t, (tagCounts.get(t) ?? 0) + 1);
			}
		}
		for (const [tag, count] of tagCounts) {
			if (count >= 4 && ctx.hasUI) {
				ctx.ui.notify(`Tag "${tag}" has ${count} facts. Consider /remember --skill ${tag}`, "info");
			}
		}
	});

	// -------------------------------------------------------------------------
	// before_agent_start: inject facts into system prompt
	// -------------------------------------------------------------------------
	pi.on("before_agent_start", async (event) => {
		const section = renderSystemPromptSection(cachedGlobalFacts, cachedProjectFacts);
		if (!section) {
			log("before_agent_start: no facts to inject");
			return;
		}
		log("before_agent_start: injecting", { chars: section.length });
		return { systemPrompt: event.systemPrompt + section };
	});

	// -------------------------------------------------------------------------
	// remember tool (LLM)
	// -------------------------------------------------------------------------
	pi.registerTool({
		name: "remember",
		label: "Remember",
		description:
			"Save a fact to persistent project memory for future sessions. " +
			"Use when you discover non-obvious knowledge: hidden dependencies, " +
			"dead ends you ruled out, non-obvious requirements. " +
			"Do NOT use for instructions (those belong in AGENTS.md) or " +
			"procedures (those belong in skills). " +
			"Always include a reason. Prefer specific, atomic facts.",
		promptSnippet: "Save a discovered fact to project memory",
		promptGuidelines: [
			"Use remember when you discover non-obvious project knowledge during work.",
			"Do not remember instructions, preferences, or procedures — only discovered facts.",
			"Always include a reason explaining why this fact matters.",
			"Prefer specific, atomic facts over vague statements.",
		],
		parameters: Type.Object({
			fact: Type.String({ description: "The fact to remember" }),
			reason: Type.String({ description: "Why this exists (context, what happened)" }),
			tags: Type.Optional(Type.Array(Type.String({ description: "Tags for categorization" }))),
		}),
		async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
			log("tool:remember", { fact: params.fact.slice(0, 80), tags: params.tags, cwd: ctx.cwd });
			const id = assignId();
			const entry = {
				op: "add" as const,
				id,
				ts: new Date().toISOString(),
				tags: (params.tags ?? []).map(normalizeTag),
				fact: params.fact,
				reason: params.reason,
			};
			const p = getProjectJsonlPath(ctx.cwd);
			await queuedWrite(p, () => {
				fs.mkdirSync(path.dirname(p), { recursive: true });
				fs.appendFileSync(p, JSON.stringify(entry) + "\n");
			});
			refreshCache(ctx.cwd);
			regenerateMarkdown(ctx.cwd);
			log("tool:remember: saved", { id, path: p });
			return {
				content: [{ type: "text", text: `✓ Remembered as ${id}: ${params.fact}` }],
				details: { id, fact: params.fact },
			};
		},
	});

	// -------------------------------------------------------------------------
	// /remember command
	// -------------------------------------------------------------------------
	pi.registerCommand("remember", {
		description: "Persistent memory: /remember <text> | --list | --delete <id> | --edit <id> | --audit",
		handler: async (args, ctx) => {
			const trimmed = args.trim();
			log("/remember", { args: trimmed.slice(0, 100) });

			if (trimmed === "--help") return handleHelp(ctx);
		if (!trimmed) return handleDashboard(ctx);
			if (trimmed.startsWith("--list"))     return handleList(trimmed, ctx);
			if (trimmed.startsWith("--delete"))   return handleDelete(trimmed, ctx);
			if (trimmed.startsWith("--project"))  return handleSave(trimmed, ctx, "project");
			if (trimmed.startsWith("--edit"))     return handleEdit(trimmed, ctx);
			if (trimmed.startsWith("--promote"))  return handlePromote(trimmed, ctx);
			if (trimmed.startsWith("--skill"))    return handleSkill(trimmed, ctx);
			if (trimmed.startsWith("--amend"))    return handleAmend(trimmed, ctx);
			if (trimmed.startsWith("--audit"))    return handleAudit(ctx);

			// Default: save to global
			return handleSave(trimmed, ctx, "global");
		},
	});
}