This repository was archived by the owner on Aug 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
2303 lines (2205 loc) · 90.8 KB
/
Copy pathserver.ts
File metadata and controls
2303 lines (2205 loc) · 90.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Code Intelligence — exact discovery and conservative code context for BB agents.
*
* What separates this from a graph indexer: the answer carries a completeness
* report, and the plugin records what the agent did afterwards. Both are only
* possible from inside the IDE — an MCP server sees its own call and nothing
* else.
*/
import { readFile, stat, writeFile } from "node:fs/promises";
import { join, resolve as resolvePath } from "node:path";
import { defineRpcContract, type BbPluginApi } from "@bb/plugin-sdk";
import ignore, { type Ignore } from "ignore";
import { z } from "zod";
import { chao1, frequenciesFromCaptures } from "./src/math/richness.js";
import { listRepositorySourceFiles } from "./src/graph/scan.js";
import { extractFile, type CodeSymbol, type FileExtraction } from "./src/graph/extract.js";
import { languageForPath } from "./src/graph/languages.js";
import { resolveProject, type ResolutionResult } from "./src/graph/resolve.js";
import { EMPTY_COCHANGE, loadCochangeIndex } from "./src/cochange.js";
import { mergeIncrementalExtractions } from "./src/incremental-scan.js";
import {
buildIndex,
retrieve,
type BlastRadius,
type IndexInput,
type ResultEdge,
type RetrievalIndex,
type RetrievedSymbol,
} from "./src/retrieval.js";
import { buildInstruction } from "./src/instruction.js";
import { analyzeImpact } from "./src/impact.js";
import {
instantGrepBatch,
instantGrepPreparedSources,
MAX_CONTEXT_LINES,
prepareInstantGrepSources,
type InstantGrepOptions,
type PreparedInstantGrepSource,
} from "./src/instant-grep.js";
import { queryCodebase } from "./src/codebase-query.js";
import {
buildRepositoryContext,
buildRepositoryContextFromSources,
repositoryContextSummary,
type RepositoryContext,
} from "./src/repository-context.js";
import { lookupSymbols } from "./src/symbol-lookup.js";
import { planVerification, runVerification } from "./src/verify-change.js";
import { findDynamicBoundaries, type DynamicBoundary } from "./src/dynamic-boundaries.js";
import { IndexRegistry, type IndexedRoot } from "./src/index-registry.js";
import { readProjectPath } from "./src/project-path.js";
import { parseContextArgs } from "./src/cli.js";
import {
collectRemoteSources,
formatRemoteInventory,
remoteInventoryBlindSpots,
type RemoteInventory,
} from "./src/remote-inventory.js";
import {
agentToolsForSurface,
mergeCodeGraphConfig,
normalizeCodeGraphConfig,
type CodeGraphConfig,
type CodeGraphConfigPatch,
} from "./src/config.js";
import {
PERSISTENCE_MIGRATIONS,
exportSnapshot,
importSnapshot,
checkFreshness,
hashContent,
loadSnapshot,
saveSnapshot,
stalenessNote,
type Snapshot,
} from "./src/persistence.js";
import {
FEEDBACK_SURFACE_MIGRATIONS,
MIGRATIONS,
deriveOutcome,
summarizeFeedback,
type FeedbackSurface,
type PendingAnswer,
type ThreadEvent,
} from "./src/feedback.js";
/** Lexical features read at most this many lines of a symbol's body. */
const BODY_LINE_LIMIT = 40;
const CONFIG_KEY = "config.v1";
const configSchema = z.object({
autoIndex: z.boolean(),
respectGitignore: z.boolean(),
includeHiddenDirectories: z.boolean(),
backgroundRefresh: z.boolean(),
refreshIntervalSeconds: z.number().int().min(5).max(3_600),
warmLimit: z.number().int().min(0).max(50),
includeSnippets: z.boolean(),
useCochange: z.boolean(),
defaultBudgetTokens: z.number().int().min(256).max(32_000),
// An A/B knob, exposed so the two instruction changes can be measured apart.
instructionStyle: z.enum(["playbook", "budget", "short", "off"]),
toolSurface: z.enum(["lean", "full"]),
});
const configPatchSchema = configSchema.partial().strict();
const indexViewSchema = z.object({
root: z.string().nullable(),
indexed: z.boolean(),
indexing: z.boolean(),
files: z.number().int(),
symbols: z.number().int(),
indexedAtMs: z.number().int().nullable(),
staleness: z.string().nullable(),
remoteInventory: z
.object({
enumerated: z.number().int(),
indexed: z.number().int(),
truncated: z.boolean(),
skipped: z.object({
ignored: z.number().int(),
excluded: z.number().int(),
tooLarge: z.number().int(),
nonUtf8: z.number().int(),
}),
})
.nullable(),
});
export const rpcContract = defineRpcContract({
status: {
input: z.null(),
output: z.object({
indexed: z.boolean(),
root: z.string().nullable(),
symbols: z.number().int(),
edges: z.number().int(),
graphCompleteness: z.number(),
answersRecorded: z.number().int(),
outcomesRecorded: z.number().int(),
hitRate: z.number().nullable(),
indexes: z.array(
z.object({
root: z.string(),
symbols: z.number().int(),
edges: z.number().int(),
graphCompleteness: z.number(),
indexedAtMs: z.number().int(),
}),
),
}),
},
getSettings: {
input: z.object({ projectId: z.string().nullable() }).strict(),
output: z.object({
config: configSchema,
status: indexViewSchema,
}),
},
updateSettings: {
input: configPatchSchema,
output: z.object({ config: configSchema }),
},
reindex: {
input: z
.object({
root: z.string().nullable(),
projectId: z.string().nullable(),
})
.strict(),
output: z.object({
status: indexViewSchema,
}),
},
});
export default async function plugin(bb: BbPluginApi) {
let config = normalizeCodeGraphConfig(await bb.storage.kv.get<unknown>(CONFIG_KEY));
const db = bb.storage.database();
// Preserve the index of every shipped migration. `storage.migrate` uses the
// statement position as its durable id, so new feedback schema statements
// belong strictly after the existing persistence sequence.
bb.storage.migrate(db, [...MIGRATIONS, ...PERSISTENCE_MIGRATIONS, ...FEEDBACK_SURFACE_MIGRATIONS]);
const indexes = new IndexRegistry<RetrievalIndex>();
const repositoryContexts = new Map<string, { indexedAtMs: number; context: RepositoryContext }>();
/** Repository selected per BB project; never use another project's last root in an agent prompt. */
const rootsByProject = new Map<string, string>();
let activeRoot: string | null = null;
/** Last persisted snapshot per root, for freshness reporting. */
const snapshots = new Map<string, Snapshot>();
/** Staleness note per root, refreshed by the sweep below. */
const staleness = new Map<string, string | null>();
/** Roots currently being built, surfaced to the settings page. */
const indexingRoots = new Set<string>();
/** Environment-routed workspaces indexed through the BB host-file API. */
const remoteWorkspaces = new Map<
string,
{
readonly path: string;
readonly projectId: string;
readonly environmentId: string;
readonly hostId: string;
}
>();
/** Last complete host-file snapshot for a remote workspace. */
const remoteSources = new Map<string, ReadonlyMap<string, string>>();
/** Sorted and line-split alongside each remote snapshot for the search hot path. */
const preparedRemoteSources = new Map<string, readonly PreparedInstantGrepSource[]>();
/** Last host-file inventory report for each remote workspace. */
const remoteInventories = new Map<string, RemoteInventory>();
/** Every retrieval answer awaiting a per-surface outcome, keyed by thread. */
const pending = new Map<string, PendingAnswer[]>();
interface RepositoryState {
readonly sources: ReadonlyMap<string, string>;
readonly fileHashes: ReadonlyMap<string, string>;
readonly remoteInventory?: RemoteInventory;
}
const throwIfAborted = (signal?: AbortSignal) => {
if (signal?.aborted) throw new Error("indexing aborted");
};
const rootLabel = (root: string): string => remoteWorkspaces.get(root)?.path ?? root;
const isRemoteRoot = (root: string): boolean => remoteWorkspaces.has(root);
const inventoryLimits = (root: string): readonly string[] => remoteInventoryBlindSpots(remoteInventories.get(root));
const inventoryLimitField = (root: string): Record<string, readonly string[]> => {
const limits = inventoryLimits(root);
return limits.length === 0 ? {} : { inventoryLimits: limits };
};
async function readRemoteRepositoryState(root: string, signal?: AbortSignal): Promise<RepositoryState> {
const workspace = remoteWorkspaces.get(root);
if (workspace === undefined) throw new Error(`remote workspace is unavailable: ${root}`);
const listed = await bb.sdk.projects.paths({
projectId: workspace.projectId,
environmentId: workspace.environmentId,
includeFiles: "true",
includeDirectories: "false",
limit: "10000",
signal,
});
let ignored: Ignore | null = null;
if (config.respectGitignore) {
try {
const gitignore = await bb.sdk.projects.fileContent({
projectId: workspace.projectId,
environmentId: workspace.environmentId,
path: ".gitignore",
signal,
});
if (gitignore.contentEncoding === "utf8") ignored = ignore().add(gitignore.content);
} catch {
// A missing or unreadable .gitignore leaves the permanent exclusions below.
}
}
const paths = listed.paths.map((entry) => entry.path.replace(/^\.\//, ""));
const collection = await collectRemoteSources({
paths,
truncated: listed.truncated,
isIgnored: (file) => ignored !== null && ignored.ignores(file),
isExcluded: (file) =>
file
.split("/")
.some(
(part) =>
part.startsWith(".") ||
["node_modules", "dist", "build", "out", "target", "vendor", "venv", "__pycache__", "coverage"].includes(
part,
),
),
throwIfAborted: () => throwIfAborted(signal),
read: async (file) => {
throwIfAborted(signal);
return bb.sdk.projects.fileContent({
projectId: workspace.projectId,
environmentId: workspace.environmentId,
path: file,
signal,
});
},
});
const fileHashes = new Map([...collection.sources].map(([file, source]) => [file, hashContent(source)]));
remoteSources.set(root, collection.sources);
preparedRemoteSources.set(root, prepareInstantGrepSources(collection.sources));
remoteInventories.set(root, collection.inventory);
return { sources: collection.sources, fileHashes, remoteInventory: collection.inventory };
}
async function readRepositoryState(root: string, signal?: AbortSignal): Promise<RepositoryState> {
if (isRemoteRoot(root)) return readRemoteRepositoryState(root, signal);
const inventory = await listRepositorySourceFiles({
root,
respectGitignore: config.respectGitignore,
includeHiddenDirectories: config.includeHiddenDirectories,
});
const sources = new Map<string, string>();
const fileHashes = new Map<string, string>();
for (const file of inventory.files) {
throwIfAborted(signal);
const source = await readFile(join(root, file), "utf8");
sources.set(file, source);
fileHashes.set(file, hashContent(source));
}
return { sources, fileHashes };
}
async function buildRootIndex(root: string, observed?: RepositoryState, signal?: AbortSignal) {
if (!isRemoteRoot(root)) {
const rootStat = await stat(root);
if (!rootStat.isDirectory()) throw new Error(`not a directory: ${root}`);
}
throwIfAborted(signal);
const started = Date.now();
const stored = loadSnapshot(db, root);
const state = observed ?? (await readRepositoryState(root, signal));
const linesByFile = new Map<string, string[]>();
const linesOf = (file: string): string[] | undefined => {
const existing = linesByFile.get(file);
if (existing !== undefined) return existing;
const source = state.sources.get(file);
if (source === undefined) return undefined;
const lines = source.split("\n");
linesByFile.set(file, lines);
return lines;
};
let unparseable = 0;
/**
* A file the parser cannot handle costs that file, not the repository.
*
* Indexing used to abort on the first failure, and on real-world code that
* is not a rare event: prettier keeps deliberately malformed sources as
* test fixtures, one of them overflowed the AST walk, and every task on
* that repository failed. This path reads sources once and parses them
* directly, so the per-file guard lives beside that parsing loop.
*/
const parseFile = async (file: string): Promise<FileExtraction> => {
throwIfAborted(signal);
const source = state.sources.get(file);
const language = languageForPath(file);
if (source === undefined || language === null) {
throw new Error(`could not parse indexed file: ${file}`);
}
return extractFile(file, language, source);
};
const parseFileOrSkip = async (file: string): Promise<FileExtraction | null> => {
// Remote snapshots also carry a tiny allowlist of orientation files;
// they participate in freshness/context but are deliberately not source
// extraction failures.
if (languageForPath(file) === null) return null;
try {
return await parseFile(file);
} catch (error) {
throwIfAborted(signal);
unparseable++;
bb.log.warn(`skipped ${file}: ${String(error).slice(0, 120)}`);
return null;
}
};
let scan: IndexInput;
let resolution: ResolutionResult | null = null;
let extractions: readonly FileExtraction[];
let mode: "restored" | "indexed" | "updated";
let changedFiles = 0;
if (stored === null) {
bb.log.info(`indexing ${rootLabel(root)}`);
const parsed: FileExtraction[] = [];
for (const file of state.sources.keys()) {
const extraction = await parseFileOrSkip(file);
if (extraction !== null) parsed.push(extraction);
}
extractions = parsed;
resolution = resolveProject(extractions);
scan = {
symbols: resolution.symbols,
edges: resolution.edges,
fileImports: resolution.fileImports,
typeRelations: resolution.typeRelations,
ambiguousCalls: resolution.stats.ambiguous,
};
mode = "indexed";
} else {
const freshness = checkFreshness(stored, state.fileHashes);
if (freshness.upToDate) {
extractions = stored.extractions;
scan = {
symbols: stored.symbols,
edges: stored.edges,
typeRelations: stored.typeRelations,
ambiguousCalls: stored.ambiguousCalls,
};
mode = "restored";
} else {
changedFiles = freshness.changed.length + freshness.added.length + freshness.removed.length;
bb.log.info(
`incremental refresh ${rootLabel(root)}: ${freshness.changed.length} changed, ` +
`${freshness.added.length} new, ${freshness.removed.length} deleted`,
);
extractions = await mergeIncrementalExtractions(stored.extractions, freshness, parseFileOrSkip);
resolution = resolveProject(extractions);
scan = {
symbols: resolution.symbols,
edges: resolution.edges,
fileImports: resolution.fileImports,
typeRelations: resolution.typeRelations,
ambiguousCalls: resolution.stats.ambiguous,
};
mode = "updated";
}
}
const bodyOf = (symbol: CodeSymbol): string => {
const lines = linesOf(symbol.file);
if (lines === undefined) return "";
return lines.slice(symbol.startLine, Math.min(symbol.endLine + 1, symbol.startLine + BODY_LINE_LIMIT)).join("\n");
};
let completenessValue: number;
let completenessReliable: boolean;
if (mode === "restored" && stored !== null) {
completenessValue = stored.completeness;
completenessReliable = stored.completenessReliable;
} else {
const frequencies = frequenciesFromCaptures(resolution!.captureCounts);
const estimate = chao1(
frequencies.observed,
frequencies.singletons,
frequencies.doubletons,
// Ambiguous call sites are edges every strategy declined to propose:
// counted directly rather than extrapolated.
resolution!.stats.ambiguous,
);
completenessValue = estimate.completenessLowerBound;
completenessReliable = estimate.reliable;
}
/**
* An index built from nothing does not get to call itself complete.
*
* When every file failed to parse there are no edges, no singletons and
* no doubletons, and Chao1 dutifully reports 100% — of a sample of zero.
* On NodeBB that is exactly what came out: `0 symbols, completeness >=
* 100.0%`, printed with a straight face while 742 files had failed. For a
* project whose entire claim is honest reporting of what it does not
* know, that is the one output that must never happen.
*/
const parsedFiles = extractions.length;
if (parsedFiles === 0 || unparseable > parsedFiles) {
completenessReliable = false;
bb.log.warn(
`${rootLabel(root)}: parsed ${parsedFiles} files, failed on ${unparseable} — ` + `completeness not reported`,
);
}
// Co-change is rebuilt even when the AST snapshot is reused: git log is
// ~0.1 s for hundreds of commits, and history moves independently of the
// working tree hashes we use for parse freshness.
const cochange = config.useCochange && !isRemoteRoot(root) ? await loadCochangeIndex(root) : EMPTY_COCHANGE;
const index = buildIndex(scan, bodyOf, completenessValue, completenessReliable, {
cochange,
});
const snapshot: Snapshot = {
symbols: scan.symbols,
edges: scan.edges as never,
typeRelations: scan.typeRelations ?? [],
extractions,
fileHashes: state.fileHashes,
ambiguousCalls: scan.ambiguousCalls,
completeness: completenessValue,
completenessReliable,
builtAtMs: mode === "restored" && stored !== null ? stored.builtAtMs : Date.now(),
};
throwIfAborted(signal);
/**
* A failed scan is not written to disk.
*
* Persisting it makes the failure permanent: the snapshot matches the
* file hashes, so every later run restores the empty index instead of
* reparsing, and the repository stays broken until someone deletes the
* row by hand. That is precisely what happened here — NodeBB was stuck
* returning zero symbols long after the parser had been fixed.
*/
const worthKeeping = parsedFiles > 0 && unparseable <= parsedFiles;
if (mode !== "restored" && worthKeeping) saveSnapshot(db, root, snapshot);
snapshots.set(root, snapshot);
staleness.set(root, null);
bb.log.info(
`${mode} ${scan.symbols.length} symbols, ${scan.edges.length} edges` +
(mode === "updated" ? ` from ${changedFiles} changed file(s)` : "") +
(cochange.commitCount > 0 ? `, ${cochange.commitCount} co-change commits` : "") +
` in ${((Date.now() - started) / 1000).toFixed(1)}s, ` +
(completenessReliable
? `completeness >= ${(completenessValue * 100).toFixed(1)}%`
: `completeness not estimable`),
);
return { index, edgeCount: scan.edges.length };
}
async function rebuildIndex(root: string, observed?: RepositoryState, signal?: AbortSignal) {
indexingRoots.add(root);
bb.realtime.publish("index-status", { root, indexing: true });
try {
return await buildRootIndex(root, observed, signal);
} finally {
indexingRoots.delete(root);
bb.realtime.publish("index-status", { root, indexing: false });
}
}
async function ensureIndex(inputRoot: string, signal?: AbortSignal): Promise<IndexedRoot<RetrievalIndex>> {
const root = isRemoteRoot(inputRoot) ? inputRoot : resolvePath(inputRoot);
// Do not bind a caller's AbortSignal into the coalesced build. Concurrent
// ensure() waiters share one promise; if the first caller's signal aborts,
// every waiter would fail even when their own requests are still live.
// Cancellation is checked around the shared work instead.
throwIfAborted(signal);
const ready = await indexes.ensure(root, () => rebuildIndex(root));
throwIfAborted(signal);
await refreshRepositoryContext(ready);
activeRoot = ready.root;
return ready;
}
/**
* Context files are not necessarily source files, so source-index freshness
* cannot invalidate them. Rebuild this tiny fixed-file snapshot separately.
*/
async function refreshRepositoryContext(ready: IndexedRoot<RetrievalIndex>): Promise<void> {
repositoryContexts.set(ready.root, {
indexedAtMs: ready.indexedAtMs,
context: isRemoteRoot(ready.root)
? buildRepositoryContextFromSources(
rootLabel(ready.root),
ready.index,
remoteSources.get(ready.root) ?? new Map(),
)
: await buildRepositoryContext(ready.root, ready.index),
});
}
async function resolveRoot(
projectId: string | null,
requestedRoot: string | null = null,
threadId: string | null = null,
signal?: AbortSignal,
): Promise<string | null> {
if (requestedRoot !== null && requestedRoot !== "") return resolvePath(requestedRoot);
if (projectId === null) return null;
try {
const project = await bb.sdk.projects.get({ projectId, signal });
let hostId: string | undefined;
if (threadId !== null) {
const thread = await bb.sdk.threads.get({ threadId, signal });
if (thread.environmentId !== null) {
const environment = await bb.sdk.environments.get({ environmentId: thread.environmentId, signal });
hostId = environment.hostId;
if (environment.path !== null) {
const key = `remote:${environment.id}:${environment.path}`;
remoteWorkspaces.set(key, {
path: environment.path,
projectId,
environmentId: environment.id,
hostId: environment.hostId,
});
rootsByProject.set(projectId, key);
return key;
}
}
}
const path = readProjectPath(project as never, hostId);
if (path === null) return null;
const root = resolvePath(path);
rootsByProject.set(projectId, root);
return root;
} catch {
return null;
}
}
async function listProjectRoots(): Promise<string[]> {
const roots: string[] = [];
try {
const projects = (await bb.sdk.projects.list()) as unknown;
const list = Array.isArray(projects) ? projects : ((projects as { projects?: unknown[] }).projects ?? []);
for (const project of list) {
const path = readProjectPath(project as never);
if (path !== null) roots.push(resolvePath(path));
}
} catch (error) {
bb.log.warn(`could not list projects: ${String(error)}`);
}
return [...new Set(roots)];
}
async function searchExact(root: string, options: readonly InstantGrepOptions[]) {
if (!isRemoteRoot(root)) return instantGrepBatch(root, options);
// A remote snapshot is acquired by ensureIndex before this is called.
// Keeping the fallback explicit gives an actionable failure rather than
// accidentally running ripgrep against the BB server's similarly named path.
const sources = remoteSources.get(root);
const prepared = preparedRemoteSources.get(root);
if (sources === undefined || prepared === undefined)
throw new Error(`remote workspace is not indexed: ${rootLabel(root)}`);
return Promise.all(
options.map(async (option) => ({
pattern: option.pattern,
...(await instantGrepPreparedSources(prepared, option)),
})),
);
}
/**
* Records every search surface separately. A thread can use an exact search,
* an exploratory query, and graph context in one turn; keeping only the last
* answer would make the feedback loop unable to say which route led to a
* repeated shell search.
*/
async function recordFeedbackAnswer(
input: Omit<PendingAnswer, "answerId" | "answeredAtMs" | "sequenceAtAnswer">,
): Promise<void> {
const sequenceAtAnswer = await currentSequence(bb, input.threadId);
const answeredAtMs = Date.now();
const result = db
.prepare(
`INSERT INTO answers (thread_id, surface, query, seeds, budget_tokens, returned_files,
returned_symbols, tokens_used, answered_at_ms, sequence_at_answer)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
input.threadId,
input.surface,
input.query,
JSON.stringify(input.seeds),
input.budgetTokens,
JSON.stringify(input.returnedFiles),
JSON.stringify(input.returnedSymbols),
input.tokensUsed,
answeredAtMs,
sequenceAtAnswer,
);
const answer: PendingAnswer = {
...input,
answerId: Number(result.lastInsertRowid),
answeredAtMs,
sequenceAtAnswer,
};
pending.set(input.threadId, [...(pending.get(input.threadId) ?? []), answer]);
}
function feedbackBySurface() {
const rows = db
.prepare(
`SELECT a.surface AS surface, o.searches_after AS searchesAfter, o.recall AS recall
FROM answers a
LEFT JOIN outcomes o ON o.answer_id = a.id
ORDER BY a.id ASC`,
)
.all() as Array<{ surface: FeedbackSurface; searchesAfter: number | null; recall: number | null }>;
return summarizeFeedback(rows);
}
function formatFeedbackBySurface(): string {
const rows = feedbackBySurface();
if (rows.length === 0) return "feedback: no completed outcomes yet\n";
return [
"feedback by surface:",
"surface\tanswers\toutcomes\tavg shell searches after\tavg recall (samples)",
...rows.map(
(row) =>
`${row.surface}\t${row.answers}\t${row.outcomes}\t` +
(row.averageSearchesAfter === null ? "n/a" : row.averageSearchesAfter.toFixed(2)) +
"\t" +
(row.averageRecall === null ? `n/a (0)` : `${row.averageRecall.toFixed(3)} (${row.recallSamples})`),
),
"",
].join("\n");
}
async function warmProjectIndexes(signal?: AbortSignal): Promise<void> {
if (!config.autoIndex) return;
const roots = await listProjectRoots();
const selected = roots.slice(0, config.warmLimit);
if (selected.length < roots.length) {
bb.log.info(
`warming ${selected.length} of ${roots.length} projects ` +
`(limit ${config.warmLimit}); the rest index on first use`,
);
}
for (const root of selected) {
if (signal?.aborted) return;
try {
await ensureIndex(root, signal);
} catch (error) {
if (!signal?.aborted) {
bb.log.warn(`could not warm ${root}: ${String(error)}`);
}
}
}
}
/**
* The primary discovery path: an exact local search, not retrieval.
*
* It is registered separately from code_graph_context because an agent
* should be able to search a fresh checkout without paying to build or query
* a graph index. The graph stays valuable after a hit, when the question is
* no longer "where is this text?" but "what else depends on it?".
*/
bb.agents.registerTool({
name: "instant_grep",
description:
"Fast literal or regex search over the active workspace. It uses ripgrep for an explicit " +
"server-local root and a BB host-file snapshot for a thread environment. " +
"Use for pure location/existence questions (identifiers, error strings, imports, regexes). " +
"For exploratory how/where questions or a known identifier's direct relation, prefer " +
"codebase_query once instead. Returns matching file/line locations without an LLM lookup.",
instructions:
"Use for pure exact-location answers only. Skip when the prompt already has enough context. " +
"For exploratory questions or a known identifier's direct caller/callee/delegation, call " +
"codebase_query once instead — do not chain this after explore. Use `regex: true` for patterns " +
"such as `import.*PaymentService`, `word: true` for whole identifiers, and a glob to narrow " +
"large searches. Omit `root` unless the user explicitly supplies another workspace. " +
"Use `patterns` to batch independent queries. For a pure location answer, cite a content hit " +
"and stop. It stops at `limit`; refine pattern/glob or use nextOffset before reading files.",
parameters: z
.object({
pattern: z
.string()
.min(1)
.max(1_000)
.optional()
.describe("One literal text pattern by default, or a regex when regex is true."),
patterns: z
.array(z.string().min(1).max(1_000))
.min(1)
.max(10)
.optional()
.describe("Independent patterns with the same search options; use instead of pattern to save tool calls."),
regex: z.boolean().default(false).describe("Interpret pattern as a ripgrep regex instead of literal text."),
caseSensitive: z
.boolean()
.default(true)
.describe("Match case exactly. Set false only for an intentional case-insensitive search."),
word: z.boolean().default(false).describe("Require word boundaries around the match."),
glob: z.string().min(1).max(300).optional().describe("Optional ripgrep glob, for example `*.ts` or `src/**`."),
limit: z.number().int().min(1).max(500).default(30).describe("Maximum matching lines returned."),
offset: z.number().int().min(0).max(100_000).default(0).describe("Content-match offset for the next page."),
outputMode: z
.enum(["content", "files_with_matches", "count"])
.default("content")
.describe("Return matching lines, matching files, or per-file counts."),
beforeContext: z
.number()
.int()
.min(0)
.max(MAX_CONTEXT_LINES)
.default(0)
.describe("Source lines before every content match (at most 32)."),
afterContext: z
.number()
.int()
.min(0)
.max(MAX_CONTEXT_LINES)
.default(0)
.describe("Source lines after every content match (at most 32)."),
root: z
.string()
.optional()
.describe(
"Explicit server-local root. Omit to use the current thread workspace, including a remote environment.",
),
})
.refine(({ pattern, patterns }) => (pattern === undefined) !== (patterns === undefined), {
message: "Pass exactly one of pattern or patterns.",
}),
async execute(
{
pattern,
patterns,
regex,
caseSensitive,
word,
glob,
limit,
offset,
outputMode,
beforeContext,
afterContext,
root: requestedRoot,
},
{ threadId, projectId, signal },
) {
const root = await resolveRoot(projectId ?? null, requestedRoot ?? null, threadId, signal);
if (root === null) {
return {
content: [
{
type: "text" as const,
text: "No BB project repository is available. Open a project or pass `root` explicitly.",
},
],
isError: true,
};
}
try {
const searchPatterns = patterns ?? [pattern!];
if (isRemoteRoot(root)) await ensureIndex(root, signal);
const results = await searchExact(
root,
searchPatterns.map((searchPattern) => ({
pattern: searchPattern,
regex,
caseSensitive,
word,
glob,
limit,
offset,
outputMode,
beforeContext,
afterContext,
signal,
})),
);
if (typeof threadId === "string") {
const returnedFiles = [
...new Set(
results.flatMap((result) => [
...result.matches.map((match) => match.file),
...(result.files ?? []),
...(result.counts ?? []).map((count) => count.file),
]),
),
];
await recordFeedbackAnswer({
threadId,
surface: "instant_grep",
query: searchPatterns.join(" OR "),
seeds: searchPatterns,
budgetTokens: 0,
returnedFiles,
returnedSymbols: [],
tokensUsed: 0,
});
}
const next = (result: (typeof results)[number]) =>
result.truncated
? "Refine pattern/glob or call again with nextOffset before treating this search as exhaustive."
: outputMode === "content"
? "For a pure location/existence answer, cite this exact hit and stop. Do not open the file or chain structural tools unless you need lines beyond this hit."
: "Use content mode on a selected file only when you need source lines.";
return JSON.stringify(
searchPatterns.length === 1
? {
engine: isRemoteRoot(root) ? "BB host-file snapshot" : "ripgrep",
root: rootLabel(root),
mode: regex ? "regex" : "literal",
outputMode,
...results[0],
...inventoryLimitField(root),
next: next(results[0]!),
}
: {
engine: isRemoteRoot(root) ? "BB host-file snapshot" : "ripgrep",
root: rootLabel(root),
outputMode,
results,
...inventoryLimitField(root),
next: "Each result is independent; answer from exact hits or narrow only the query that needs it.",
},
null,
2,
);
} catch (error) {
return {
content: [{ type: "text" as const, text: `instant_grep failed: ${String(error)}` }],
isError: true,
};
}
},
});
bb.agents.registerTool({
name: "codebase_query",
description:
"PRIMARY one-shot navigation for exploratory how/where questions and known-ID relations. " +
"Explore mode is Read-equivalent: exact hits plus ranked symbol snippets (line-numbered), " +
"call edges, blast radius, and dynamicBoundaries in one capped call — treat snippets as " +
"already Read. Trace mode returns exact source context and direct static relations for a " +
"known identifier. No LLM runs inside it.",
instructions:
"Call once for an exploratory question or a known identifier's direct caller/callee/delegation " +
"(mode trace). Skip when the prompt already has enough context. Explore returns Read-equivalent " +
"snippets + edges + blast radius — answer from that payload; do not follow with instant_grep, " +
"symbol_lookup, or code_graph_context unless you need lines beyond the snippets. For a pure " +
"location or literal question with no structural need, use instant_grep instead.",
parameters: z.object({
query: z
.string()
.min(3)
.max(1_000)
.describe(
"Natural-language question about the codebase. Include an identifier in backticks when you know one.",
),
explanation: z
.string()
.min(8)
.max(300)
.describe("Why this bounded exploration or direct-relation trace fits the question."),
mode: z
.enum(["explore", "trace"])
.optional()
.describe(
"Use trace only for a known identifier's direct caller, callee, or delegation; otherwise omit for exploratory ranking.",
),
budgetTokens: z
.number()
.int()
.min(256)
.max(32_000)
.optional()
.describe("Graph-context budget. Omit to use the plugin setting."),
root: z
.string()
.optional()
.describe(
"Explicit server-local root. Omit to use the current thread workspace, including a remote environment.",
),
}),
async execute({ query, explanation, mode, budgetTokens, root: requestedRoot }, { threadId, projectId, signal }) {
const root = await resolveRoot(projectId ?? null, requestedRoot ?? null, threadId, signal);
if (root === null) {
return {
content: [
{
type: "text" as const,
text: "No BB project repository is available. Open a project or pass `root` explicitly.",
},
],
isError: true,
};
}
try {
const indexStartedAt = performance.now();
const ready = await ensureIndex(root, signal);
const indexMs = performance.now() - indexStartedAt;
const effectiveBudget = budgetTokens ?? config.defaultBudgetTokens;
const result = await queryCodebase(ready.root, ready.index, {
query,
mode,
budgetTokens: effectiveBudget,
signal,
search: (options) => searchExact(ready.root, options),
});
const context = result.context;
const trace = result.trace;
const exploreSymbols =
context === undefined
? undefined
: config.includeSnippets
? await attachSnippets(ready.root, context.symbols, BODY_LINE_LIMIT, remoteSources.get(ready.root))
: context.symbols;
if (typeof threadId === "string") {
await recordFeedbackAnswer({
threadId,
surface: "codebase_query",
query,
seeds: result.patterns,
budgetTokens: effectiveBudget,
returnedFiles: [
...new Set([
...result.exactMatches.map((match) => match.file),
...(context?.files ?? []),
...(trace?.symbols.map((symbol) => symbol.file) ?? []),
]),
],
returnedSymbols:
context?.symbols.map((symbol) => symbol.id) ?? trace?.symbols.map((symbol) => symbol.id) ?? [],
tokensUsed: context?.tokensUsed ?? 0,
});
}
return JSON.stringify(
{
engine: isRemoteRoot(ready.root) ? "BB host-file snapshot + graph index" : "ripgrep + local graph index",
root: rootLabel(ready.root),