repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/pulse.ts

Raw
File outline
/**
 * Pulse - Living documentation sync
 *
 * Run /pulse help for usage.
 */

import type { ExtensionAPI, AutocompleteItem } from "@mariozechner/pi-coding-agent";
import type { ExtensionCommandContext } from "@mariozechner/pi-coding-agent";
import { convertToLlm, serializeConversation } from "@mariozechner/pi-coding-agent";
import { complete, getModel } from "@mariozechner/pi-ai";
import * as fs from "node:fs";
import * as path from "node:path";
import { assertArray, assert, invariant } from "../lib/assert.ts";

const PULSE_CONFIG = ".pulse.json";
const DEFAULT_INTERVAL_MIN = 30;
const IDLE_RUN_THRESHOLD = 2;
const COOLDOWN_MS = 5 * 60 * 1000;

interface PulseDoc {
    path: string;
    instruction?: string;
    model?: string;
}

interface PulseConfig {
    documents: PulseDoc[];
    model?: string;
    interval?: number; // minutes between timer checks, 0 = disabled
}

const SUBCOMMANDS = [
    "help",
    "init",
    "add",
    "remove",
    "list",
    "status",
    "force",
    "pause",
    "resume",
    "config",
] as const;

type Subcommand = (typeof SUBCOMMANDS)[number];

// ============================================================================
// CONFIG FILE OPERATIONS
// ============================================================================

function loadConfig(cwd: string): PulseConfig | null {
    const configPath = path.join(cwd, PULSE_CONFIG);
    try {
        const content = fs.readFileSync(configPath, "utf-8");
        const raw = JSON.parse(content);
        assert(typeof raw === "object" && raw !== null, "pulse config should be object");
        const parsed = raw as PulseConfig;
        if (!parsed.documents || !Array.isArray(parsed.documents)) return null;
        assertArray(parsed.documents, "pulse documents should be array");
        if (parsed.interval !== undefined && parsed.interval < 0) return null;
        parsed.documents = parsed.documents.filter((d) => d.path);
        return parsed;
    } catch {
        return null;
    }
}

function saveConfig(cwd: string, config: PulseConfig): void {
    fs.writeFileSync(path.join(cwd, PULSE_CONFIG), JSON.stringify(config, null, 2), "utf-8");
}

function configExists(cwd: string): boolean {
    return fs.existsSync(path.join(cwd, PULSE_CONFIG));
}

function getCwd(pi: ExtensionAPI, ctx?: ExtensionCommandContext): string {
    return (pi as Record<string, unknown>)["_cwd"] as string || ctx?.cwd || process.cwd();
}

function normalizePath(cwd: string, docPath: string): string {
    const resolved = path.resolve(cwd, docPath);
    return path.relative(cwd, resolved);
}

// ============================================================================
// MODEL CHECK
// ============================================================================

async function shouldUpdateDocs(
    docs: PulseDoc[],
    recentMessages: unknown[],
    model: { provider: string; id: string },
    apiKey: string,
    cwd: string,
): Promise<{ update: boolean; reason: string }> {
    try {
        const docSections = docs.map((d) => {
            const filePath = path.resolve(cwd, d.path);
            let content = "(file not found)";
            try {
                content = fs.readFileSync(filePath, "utf-8");
            } catch {}
            return `--- ${d.path} ---\n${content}`;
        }).join("\n\n");

        const conversation = serializeConversation(convertToLlm(recentMessages));

        const response = await complete(
            getModel(model.provider, model.id)!,
            {
                systemPrompt:
                    "You determine whether documents need updating. " +
                    "Reply ONLY with JSON: {\"update\": true/false, \"reason\": \"brief explanation\"}",
                messages: [
                    {
                        role: "user" as const,
                        content: [
                            {
                                type: "text" as const,
                                text:
                                    `Compare the conversation against the current document contents.\n` +
                                    `Update=true only if the conversation contains new decisions, changes, or corrections\n` +
                                    `that are NOT yet reflected in the document. Skip for unrelated topics.\n\n` +
                                    `Documents:\n${docSections}\n\n` +
                                    `Conversation:\n${conversation}`,
                            },
                        ],
                        timestamp: Date.now(),
                    },
                ],
            },
            { apiKey },
        );

        const text = response.content.find(
            (c: unknown): c is { type: "text"; text: string } =>
                typeof c === "object" && c !== null && (c as { type?: string }).type === "text",
        );

        if (!text) return { update: true, reason: "no text response" };

        const cleaned = text.text.replace(/```json\n?|```\n?/g, "").trim();
        const parsed = JSON.parse(cleaned);
        return {
            update: parsed.update === true,
            reason: parsed.reason || "parsed from response",
        };
    } catch (e) {
        return { update: true, reason: `check failed: ${e}` };
    }
}

