pi-plans 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +74 -21
  2. package/index.ts +115 -9
  3. package/package.json +7 -1
  4. package/references/pi-planning-workflow.md +18 -3
  5. package/references/state-and-config.md +34 -2
  6. package/scripts/validate.ts +4 -0
  7. package/src/code-graph/commands.ts +437 -0
  8. package/src/code-graph/discovery.ts +118 -0
  9. package/src/code-graph/git.ts +108 -0
  10. package/src/code-graph/identity.ts +59 -0
  11. package/src/code-graph/indexer.ts +281 -0
  12. package/src/code-graph/materialize.ts +166 -0
  13. package/src/code-graph/mode.ts +28 -0
  14. package/src/code-graph/mutations.ts +160 -0
  15. package/src/code-graph/parser.ts +51 -0
  16. package/src/code-graph/parsers/javascript.ts +35 -0
  17. package/src/code-graph/parsers/python.ts +160 -0
  18. package/src/code-graph/parsers/tree-sitter.ts +316 -0
  19. package/src/code-graph/paths.ts +85 -0
  20. package/src/code-graph/prompts.ts +18 -0
  21. package/src/code-graph/resolver.ts +69 -0
  22. package/src/code-graph/runtime.ts +158 -0
  23. package/src/code-graph/schema.ts +135 -0
  24. package/src/code-graph/screening.ts +82 -0
  25. package/src/code-graph/store.ts +278 -0
  26. package/src/code-graph/summary.ts +435 -0
  27. package/src/code-graph/types.ts +163 -0
  28. package/src/compaction.ts +1125 -371
  29. package/src/config-command.ts +326 -0
  30. package/src/exec.ts +356 -686
  31. package/src/refine-prompts.ts +50 -0
  32. package/src/refine-ui-helpers.ts +71 -18
  33. package/src/refine-ui-state.ts +87 -21
  34. package/src/refine-ui.ts +210 -102
  35. package/src/state.ts +19 -6
  36. package/src/subagent.ts +163 -61
  37. package/tests/ask-choice.test.ts +263 -0
  38. package/tests/autocomplete.test.ts +6 -1
  39. package/tests/code-graph-apply.test.ts +185 -0
  40. package/tests/code-graph-commands.test.ts +211 -0
  41. package/tests/code-graph-db.test.ts +166 -0
  42. package/tests/code-graph-discovery.test.ts +38 -0
  43. package/tests/code-graph-git.test.ts +94 -0
  44. package/tests/code-graph-index.test.ts +175 -0
  45. package/tests/code-graph-loop.e2e.test.ts +159 -0
  46. package/tests/code-graph-mutations.test.ts +117 -0
  47. package/tests/code-graph-parser.test.ts +85 -0
  48. package/tests/code-graph-rollback.test.ts +100 -0
  49. package/tests/code-graph-summary-batching.test.ts +518 -0
  50. package/tests/code-graph-summary.test.ts +148 -0
  51. package/tests/compaction.test.ts +371 -57
  52. package/tests/config-command.test.ts +255 -0
  53. package/tests/exec.test.ts +665 -241
  54. package/tests/fixtures/code-graph/sample.js +36 -0
  55. package/tests/fixtures/code-graph/sample.py +20 -0
  56. package/tests/fixtures/code-graph/sample.ts +15 -0
  57. package/tests/graph-aware-file-tools.test.ts +411 -0
  58. package/tests/refine-prompts.test.ts +67 -2
  59. package/tests/refine-ui.test.ts +337 -72
  60. package/tests/subagent.test.ts +26 -20
  61. package/tools/ask-choice.ts +158 -11
  62. package/tools/code-graph.ts +254 -0
  63. package/tools/graph-aware-file-tools.ts +392 -0
  64. package/tools/plans.ts +84 -1
  65. package/tools/refine.ts +61 -15
@@ -15,8 +15,118 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
15
15
  import { Text } from "@earendil-works/pi-tui";
16
16
  import { Type } from "typebox";
17
17
  import { disableAutoComplete, enableAutoComplete, isAutoCompleteEnabled, recordAskChoice } from "../src/autocomplete.ts";
