@danypops/pi-lector 0.3.0 → 0.4.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.
@@ -10,6 +10,8 @@ import type {
10
10
  JobSnapshot,
11
11
  LineEdit,
12
12
  LineEditOutcome,
13
+ MutationHistoryEntry,
14
+ OperationOutputs,
13
15
  PackageSourceOperationResult,
14
16
  PopulateSymbolGraphResult,
15
17
  RepoFetchResult,
@@ -66,12 +68,17 @@ import { createLectorFindSymbolsOperations } from "./find-symbols-operations.ts"
66
68
  import { describeFindSymbolSources, formatFindSymbolsCall, formatFindSymbolsResult } from "./find-symbols-rendering.ts";
67
69
  import { createLectorGitOperations } from "./git-operations.ts";
68
70
  import { formatGitCall, formatGitResult, type GitToolDetails } from "./git-rendering.ts";
71
+ import { setNewWorkspaceObserver } from "./lector-client.ts";
69
72
  import { createLectorLineEditOperations } from "./line-edit-operations.ts";
70
73
  import { formatLineEditCall, formatLineEditResult } from "./line-edit-rendering.ts";
74
+ import { createMutationHistoryOperations } from "./mutation-history-operations.ts";
71
75
  import { nearestGitRoot } from "./nearest-workspace-root.ts";
72
76
  import { createLectorPackageSourceOperations } from "./package-source-operations.ts";
73
77
  import { formatPackageSourceCall, formatPackageSourceResult } from "./package-source-rendering.ts";
74
78
  import { createLectorReadOperations } from "./read-operations.ts";
79
+ import { createReferenceBasedRenameOperations } from "./reference-based-rename-operations.ts";
80
+ import { createRenameOperations } from "./rename-operations.ts";
81
+ import { createRepoCacheListOperations } from "./repo-cache-list-operations.ts";
75
82
  import { createLectorRepoFetchOperations } from "./repo-fetch-operations.ts";
76
83
  import { formatRepoFetchCall, formatRepoFetchResult } from "./repo-fetch-rendering.ts";
77
84
  import { createLectorSearchOperations } from "./search-operations.ts";
@@ -115,63 +122,115 @@ function renderIntelligenceSource(body: string, provenance: IntelligenceProvenan
115
122
  */
116
123
  export default function (pi: ExtensionAPI) {
117
124
  const cacheOperations = createWorkspaceCacheOperations();
118
- let cacheRun = 0;
119
- let cacheState: CachePresentationState | undefined;
120
- let lastInjectedCacheState: string | undefined;
125
+ // One generation counter shared by every root's monitor loop, not per-root -- a new session
126
+ // (or shutdown) invalidates every previous session's in-flight monitor regardless of which
127
+ // root it tracked, and there is exactly one "current session" at a time.
128
+ let sessionGeneration = 0;
129
+ // Every workspace root actually touched so far this session, not just one fixed cwd root --
130
+ // populated by setNewWorkspaceObserver below, the real "first touch" trigger.
131
+ const cacheStatesByRoot = new Map<string, CachePresentationState>();
132
+ // Roots already monitored this session -- guards against starting the SAME root's monitor
133
+ // twice: session_start's own direct kick-off for the cwd root itself calls
134
+ // cacheOperations.status(), which registers that root via workspace.registerPath, which fires
135
+ // setNewWorkspaceObserver for it a moment later -- without this guard that would start a
136
+ // second, redundant concurrent monitor loop for the exact same root.
137
+ const monitoringRoots = new Set<string>();
138
+ let lastInjectedSummary: string | undefined;
139
+ let uiContext: Parameters<Parameters<ExtensionAPI["on"]>[1]>[1] | undefined;
140
+
141
+ function combinedSummary(): string {
142
+ const states = [...cacheStatesByRoot.values()];
143
+ if (states.length === 0) return "";
144
+ const [only] = states;
145
+ if (states.length === 1 && only) return describeCacheState(only);
146
+ const counts = new Map<string, number>();
147
+ for (const state of states) counts.set(state.status, (counts.get(state.status) ?? 0) + 1);
148
+ return [...counts.entries()].map(([status, count]) => `${count} ${status}`).join(", ");
149
+ }
150
+
151
+ function refreshStatusBar(): void {
152
+ if (!uiContext) return;
153
+ const summary = combinedSummary();
154
+ if (!summary) {
155
+ uiContext.ui.setStatus("lector-cache", undefined);
156
+ return;
157
+ }
158
+ const states = [...cacheStatesByRoot.values()];
159
+ const worst = states.some((state) => state.status === "not-cached" || state.status === "caching")
160
+ ? "warning"
161
+ : states.every((state) => state.status === "cached")
162
+ ? "success"
163
+ : "accent";
164
+ uiContext.ui.setStatus("lector-cache", uiContext.ui.theme.fg(worst, `Lector: ${summary}`));
165
+ }
166
+
167
+ /** Starts (or restarts, on a stale generation) monitoring one workspace root's cache lifecycle -- shared by session_start's own cwd root and every later root a tool call first touches. */
168
+ function startMonitoringRoot(root: string, ctx: Parameters<Parameters<ExtensionAPI["on"]>[1]>[1]): void {
169
+ if (monitoringRoots.has(root)) return;
170
+ monitoringRoots.add(root);
171
+ const thisGeneration = sessionGeneration;
172
+ void monitorWorkspaceCache(cacheOperations, {
173
+ directory: root,
174
+ maxFiles: 500,
175
+ maxSymbolsPerFile: 100,
176
+ pollIntervalMs: 1_000,
177
+ maxPolls: 300,
178
+ shouldContinue: () => sessionGeneration === thisGeneration,
179
+ onState: (state) => {
180
+ if (sessionGeneration !== thisGeneration) return;
181
+ cacheStatesByRoot.set(root, state);
182
+ if (state.status === "finished-caching") {
183
+ if (ctx.hasUI) ctx.ui.notify(`Lector finished caching ${root}`, "info");
184
+ return;
185
+ }
186
+ refreshStatusBar();
187
+ },
188
+ }).catch((error: unknown) => {
189
+ if (sessionGeneration !== thisGeneration) return;
190
+ const message = error instanceof Error ? error.message : String(error);
191
+ cacheStatesByRoot.delete(root);
192
+ refreshStatusBar();
193
+ if (ctx.hasUI) ctx.ui.notify(`Lector cache failed for ${root}: ${message}`, "error");
194
+ });
195
+ }
121
196
 
122
197
  pi.on("before_agent_start", () => {
123
- if (!cacheState) return;
124
- const description = describeCacheState(cacheState);
125
- if (description === lastInjectedCacheState) return;
126
- lastInjectedCacheState = description;
198
+ const summary = combinedSummary();
199
+ if (!summary || summary === lastInjectedSummary) return;
200
+ lastInjectedSummary = summary;
201
+ const messages = [...cacheStatesByRoot.entries()]
202
+ .filter(([, state]) => state.status !== "cached")
203
+ .map(([root, state]) => `${root}: ${cacheContextMessage(state)}`);
204
+ if (messages.length === 0) return;
127
205
  return {
128
206
  message: {
129
207
  customType: "lector-cache-status",
130
- content: cacheContextMessage(cacheState),
208
+ content: messages.join("\n"),
131
209
  display: false,
132
210
  },
133
211
  };
134
212
  });
135
213
 
136
214
  pi.on("session_shutdown", (_event, ctx) => {
137
- cacheRun++;
138
- cacheState = undefined;
139
- lastInjectedCacheState = undefined;
215
+ sessionGeneration++;
216
+ cacheStatesByRoot.clear();
217
+ monitoringRoots.clear();
218
+ lastInjectedSummary = undefined;
219
+ uiContext = undefined;
140
220
  ctx.ui.setStatus("lector-cache", undefined);
141
221
  });
142
222
 
143
223
  pi.on("session_start", (_event, ctx) => {
144
224
  const { cwd } = ctx;
225
+ sessionGeneration++;
226
+ cacheStatesByRoot.clear();
227
+ monitoringRoots.clear();
228
+ lastInjectedSummary = undefined;
229
+ uiContext = ctx;
230
+ setNewWorkspaceObserver((root) => startMonitoringRoot(root, ctx));
145
231
  const projectRoot = nearestGitRoot(cwd);
146
- const thisRun = ++cacheRun;
147
- cacheState = undefined;
148
- lastInjectedCacheState = undefined;
149
- if (projectRoot) {
150
- void monitorWorkspaceCache(cacheOperations, {
151
- directory: projectRoot,
152
- maxFiles: 500,
153
- maxSymbolsPerFile: 100,
154
- pollIntervalMs: 1_000,
155
- maxPolls: 300,
156
- shouldContinue: () => cacheRun === thisRun,
157
- onState: (state) => {
158
- cacheState = state;
159
- if (state.status === "finished-caching") {
160
- if (ctx.hasUI) ctx.ui.notify(`Lector finished caching ${projectRoot}`, "info");
161
- return;
162
- }
163
- const color = state.status === "cached" ? "success" : state.status === "caching" ? "accent" : "warning";
164
- ctx.ui.setStatus("lector-cache", ctx.ui.theme.fg(color, `Lector: ${describeCacheState(state)}`));
165
- },
166
- }).catch((error: unknown) => {
167
- if (cacheRun !== thisRun) return;
168
- const message = error instanceof Error ? error.message : String(error);
169
- ctx.ui.setStatus("lector-cache", ctx.ui.theme.fg("error", "Lector: cache error"));
170
- if (ctx.hasUI) ctx.ui.notify(`Lector cache failed: ${message}`, "error");
171
- });
172
- } else {
173
- ctx.ui.setStatus("lector-cache", undefined);
174
- }
232
+ if (projectRoot) startMonitoringRoot(projectRoot, ctx);
233
+ else ctx.ui.setStatus("lector-cache", undefined);
175
234
 
176
235
  pi.registerTool(createReadToolDefinition(cwd, { operations: createLectorReadOperations() }));
177
236
  pi.registerTool(createWriteToolDefinition(cwd, { operations: createLectorWriteOperations() }));
@@ -241,6 +300,8 @@ export default function (pi: ExtensionAPI) {
241
300
  });
242
301
 
243
302
  const codeIntelligenceOperations = createLectorCodeIntelligenceOperations();
303
+ const referenceBasedRenameOperations = createReferenceBasedRenameOperations();
304
+ const renameOperations = createRenameOperations();
244
305
  const positionParameters = {
245
306
  path: Type.String({ description: "Absolute or cwd-relative path to the file" }),
246
307
  line: Type.Number({ description: "1-indexed line number" }),
@@ -622,6 +683,125 @@ export default function (pi: ExtensionAPI) {
622
683
  },
623
684
  });
624
685
 
686
+ pi.registerTool({
687
+ name: "reference_based_rename",
688
+ label: "Reference-Based Rename",
689
+ description:
690
+ "Move/rename a file and rewrite every static import/export specifier the workspace's own populated symbol graph knows references it -- atomically, rolled back entirely on any failure. Non-LSP: uses find_references + a real parse of import/export declarations, not a language server's own rename. Refuses outright (touches nothing) unless the workspace's symbol graph is fully populated and current for the given bounds -- a partial rename that silently misses a reference is worse than refusing (Sourcegraph's CodeScaleBench finding). Does not follow dynamic import(expr)/require(expr) or any plain string reference to the file -- always check the returned caveats.",
691
+ promptSnippet: "Move a file and update every import that references it",
692
+ promptGuidelines: [
693
+ "Run populate_symbol_graph for this workspace first if cache_status/has_warm_index doesn't already show a fully cached (never partial) graph -- reference_based_rename refuses outright otherwise.",
694
+ "Always read the returned caveats: this never rewrites a dynamic import(expr)/require(expr) or a plain string reference to the old path, even if one exists.",
695
+ ],
696
+ parameters: Type.Object({
697
+ fromPath: Type.String({ description: "Absolute or cwd-relative path to the file to move" }),
698
+ toPath: Type.String({ description: "Absolute or cwd-relative path for its new location" }),
699
+ maxFiles: Type.Number({ description: "Maximum number of source files the workspace's symbol graph must have scanned" }),
700
+ maxSymbolsPerFile: Type.Number({ description: "Maximum number of declarations per file the workspace's symbol graph must have processed" }),
701
+ }),
702
+ async execute(_toolCallId, params) {
703
+ const fromPath = resolve(cwd, params.fromPath);
704
+ const toPath = resolve(cwd, params.toPath);
705
+ const outcome = await referenceBasedRenameOperations.rename(fromPath, toPath, params.maxFiles, params.maxSymbolsPerFile);
706
+ const lines = [
707
+ `moved to ${outcome.movedTo}`,
708
+ outcome.filesUpdated.length === 0
709
+ ? "no other files referenced it"
710
+ : `updated imports in ${outcome.filesUpdated.length} file(s): ${outcome.filesUpdated.join(", ")}`,
711
+ ...outcome.caveats.map((caveat) => `caveat: ${caveat}`),
712
+ ];
713
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { outcome } };
714
+ },
715
+ renderCall(args, theme, context) {
716
+ const fromPath = typeof args.fromPath === "string" ? args.fromPath : "";
717
+ const toPath = typeof args.toPath === "string" ? args.toPath : "";
718
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
719
+ text.setText(
720
+ `${theme.fg("toolTitle", theme.bold("reference_based_rename"))} ${theme.fg("accent", fromPath)} ${theme.fg("dim", "->")} ${theme.fg("accent", toPath)}`,
721
+ );
722
+ return text;
723
+ },
724
+ renderResult(result, { isPartial }, theme, context) {
725
+ if (isPartial) return new Text(theme.fg("warning", "Renaming..."), 0, 0);
726
+ if (context.isError) {
727
+ const errorText = result.content
728
+ .filter((block) => block.type === "text")
729
+ .map((block) => block.text)
730
+ .join("\n");
731
+ return new Text(theme.fg("error", errorText || "reference_based_rename failed"), 0, 0);
732
+ }
733
+ const details = result.details as { outcome?: { movedTo: string; filesUpdated: readonly string[] } } | undefined;
734
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
735
+ text.setText(
736
+ details?.outcome
737
+ ? `${theme.fg("success", "moved")} ${theme.fg("accent", details.outcome.movedTo)} ${theme.fg("dim", `(${details.outcome.filesUpdated.length} import(s) updated)`)}`
738
+ : theme.fg("success", "rename complete"),
739
+ );
740
+ return text;
741
+ },
742
+ });
743
+
744
+ interface RenameToolDetails {
745
+ prepared?: OperationOutputs["workspace.prepareRename"];
746
+ applied?: OperationOutputs["workspace.rename"];
747
+ }
748
+
749
+ pi.registerTool({
750
+ name: "rename",
751
+ label: "Rename",
752
+ description:
753
+ "LSP-driven rename via the negotiated language server's own textDocument/prepareRename and textDocument/rename -- the semantic sibling of reference_based_rename, cross-file and identity-aware (resolves through re-exports/aliasing, not just static import specifiers), but only where the workspace's language server actually implements rename. prepare checks whether the symbol at a position can be renamed at all before committing; apply requests the rename and applies the server's own WorkspaceEdit atomically across every file it touches, rolled back entirely on any failure. Actions: prepare, apply.",
754
+ promptSnippet: "Rename a symbol everywhere it's used, via the language server",
755
+ promptGuidelines: [
756
+ "Call prepare first when unsure a position is renameable -- a null range means nothing to rename there, not an error.",
757
+ "apply fails outright if the negotiated server never advertised rename support -- reference_based_rename is the non-LSP fallback for that case.",
758
+ ],
759
+ parameters: Type.Object({
760
+ action: Type.String({ description: "prepare | apply" }),
761
+ ...positionParameters,
762
+ newName: Type.Optional(Type.String({ description: "Required for apply" })),
763
+ }),
764
+ async execute(_toolCallId, params): Promise<{ content: [{ type: "text"; text: string }]; details: RenameToolDetails }> {
765
+ const path = resolve(cwd, params.path);
766
+ if (params.action === "prepare") {
767
+ const prepared = await renameOperations.prepareRename(path, params.line, params.character);
768
+ const text = prepared.range
769
+ ? `renameable${prepared.range.placeholder ? `: "${prepared.range.placeholder}"` : ""}`
770
+ : "nothing renameable at this position";
771
+ return { content: [{ type: "text", text }], details: { prepared } };
772
+ }
773
+ if (params.action === "apply") {
774
+ if (!params.newName) throw new Error("rename apply requires newName");
775
+ const applied = await renameOperations.rename(path, params.line, params.character, params.newName);
776
+ const text = `renamed to "${params.newName}" -- updated ${applied.touchedPaths.length} file(s): ${applied.touchedPaths.join(", ")}`;
777
+ return { content: [{ type: "text", text }], details: { applied } };
778
+ }
779
+ throw new Error(`unknown rename action "${params.action}" -- expected prepare or apply`);
780
+ },
781
+ renderCall(args, theme, context) {
782
+ const action = typeof args.action === "string" ? args.action : "";
783
+ const path = typeof args.path === "string" ? args.path : "";
784
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
785
+ text.setText(`${theme.fg("toolTitle", theme.bold("rename"))} ${theme.fg("dim", action)} ${theme.fg("accent", path)}`);
786
+ return text;
787
+ },
788
+ renderResult(result, { isPartial }, theme, context) {
789
+ if (isPartial) return new Text(theme.fg("warning", "Renaming..."), 0, 0);
790
+ if (context.isError) {
791
+ const errorText = result.content
792
+ .filter((block) => block.type === "text")
793
+ .map((block) => block.text)
794
+ .join("\n");
795
+ return new Text(theme.fg("error", errorText || "rename failed"), 0, 0);
796
+ }
797
+ const text = result.content
798
+ .filter((block) => block.type === "text")
799
+ .map((block) => block.text)
800
+ .join("\n");
801
+ return new Text(theme.fg("success", text), 0, 0);
802
+ },
803
+ });
804
+
625
805
  const symbolAnnotationOperations = createLectorSymbolAnnotationOperations();
626
806
  function resolveAnchorInputs(anchors: readonly { path: string; line: number; character: number }[]): AnnotationAnchorInput[] {
627
807
  return anchors.map((anchor) => ({ path: resolve(cwd, anchor.path), line: anchor.line, character: anchor.character }));
@@ -1165,6 +1345,67 @@ export default function (pi: ExtensionAPI) {
1165
1345
  },
1166
1346
  });
1167
1347
 
1348
+ type MutationHistoryToolDetails =
1349
+ | { readonly action: "list"; readonly entries: readonly MutationHistoryEntry[] }
1350
+ | { readonly action: "revert"; readonly reverted: { readonly path: string; readonly newHash: string | null } };
1351
+
1352
+ const mutationHistoryOperations = createMutationHistoryOperations();
1353
+ pi.registerTool({
1354
+ name: "mutation_history",
1355
+ label: "Mutation History",
1356
+ description:
1357
+ "List or revert a file's recorded edit history. Every successful edit/line_edit/apply_patch is recorded (newest first, bounded, not durable across a daemon restart). Reverting restores the file to its exact content immediately before that entry's own mutation, guarded the same way every Lector write is -- refuses if the file changed since, rather than silently clobbering a newer change. A revert is itself a real, further-revertible mutation -- reverting a revert works.",
1358
+ promptSnippet: "List or revert a file's recorded edit history",
1359
+ promptGuidelines: [
1360
+ "list first to find the entry id you want, then revert -- an id from a different file's history, or one already evicted by the bounded history, fails closed rather than guessing.",
1361
+ ],
1362
+ parameters: Type.Object({
1363
+ action: Type.Union([Type.Literal("list"), Type.Literal("revert")]),
1364
+ path: Type.String({ description: "Absolute or workspace-relative path to the file" }),
1365
+ maxResults: Type.Optional(Type.Number({ description: "Required for action=list -- maximum entries to return, newest first" })),
1366
+ entryId: Type.Optional(Type.String({ description: "Required for action=revert -- an id returned by a prior action=list" })),
1367
+ }),
1368
+ async execute(_toolCallId, params): Promise<AgentToolResult<MutationHistoryToolDetails>> {
1369
+ const absolutePath = resolve(cwd, params.path);
1370
+ if (params.action === "list") {
1371
+ if (params.maxResults === undefined) throw new Error("mutation_history action=list requires maxResults");
1372
+ const entries = await mutationHistoryOperations.list(absolutePath, params.maxResults);
1373
+ const text =
1374
+ entries.length === 0
1375
+ ? "no recorded mutation history for this path"
1376
+ : entries.map((entry) => `${entry.id} ${new Date(entry.timestamp).toISOString()} ${entry.operation}`).join("\n");
1377
+ return { content: [{ type: "text", text }], details: { action: "list", entries } };
1378
+ }
1379
+ if (params.entryId === undefined) throw new Error("mutation_history action=revert requires entryId");
1380
+ const reverted = await mutationHistoryOperations.revert(absolutePath, params.entryId);
1381
+ return {
1382
+ content: [{ type: "text", text: `${reverted.path} reverted -> ${reverted.newHash ?? "(deleted)"}` }],
1383
+ details: { action: "revert", reverted },
1384
+ };
1385
+ },
1386
+ renderCall(args, theme, context) {
1387
+ const action = typeof args.action === "string" ? args.action : "";
1388
+ const path = typeof args.path === "string" ? args.path : "";
1389
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
1390
+ text.setText(`${theme.fg("toolTitle", theme.bold("mutation_history"))} ${theme.fg("accent", action)} ${theme.fg("dim", path)}`);
1391
+ return text;
1392
+ },
1393
+ renderResult(result, { isPartial }, theme, context) {
1394
+ if (isPartial) return new Text(theme.fg("warning", "Working on mutation history..."), 0, 0);
1395
+ if (context.isError) {
1396
+ const errorText = result.content
1397
+ .filter((block) => block.type === "text")
1398
+ .map((block) => block.text)
1399
+ .join("\n");
1400
+ return new Text(theme.fg("error", errorText || "mutation_history failed"), 0, 0);
1401
+ }
1402
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
1403
+ const textBlock = result.content.find((block) => block.type === "text");
1404
+ text.setText(theme.fg("success", textBlock && "text" in textBlock ? textBlock.text : "done"));
1405
+ return text;
1406
+ },
1407
+ });
1408
+
1168
1409
  const packageSourceOperations = createLectorPackageSourceOperations();
1169
1410
  pi.registerTool({
1170
1411
  name: "package_source",
@@ -1205,6 +1446,7 @@ export default function (pi: ExtensionAPI) {
1205
1446
  });
1206
1447
 
1207
1448
  const repoFetchOperations = createLectorRepoFetchOperations();
1449
+ const repoCacheListOperations = createRepoCacheListOperations();
1208
1450
  pi.registerTool({
1209
1451
  name: "repo_fetch",
1210
1452
  label: "Repo Fetch",
@@ -1242,6 +1484,53 @@ export default function (pi: ExtensionAPI) {
1242
1484
  },
1243
1485
  });
1244
1486
 
1487
+ pi.registerTool({
1488
+ name: "repo_cache_list",
1489
+ label: "Repo Cache List",
1490
+ description:
1491
+ "Lists and queries repo_fetch's own on-disk cache -- no network call, no cache mutation. Filter by any combination of host/owner/repo/ref (exact match) and text (case-insensitive substring across host/owner/repo/refs). Each entry reports whether it's currently a registered workspace (usable directly by other tools) or just present on disk. Bounded and paginated via cursor.",
1492
+ promptSnippet: "List or search previously-fetched external repositories",
1493
+ parameters: Type.Object({
1494
+ text: Type.Optional(Type.String({ description: "Case-insensitive substring match across host/owner/repo/refs" })),
1495
+ host: Type.Optional(Type.String({ description: "Exact host match, e.g. github.com" })),
1496
+ owner: Type.Optional(Type.String()),
1497
+ repo: Type.Optional(Type.String()),
1498
+ ref: Type.Optional(Type.String({ description: "Matches either the requested or the resolved ref" })),
1499
+ maxResults: Type.Number({ description: "Maximum entries to return in this page" }),
1500
+ cursor: Type.Optional(Type.String({ description: "Opaque cursor from a prior call's nextCursor, to fetch the next page" })),
1501
+ }),
1502
+ async execute(_toolCallId, params) {
1503
+ const page = await repoCacheListOperations.list(
1504
+ { text: params.text, host: params.host, owner: params.owner, repo: params.repo, ref: params.ref },
1505
+ params.maxResults,
1506
+ params.cursor,
1507
+ );
1508
+ return { content: [{ type: "text", text: JSON.stringify(page) }], details: { page } };
1509
+ },
1510
+ renderCall(_args, theme, context) {
1511
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
1512
+ text.setText(`${theme.fg("toolTitle", theme.bold("repo_cache_list"))}`);
1513
+ return text;
1514
+ },
1515
+ renderResult(result, { isPartial }, theme, context) {
1516
+ if (isPartial) return new Text(theme.fg("warning", "Listing cached repositories..."), 0, 0);
1517
+ if (context.isError) {
1518
+ const errorText = result.content
1519
+ .filter((block) => block.type === "text")
1520
+ .map((block) => block.text)
1521
+ .join("\n");
1522
+ return new Text(theme.fg("error", errorText || "repo_cache_list failed"), 0, 0);
1523
+ }
1524
+ const details = result.details as
1525
+ | { page?: { entries: readonly { host: string; owner: string; repo: string }[]; nextCursor: string | null } }
1526
+ | undefined;
1527
+ const text = context.lastComponent instanceof Text ? context.lastComponent : new Text("", 0, 0);
1528
+ const count = details?.page?.entries.length ?? 0;
1529
+ text.setText(count === 0 ? theme.fg("dim", "no cached repositories") : theme.fg("success", `${count} cached repositor${count === 1 ? "y" : "ies"}`));
1530
+ return text;
1531
+ },
1532
+ });
1533
+
1245
1534
  const crossWorkspaceSearchOperations = createLectorCrossWorkspaceSearchOperations();
1246
1535
  pi.registerTool({
1247
1536
  name: "find_symbols_across_projects",
@@ -39,6 +39,19 @@ let connector: ClientConnector = () => connectLectorClient();
39
39
  const retryingClient: RetryingClient<LectorClient> = createRetryingClient(() => connector(), { label: "Lector" });
40
40
  const workspaceIdByRoot = new Map<string, WorkspaceId>();
41
41
 
42
+ /**
43
+ * Fires exactly once per distinct root, the moment it's first registered in this process --
44
+ * never on a later call that reuses the cached workspaceId. The single choke point every
45
+ * resolver (workspaceForPath, workspaceForDirectory, workspaceForCodeIntelligencePath,
46
+ * workspaceForPathOrDirectory) funnels through, so this is genuinely "the first time any tool
47
+ * call resolves this workspace," not just the one cwd workspace at session start.
48
+ */
49
+ let onNewWorkspace: ((root: string) => void) | undefined;
50
+
51
+ export function setNewWorkspaceObserver(observer: ((root: string) => void) | undefined): void {
52
+ onNewWorkspace = observer;
53
+ }
54
+
42
55
  export interface RetryingLectorClient {
43
56
  call<Name extends OperationName>(operation: Name, input: OperationInputs[Name]): Promise<OperationOutputs[Name]>;
44
57
  }
@@ -64,6 +77,7 @@ async function workspaceForRoot(root: string): Promise<ResolvedWorkspace> {
64
77
  const client = await lectorClient();
65
78
  const { workspaceId } = await client.call("workspace.registerPath", { path: root });
66
79
  workspaceIdByRoot.set(root, workspaceId);
80
+ onNewWorkspace?.(root);
67
81
  return { workspaceId, root };
68
82
  }
69
83
 
@@ -0,0 +1,34 @@
1
+ import type { MutationHistoryEntry } from "@danypops/lector";
2
+ import { lectorClient, withWorkspace, workspaceForPath } from "./lector-client.ts";
3
+ import { toWorkspaceRelativePath } from "./workspace-relative-path.ts";
4
+
5
+ /** Thin wrapper over Lector's mutation history: every successful edit is recorded, and any entry can be reverted -- guarded the same way every other Lector write is. */
6
+ export interface MutationHistoryOperations {
7
+ list(absolutePath: string, maxResults: number): Promise<readonly MutationHistoryEntry[]>;
8
+ revert(absolutePath: string, entryId: string): Promise<{ path: string; newHash: string | null }>;
9
+ }
10
+
11
+ export function createMutationHistoryOperations(): MutationHistoryOperations {
12
+ return {
13
+ list(absolutePath, maxResults) {
14
+ return withWorkspace(
15
+ () => workspaceForPath(absolutePath),
16
+ async ({ workspaceId, root }) => {
17
+ const client = await lectorClient();
18
+ const path = toWorkspaceRelativePath(root, absolutePath);
19
+ const { entries } = await client.call("workspace.mutationHistory", { workspaceId, path, maxResults });
20
+ return entries;
21
+ },
22
+ );
23
+ },
24
+ revert(absolutePath, entryId) {
25
+ return withWorkspace(
26
+ () => workspaceForPath(absolutePath),
27
+ async ({ workspaceId }) => {
28
+ const client = await lectorClient();
29
+ return client.call("workspace.revertMutation", { workspaceId, entryId });
30
+ },
31
+ );
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,26 @@
1
+ import type { OperationOutputs } from "@danypops/lector";
2
+ import { lectorClient, withWorkspace, workspaceForCodeIntelligencePath } from "./lector-client.ts";
3
+
4
+ /**
5
+ * Thin wrapper over Lector's non-LSP reference-based rename: moves a file and rewrites every
6
+ * static import/export specifier the workspace's own populated symbol graph knows references it.
7
+ * `fromPath` resolves its own workspace (workspaceForCodeIntelligencePath -- this spawns a real
8
+ * language server), matching every other code-intelligence operation's convention.
9
+ */
10
+ export interface ReferenceBasedRenameOperations {
11
+ rename(fromPath: string, toPath: string, maxFiles: number, maxSymbolsPerFile: number): Promise<OperationOutputs["workspace.referenceBasedRename"]>;
12
+ }
13
+
14
+ export function createReferenceBasedRenameOperations(): ReferenceBasedRenameOperations {
15
+ return {
16
+ async rename(fromPath, toPath, maxFiles, maxSymbolsPerFile) {
17
+ return withWorkspace(
18
+ () => workspaceForCodeIntelligencePath(fromPath),
19
+ async ({ workspaceId }) => {
20
+ const client = await lectorClient();
21
+ return client.call("workspace.referenceBasedRename", { workspaceId, fromPath, toPath, maxFiles, maxSymbolsPerFile });
22
+ },
23
+ );
24
+ },
25
+ };
26
+ }
@@ -0,0 +1,36 @@
1
+ import type { OperationOutputs } from "@danypops/lector";
2
+ import { lectorClient, withWorkspace, workspaceForCodeIntelligencePath } from "./lector-client.ts";
3
+
4
+ /**
5
+ * Thin wrappers over Lector's LSP-driven prepareRename/rename -- position-based (path + 1-indexed
6
+ * line + character), matching every other code-intelligence operation's convention. `path`
7
+ * resolves its own workspace per call (workspaceForCodeIntelligencePath -- spawns a real
8
+ * language server).
9
+ */
10
+ export interface RenameOperations {
11
+ prepareRename(path: string, line: number, character: number): Promise<OperationOutputs["workspace.prepareRename"]>;
12
+ rename(path: string, line: number, character: number, newName: string): Promise<OperationOutputs["workspace.rename"]>;
13
+ }
14
+
15
+ export function createRenameOperations(): RenameOperations {
16
+ return {
17
+ async prepareRename(path, line, character) {
18
+ return withWorkspace(
19
+ () => workspaceForCodeIntelligencePath(path),
20
+ async ({ workspaceId }) => {
21
+ const client = await lectorClient();
22
+ return client.call("workspace.prepareRename", { workspaceId, path, line, character });
23
+ },
24
+ );
25
+ },
26
+ async rename(path, line, character, newName) {
27
+ return withWorkspace(
28
+ () => workspaceForCodeIntelligencePath(path),
29
+ async ({ workspaceId }) => {
30
+ const client = await lectorClient();
31
+ return client.call("workspace.rename", { workspaceId, path, line, character, newName });
32
+ },
33
+ );
34
+ },
35
+ };
36
+ }
@@ -0,0 +1,24 @@
1
+ import type { CachedRepositoryPage } from "@danypops/lector";
2
+ import { lectorClient } from "./lector-client.ts";
3
+
4
+ /**
5
+ * Thin wrapper over repo.listCache -- no network, no cache mutation, no `directory`/
6
+ * workspaceForDirectory resolution (matching repo-fetch-operations.ts: this queries the
7
+ * daemon-wide fetch cache, not a workspace-scoped concept).
8
+ */
9
+ export interface RepoCacheListOperations {
10
+ list(
11
+ filters: { text?: string; host?: string; owner?: string; repo?: string; ref?: string },
12
+ maxResults: number,
13
+ cursor?: string,
14
+ ): Promise<CachedRepositoryPage>;
15
+ }
16
+
17
+ export function createRepoCacheListOperations(): RepoCacheListOperations {
18
+ return {
19
+ async list(filters, maxResults, cursor) {
20
+ const client = await lectorClient();
21
+ return client.call("repo.listCache", { ...filters, maxResults, cursor });
22
+ },
23
+ };
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danypops/pi-lector",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Pi host adapter for Lector: overrides read/write/edit with a daemon-backed, hash-guarded filesystem",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "dependencies": {
21
21
  "@danypops/daemon-kit": "^0.22.1",
22
- "@danypops/lector": "^0.3.0"
22
+ "@danypops/lector": "^0.5.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@earendil-works/pi-ai": "^0.81.1",