// ============================================================================
// UTILITIES
// ============================================================================

function parseModel(modelStr: string): { provider: string; id: string } | null {
    const parts = modelStr.split("/");
    if (parts.length !== 2) return null;
    return { provider: parts[0], id: parts[1] };
}

function formatTimeRemaining(ms: number): string {
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
    return `${seconds}s`;
}

function getFileCompletions(cwd: string, prefix: string): AutocompleteItem[] {
    const items: AutocompleteItem[] = [];
    try {
        for (const entry of fs.readdirSync(cwd)) {
            if (entry.startsWith(".")) continue;
            const fullPath = path.join(cwd, entry);
            try {
                if (fs.statSync(fullPath).isFile() && entry.startsWith(prefix)) {
                    items.push({ value: entry, label: entry });
                }
            } catch {}
        }
    } catch {}
    return items;
}

function getDocCompletions(cwd: string, prefix: string): AutocompleteItem[] | null {
    const config = loadConfig(cwd);
    if (!config || config.documents.length === 0) return null;
    const p = prefix.toLowerCase();
    const results = config.documents
        .filter((d) => d.path.toLowerCase().includes(p))
        .map((d) => ({ value: d.path, label: d.path }));
    return results.length > 0 ? results : null;
}

// ============================================================================
// EXTENSION STATE
// ============================================================================

interface PulseState {
    config: PulseConfig;
    cwd: string;
    agentRunHadToolCalls: boolean;
    consecutiveIdleRuns: number;
    lastUpdateTime: number;
    lastTimerCheck: number;
    isTracking: boolean;
    isPaused: boolean;
    timerHandle: ReturnType<typeof setInterval> | null;
    timerFired: boolean;
    pendingUpdateDocs: PulseDoc[];
    configWatcher: ReturnType<typeof fs.watch> | null;
    configWatcherCwd: string;
}

// ============================================================================
// EXTENSION
// ============================================================================

