repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor(pulse): use pi settings config

b722efff8e77fd931dbd6ea5cdf7b6716a8abe23

Review <review@example.invalid> ·

unsigned

Browse filesCompare with HEAD

Changed files (6)

.pi/pulse.json

Deleted
deleted file mode 100644
1 -{
2 - "documents": [
3 - {
4 - "path": "CHANGELOG.md"
5 - }
6 - ]
7 -}

.pi/settings.json

Added
new file mode 100644
1 +{
2 + "pulse": {
3 + "documents": [
4 + {
5 + "path": "CHANGELOG.md",
6 + "instruction": "only add changes of interest to users, use user language"
7 + }
8 + ]
9 + }

extensions/pulse/README.md

Modified
28 28 - `/pulse force`
29 29 - `/pulse pause`
30 30 - `/pulse resume`
31 -- `/pulse config`
33 32 Completions:
43 42 Hooks:
45 44 - `session_start`:
46 - loads config, restores last run state, starts config watcher, starts timer
47 - when docs exist.
45 + loads settings, restores last run state, starts timer when docs exist.
48 46 - `session_shutdown`:
49 - stops watcher and timer.
47 + stops timer.
50 48 - `agent_start`:
51 49 refreshes status when tracking and not paused.
52 50 - `tool_execution_end`:
55 53 - `agent_end`:
56 54 runs an automatic check when tracking is active and ready.
58 -Settings live in `.pi/pulse.json`:
56 +Settings live under the `pulse` key in Pi settings.
57 +Global defaults use `~/.pi/agent/settings.json`; project overrides use `.pi/settings.json`.
60 59 ```json
62 - "documents": [{ "path": "README.md" }],
63 - "interval": 10,
64 - "apply": "auto"
61 + "pulse": {
62 + "documents": [{ "path": "README.md" }],
63 + "model": "minimax/MiniMax-M3",
64 + "interval": 10,
65 + "apply": "auto"
66 + }
100 102 ## Behavior
102 -- `/pulse init` creates `.pi/pulse.json`; it tracks root `README*` files and
103 - `AGENTS.md` when present.
104 +- `/pulse init` creates `.pi/settings.json` with a `pulse` section; it tracks
105 + root `README*` files and `AGENTS.md` when present.
104 106 - `/pulse add` requires an existing file.
105 107 - `/pulse add-dir` requires an existing directory and explicit glob.
106 108 - `/pulse add-glob` stores an explicit glob pattern.
108 110 - `/pulse force` runs a manual check unless paused.
109 111 - `/pulse pause` stops timer-driven checks.
110 112 `/pulse resume` restarts them.
111 -- `/pulse config` opens `.pi/pulse.json` in an editor.
112 113 - Absolute paths and `..` path escapes are rejected.
113 114 Existing symlinks resolving outside the workspace are rejected or skipped.
114 115 - Invalid config fields make the config unloadable.
115 - Invalid persisted document specs are dropped while loading config.
116 + Invalid document specs make the config unloadable.
116 117 - Dir and glob specs expand to sorted files; duplicate paths are ignored.
117 118 - Automatic checks wait for Pi idle, a 60 second quiet window after mutations,
118 119 and a 5 minute cooldown after the last update.
131 132 `confirm` asks before writing.
132 133 `review` opens each proposed file in an editor before writing.
133 134 - Writes are refused if a tracked file changed between load and apply.
134 -- `.pi/pulse.json` is watched and reloaded after changes.
135 135 - Last run state is stored in the session as `pulse-state`.

extensions/pulse/__tests__/harness.test.ts

Modified
24 24 return t?.session.extensionRunner.createCommandContext();
27 -function configPath(): string {
28 - return path.join(t?.cwd, ".pi/pulse.json");
27 +function settingsPath(): string {
28 + return path.join(t?.cwd, ".pi/settings.json");
31 31 function writeConfig(config: unknown): void {
32 - mkdirSync(path.dirname(configPath()), { recursive: true });
33 - writeFileSync(configPath(), JSON.stringify(config, null, 2), "utf8");
32 + mkdirSync(path.dirname(settingsPath()), { recursive: true });
33 + writeFileSync(
34 + settingsPath(),
35 + JSON.stringify({ pulse: config }, null, 2),
36 + "utf8",
37 + );
40 +function readConfig(): any {
41 + return JSON.parse(readFileSync(settingsPath(), "utf8")).pulse;
36 44 function notifyText(): string[] {
67 75 writeFileSync(path.join(t.cwd, "README.md"), "# Test\n", "utf8");
69 77 await pulseCommand().handler("init", ctx());
70 - expect(existsSync(configPath())).toBe(true);
71 - expect(JSON.parse(readFileSync(configPath(), "utf8")).documents).toEqual([
72 - { path: "README.md" },
73 - ]);
78 + expect(existsSync(settingsPath())).toBe(true);
79 + expect(readConfig().documents).toEqual([{ path: "README.md" }]);
75 81 await pulseCommand().handler("help", ctx());
76 82 await pulseCommand().handler("list", ctx());
77 83 await pulseCommand().handler("status", ctx());
78 84 await pulseCommand().handler("pause", ctx());
79 85 await pulseCommand().handler("resume", ctx());
80 - await pulseCommand().handler("config", ctx());
82 87 expect(notifyText()).toContain("Pulse: initialized 1 doc(s)");
83 88 expect(
90 95 expect(notifyText()).toContain("Pulse: paused");
91 96 expect(notifyText()).toContain("Pulse: resumed");
92 97 expect(statusText().some((s) => s === "󰐰 paused")).toBe(true);
93 - expect(
94 - t.events.uiCallsFor("editor").some((c) => c.args[0] === "pulse-config"),
95 - ).toBe(true);
98 + expect(pulseCommand().getArgumentCompletions("con") ?? []).toEqual([]);
98 101 it("handles add/add-dir/add-glob/remove completions with real runtime", async () => {
108 111 await pulseCommand().handler('add "my file.md" note here', ctx());
109 112 await pulseCommand().handler("add-dir docs **/*.md docs note", ctx());
110 113 await pulseCommand().handler("add-glob adr/**/*.md adr note", ctx());
111 - expect(JSON.parse(readFileSync(configPath(), "utf8")).documents).toEqual([
114 + expect(readConfig().documents).toEqual([
112 115 { path: "my file.md", instruction: "note here" },
113 116 { path: "docs", type: "dir", glob: "**/*.md", instruction: "docs note" },
114 117 { path: "adr/**/*.md", type: "glob", instruction: "adr note" },
129 132 await pulseCommand().handler('remove "my file.md"', ctx());
130 - expect(
131 - JSON.parse(readFileSync(configPath(), "utf8")).documents.map(
132 - (d: { path: string }) => d.path,
133 - ),
134 - ).toEqual(["docs", "adr/**/*.md"]);
133 + expect(readConfig().documents.map((d: { path: string }) => d.path)).toEqual(
134 + ["docs", "adr/**/*.md"],
135 + );
137 138 it("starts cleanly on session_start without notification spam and reports status", async () => {

extensions/pulse/__tests__/index.test.ts

Modified
29 29 let tmp = "";
30 30 const supportsControlCharPaths = process.platform !== "win32";
32 +const oldAgentDir = process.env.PI_CODING_AGENT_DIR;
32 34 function cwd(): string {
33 35 tmp = fs.mkdtempSync(path.join(os.tmpdir(), "pulse-index-"));
36 + process.env.PI_CODING_AGENT_DIR = path.join(tmp, "agent");
34 37 return tmp;
43 46 function writeConfig(root: string, config: unknown): void {
44 - write(root, ".pi/pulse.json", JSON.stringify(config, null, 2));
47 + write(root, ".pi/settings.json", JSON.stringify({ pulse: config }, null, 2));
50 +function readConfig(root: string): any {
51 + return JSON.parse(
52 + fs.readFileSync(path.join(root, ".pi/settings.json"), "utf8"),
53 + ).pulse;
56 +function writeGlobalConfig(root: string, config: unknown): void {
57 + write(
58 + path.join(root, "agent"),
59 + "settings.json",
60 + JSON.stringify({ pulse: config }, null, 2),
61 + );
47 64 function harness(root: string) {
138 155 }) as never,
139 156 getModel: ((provider: string, id: string) => ({ provider, id })) as never,
158 + if (oldAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
159 + else process.env.PI_CODING_AGENT_DIR = oldAgentDir;
141 160 if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
142 161 tmp = "";
168 187 await h.commands
169 188 .get("pulse")
170 189 .handler('add "my file.md" keep concise', h.ctx);
171 - expect(
172 - JSON.parse(fs.readFileSync(path.join(root, ".pi/pulse.json"), "utf8"))
173 - .documents,
174 - ).toEqual([{ path: "my file.md", instruction: "keep concise" }]);
190 + expect(readConfig(root).documents).toEqual([
191 + { path: "my file.md", instruction: "keep concise" },
192 + ]);
176 194 await h.commands.get("pulse").handler('remove "my file.md"', h.ctx);
195 + expect(readConfig(root).documents).toEqual([]);
196 + });
198 + it("rejects the removed config subcommand", async () => {
199 + const root = cwd();
200 + const h = harness(root);
202 + expect(h.commands.get("pulse").getArgumentCompletions("con") ?? []).toEqual(
203 + [],
204 + );
205 + await h.commands.get("pulse").handler("config", h.ctx);
207 + expect(h.notifications).toContainEqual({
208 + message: "Pulse: unknown command config",
209 + level: "warning",
210 + });
211 + });
213 + it("reports invalid settings instead of silently dropping docs", async () => {
214 + const root = cwd();
215 + writeConfig(root, { documents: [{ path: "README.md", model: "bad" }] });
216 + const h = harness(root);
218 + await h.commands.get("pulse").handler("status", h.ctx);
220 + expect(h.notifications).toContainEqual({
221 + message: "Pulse: invalid config: documents[0].model must be provider/id",
222 + level: "warning",
223 + });
224 + });
226 + it("merges global and project pulse settings", async () => {
227 + const root = cwd();
228 + write(root, "README.md", "doc");
229 + writeGlobalConfig(root, { model: "global/model", interval: 0 });
230 + writeConfig(root, { documents: [{ path: "README.md" }] });
231 + const h = harness(root);
233 + await h.commands.get("pulse").handler("status", h.ctx);
177 235 expect(
178 - JSON.parse(fs.readFileSync(path.join(root, ".pi/pulse.json"), "utf8"))
179 - .documents,
180 - ).toEqual([]);
236 + h.notifications.some((n) => n.message.includes("model: global/model")),
237 + ).toBe(true);
238 + expect(
239 + h.notifications.some((n) => n.message.includes("periodic: off")),
240 + ).toBe(true);
241 + });
243 + it("ignores legacy .pi/pulse.json", async () => {
244 + const root = cwd();
245 + write(root, "README.md", "doc");
246 + write(
247 + root,
248 + ".pi/pulse.json",
249 + JSON.stringify({ documents: [{ path: "README.md" }] }),
250 + );
251 + const h = harness(root);
253 + await h.commands.get("pulse").handler("status", h.ctx);
255 + expect(h.notifications).toContainEqual({
256 + message: "Pulse: not initialized",
257 + level: "info",
258 + });
183 261 it("reports missing auth instead of saying nothing to update", async () => {

extensions/pulse/index.ts

Modified
20 20 } from "@earendil-works/pi-coding-agent";
21 21 import {
22 22 convertToLlm,
23 + getAgentDir,
23 24 serializeConversation,
24 25 } from "@earendil-works/pi-coding-agent";
25 26 import {
35 36 stripUnsafeText,
36 37 } from "./core.ts";
38 -const PULSE_CONFIG = ".pi/pulse.json";
39 +const PULSE_SETTINGS = ".pi/settings.json";
40 +const PULSE_SETTINGS_KEY = "pulse";
39 41 const PULSE_STATE_ENTRY = "pulse-state";
40 42 const DEFAULT_INTERVAL_MIN = 10;
41 43 const COOLDOWN_MS = 5 * 60 * 1000;
44 46 // Magic numbers
45 47 const TIMER_TICK_MS = 30_000;
46 -const CONFIG_WATCHER_DEBOUNCE_MS = 200;
47 48 const RECENT_MESSAGES_LIMIT = 50;
48 49 const MAX_JSON_RETRIES = 2;
49 50 const MAX_SUMMARY_CHARS = 240;
71 72 "force",
72 73 "pause",
73 74 "resume",
74 - "config",
75 75 ] as const;
77 77 type Subcommand = (typeof SUBCOMMANDS)[number];
79 -function assert(
80 - condition: boolean,
81 - message = "assertion failed",
82 -): asserts condition {
83 - if (!condition) throw new Error(`[assert] ${message}`);
86 -function invariant(
87 - condition: boolean,
88 - message = "invariant violated",
89 -): asserts condition {
90 - if (!condition) throw new Error(`[invariant] ${message}`);
93 -function assertArray(
94 - val: unknown,
95 - message = "expected array",
96 -): asserts val is unknown[] {
97 - if (!Array.isArray(val)) throw new Error(`[assert] ${message}`);
100 79 // ============================================================================
101 80 // CONFIG FILE OPERATIONS
102 81 // ============================================================================
104 -function loadConfig(cwd: string): PulseConfig | null {
105 - const configPath = path.join(cwd, PULSE_CONFIG);
83 +type ConfigLoadResult =
84 + | { config: PulseConfig | null; error?: undefined }
85 + | { config: null; error: string };
87 +function isRecord(value: unknown): value is Record<string, unknown> {
88 + return typeof value === "object" && value !== null && !Array.isArray(value);
91 +function readJsonObject(filePath: string): Record<string, unknown> | null {
107 - const content = fs.readFileSync(configPath, "utf-8");
108 - const raw = JSON.parse(content);
109 - assert(
110 - typeof raw === "object" && raw !== null,
111 - "pulse config should be object",
112 - );
113 - const parsed = raw as PulseConfig;
114 - if (!parsed.documents || !Array.isArray(parsed.documents)) return null;
115 - assertArray(parsed.documents, "pulse documents should be array");
93 + const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8"));
94 + return isRecord(parsed) ? parsed : null;
95 + } catch {
96 + return null;
97 + }
100 +function readPulseSettings(filePath: string): unknown {
101 + const parsed = readJsonObject(filePath);
102 + return parsed?.[PULSE_SETTINGS_KEY];
105 +function mergeRawConfig(globalRaw: unknown, projectRaw: unknown): unknown {
106 + if (globalRaw === undefined) return projectRaw;
107 + if (projectRaw === undefined) return globalRaw;
108 + if (isRecord(globalRaw) && isRecord(projectRaw))
109 + return { ...globalRaw, ...projectRaw };
110 + return projectRaw;
113 +function validateConfig(cwd: string, raw: unknown): PulseConfig {
114 + if (!isRecord(raw)) throw new Error("config must be object");
115 + const documentsRaw = raw.documents ?? [];
116 + if (!Array.isArray(documentsRaw)) throw new Error("documents must be array");
117 + if (
118 + raw.interval !== undefined &&
119 + (typeof raw.interval !== "number" || raw.interval < 0)
121 + throw new Error("interval must be a non-negative number");
122 + if (
123 + raw.apply !== undefined &&
124 + raw.apply !== "auto" &&
125 + raw.apply !== "confirm" &&
126 + raw.apply !== "review"
128 + throw new Error("apply must be auto, confirm, or review");
129 + if (
130 + raw.model !== undefined &&
131 + (typeof raw.model !== "string" || !isModelSpec(raw.model))
133 + throw new Error("model must be provider/id");
135 + const documents = documentsRaw.map((entry, index) => {
136 + if (!isRecord(entry)) throw new Error(`documents[${index}] must be object`);
137 + if (typeof entry.path !== "string")
138 + throw new Error(`documents[${index}].path must be string`);
117 - parsed.interval !== undefined &&
118 - (typeof parsed.interval !== "number" || parsed.interval < 0)
140 + entry.type !== undefined &&
141 + entry.type !== "file" &&
142 + entry.type !== "dir" &&
143 + entry.type !== "glob"
120 - return null;
145 + throw new Error(`documents[${index}].type must be file, dir, or glob`);
146 + if (entry.glob !== undefined && typeof entry.glob !== "string")
147 + throw new Error(`documents[${index}].glob must be string`);
122 - parsed.apply !== undefined &&
123 - parsed.apply !== "auto" &&
124 - parsed.apply !== "confirm" &&
125 - parsed.apply !== "review"
149 + entry.instruction !== undefined &&
150 + typeof entry.instruction !== "string"
127 - return null;
152 + throw new Error(`documents[${index}].instruction must be string`);
129 - parsed.model !== undefined &&
130 - (typeof parsed.model !== "string" || !isModelSpec(parsed.model))
154 + entry.model !== undefined &&
155 + (typeof entry.model !== "string" || !isModelSpec(entry.model))
132 - return null;
133 - parsed.documents = parsed.documents
134 - .map((d) => normalizeDoc(cwd, d))
135 - .filter((d): d is PulseDoc => d !== null);
136 - return parsed;
157 + throw new Error(`documents[${index}].model must be provider/id`);
158 + const normalized = normalizeDoc(cwd, entry as unknown as PulseDoc);
159 + if (!normalized) throw new Error(`documents[${index}] is invalid`);
160 + return normalized;
161 + });
163 + const config: PulseConfig = { documents };
164 + if (typeof raw.model === "string") config.model = raw.model;
165 + if (typeof raw.interval === "number") config.interval = raw.interval;
166 + if (raw.apply === "auto" || raw.apply === "confirm" || raw.apply === "review")
167 + config.apply = raw.apply;
168 + return config;
171 +function loadConfigResult(cwd: string): ConfigLoadResult {
172 + const globalRaw = readPulseSettings(
173 + path.join(getAgentDir(), "settings.json"),
174 + );
175 + const projectRaw = readPulseSettings(path.join(cwd, PULSE_SETTINGS));
176 + const raw = mergeRawConfig(globalRaw, projectRaw);
177 + if (raw === undefined) return { config: null };
178 + try {
179 + return { config: validateConfig(cwd, raw) };
180 + } catch (e) {
181 + return {
182 + config: null,
183 + error: e instanceof Error ? e.message : "invalid config",
184 + };
188 +function loadConfig(cwd: string): PulseConfig | null {
189 + return loadConfigResult(cwd).config;
192 +function readProjectConfig(cwd: string): PulseConfig | null {
193 + const raw = readPulseSettings(path.join(cwd, PULSE_SETTINGS));
194 + if (raw === undefined) return null;
195 + try {
196 + return validateConfig(cwd, raw);
137 197 } catch {
138 198 return null;
142 202 function saveConfig(cwd: string, config: PulseConfig): void {
143 - const configPath = path.join(cwd, PULSE_CONFIG);
144 - fs.mkdirSync(path.dirname(configPath), { recursive: true });
145 - fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
203 + const settingsPath = path.join(cwd, PULSE_SETTINGS);
204 + const settings = readJsonObject(settingsPath) ?? {};
205 + const projectConfig = readProjectConfig(cwd) ?? { documents: [] };
206 + settings[PULSE_SETTINGS_KEY] = {
207 + ...projectConfig,
208 + documents: config.documents,
209 + };
210 + fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
211 + fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), "utf-8");
148 214 function configExists(cwd: string): boolean {
149 - return fs.existsSync(path.join(cwd, PULSE_CONFIG));
215 + return readPulseSettings(path.join(cwd, PULSE_SETTINGS)) !== undefined;
152 218 function getCwd(pi: ExtensionAPI, ctx?: ExtensionCommandContext): string {
584 650 lastRunReason: string;
585 651 lastResult: string;
586 652 timerHandle: ReturnType<typeof setInterval> | null;
587 - configWatcher: ReturnType<typeof fs.watch> | null;
588 - configWatcherCwd: string;
591 655 // ============================================================================
610 674 lastRunReason: "",
611 675 lastResult: "never",
612 676 timerHandle: null,
613 - configWatcher: null,
614 - configWatcherCwd: "",
617 679 // ------------------------------------------------------------------------
651 - // ------------------------------------------------------------------------
652 - // Config watcher
653 - // ------------------------------------------------------------------------
655 - let watcherDebounce: ReturnType<typeof setTimeout> | null = null;
657 - function startConfigWatcher(ctx: ExtensionCommandContext): void {
658 - stopConfigWatcher();
659 - const ticket = generation;
660 - const configPath = path.join(state.cwd, PULSE_CONFIG);
661 - if (!fs.existsSync(configPath)) return;
662 - state.configWatcherCwd = state.cwd;
663 - try {
664 - state.configWatcher = fs.watch(configPath, (eventType) => {
665 - if (eventType !== "change") return;
666 - if (watcherDebounce) clearTimeout(watcherDebounce);
667 - watcherDebounce = setTimeout(() => {
668 - watcherDebounce = null;
669 - if (ticket !== generation) return;
670 - if (state.cwd !== state.configWatcherCwd) return;
671 - const reloaded = loadConfig(state.cwd);
672 - if (!reloaded) return;
673 - state.config = reloaded;
674 - state.isTracking = state.config.documents.length > 0;
675 - // Captured ctx from the watcher closure can be
676 - // invalidated by ctx.reload() between ticket check and use;
677 - // session_start reinstalls the watcher with a fresh ctx.
678 - try {
679 - setStatus(ctx);
680 - } catch {}
681 - }, CONFIG_WATCHER_DEBOUNCE_MS);
682 - });
683 - state.configWatcher.on("error", () => {
684 - state.configWatcher?.close();
685 - state.configWatcher = null;
686 - state.configWatcherCwd = "";
687 - });
688 - } catch {}
691 - function stopConfigWatcher(): void {
692 - if (watcherDebounce) {
693 - clearTimeout(watcherDebounce);
694 - watcherDebounce = null;
696 - if (state.configWatcher) {
697 - state.configWatcher.close();
698 - state.configWatcher = null;
700 - state.configWatcherCwd = "";
703 713 // ------------------------------------------------------------------------
704 714 // Dirty state
705 715 // ------------------------------------------------------------------------
1065 1075 " /pulse add-dir <dir> <glob> [note]",
1066 1076 " /pulse add-glob <glob> [note]",
1067 1077 " /pulse remove <path|index>",
1068 - " /pulse list | status | force | pause | resume | config",
1078 + " /pulse list | status | force | pause | resume",
1070 - `Config: ${PULSE_CONFIG}`,
1080 + `Config: ${PULSE_SETTINGS} key "${PULSE_SETTINGS_KEY}"`,
1071 1081 "Fields: documents[], model, interval, apply",
1072 1082 "Doc fields: path, type, glob, instruction, model",
1073 1083 ].join("\n");
1112 1122 if (state.isTracking) {
1113 - startConfigWatcher(ctx);
1114 1123 ensureTimer(ctx);
1115 1124 setStatus(ctx);
1355 1364 setStatus(ctx);
1358 - function handleConfig(ctx: ExtensionCommandContext): void {
1359 - const configPath = path.join(state.cwd, PULSE_CONFIG);
1360 - if (!fs.existsSync(configPath)) {
1361 - ctx.ui.notify("Pulse: not initialized", "warning");
1362 - return;
1364 - const content = fs.readFileSync(configPath, "utf-8");
1365 - (ctx.ui.editor as any)("pulse-config", content, (newContent: string) => {
1366 - try {
1367 - const parsed = JSON.parse(newContent);
1368 - invariant(
1369 - typeof parsed === "object" && parsed !== null,
1370 - "config should be object",
1371 - );
1372 - if (parsed.interval !== undefined) {
1373 - assert(
1374 - typeof parsed.interval === "number" && parsed.interval >= 0,
1375 - "interval must be >= 0",
1376 - );
1378 - if (parsed.apply !== undefined) {
1379 - assert(
1380 - parsed.apply === "auto" ||
1381 - parsed.apply === "confirm" ||
1382 - parsed.apply === "review",
1383 - "apply must be auto, confirm, or review",
1384 - );
1386 - fs.writeFileSync(configPath, newContent, "utf-8");
1387 - state.config = loadConfig(state.cwd) || { documents: [] };
1388 - return { saved: true };
1389 - } catch (e) {
1390 - return {
1391 - saved: false,
1392 - error: e instanceof Error ? e.message : "Invalid config",
1393 - };
1395 - });
1398 1367 // ------------------------------------------------------------------------
1399 1368 // Command: /pulse
1400 1369 // ------------------------------------------------------------------------
1457 1426 async handler(args, ctx) {
1458 1427 state.cwd = getCwd(pi, ctx);
1459 - state.config = loadConfig(state.cwd) || { documents: [] };
1460 - state.isTracking = state.config.documents.length > 0;
1462 1428 const parts = parsePulseArgs(args || "");
1463 1429 const subcmd = (parts[0]?.toLowerCase() as Subcommand) || "help";
1464 1430 const subArgs = parts.slice(1);
1431 + const loaded = loadConfigResult(state.cwd);
1432 + if (loaded.error && subcmd !== "help" && subcmd !== "init") {
1433 + state.config = { documents: [] };
1434 + state.isTracking = false;
1435 + ctx.ui.notify(`Pulse: invalid config: ${loaded.error}`, "warning");
1436 + return;
1438 + state.config = loaded.config || { documents: [] };
1439 + state.isTracking = state.config.documents.length > 0;
1466 1441 switch (subcmd) {
1467 1442 case "help":
1497 1472 case "resume":
1498 1473 handleResume(ctx);
1500 - case "config":
1501 - handleConfig(ctx);
1502 - break;
1503 1475 default:
1504 1476 ctx.ui.notify(`Pulse: unknown command ${subcmd}`, "warning");
1535 1507 pi.on("session_start", async (_event, ctx) => {
1536 1508 const ticket = ++generation;
1537 - stopConfigWatcher();
1538 1509 stopTimer();
1539 1510 state.cwd = getCwd(pi, ctx as any);
1541 - const config = loadConfig(state.cwd);
1542 - if (config) {
1543 - state.config = config;
1544 - state.isTracking = config.documents.length > 0;
1512 + const loaded = loadConfigResult(state.cwd);
1513 + if (loaded.error) {
1514 + (ctx as any).ui.notify(
1515 + `Pulse: invalid config: ${loaded.error}`,
1516 + "warning",
1517 + );
1518 + state.config = { documents: [] };
1519 + state.isTracking = false;
1520 + } else if (loaded.config) {
1521 + state.config = loaded.config;
1522 + state.isTracking = loaded.config.documents.length > 0;
1545 1523 } else {
1546 1524 state.config = { documents: [] };
1547 1525 state.isTracking = false;
1559 1537 state.isChecking = false;
1560 1538 restoreState(ctx as any);
1562 - startConfigWatcher(ctx as any);
1563 1540 if (state.isTracking && state.config.documents.length > 0) {
1564 1541 startTimer(ctx as any);
1569 1546 pi.on("session_shutdown", async (_event, _ctx) => {
1570 1547 generation++;
1571 1548 state.isChecking = false;
1572 - stopConfigWatcher();
1573 1549 stopTimer();