18
+ import { truncateToWidth, visibleWidth } from "../src/refine-ui-helpers.ts";
18
19
  import { normalizeWorkdir, readActive, recordDecision } from "../src/state.ts";
19
20
 
21
+ // ---------------------------------------------------------------------------
22
+ // Panel fitting: pi's ExtensionSelectorComponent renders each option as an
23
+ // auto-wrapping Text with NO height cap — an oversized panel exceeds the
24
+ // terminal rows and the TUI thrashes (flicker). These helpers sanitize and
25
+ // shrink the question/labels before they reach ctx.ui.select.
26
+ // ---------------------------------------------------------------------------
27
+
28
+ export const STATUS_BAR_HEIGHT = 1;
29
+ export const PANEL_SAFETY_MARGIN = 2;
30
+ export const PANEL_CHROME_LINES = 9; // 8 measured in extension-selector.js (DynamicBorder×2 + Spacer×4 + title + keyHint) + 1 slack
31
+ /** Each option renders in at most three wrapped lines (user-facing contract). */
32
+ export const OPTION_MAX_LINES = 3;
33
+ /**
34
+ * Per-row width overhead, pinned to extension-selector.js: DynamicBorder 1 +
35
+ * Text padding 1 + selected marker "→ " 2 = 4, plus 2 columns of slack for
36
+ * word-wrap inefficiency. Re-verify against that file if pi changes its layout.
37
+ */
38
+ export const SELECTOR_WIDTH_OVERHEAD = 6;
39
+ export const FALLBACK_COLUMNS = 100;
40
+ export const FALLBACK_ROWS = 30;
41
+ /** Minimal-form floor for tiny terminals (stage-3 width). */
42
+ const MINIMAL_LINE_WIDTH = 20;
43
+ /**
44
+ * Truncation floor for fixed tail labels (Other…/Auto-complete/Auto-refine
45
+ * loop): the longest magic prefix ("Auto-refine loop", 16 cols) plus slack.
46
+ * These labels drive startsWith() answer routing and must never lose it.
47
+ */
48
+ const FIXED_LABEL_FLOOR = 18;
49
+
50
+ export interface PanelItem {
51
+ /** Label without description (degradation stage 1+). */
52
+ core: string;
53
+ /** Full display label: core + description (degradation stage 0). */
54
+ display: string;
55
+ /** Fixed tail labels (Other…/Auto-complete/Auto-refine loop): truncation keeps at least the magic prefix. */
56
+ fixed?: boolean;
57
+ }
58
+
59
+ export interface FittedPanel {
60
+ question: string;
61
+ labels: string[];
62
+ /** True when even the minimal form exceeds the terminal budget. */
63
+ overflowWarned: boolean;
64
+ }
65
+
66
+ function sanitizeLine(text: string): string {
67
+ return text.replace(/\r\n|\n|\r/g, " ");
68
+ }
69
+
70
+ function truncateWithDotDot(text: string, budget: number): string {
71
+ if (visibleWidth(text) <= budget) return text;
72
+ return `${truncateToWidth(text, Math.max(0, budget - 2), "")}..`;
73
+ }
74
+
75
+ function truncateForItem(item: PanelItem, budget: number): string {
76
+ const effective = item.fixed ? Math.max(budget, FIXED_LABEL_FLOOR) : budget;
77
+ return truncateWithDotDot(item.display, effective);
78
+ }
79
+
80
+ function wrappedLineCount(text: string, lineWidth: number): number {
81
+ return Math.max(1, Math.ceil(visibleWidth(text) / lineWidth));
82
+ }
83
+
84
+ /**
85
+ * Sanitize and shrink the question/labels so the projected panel height stays
86
+ * under rows − statusBar − margin. Degradation order (D-001): per-label 3-line
87
+ * budget → strip descriptions → labels to one line → truncate the question →
88
+ * minimal 20-column form (overflowWarned; never fails closed).
89
+ */
90
+ export function fitAskChoicePanel(question: string, items: PanelItem[], columns: number, rows: number): FittedPanel {
91
+ const cols = columns > 0 ? columns : FALLBACK_COLUMNS;
92
+ const termRows = rows > 0 ? rows : FALLBACK_ROWS;
93
+ const lineBudget = Math.max(20, cols - SELECTOR_WIDTH_OVERHEAD);
94
+ const rowBudget = Math.max(10, termRows - STATUS_BAR_HEIGHT - PANEL_SAFETY_MARGIN);
95
+
96
+ const cleanQuestion = sanitizeLine(question);
97
+ const clean = items.map((item) => ({ core: sanitizeLine(item.core), display: sanitizeLine(item.display), fixed: item.fixed === true }));
98
+
99
+ const projected = (q: string, ls: string[]) =>
100
+ PANEL_CHROME_LINES + wrappedLineCount(q, lineBudget) + ls.reduce((sum, l) => sum + wrappedLineCount(l, lineBudget), 0);
101
+
102
+ // Stage 0: full display labels, each within the 3-line budget.
103
+ // (Signature note: items carry {core, display} because D-001 stage 1 strips
104
+ // descriptions, which a plain string list cannot express.)
105
+ let currentQuestion = cleanQuestion;
106
+ let currentLabels = clean.map((item) => truncateForItem(item, OPTION_MAX_LINES * lineBudget));
107
+
108
+ if (projected(currentQuestion, currentLabels) >= rowBudget) {
109
+ // Stage 1: strip descriptions (core labels only).
110
+ currentLabels = clean.map((item) => truncateForItem({ ...item, display: item.core }, OPTION_MAX_LINES * lineBudget));
111
+ }
112
+ if (projected(currentQuestion, currentLabels) >= rowBudget) {
113
+ // Stage 2: labels to a single line.
114
+ currentLabels = clean.map((item) => truncateForItem({ ...item, display: item.core }, lineBudget));
115
+ }
116
+ if (projected(currentQuestion, currentLabels) >= rowBudget) {
117
+ // Stage 3: truncate the question too.
118
+ currentQuestion = truncateWithDotDot(currentQuestion, lineBudget);
119
+ }
120
+ let overflowWarned = false;
121
+ if (projected(currentQuestion, currentLabels) >= rowBudget) {
122
+ // Minimal form for tiny terminals: 20-column floor; still over → warn, never fail closed.
123
+ currentQuestion = truncateWithDotDot(cleanQuestion, MINIMAL_LINE_WIDTH);
124
+ currentLabels = clean.map((item) => truncateForItem({ ...item, display: item.core }, MINIMAL_LINE_WIDTH));
125
+ overflowWarned = projected(currentQuestion, currentLabels) >= rowBudget;
126
+ }
127
+ return { question: currentQuestion, labels: currentLabels, overflowWarned };
128
+ }
129
+
20
130
  const Option = Type.Object({
21
131
  label: Type.String({ description: "Option label" }),
22
132
  description: Type.Optional(Type.String({ description: "Short tradeoff that matters, shown to the user" })),
@@ -33,6 +143,12 @@ const AskChoiceParams = Type.Object({
33
143
  "Offer the Auto-complete option (default true). MUST be false for the execution handoff, install waivers, publishing, deployment, merge, push, credential use, or any external-state change.",
34
144
  }),
35
145
  ),
146
+ trailing: Type.Optional(
147
+ StringEnum(["auto-refine-loop"] as const, {
148
+ description:
149
+ 'Replace the trailing Auto-complete option with "Auto-refine loop" (post-execution amelioration prompt). Selecting it returns instructions to ask the rounds/termination follow-up; Auto-complete is suppressed entirely for this question.',
150
+ }),
151
+ ),
36
152
  workdir: Type.Optional(Type.String({ description: "Target workspace; default current working directory" })),
37
153
  });
