repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
pi/agent/extensions/pulse/index.ts
RawFile outline
- PULSE_CONFIG line 25
- DEFAULT_INTERVAL_MIN line 26
- COOLDOWN_MS line 27
- QUIET_WINDOW_MS line 28
- TIMER_TICK_MS line 31
- CONFIG_WATCHER_DEBOUNCE_MS line 32
- RECENT_MESSAGES_LIMIT line 33
- SUBCOMMANDS line 35
- Subcommand line 50
- assert line 52
- invariant line 56
- assertArray line 60
- loadConfig line 68
- saveConfig line 87
- configExists line 93
- getCwd line 97
- shouldUpdateDocs line 105
- text line 152
- type line 152
- type line 153
- parseModel line 173
- formatTimeRemaining line 179
- getPathCompletions line 186
- getDocCompletions line 203
- gitFingerprint line 213
- mutatesWorkspace line 225
- PulseState line 233
- config line 234
- cwd line 235
- workspaceDirty line 236
- maybeWorkspaceDirty line 237
- lastMutationAt line 238
- lastUpdateTime line 239
- lastTimerCheck line 240
- lastGitFingerprint line 241
- isTracking line 242
- isPaused line 243
- timerHandle line 244
- timerFired line 245
- pendingUpdateDocs line 246
- configWatcher line 247
- configWatcherCwd line 248
- getIntervalMs line 278
- isTimerEnabled line 282
- startTimer line 286
- ensureTimer line 301
- stopTimer line 306
- startConfigWatcher line 319
- stopConfigWatcher line 341
- markWorkspaceDirty line 357
- reconcileMaybeDirty line 363
- setStatus line 378
- getTrackedDocs line 405
- groupDocsByModel line 410
- runPulseCheck line 429
- type line 445
- message line 446
- removeDoc line 482
- handleHelp line 506
- handleInit line 565
- handleAdd line 602
- addDocSpec line 635
- handleAddDir line 649
- handleAddGlob line 667
- handleRemove line 684
- handleList line 710
- handleStatus line 726
- handleForce line 757
- handlePause line 767
- handleResume line 778
- handleConfig line 790
- getArgumentCompletions line 824
- withSubcmd line 845
- handler line 865
/**
* Pulse - Living documentation sync
*
* Run /pulse help for usage.
*/
import type { ExtensionAPI, AutocompleteItem } from "@earendil-works/pi-coding-agent";
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
import { complete, getModel } from "@earendil-works/pi-ai";
import * as fs from "node:fs";
import * as path from "node:path";
import { execFileSync } from "node:child_process";
import {
createDirDoc,
createFileDoc,
createGlobDoc,
expandPulseDocuments,
formatDoc,
normalizeDoc,
type PulseConfig,
type PulseDoc,
} from "./core.ts";
const PULSE_CONFIG = ".pi/pulse.json";
const DEFAULT_INTERVAL_MIN = 10;
const COOLDOWN_MS = 5 * 60 * 1000;
const QUIET_WINDOW_MS = 60 * 1000;
// Magic numbers
const TIMER_TICK_MS = 30_000;
const CONFIG_WATCHER_DEBOUNCE_MS = 200;
const RECENT_MESSAGES_LIMIT = 50;
const SUBCOMMANDS = [
"help",
"init",
"add",
"add-dir",
"add-glob",
"remove",
"list",
"status",
"force",
"pause",
"resume",
"config",
] as const;
type Subcommand = (typeof SUBCOMMANDS)[number];
function assert(condition: boolean, message = "assertion failed"): asserts condition {
if (!condition) throw new Error(`[assert] ${message}`);
}
function invariant(condition: boolean, message = "invariant violated"): asserts condition {
if (!condition) throw new Error(`[invariant] ${message}`);
}
function assertArray(val: unknown, message = "expected array"): asserts val is unknown[] {
if (!Array.isArray(val)) throw new Error(`[assert] ${message}`);
}
// ============================================================================
// 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
.map((d) => normalizeDoc(cwd, d))
.filter((d): d is PulseDoc => d !== null);
return parsed;
} catch {
return null;
}
}
function saveConfig(cwd: string, config: PulseConfig): void {
const configPath = path.join(cwd, PULSE_CONFIG);
fs.mkdirSync(path.dirname(configPath), { recursive: true });
fs.writeFileSync(configPath, 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();
}
// ============================================================================
// 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 getPathCompletions(cwd: string, prefix: string, kind: "file" | "dir"): AutocompleteItem[] {
const items: AutocompleteItem[] = [];
try {
for (const entry of fs.readdirSync(cwd)) {
if (entry.startsWith(".")) continue;
const fullPath = path.join(cwd, entry);
try {
const st = fs.statSync(fullPath);
if (entry.startsWith(prefix) && (kind === "file" ? st.isFile() : st.isDirectory())) {
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;
}
function gitFingerprint(cwd: string): string | null {
try {
return execFileSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], {
cwd,
encoding: "utf-8",
stdio: ["ignore", "pipe", "ignore"],
});
} catch {
return null;
}
}
function mutatesWorkspace(toolName: string): boolean {
return toolName === "edit" || toolName === "write";
}
// ============================================================================
// EXTENSION STATE
// ============================================================================
interface PulseState {
config: PulseConfig;
cwd: string;
workspaceDirty: boolean;
maybeWorkspaceDirty: boolean;
lastMutationAt: number;
lastUpdateTime: number;
lastTimerCheck: number;
lastGitFingerprint: string | null;
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: "",
workspaceDirty: false,
maybeWorkspaceDirty: false,
lastMutationAt: 0,
lastUpdateTime: 0,
lastTimerCheck: Date.now(),
lastGitFingerprint: null,
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);
}, TIMER_TICK_MS);
}
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);
}, CONFIG_WATCHER_DEBOUNCE_MS);
});
} catch {}
}
function stopConfigWatcher(): void {
if (watcherDebounce) {
clearTimeout(watcherDebounce);
watcherDebounce = null;
}
if (state.configWatcher) {
state.configWatcher.close();
state.configWatcher = null;
}
state.configWatcherCwd = "";
}
// ------------------------------------------------------------------------
// Dirty state
// ------------------------------------------------------------------------
function markWorkspaceDirty(fingerprint = gitFingerprint(state.cwd)): void {
state.workspaceDirty = true;
state.lastMutationAt = Date.now();
state.lastGitFingerprint = fingerprint;
}
function reconcileMaybeDirty(): void {
if (!state.maybeWorkspaceDirty) return;
state.maybeWorkspaceDirty = false;
const next = gitFingerprint(state.cwd);
if (next === null || next !== state.lastGitFingerprint) {
markWorkspaceDirty(next);
return;
}
state.lastGitFingerprint = next;
}
// ------------------------------------------------------------------------
// 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 now = Date.now();
const intervalMin = state.config.interval ?? DEFAULT_INTERVAL_MIN;
const timerRemaining = Math.max(0, getIntervalMs() - (now - state.lastTimerCheck));
const timerMins = Math.ceil(timerRemaining / 60000);
const cooldownRemaining = Math.max(0, COOLDOWN_MS - (now - state.lastUpdateTime));
const quietRemaining = Math.max(0, QUIET_WINDOW_MS - (now - state.lastMutationAt));
const parts: string[] = [];
if (state.workspaceDirty) parts.push(quietRemaining > 0 ? `settle ${formatTimeRemaining(quietRemaining)}` : cooldownRemaining > 0 ? `cooldown ${formatTimeRemaining(cooldownRemaining)}` : "dirty");
if (state.maybeWorkspaceDirty) parts.push("maybe dirty");
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 specs = getTrackedDocs();
const docs = expandPulseDocuments(state.cwd, specs);
if (docs.length === 0) {
ctx.ui.notify("Pulse: no matching files 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(-RECENT_MESSAGES_LIMIT);
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");
}
}
state.workspaceDirty = false;
state.maybeWorkspaceDirty = false;
state.lastGitFingerprint = gitFingerprint(state.cwd);
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 };
}
// ------------------------------------------------------------------------
// Case handlers (extracted to reduce nesting)
// ------------------------------------------------------------------------
function handleHelp(ctx: ExtensionCommandContext): void {
const help = [
"Pulse - living documentation sync",
"",
"Tracks documents and keeps them in sync with the conversation.",
"Two trigger mechanisms:",
" - Dirty workspace: edit/write or bash-caused git status change, then 60s settle",
" - Timer: periodic check every 10m (configurable, 0 = disabled)",
"5 min cooldown between auto-checks. /pulse force bypasses cooldown.",
"",
"Commands:",
" /pulse help show this help",
` /pulse init scaffold ${PULSE_CONFIG} with README* and AGENTS.md`,
" /pulse add <file> [instruction]",
" /pulse add-dir <dir> <glob> [instruction]",
" /pulse add-glob <glob> [instruction]",
" /pulse remove <path>",
" /pulse list",
" /pulse status",
" /pulse force run check NOW",
" /pulse pause",
" /pulse resume",
` /pulse config edit ${PULSE_CONFIG}`,
"",
`${PULSE_CONFIG} format:`,
" {",
" \"documents\": [",
" {\"path\": \"README.md\"},",
" {\"path\": \"docs\", \"type\": \"dir\", \"glob\": \"**/*.md\"},",
" {\"path\": \"adr/**/*.md\", \"type\": \"glob\"}",
" ],",
" \"model\": \"provider/model-id\",",
" \"interval\": 10",
" }",
"",
"Document fields:",
" path - file path, dir path, or glob (relative to project root)",
" type - file | dir | glob (default: file)",
" glob - dir-only file pattern, e.g. **/*.md",
" 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: 10, 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");
}
function handleInit(ctx: ExtensionCommandContext): void {
if (configExists(state.cwd)) {
ctx.ui.notify(`Pulse: ${PULSE_CONFIG} 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_CONFIG}` : `Pulse: initialized with ${docs.length} doc(s)`,
"info",
);
if (state.isTracking) {
startConfigWatcher(ctx);
ensureTimer(ctx);
setStatus(ctx);
}
}
function handleAdd(ctx: ExtensionCommandContext, subArgs: string[]): void {
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 <file> [instruction]", "warning");
return;
}
let doc: PulseDoc;
try {
doc = createFileDoc(state.cwd, docPath, subArgs[1] ? subArgs.slice(1).join(" ") : undefined);
} catch (e) {
ctx.ui.notify(`Pulse: ${e instanceof Error ? e.message : String(e)}`, "warning");
return;
}
if (state.config.documents.find((d) => d.path === doc.path && (d.type ?? "file") === "file")) {
ctx.ui.notify(`Pulse: already tracking: ${doc.path}`, "info");
return;
}
state.config.documents.push(doc);
saveConfig(state.cwd, state.config);
state.isTracking = true;
ctx.ui.notify(`Pulse: added ${doc.path}`, "info");
ensureTimer(ctx);
setStatus(ctx);
}
function addDocSpec(ctx: ExtensionCommandContext, doc: PulseDoc): void {
if (state.config.documents.find((d) => formatDoc(d) === formatDoc(doc) && (d.type ?? "file") === (doc.type ?? "file"))) {
ctx.ui.notify(`Pulse: already tracking: ${formatDoc(doc)}`, "info");
return;
}
state.config.documents.push(doc);
saveConfig(state.cwd, state.config);
state.isTracking = true;
const count = expandPulseDocuments(state.cwd, [doc]).length;
ctx.ui.notify(`Pulse: added ${formatDoc(doc)} (${count} file(s) now)`, "info");
ensureTimer(ctx);
setStatus(ctx);
}
function handleAddDir(ctx: ExtensionCommandContext, subArgs: string[]): void {
if (!configExists(state.cwd)) {
ctx.ui.notify("Pulse: run /pulse init first", "warning");
return;
}
const dirPath = subArgs[0];
const glob = subArgs[1];
if (!dirPath || !glob) {
ctx.ui.notify("Pulse: /pulse add-dir <dir> <glob> [instruction]", "warning");
return;
}
try {
addDocSpec(ctx, createDirDoc(state.cwd, dirPath, glob, subArgs[2] ? subArgs.slice(2).join(" ") : undefined));
} catch (e) {
ctx.ui.notify(`Pulse: ${e instanceof Error ? e.message : String(e)}`, "warning");
}
}
function handleAddGlob(ctx: ExtensionCommandContext, subArgs: string[]): void {
if (!configExists(state.cwd)) {
ctx.ui.notify("Pulse: run /pulse init first", "warning");
return;
}
const pattern = subArgs[0];
if (!pattern) {
ctx.ui.notify("Pulse: /pulse add-glob <glob> [instruction]", "warning");
return;
}
try {
addDocSpec(ctx, createGlobDoc(pattern, subArgs[1] ? subArgs.slice(1).join(" ") : undefined));
} catch (e) {
ctx.ui.notify(`Pulse: ${e instanceof Error ? e.message : String(e)}`, "warning");
}
}
function handleRemove(ctx: ExtensionCommandContext, subArgs: string[]): void {
if (!configExists(state.cwd)) {
ctx.ui.notify(`Pulse: no ${PULSE_CONFIG} 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");
return;
}
ctx.ui.notify(`Pulse: removed ${removedPath}`, "info");
if (state.config.documents.length === 0) {
state.isTracking = false;
stopTimer();
}
setStatus(ctx);
}
function handleList(ctx: ExtensionCommandContext): void {
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}: ${formatDoc(doc)}${modelHint}${instrHint}`);
});
ctx.ui.notify(lines.join("\n"), "info");
}
function handleStatus(ctx: ExtensionCommandContext): void {
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 now = Date.now();
const cooldownRemaining = Math.max(0, COOLDOWN_MS - (now - state.lastUpdateTime));
const timerRemaining = Math.max(0, getIntervalMs() - (now - state.lastTimerCheck));
const quietRemaining = Math.max(0, QUIET_WINDOW_MS - (now - state.lastMutationAt));
const intervalMin = state.config.interval ?? DEFAULT_INTERVAL_MIN;
const lines = [
"Pulse status:",
` Tracking: ${config.documents.length} doc(s)`,
` Dirty: ${state.workspaceDirty ? (quietRemaining > 0 ? `settling ${formatTimeRemaining(quietRemaining)}` : "yes") : state.maybeWorkspaceDirty ? "maybe" : "no"}`,
` 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");
}
async function handleForce(ctx: ExtensionCommandContext): Promise<void> {
if (state.isPaused) {
ctx.ui.notify("Pulse: paused, use /pulse resume first", "warning");
return;
}
state.lastTimerCheck = Date.now();
await runPulseCheck(ctx);
setStatus(ctx);
}
function handlePause(ctx: ExtensionCommandContext): void {
if (state.isPaused) {
ctx.ui.notify("Pulse: already paused", "info");
return;
}
state.isPaused = true;
stopTimer();
ctx.ui.notify("Pulse: paused", "info");
setStatus(ctx);
}
function handleResume(ctx: ExtensionCommandContext): void {
if (!state.isPaused) {
ctx.ui.notify("Pulse: not paused", "info");
return;
}
state.isPaused = false;
state.lastTimerCheck = Date.now();
startTimer(ctx);
ctx.ui.notify("Pulse: resumed", "info");
setStatus(ctx);
}
function handleConfig(ctx: ExtensionCommandContext): void {
const configPath = path.join(state.cwd, PULSE_CONFIG);
if (!fs.existsSync(configPath)) {
ctx.ui.notify(`Pulse: no ${PULSE_CONFIG} 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" };
}
});
}
// ------------------------------------------------------------------------
// 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(getPathCompletions(cwd, argPrefix, "file"));
case "add-dir":
return withSubcmd(getPathCompletions(cwd, argPrefix, "dir"));
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": handleHelp(ctx); break;
case "init": handleInit(ctx); break;
case "add": handleAdd(ctx, subArgs); break;
case "add-dir": handleAddDir(ctx, subArgs); break;
case "add-glob": handleAddGlob(ctx, subArgs); break;
case "remove": handleRemove(ctx, subArgs); break;
case "list": handleList(ctx); break;
case "status": handleStatus(ctx); break;
case "force": await handleForce(ctx); break;
case "pause": handlePause(ctx); break;
case "resume": handleResume(ctx); break;
case "config": handleConfig(ctx); break;
default: ctx.ui.notify(`Pulse: unknown command "${subcmd}". Run /pulse help`, "warning");
}
},
});
// ------------------------------------------------------------------------
// Events
// ------------------------------------------------------------------------
pi.on("agent_start", async (_event, ctx) => {
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("tool_execution_end", async (event, ctx) => {
if (event.isError) return;
if (mutatesWorkspace(event.toolName)) markWorkspaceDirty();
if (event.toolName === "bash") state.maybeWorkspaceDirty = 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;
reconcileMaybeDirty();
if (!state.workspaceDirty) return;
const now = Date.now();
if (now - state.lastMutationAt < QUIET_WINDOW_MS) return;
if (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.workspaceDirty = false;
state.maybeWorkspaceDirty = false;
state.lastMutationAt = 0;
state.lastGitFingerprint = gitFingerprint(state.cwd);
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) => ` - ${formatDoc(d)}`).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,
};
});
}