export default function (pi: ExtensionAPI) {
    const state: PulseState = {
        config: { documents: [] },
        cwd: "",
        agentRunHadToolCalls: false,
        consecutiveIdleRuns: 0,
        lastUpdateTime: 0,
        lastTimerCheck: Date.now(),
        isTracking: false,
        isPaused: false,
        timerHandle: null,
        timerFired: false,
        pendingUpdateDocs: [],
        configWatcher: null,
        configWatcherCwd: "",
    };

    // ------------------------------------------------------------------------
    // Timer
    // ------------------------------------------------------------------------

    function getIntervalMs(): number {
        return (state.config.interval ?? DEFAULT_INTERVAL_MIN) * 60 * 1000;
    }

    function isTimerEnabled(): boolean {
        return (state.config.interval ?? DEFAULT_INTERVAL_MIN) > 0;
    }

    function startTimer(ctx: ExtensionCommandContext): void {
        stopTimer();
        if (!isTimerEnabled()) return;
        state.lastTimerCheck = Date.now();
        state.timerFired = false;
        state.timerHandle = setInterval(() => {
            if (state.isPaused || !state.isTracking || state.config.documents.length === 0) return;
            if (Date.now() - state.lastTimerCheck >= getIntervalMs()) {
                state.lastTimerCheck = Date.now();
                state.timerFired = true;
            }
            setStatus(ctx);
        }, 30_000);
    }

    function ensureTimer(ctx: ExtensionCommandContext): void {
        if (state.timerHandle || !isTimerEnabled()) return;
        startTimer(ctx);
    }

    function stopTimer(): void {
        if (state.timerHandle) {
            clearInterval(state.timerHandle);
            state.timerHandle = null;
        }
    }

    // ------------------------------------------------------------------------
    // Config watcher
    // ------------------------------------------------------------------------

    let watcherDebounce: ReturnType<typeof setTimeout> | null = null;

    function startConfigWatcher(ctx: ExtensionCommandContext): void {
        stopConfigWatcher();
        const configPath = path.join(state.cwd, PULSE_CONFIG);
        if (!fs.existsSync(configPath)) return;
        state.configWatcherCwd = state.cwd;
        try {
            state.configWatcher = fs.watch(configPath, (eventType) => {
                if (eventType !== "change") return;
                if (watcherDebounce) clearTimeout(watcherDebounce);
                watcherDebounce = setTimeout(() => {
                    watcherDebounce = null;
                    if (state.cwd !== state.configWatcherCwd) return;
                    const reloaded = loadConfig(state.cwd);
                    if (!reloaded) return;
                    state.config = reloaded;
                    state.isTracking = state.config.documents.length > 0;
                    setStatus(ctx);
                }, 200);
            });
        } catch {}
    }

    function stopConfigWatcher(): void {
        if (watcherDebounce) {
            clearTimeout(watcherDebounce);
            watcherDebounce = null;
        }
        if (state.configWatcher) {
            state.configWatcher.close();
            state.configWatcher = null;
        }
        state.configWatcherCwd = "";
    }

    // ------------------------------------------------------------------------
    // Status
    // ------------------------------------------------------------------------

    function setStatus(ctx: ExtensionCommandContext): void {
        if (!state.isTracking || state.config.documents.length === 0) {
            ctx.ui.setStatus("pulse", undefined);
            return;
        }
        if (state.isPaused) {
            ctx.ui.setStatus("pulse", `󰐰 ${state.config.documents.length} doc(s) paused`);
            return;
        }
        const intervalMin = state.config.interval ?? DEFAULT_INTERVAL_MIN;
        const timerRemaining = Math.max(0, getIntervalMs() - (Date.now() - state.lastTimerCheck));
        const timerMins = Math.ceil(timerRemaining / 60000);
        const parts: string[] = [];
        parts.push(`${state.consecutiveIdleRuns}/${IDLE_RUN_THRESHOLD} turns`);
        if (isTimerEnabled()) parts.push(`${timerMins}m/${intervalMin}m`);
        if (state.pendingUpdateDocs.length > 0) parts.push(`${state.pendingUpdateDocs.length} pending`);
        ctx.ui.setStatus("pulse", `󰐰 ${state.config.documents.length} doc(s) [${parts.join(", ")}]`);
    }

    // ------------------------------------------------------------------------
    // Helpers
    // ------------------------------------------------------------------------

    function getTrackedDocs(): PulseDoc[] {
        if (!state.isTracking) return [];
        return state.config.documents;
    }

    function groupDocsByModel(
        docs: PulseDoc[],
        defaultModel: { provider: string; id: string } | undefined,
    ): Array<{ model: { provider: string; id: string }; docs: PulseDoc[] }> {
        const groups = new Map<string, PulseDoc[]>();
        const defaultKey = defaultModel ? `${defaultModel.provider}/${defaultModel.id}` : "default";

        for (const doc of docs) {
            const modelKey = doc.model || defaultKey;
            if (!groups.has(modelKey)) groups.set(modelKey, []);
            groups.get(modelKey)!.push(doc);
        }

        return Array.from(groups.entries()).map(([key, docList]) => ({
            model: parseModel(key) || defaultModel!,
            docs: docList,
        }));
    }

    async function runPulseCheck(ctx: ExtensionCommandContext): Promise<void> {
        const docs = getTrackedDocs();
        if (docs.length === 0) {
            ctx.ui.notify("Pulse: no documents to check", "info");
            return;
        }

        const defaultModel = state.config.model ? parseModel(state.config.model) : ctx.model;
        if (!defaultModel) {
            ctx.ui.notify("Pulse: no model available", "warning");
            return;
        }

        const recentMessages = ctx.sessionManager
            .getBranch()
            .filter((e: unknown) => (e as { type?: string }).type === "message")
            .map((e: unknown) => (e as { message: unknown }).message)
            .slice(-50);

        const groups = groupDocsByModel(docs, defaultModel);
        const docsToUpdate: PulseDoc[] = [];

        for (const { model, docs: groupDocs } of groups) {
            const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model as Parameters<typeof ctx.modelRegistry.getApiKeyAndHeaders>[0]);
            if (!auth.ok || !auth.apiKey) continue;

            const { update, reason } = await shouldUpdateDocs(groupDocs, recentMessages, model, auth.apiKey, state.cwd);
            if (update) {
                docsToUpdate.push(...groupDocs);
            } else {
                ctx.ui.notify(`Pulse (${model.id}): skipped — ${reason}`, "info");
            }
        }

        // Only reset counters after actual check
        state.consecutiveIdleRuns = 0;
        state.lastUpdateTime = Date.now();

        if (docsToUpdate.length === 0) {
            ctx.ui.notify("Pulse: nothing to update", "info");
            setStatus(ctx);
            return;
        }

        // Queue update for next natural agent turn instead of forcing one
        state.pendingUpdateDocs = docsToUpdate;
        ctx.ui.notify(`Pulse: ${docsToUpdate.length} doc(s) queued for update`, "info");

        setStatus(ctx);
    }

    function removeDoc(target: string): { removed: boolean; path?: string } {
        // Try index first
        const index = parseInt(target, 10);
        if (!isNaN(index) && index >= 0 && index < state.config.documents.length) {
            const doc = state.config.documents.splice(index, 1)[0];
            saveConfig(state.cwd, state.config);
            return { removed: true, path: doc.path };
        }

        // Try path match
        const idx = state.config.documents.findIndex((d) => d.path === target);
        if (idx !== -1) {
            const doc = state.config.documents.splice(idx, 1)[0];
            saveConfig(state.cwd, state.config);
            return { removed: true, path: doc.path };
        }

        return { removed: false };
    }

    // ------------------------------------------------------------------------
    // Command: /pulse
    // ------------------------------------------------------------------------

    pi.registerCommand("pulse", {
        description: "Pulse - living documentation sync",
        // FIXME: Explicit TAB on "/pulse remove " (space at end) forces file completions
        // instead of calling getArgumentCompletions. Pi's handleTabCompletion() routes
        // "/cmd arg " to forceFileAutocomplete(force=true), which skips the slash command
        // branch in getSuggestions(). Only auto-popup (typing) uses force=false.
        // See: https://github.com/badlogic/pi-mono/issues/2874
        getArgumentCompletions(argumentText: string): AutocompleteItem[] | null {
            const cwd = getCwd(pi);
            // Pi passes the ENTIRE text after the command name as argumentText.
            // e.g. "/pulse remove p" → argumentText = "remove p"
            // Pi replaces all of argumentText with item.value on completion.
            // So item values must include the subcommand prefix.
            const spaceIdx = argumentText.indexOf(" ");
            const noSubcmdArg = spaceIdx === -1 && !argumentText.endsWith(" ");

            if (noSubcmdArg) {
                const filtered = SUBCOMMANDS.filter((s) => s.startsWith(argumentText));
                if (filtered.length > 0 || argumentText === "") {
                    return filtered.map((s) => ({ value: s, label: s }));
                }
                return null;
            }

            const subcmd = (spaceIdx === -1 ? argumentText : argumentText.slice(0, spaceIdx)).toLowerCase() as Subcommand;
            const argPrefix = spaceIdx === -1 ? "" : argumentText.slice(spaceIdx + 1);

            // Prepend subcommand to values so pi's full-prefix replacement preserves it
            const withSubcmd = (items: AutocompleteItem[] | null): AutocompleteItem[] | null => {
                if (!items) return null;
                const subPart = argumentText.slice(0, (spaceIdx === -1 ? argumentText.length : spaceIdx + 1));
                return items.map((it) => ({
                    value: subPart + it.value,
                    label: it.label ?? it.value,
                }));
            };

            switch (subcmd) {
                case "add":
                    return withSubcmd(getFileCompletions(cwd, argPrefix));
                case "remove":
                    return withSubcmd(getDocCompletions(cwd, argPrefix));
                default:
                    return null;
            }
        },
        async handler(args, ctx) {
            state.cwd = getCwd(pi, ctx);
            state.config = loadConfig(state.cwd) || { documents: [] };

            const parts = (args || "").trim().split(/\s+/);
            const subcmd = (parts[0]?.toLowerCase() as Subcommand) || "help";
            const subArgs = parts.slice(1);

            switch (subcmd) {
                case "help": {
                    const help = [
                        "Pulse - living documentation sync",
                        "",
                        "Tracks documents and keeps them in sync with the conversation.",
                        "Two trigger mechanisms:",
                        "  - Idle turns: 2 consecutive turns with no tool calls",
                        "  - Timer: periodic check every 30m (configurable, 0 = disabled)",
                        "5 min cooldown between auto-checks. /pulse force bypasses cooldown.",
                        "",
                        "Commands:",
                        "  /pulse help                  show this help",
                        "  /pulse init                  scaffold .pulse.json with README* and AGENTS.md",
                        "  /pulse add <path> [instruction]",
                        "  /pulse remove <path>",
                        "  /pulse list",
                        "  /pulse status",
                        "  /pulse force                 run check NOW",
                        "  /pulse pause",
                        "  /pulse resume",
                        "  /pulse config                edit .pulse.json",
                        "",
                        ".pulse.json format:",
                        "  {",
                        "    \"documents\": [",
                        "      {\"path\": \"...\", \"instruction\": \"...\", \"model\": \"...\"}",
                        "    ],",
                        "    \"model\": \"provider/model-id\",",
                        "    \"interval\": 30",
                        "  }",
                        "",
                        "Document fields:",
                        "  path        - file path (relative to .pulse.json)",
                        "  instruction - optional guidance for updates",
                        "  model      - optional provider/model-id override",
                        "",
                        "Top-level fields:",
                        "  model     - optional default provider/model-id for all docs",
                        "  interval  - timer check interval in minutes (default: 30, 0 = disabled)",
                        "",
                        "Model resolution: doc.model > config.model > current default",
                        "",
                        "How it works:",
                        "  1. Silent API call asks the model: \"do these docs need updates?\"",
                        "     - Not part of session history, output is not shown",
                        "  2. If yes, update instructions are queued",
                        "     - Injected into the next natural agent turn via system prompt",
                        "     - No forced turn — agent continues its current work",
                        "  3. If no, a notification shows the skip reason",
                    ].join("\n");
                    ctx.ui.notify(help, "info");
                    break;
                }

                case "init": {
                    if (configExists(state.cwd)) {
                        ctx.ui.notify("Pulse: .pulse.json already exists", "warning");
                        return;
                    }

                    const docs: PulseDoc[] = [];
                    for (const entry of fs.readdirSync(state.cwd)) {
                        if (/^README(\..+)?$/i.test(entry)) {
                            const fullPath = path.join(state.cwd, entry);
                            if (fs.statSync(fullPath).isFile()) {
                                docs.push({ path: entry });
                            }
                        }
                    }

                    const agentsPath = path.join(state.cwd, "AGENTS.md");
                    if (fs.existsSync(agentsPath)) {
                        docs.push({ path: "AGENTS.md", instruction: "project guidelines and context" });
                    }

                    state.config = { documents: docs };
                    saveConfig(state.cwd, state.config);
                    state.isTracking = docs.length > 0;

                    ctx.ui.notify(
                        docs.length === 0
                            ? "Pulse: created empty .pulse.json"
                            : `Pulse: initialized with ${docs.length} doc(s)`,
                        "info",
                    );

                    if (state.isTracking) {
                        startConfigWatcher(ctx);
                        ensureTimer(ctx);
                        setStatus(ctx);
                    }
                    break;
                }

                case "add": {
                    if (!configExists(state.cwd)) {
                        ctx.ui.notify("Pulse: run /pulse init first", "warning");
                        return;
                    }

                    const docPath = subArgs[0];
                    if (!docPath) {
                        ctx.ui.notify("Pulse: /pulse add <path> [instruction]", "warning");
                        return;
                    }

                    const instruction = subArgs[1] ? subArgs.slice(1).join(" ") : undefined;
                    const relativePath = normalizePath(state.cwd, docPath);

                    if (!fs.existsSync(path.resolve(state.cwd, relativePath))) {
                        ctx.ui.notify(`Pulse: file not found: ${relativePath}`, "warning");
                        return;
                    }

                    if (state.config.documents.find((d) => d.path === relativePath)) {
                        ctx.ui.notify(`Pulse: already tracking: ${relativePath}`, "info");
                        return;
                    }

                    state.config.documents.push({ path: relativePath, instruction });
                    saveConfig(state.cwd, state.config);
                    state.isTracking = true;
                    ctx.ui.notify(`Pulse: added ${relativePath}`, "info");
                    ensureTimer(ctx);
                    setStatus(ctx);
                    break;
                }

                case "remove": {
                    if (!configExists(state.cwd)) {
                        ctx.ui.notify("Pulse: no .pulse.json found", "warning");
                        return;
                    }

                    const target = subArgs[0];
                    if (!target) {
                        ctx.ui.notify("Pulse: /pulse remove <path|index>", "warning");
                        return;
                    }

                    const { removed, path: removedPath } = removeDoc(target);
                    if (!removed) {
                        ctx.ui.notify(`Pulse: doc not found: ${target}`, "warning");
                        break;
                    }

                    ctx.ui.notify(`Pulse: removed ${removedPath}`, "info");
                    if (state.config.documents.length === 0) {
                        state.isTracking = false;
                        stopTimer();
                        setStatus(ctx);
                    } else {
                        setStatus(ctx);
                    }
                    break;
                }

                case "list": {
                    if (state.config.documents.length === 0) {
                        ctx.ui.notify("Pulse: no documents tracked (run /pulse init or /pulse add)", "info");
                        return;
                    }

                    const lines = [`Pulse: tracking ${state.config.documents.length} doc(s):`];
                    state.config.documents.forEach((doc, i) => {
                        const modelHint = doc.model ? ` [${doc.model}]` : "";
                        const instrHint = doc.instruction ? ` — "${doc.instruction}"` : "";
                        lines.push(`  ${i}: ${doc.path}${modelHint}${instrHint}`);
                    });

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

                case "status": {
                    const config = loadConfig(state.cwd);
                    if (!config) {
                        ctx.ui.notify("Pulse: not initialized. Run /pulse init", "info");
                        return;
                    }
                    if (config.documents.length === 0) {
                        ctx.ui.notify("Pulse: no documents tracked. Run /pulse add <path>", "info");
                        return;
                    }

                    const cooldownRemaining = Math.max(0, COOLDOWN_MS - (Date.now() - state.lastUpdateTime));
                    const timerRemaining = Math.max(0, getIntervalMs() - (Date.now() - state.lastTimerCheck));
                    const intervalMin = state.config.interval ?? DEFAULT_INTERVAL_MIN;

                    const lines = [
                        "Pulse status:",
                        `  Tracking: ${config.documents.length} doc(s)`,
                        `  Interval: ${isTimerEnabled() ? `${intervalMin}m` : "disabled"}`,
                        `  Timer: ${isTimerEnabled() ? formatTimeRemaining(timerRemaining) : "off"}`,
                        `  Cooldown: ${cooldownRemaining > 0 ? formatTimeRemaining(cooldownRemaining) : "ready"}`,
                        `  Paused: ${state.isPaused ? "yes" : "no"}`,
                        config.model ? `  Model: ${config.model}` : "  Model: default",
                    ];

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

                case "force": {
                    if (state.isPaused) {
                        ctx.ui.notify("Pulse: paused, use /pulse resume first", "warning");
                        return;
                    }
                    state.consecutiveIdleRuns = 0;
                    state.lastTimerCheck = Date.now();
                    await runPulseCheck(ctx);
                    setStatus(ctx);
                    break;
                }

                case "pause": {
                    if (state.isPaused) {
                        ctx.ui.notify("Pulse: already paused", "info");
                        return;
                    }
                    state.isPaused = true;
                    stopTimer();
                    ctx.ui.notify("Pulse: paused", "info");
                    setStatus(ctx);
                    break;
                }

                case "resume": {
                    if (!state.isPaused) {
                        ctx.ui.notify("Pulse: not paused", "info");
                        return;
                    }
                    state.isPaused = false;
                    state.consecutiveIdleRuns = 0;
                    state.lastTimerCheck = Date.now();
                    startTimer(ctx);
                    ctx.ui.notify("Pulse: resumed", "info");
                    setStatus(ctx);
                    break;
                }

                case "config": {
                    const configPath = path.join(state.cwd, PULSE_CONFIG);
                    if (!fs.existsSync(configPath)) {
                        ctx.ui.notify("Pulse: no .pulse.json found", "warning");
                        return;
                    }
                    const content = fs.readFileSync(configPath, "utf-8");
                    ctx.ui.editor?.("pulse-config", content, (newContent: string) => {
                        try {
                            const parsed = JSON.parse(newContent);
                            invariant(typeof parsed === "object" && parsed !== null, "config should be object");
                            if (parsed.interval !== undefined) {
                                assert(typeof parsed.interval === "number" && parsed.interval >= 0, "interval must be >= 0");
                            }
                            fs.writeFileSync(configPath, newContent, "utf-8");
                            state.config = loadConfig(state.cwd) || { documents: [] };
                            return { saved: true };
                        } catch (e) {
                            return { saved: false, error: e instanceof Error ? e.message : "Invalid config" };
                        }
                    });
                    break;
                }

                default: {
                    ctx.ui.notify(`Pulse: unknown command "${subcmd}". Run /pulse help`, "warning");
                    break;
                }
            }
        },
    });

    // ------------------------------------------------------------------------
    // Events
    // ------------------------------------------------------------------------

    pi.on("agent_start", async (_event, ctx) => {
        state.agentRunHadToolCalls = false;

        if (state.timerFired && !state.isPaused) {
            state.timerFired = false;
            if (Date.now() - state.lastUpdateTime >= COOLDOWN_MS) {
                await runPulseCheck(ctx);
            }
        }

        if (state.isTracking && !state.isPaused) {
            setStatus(ctx);
        }
    });

    pi.on("turn_end", async (event, ctx) => {
        const evt = event as { toolResults?: unknown[] };
        if ((evt.toolResults?.length ?? 0) > 0) {
            state.agentRunHadToolCalls = true;
        }

        if (state.isTracking && !state.isPaused) {
            setStatus(ctx);
        }
    });

    pi.on("agent_end", async (_event, ctx) => {
        if (state.isPaused) return;

        const docs = getTrackedDocs();
        if (docs.length === 0) return;

        if (state.agentRunHadToolCalls) {
            state.consecutiveIdleRuns = 0;
            return;
        }

        state.consecutiveIdleRuns++;
        if (state.consecutiveIdleRuns < IDLE_RUN_THRESHOLD) return;
        if (Date.now() - state.lastUpdateTime < COOLDOWN_MS) return;

        await runPulseCheck(ctx);
    });

    pi.on("session_start", async (_event, ctx) => {
        stopConfigWatcher();
        stopTimer();
        state.cwd = getCwd(pi, ctx);

        const config = loadConfig(state.cwd);
        if (config) {
            state.config = config;
            state.isTracking = config.documents.length > 0;
            ctx.ui.notify(`Pulse: tracking ${state.config.documents.length} doc(s)`, "info");
        } else {
            state.config = { documents: [] };
            state.isTracking = false;
        }

        state.agentRunHadToolCalls = false;
        state.consecutiveIdleRuns = 0;
        state.isPaused = false;

        startConfigWatcher(ctx);
        if (state.isTracking && state.config.documents.length > 0) {
            startTimer(ctx);
        }
        setStatus(ctx);
    });

    pi.on("session_shutdown", async (_event, ctx) => {
        stopConfigWatcher();
        stopTimer();
    });

    pi.on("before_agent_start", async (event) => {
        if (state.isPaused) return;
        const docs = getTrackedDocs();
        if (docs.length === 0) return;

        const list = docs.map((d) => `  - ${d.path}`).join("\n");
        let systemAddition =
            event.systemPrompt +
            "\n\n## Tracked Documents\n\n" +
            "The following documents are being kept in sync with this conversation:\n" +
            `${list}\n\n` +
            "When asked to update them: read the files, edit in-place with relevant changes, " +
            "delete outdated sections, be concise.";

        // Inject pending update instruction into this natural turn
        if (state.pendingUpdateDocs.length > 0) {
            const updateList = state.pendingUpdateDocs.map((d) => {
                let s = `  - \`${d.path}\``;
                if (d.instruction) s += ` (focus: ${d.instruction})`;
                return s;
            }).join("\n");
            systemAddition +=
                `\n\n## Pulse Update Required\n\n` +
                `The following tracked docs need updating based on recent conversation:\n${updateList}\n\n` +
                `Re-read each file, edit in-place with relevant information. ` +
                `Be concise. Delete outdated sections. Never append "Previously..." notes. ` +
                `If nothing meaningful changed, skip silently.`;
            state.pendingUpdateDocs = [];
        }

        return {
            systemPrompt: systemAddition,
        };
    });
}