38
154
 
@@ -48,7 +164,7 @@ export function registerAskChoiceTool(pi: ExtensionAPI): void {
48
164
  name: "ask_choice",
49
165
  label: "Ask Choice",
50
166
  description:
51
- "Ask the user one planning or refinement question as a numbered choice prompt: recommended option first, alternatives next, then Other and Auto-complete. One question per call. Use for every user-facing planning question, the final scope confirmation, refinement-mode questions, language/role/model settings, and the execution handoff (with autoComplete: false).",
167
+ "Ask the user one planning or refinement question as a numbered choice prompt: recommended option first, alternatives next, then Other and Auto-complete. One question per call. Use for every user-facing planning question, the final scope confirmation, refinement-mode questions, language/role/model settings, and the execution handoff (with autoComplete: false). The optional trailing parameter swaps the trailing option to Auto-refine loop for the post-execution amelioration prompt.",
52
168
  promptSnippet: "Ask structured planning questions with recommended/Other/Auto-complete ordering",
53
169
  promptGuidelines: [
54
170
  "Use ask_choice for every pi-plans question to the user instead of plain-text questions; it enforces option ordering and records decisions.",
@@ -59,7 +175,10 @@ export function registerAskChoiceTool(pi: ExtensionAPI): void {
59
175
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
60
176
  const workdir = normalizeWorkdir(params.workdir ?? ctx.cwd);
61
177
  const allowOther = params.allowOther ?? true;
62
- const autoComplete = params.autoComplete ?? true;
178
+ // Param normalization: a trailing option replaces Auto-complete entirely,
179
+ // so an erroneously passed autoComplete flag is suppressed here.
180
+ const trailing = params.trailing;
181
+ const autoComplete = (params.autoComplete ?? true) && trailing === undefined;
63
182
  const options = params.options;
64
183
  if (options.length === 0) throw new Error("ask_choice requires at least one option");
65
184
  const recommended = options.find((option) => option.recommended) ?? options[0];
@@ -120,16 +239,30 @@ export function registerAskChoiceTool(pi: ExtensionAPI): void {
120
239
  };
121
240
  }
122
241
 
123
- const displayLabels: string[] = options.map((option, index) => {
124
- let label = `${index + 1}. ${option.label}`;
125
- if (option === recommended) label += " (recommended)";
126
- if (option.description) label += ` ${option.description}`;
127
- return label;
242
+ const AUTO_REFINE_LOOP_LABEL =
243
+ "Auto-refine loop (run refinement rounds until no high-severity finding or the 5-round cap)";
244
+ const panelItems: PanelItem[] = options.map((option, index) => {
245
+ const core = `${index + 1}. ${option.label}${option === recommended ? " (recommended)" : ""}`;
246
+ let display = `${index + 1}. ${option.label}`;
247
+ if (option === recommended) display += " (recommended)";
248
+ if (option.description) display += ` — ${option.description}`;
249
+ return { core, display };
128
250
  });
129
- if (allowOther) displayLabels.push("Other… (type your own answer)");
130
- if (autoComplete) displayLabels.push("Auto-complete (take the recommended option)");
251
+ if (allowOther) panelItems.push({ core: "Other… (type your own answer)", display: "Other… (type your own answer)", fixed: true });
252
+ if (autoComplete) panelItems.push({ core: "Auto-complete (take the recommended option)", display: "Auto-complete (take the recommended option)", fixed: true });
253
+ else if (trailing) panelItems.push({ core: AUTO_REFINE_LOOP_LABEL, display: AUTO_REFINE_LOOP_LABEL, fixed: true });
254
+
255
+ const panel = fitAskChoicePanel(
256
+ params.question,
257
+ panelItems,
258
+ process.stdout.columns ?? 0,
259
+ process.stdout.rows ?? 0,
260
+ );
261
+ if (panel.overflowWarned) {
262
+ ctx.ui.notify?.("Terminal too small: the ask_choice panel may overflow even in its minimal form.", "warning");
263
+ }
131
264
 
132
- const selected = await ctx.ui.select(params.question, displayLabels);
265
+ const selected = await ctx.ui.select(panel.question, panel.labels);
133
266
  if (selected === undefined) {
134
267
  disableAutoComplete(ctx, "question cancelled");
135
268
  return {
@@ -158,6 +291,20 @@ export function registerAskChoiceTool(pi: ExtensionAPI): void {
158
291
  };
159
292
  }
160
293
 
294
+ if (trailing && selected.startsWith("Auto-refine loop")) {
295
+ recordAskChoice(ctx, false);
296
+ record("Auto-refine loop", "user");
297
+ return {
298
+ content: [
299
+ {
300
+ type: "text",
301
+ text: `User selected Auto-refine loop. Immediately ask the follow-up with ask_choice (autoComplete: false, in the session language): how should the amelioration loop terminate? Options (recommended first): 1. until no high-severity finding (hard cap 5 rounds) 2. 1 round 3. 2 rounds 4. 3 rounds. Then run the loop per the completion instructions: each round calls refine (role: "reviewer", target: "implementation"), accepts findings on evidence, applies fixes, re-runs relevant tests, and continues until the termination condition or the 5-round cap.`,
302
+ },
303
+ ],
304
+ details: details("Auto-refine loop", "user"),
305
+ };
306
+ }
307
+
161
308
  if (allowOther && selected.startsWith("Other…")) {
162
309
  const typed = await ctx.ui.input(`${params.question} — your answer:`);
163
310
  if (typed === undefined || !typed.trim()) {
@@ -176,7 +323,7 @@ export function registerAskChoiceTool(pi: ExtensionAPI): void {
176
323
  };
177
324
  }
178
325
 
179
- const index = displayLabels.indexOf(selected);
326
+ const index = panel.labels.indexOf(selected);
180
327
  const option = index >= 0 && index < options.length ? options[index] : undefined;
181
328
  if (!option) {
182
329
  recordAskChoice(ctx, false);
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Agent-facing graph tool. Eagerly avoids importing node:sqlite or the
3
+ * parsers at module load; both are loaded on first action call.
4
+ */
5
+
6
+ import { StringEnum } from "@earendil-works/pi-ai";
7
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
8
+ import { Type } from "typebox";
9
+ import {
10
+ loadGraphRuntime,
11
+ describeRuntimeIssues,
12
+ type RuntimeStatus,
13
+ } from "../src/code-graph/runtime.ts";
14
+ import { resolveCanonicalWorktree } from "../src/code-graph/paths.ts";
15
+ import type { WorktreePaths } from "../src/code-graph/paths.ts";
16
+ import { Store } from "../src/code-graph/store.ts";
17
+ import { makeBackend } from "../src/code-graph/parsers/javascript.ts";
18
+ import { PythonBackend } from "../src/code-graph/parsers/python.ts";
19
+ import type { ParserBackend } from "../src/code-graph/parser.ts";
20
+ import { hashText } from "../src/code-graph/parser.ts";
21
+ import type { Language } from "../src/code-graph/types.ts";
22
+ import { screeningQuery } from "../src/code-graph/screening.ts";
23
+ import { deleteFile, listPending, updateFile, updateFunction } from "../src/code-graph/mutations.ts";
24
+
25
+ const CodeGraphParams = Type.Object({
26
+ action: StringEnum(
27
+ [
28
+ "status",
29
+ "screening",
30
+ "get-function",
31
+ "update-function",
32
+ "update-file",
33
+ "delete-file",
34
+ "list-pending",
35
+ "reindex",
36
+ "manifest",
37
+ ] as const,
38
+ { description: "Code graph action to perform" },
39
+ ),
40
+ workdir: Type.Optional(Type.String({ description: "Target workspace directory" })),
41
+ language: Type.Optional(StringEnum(["javascript", "typescript", "tsx", "python"] as const)),
42
+ functionName: Type.Optional(Type.String()),
43
+ fileDir: Type.Optional(Type.String({ description: "File directory (POSIX, '.' for root)" })),
44
+ fileName: Type.Optional(Type.String({ description: "File name without directory" })),
45
+ fullCode: Type.Optional(Type.String({ description: "New function body text for update-function" })),
46
+ text: Type.Optional(Type.String({ description: "New whole-file text for update-file" })),
47
+ limit: Type.Optional(Type.Number()),
48
+ force: Type.Optional(Type.Boolean()),
49
+ });
50
+
51
+ export type CodeGraphContext = Parameters<Parameters<ExtensionAPI["registerTool"]>[0]["execute"]>[4];
52
+
53
+ export interface RuntimeCacheEntry {
54
+ runtime: Awaited<ReturnType<typeof loadGraphRuntime>>["runtime"];
55
+ parsers: Record<Language, ParserBackend>;
56
+ paths: WorktreePaths;
57
+ store: Store;
58
+ }
59
+
60
+ let runtimeCache: RuntimeCacheEntry | null = null;
61
+
62
+ export async function ensureRuntime(workdir: string, ctx: CodeGraphContext): Promise<{ entry: RuntimeCacheEntry; status: RuntimeStatus } | null> {
63
+ const { runtime, status } = await loadGraphRuntime();
64
+ if (status.issues.length > 0 && !status.sqliteAvailable && !status.parserAvailable) {
65
+ ctx.ui?.notify?.(`code-graph unavailable: ${describeRuntimeIssues(status).join("; ")}`, "warning");
66
+ return null;
67
+ }
68
+ const paths = resolveCanonicalWorktree(workdir);
69
+ if (!runtimeCache || runtimeCache.paths.codeGraphDb !== paths.codeGraphDb) {
70
+ if (runtimeCache) {
71
+ runtimeCache.store.close();
72
+ runtimeCache = null;
73
+ }
74
+ const store = new Store({ dbPath: paths.codeGraphDb, worktreeRoot: paths.worktreeRoot, gitCommonDir: paths.gitCommonDir }, runtime.sqlite);
75
+ try {
76
+ store.checkWorktree(paths.worktreeRoot, paths.gitCommonDir);
77
+ } catch (error) {
78
+ store.close();
79
+ ctx.ui?.notify?.(`code-graph: ${(error as Error).message}`, "error");
80
+ return null;
81
+ }
82
+ const ParserCtor = runtime.parser.Parser as unknown as new () => { parse(input: string | Buffer): unknown; setLanguage(language: unknown): void };
83
+ const parsers: Record<Language, ParserBackend> = {
84
+ javascript: makeBackend("javascript", ParserCtor, runtime.parser.javascript),
85
+ typescript: makeBackend("typescript", ParserCtor, runtime.parser.typescript),
86
+ tsx: makeBackend("tsx", ParserCtor, runtime.parser.tsx),
87
+ python: new PythonBackend(ParserCtor, runtime.parser.python),
88
+ };
89
+ runtimeCache = { runtime, parsers, paths, store };
90
+ }
91
+ return { entry: runtimeCache, status };
92
+ }
93
+
94
+ export function registerCodeGraphTool(pi: ExtensionAPI): void {
95
+ pi.registerTool({
96
+ name: "code_graph",
97
+ label: "Code Graph",
98
+ description:
99
+ "Read-only code-graph actions: status, screening (no full_code), function read, reindex guard, manifest summary. No agent mutation API in v1.",
100
+ promptSnippet: "Read-only code graph queries",
101
+ parameters: CodeGraphParams,
102
+ async execute(_id, params, _signal, _onUpdate, ctx) {
103
+ const workdir = params.workdir ?? ctx.cwd;
104
+ const ensured = await ensureRuntime(workdir, ctx);
105
+ if (!ensured) {
106
+ return {
107
+ content: [{ type: "text", text: JSON.stringify({ ok: false, reason: "runtime unavailable" }) }],
108
+ details: {},
109
+ };
110
+ }
111
+ const { entry } = ensured;
112
+ switch (params.action) {
113
+ case "status":
114
+ return {
115
+ content: [
116
+ {
117
+ type: "text",
118
+ text: JSON.stringify({
119
+ ok: true,
120
+ dbPath: entry.paths.codeGraphDb,
121
+ worktreeRoot: entry.paths.worktreeRoot,
122
+ files: entry.store.read(() => entry.store.db.prepare("SELECT COUNT(*) AS c FROM files").get()) as { c: number } | undefined,
123
+ functions: entry.store.read(() => entry.store.db.prepare("SELECT COUNT(*) AS c FROM functions").get()) as { c: number } | undefined,
124
+ }),
125
+ },
126
+ ],
127
+ details: {},
128
+ };
129
+ case "screening": {
130
+ const items = screeningQuery({
131
+ store: entry.store,
132
+ language: params.language,
133
+ functionNameLike: params.functionName,
134
+ limit: params.limit ?? 100,
135
+ });
136
+ return {
137
+ content: [{ type: "text", text: JSON.stringify({ ok: true, items }) }],
138
+ details: {},
139
+ };
140
+ }
141
+ case "get-function": {
142
+ if (!params.functionName) {
143
+ return {
144
+ content: [{ type: "text", text: JSON.stringify({ ok: false, reason: "functionName required" }) }],
145
+ details: {},
146
+ };
147
+ }
148
+ const row = entry.store.read(() =>
149
+ entry.store.db
150
+ .prepare(
151
+ `SELECT file_dir, file_name, function_name, full_code, render_code,
152
+ full_code_hash, render_code_hash, version, kind
153
+ FROM functions
154
+ WHERE function_name = ? LIMIT 1`,
155
+ )
156
+ .get(params.functionName),
157
+ ) as
158
+ | {
159
+ file_dir: string;
160
+ file_name: string;
161
+ function_name: string;
162
+ full_code: string;
163
+ render_code: string;
164
+ full_code_hash: string;
165
+ render_code_hash: string;
166
+ version: number;
167
+ kind: string;
168
+ }
169
+ | undefined;
170
+ if (!row) {
171
+ return {
172
+ content: [{ type: "text", text: JSON.stringify({ ok: false, reason: "not found" }) }],
173
+ details: {},
174
+ };
175
+ }
176
+ return {
177
+ content: [{ type: "text", text: JSON.stringify({ ok: true, function: row }) }],
178
+ details: {},
179
+ };
180
+ }
181
+ case "update-function": {
182
+ if (!params.fileDir || !params.fileName || !params.functionName || typeof params.fullCode !== "string") {
183
+ return {
184
+ content: [{ type: "text", text: JSON.stringify({ ok: false, reason: "fileDir, fileName, functionName, and fullCode are required" }) }],
185
+ details: {},
186
+ };
187
+ }
188
+ const result = updateFunction(entry.store, {
189
+ fileDir: params.fileDir,
190
+ fileName: params.fileName,
191
+ functionName: params.functionName,
192
+ fullCode: params.fullCode,
193
+ });
194
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: {} };
195
+ }
196
+ case "update-file": {
197
+ if (!params.fileDir || !params.fileName || typeof params.text !== "string") {
198
+ return {
199
+ content: [{ type: "text", text: JSON.stringify({ ok: false, reason: "fileDir, fileName, and text are required" }) }],
200
+ details: {},
201
+ };
202
+ }
203
+ const result = updateFile(entry.store, {
204
+ fileDir: params.fileDir,
205
+ fileName: params.fileName,
206
+ text: params.text,
207
+ ...(params.language ? { language: params.language } : {}),
208
+ });
209
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: {} };
210
+ }
211
+ case "delete-file": {
212
+ if (!params.fileDir || !params.fileName) {
213
+ return {
214
+ content: [{ type: "text", text: JSON.stringify({ ok: false, reason: "fileDir and fileName are required" }) }],
215
+ details: {},
216
+ };
217
+ }
218
+ const result = deleteFile(entry.store, { fileDir: params.fileDir, fileName: params.fileName });
219
+ return { content: [{ type: "text", text: JSON.stringify(result) }], details: {} };
220
+ }
221
+ case "list-pending": {
222
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, pending: listPending(entry.store) }) }], details: {} };
223
+ }
224
+
225
+ case "reindex":
226
+ return {
227
+ content: [
228
+ {
229
+ type: "text",
230
+ text: JSON.stringify({
231
+ ok: false,
232
+ reason: "reindex must run via the /init-graph slash command (D-013)",
233
+ }),
234
+ },
235
+ ],
236
+ details: {},
237
+ };
238
+ case "manifest": {
239
+ const rows = entry.store.read(() =>
240
+ entry.store.db
241
+ .prepare(
242
+ `SELECT file_dir, file_name, COUNT(*) AS c FROM file_entries GROUP BY file_dir, file_name ORDER BY file_dir, file_name`,
243
+ )
244
+ .all(),
245
+ ) as Array<{ file_dir: string; file_name: string; c: number }>;
246
+ return {
247
+ content: [{ type: "text", text: JSON.stringify({ ok: true, manifest: rows }) }],
248
+ details: {},
249
+ };
250
+ }
251
+ }
252
+ },
253
+ });
254
+ }