Skip to content

Commit a04c76f

Browse files
committed
Merge main into feature/dynamic-codebase-routing-hints
2 parents c2b4c13 + d29373d commit a04c76f

File tree

5 files changed

+154
-8
lines changed

5 files changed

+154
-8
lines changed

src/tools/index.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { tool, type ToolDefinition } from "@opencode-ai/plugin";
22

3+
import { parseConfig, type ParsedCodebaseIndexConfig } from "../config/schema.js";
34
import { Indexer } from "../indexer/index.js";
4-
import { ParsedCodebaseIndexConfig } from "../config/schema.js";
55
import { formatCostEstimate } from "../utils/cost.js";
66
import type { LogLevel } from "../config/schema.js";
77
import type { LogEntry } from "../utils/logger.js";
@@ -34,6 +34,14 @@ export function getSharedIndexer(): Indexer {
3434
return getIndexer();
3535
}
3636

37+
function refreshIndexerFromConfig(): void {
38+
if (!sharedProjectRoot) {
39+
throw new Error("Codebase index tools not initialized. Plugin may not be loaded correctly.");
40+
}
41+
42+
sharedIndexer = new Indexer(sharedProjectRoot, parseConfig(loadConfig()));
43+
}
44+
3745
function getIndexer(): Indexer {
3846
if (!sharedIndexer) {
3947
throw new Error("Codebase index tools not initialized. Plugin may not be loaded correctly.");
@@ -376,6 +384,7 @@ export const add_knowledge_base: ToolDefinition = tool({
376384
knowledgeBases.push(resolvedPath);
377385
config.knowledgeBases = knowledgeBases;
378386
saveConfig(config);
387+
refreshIndexerFromConfig();
379388

380389
let result = `${resolvedPath}\n`;
381390
result += `Total knowledge bases: ${knowledgeBases.length}\n`;
@@ -462,6 +471,7 @@ export const remove_knowledge_base: ToolDefinition = tool({
462471
const removed = knowledgeBases.splice(index, 1)[0];
463472
config.knowledgeBases = knowledgeBases;
464473
saveConfig(config);
474+
refreshIndexerFromConfig();
465475

466476
let result = `Removed: ${removed}\n\n`;
467477
result += `Remaining knowledge bases: ${knowledgeBases.length}\n`;

src/utils/files.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,16 @@ export function shouldIncludeFile(
111111
}
112112

113113
function matchGlob(filePath: string, pattern: string): boolean {
114-
let regexPattern = pattern
114+
if (pattern.startsWith("**/")) {
115+
const withoutPrefix = pattern.slice(3);
116+
if (withoutPrefix && matchGlob(filePath, withoutPrefix)) {
117+
return true;
118+
}
119+
}
120+
121+
const escapedPattern = pattern.replace(/[.+^$()|[\]\\]/g, "\\$&");
122+
123+
let regexPattern = escapedPattern
115124
.replace(/\*\*/g, "<<<DOUBLESTAR>>>")
116125
.replace(/\*/g, "[^/]*")
117126
.replace(/<<<DOUBLESTAR>>>/g, ".*")

tests/files.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,22 @@ describe("files utilities", () => {
8282
)
8383
).toBe(false);
8484
});
85+
86+
it("should include root-level files with dots in their names", () => {
87+
const filter = createIgnoreFilter(tempDir);
88+
const includePatterns = ["**/*.{ts,tsx,js,jsx,mjs,cjs}"];
89+
const excludePatterns = ["**/.*"];
90+
91+
expect(
92+
shouldIncludeFile(
93+
path.join(tempDir, "watcher.probe.ts"),
94+
tempDir,
95+
includePatterns,
96+
excludePatterns,
97+
filter
98+
)
99+
).toBe(true);
100+
});
85101
});
86102

87103
describe("collectFiles", () => {
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import * as fs from "fs";
2+
import * as os from "os";
3+
import * as path from "path";
4+
5+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6+
7+
const { indexerInstances, MockIndexer } = vi.hoisted(() => {
8+
const indexerInstances: Array<{ projectRoot: string; config: Record<string, unknown> }> = [];
9+
10+
class MockIndexer {
11+
public readonly projectRoot: string;
12+
public readonly config: Record<string, unknown>;
13+
14+
public constructor(projectRoot: string, config: Record<string, unknown>) {
15+
this.projectRoot = projectRoot;
16+
this.config = config;
17+
indexerInstances.push({ projectRoot, config });
18+
}
19+
20+
public estimateCost = vi.fn().mockResolvedValue({
21+
filesCount: 0,
22+
totalSizeBytes: 0,
23+
estimatedChunks: 0,
24+
estimatedTokens: 0,
25+
estimatedCost: 0,
26+
isFree: true,
27+
provider: "ollama",
28+
model: "nomic-embed-text",
29+
});
30+
31+
public clearIndex = vi.fn().mockResolvedValue(undefined);
32+
public index = vi.fn().mockResolvedValue({
33+
totalFiles: 0,
34+
totalChunks: 0,
35+
indexedChunks: 0,
36+
failedChunks: 0,
37+
tokensUsed: 0,
38+
durationMs: 0,
39+
existingChunks: 0,
40+
removedChunks: 0,
41+
skippedFiles: [],
42+
parseFailures: [],
43+
});
44+
45+
public getStatus = vi.fn().mockResolvedValue({
46+
indexed: true,
47+
vectorCount: 0,
48+
provider: "ollama",
49+
model: "nomic-embed-text",
50+
indexPath: "/tmp/index",
51+
currentBranch: "main",
52+
baseBranch: "main",
53+
});
54+
55+
public healthCheck = vi.fn().mockResolvedValue({
56+
removed: 0,
57+
gcOrphanEmbeddings: 0,
58+
gcOrphanChunks: 0,
59+
gcOrphanSymbols: 0,
60+
gcOrphanCallEdges: 0,
61+
filePaths: [],
62+
});
63+
64+
public getLogger = vi.fn().mockReturnValue({
65+
isEnabled: vi.fn().mockReturnValue(false),
66+
isMetricsEnabled: vi.fn().mockReturnValue(false),
67+
getLogs: vi.fn().mockReturnValue([]),
68+
getLogsByCategory: vi.fn().mockReturnValue([]),
69+
getLogsByLevel: vi.fn().mockReturnValue([]),
70+
formatMetrics: vi.fn().mockReturnValue(""),
71+
});
72+
}
73+
74+
return { indexerInstances, MockIndexer };
75+
});
76+
77+
vi.mock("../src/indexer/index.js", () => ({
78+
Indexer: MockIndexer,
79+
}));
80+
81+
import { parseConfig } from "../src/config/schema.js";
82+
import { add_knowledge_base, initializeTools, remove_knowledge_base } from "../src/tools/index.js";
83+
84+
describe("knowledge base tool config refresh", () => {
85+
let tempDir: string;
86+
let kbDir: string;
87+
88+
beforeEach(() => {
89+
indexerInstances.length = 0;
90+
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "kb-tools-test-"));
91+
kbDir = fs.mkdtempSync(path.join(os.tmpdir(), "kb-source-"));
92+
initializeTools(tempDir, parseConfig({ indexing: { watchFiles: false } }));
93+
});
94+
95+
afterEach(() => {
96+
fs.rmSync(tempDir, { recursive: true, force: true });
97+
fs.rmSync(kbDir, { recursive: true, force: true });
98+
});
99+
100+
it("rebuilds the shared indexer after adding a knowledge base", async () => {
101+
await add_knowledge_base.execute({ path: kbDir });
102+
103+
expect(indexerInstances).toHaveLength(2);
104+
expect(indexerInstances[1]?.projectRoot).toBe(tempDir);
105+
expect(indexerInstances[1]?.config.knowledgeBases).toEqual([path.normalize(kbDir)]);
106+
});
107+
108+
it("rebuilds the shared indexer after removing a knowledge base", async () => {
109+
await add_knowledge_base.execute({ path: kbDir });
110+
await remove_knowledge_base.execute({ path: kbDir });
111+
112+
expect(indexerInstances).toHaveLength(3);
113+
expect(indexerInstances[2]?.projectRoot).toBe(tempDir);
114+
expect(indexerInstances[2]?.config.knowledgeBases).toEqual([]);
115+
});
116+
});

tests/watcher.test.ts

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
22
import * as fs from "fs";
33
import * as path from "path";
44
import * as os from "os";
5-
import {
6-
FileWatcher,
7-
GitHeadWatcher,
8-
FileChange,
9-
createWatcherWithIndexer,
10-
} from "../src/watcher/index.js";
5+
import { FileWatcher, GitHeadWatcher, FileChange, createWatcherWithIndexer } from "../src/watcher/index.js";
116
import { ParsedCodebaseIndexConfig } from "../src/config/schema.js";
127

138
const createTestConfig = (overrides: Partial<ParsedCodebaseIndexConfig> = {}): ParsedCodebaseIndexConfig => ({

0 commit comments

Comments
 (0)