@leolastforce/chalice-code-index 0.0.0-stage → 0.1.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.
package/src/tool.ts ADDED
@@ -0,0 +1,146 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { embedTexts } from "./embeddings.ts";
4
+ import { describeCredentials, resolveConfig } from "./config.ts";
5
+ import { getProjectInfo } from "./project.ts";
6
+ import { loadManifest, manifestCompatible, searchIndex } from "./store.ts";
7
+ import { buildTagResolver, computeTagStats, EMPTY_TAGS_HELP, formatDeclaredTags, listDeclaredTags, matchesTagFilter, normalizeTag } from "./tagging.ts";
8
+
9
+ function snippet(content: string): string {
10
+ const lines = content.trim().split(/\r?\n/).slice(0, 8);
11
+ return lines.map((l) => ` ${l.length > 180 ? `${l.slice(0, 177)}...` : l}`).join("\n");
12
+ }
13
+
14
+ function textResult(text: string, details: Record<string, unknown> = {}) {
15
+ return { content: [{ type: "text" as const, text }], details };
16
+ }
17
+
18
+ function matchesFilters(path: string, params: { path?: string; include?: string[]; exclude?: string[] }): boolean {
19
+ if (params.path && !path.startsWith(params.path)) return false;
20
+ if (params.include?.length && !params.include.some((p) => path.includes(p))) return false;
21
+ if (params.exclude?.length && params.exclude.some((p) => path.includes(p))) return false;
22
+ return true;
23
+ }
24
+
25
+ export function registerTools(pi: ExtensionAPI): void {
26
+ registerSemanticSearchTool(pi);
27
+ registerListCodeTagsTool(pi);
28
+ }
29
+
30
+ function registerListCodeTagsTool(pi: ExtensionAPI): void {
31
+ pi.registerTool({
32
+ name: "list_code_tags",
33
+ label: "List Code Tags",
34
+ description: "List all .index_tag declarations in this project with file counts, descriptions, and declaring directories. Use this before filtering semantic_code_search to understand what tags exist and how many files they cover.",
35
+ promptSnippet: "Discover project tags (name, description, file count) to decide include_tags/exclude_tags for semantic_code_search",
36
+ parameters: Type.Object({}),
37
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
38
+ const project = await getProjectInfo(ctx.cwd);
39
+ if (!project.safe) return textResult(`Code index unavailable: ${project.reason}`);
40
+ const { resolved } = await resolveConfig(project);
41
+ const tagMap = await listDeclaredTags(project.root, new Set(resolved.excludeDirs));
42
+ if (tagMap.size === 0) return textResult(EMPTY_TAGS_HELP);
43
+ const manifest = await loadManifest(project);
44
+ const filePaths = manifest ? Object.keys(manifest.files) : [];
45
+ const tagResolver = await buildTagResolver(project.root, new Set(resolved.excludeDirs));
46
+ const stats = computeTagStats(filePaths, (p) => tagResolver.resolveTags(p));
47
+ return textResult(formatDeclaredTags(tagMap, stats));
48
+ },
49
+ });
50
+ }
51
+
52
+ export function registerSemanticSearchTool(pi: ExtensionAPI): void {
53
+ pi.registerTool({
54
+ name: "semantic_code_search",
55
+ label: "Semantic Code Search",
56
+ description: "Search the enabled codebase index by meaning/intent when exact keywords or symbol names are unknown.",
57
+ promptSnippet: "Search the codebase semantically by intent when exact keywords are unknown",
58
+ promptGuidelines: [
59
+ "Use semantic_code_search only for intent-based code discovery when you do not know the exact filename, keyword, or symbol name.",
60
+ "Use ffgrep for exact text or identifier search, fffind for file/path discovery, and lsp_navigation for definitions/references instead of semantic_code_search.",
61
+ "The index only covers files that pass all ignore layers: git (root + nested .gitignore, core.excludesFile, .git/info/exclude), then .indexignore, then .contextignore. Add paths to .indexignore to narrow indexing scope without touching git rules.",
62
+ "Tag filtering: this project may declare code tags in .index_tag files (comma/space-separated names, subdirs inherit, no reindex). When tags exist, search results append a tags hint — call list_code_tags for current tags, counts, and untagged share, then pass include_tags/exclude_tags (see their param docs for whitelist-vs-blacklist semantics). You may create or edit .index_tag files to organize areas.",
63
+ ],
64
+ parameters: Type.Object({
65
+ query: Type.String({ description: "Natural-language description of the code you are looking for" }),
66
+ top_k: Type.Optional(Type.Number({ description: "Max results to return (default 8). Raise to scan broadly, lower for precision; clamped to the configured maxTopK." })),
67
+ path: Type.Optional(Type.String({ description: "Optional path prefix to restrict results" })),
68
+ include: Type.Optional(Type.Array(Type.String(), { description: "Optional substring filters that paths must include" })),
69
+ exclude: Type.Optional(Type.Array(Type.String(), { description: "Optional substring filters that paths must not include" })),
70
+ include_tags: Type.Optional(Type.Array(Type.String(), { description: "Strict tag whitelist: only results whose .index_tag-declared tags contain at least one of these pass. Untagged files are excluded when this is set." })),
71
+ exclude_tags: Type.Optional(Type.Array(Type.String(), { description: "Tag exclusion list: results whose .index_tag-declared tags contain any of these are filtered out. Untagged files are not affected." })),
72
+ }),
73
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
74
+ const project = await getProjectInfo(ctx.cwd);
75
+ const { project: state, resolved } = await resolveConfig(project);
76
+ if (!project.safe) return textResult(`Code index unavailable: ${project.reason}`);
77
+ if (!state.enabled) return textResult("Code index is disabled for this project. Run `/index on` to enable it.");
78
+ const manifest = await loadManifest(project);
79
+ const compatible = manifestCompatible(manifest, resolved);
80
+ if (!manifest) return textResult("Code index is not built yet. Run `/index reindex` to build it.");
81
+ if (!compatible.ok) return textResult(`Code index is stale: ${compatible.reason}. Run /index reindex before searching.`);
82
+ if (!resolved.apiKeyPresent && resolved.provider !== "local") return textResult(`Missing API key: ${describeCredentials(resolved)}. Run /index config.`);
83
+
84
+ // Normalize tag filter inputs once.
85
+ const includeTags = params.include_tags?.map(normalizeTag).filter((t): t is string => t !== undefined);
86
+ const excludeTags = params.exclude_tags?.map(normalizeTag).filter((t): t is string => t !== undefined);
87
+ const tagFilterActive = (includeTags && includeTags.length > 0) || (excludeTags && excludeTags.length > 0);
88
+
89
+ // final-k returned to the agent: the agent chooses freely, clamped only by configured maxTopK.
90
+ const topK = Math.max(1, Math.min(resolved.maxTopK, Math.floor(params.top_k ?? 8)));
91
+ const embedded = await embedTexts(resolved, [params.query], signal, "query");
92
+ if (embedded.dimension !== manifest.embeddingDim) return textResult(`Query embedding dimension ${embedded.dimension} does not match index dimension ${manifest.embeddingDim}. Run /index reindex.`);
93
+
94
+ // D4: enlarge candidate pool when include_tags is active (whitelist can be sparse), capped at
95
+ // 1024. The existing pool formula is kept for the exclude-only and no-tag cases.
96
+ const candidateN = includeTags && includeTags.length > 0
97
+ ? Math.min(topK * 20, 1024)
98
+ : Math.min(Math.max(topK * 5, topK), 256);
99
+ const raw = await searchIndex(project, embedded.vectors[0], candidateN);
100
+
101
+ // Build tag resolver once per query (walks .index_tag files; lightweight, zero reindex).
102
+ // Always construct when !tagFilterActive too, so we can check hasTags for the inline hint.
103
+ const tagResolver = await buildTagResolver(project.root, new Set(resolved.excludeDirs));
104
+
105
+ // scoreThreshold (0 = off) trims low-relevance noise before the final-k cut; score is a
106
+ // similarity in (0,1] so higher passes. Lifts precision / agent signal, not recall.
107
+ const results = raw
108
+ .filter((r) => matchesFilters(r.path, params))
109
+ .filter((r) => r.score >= resolved.scoreThreshold)
110
+ .filter((r) => {
111
+ if (!tagFilterActive) return true;
112
+ const fileTags = tagResolver.resolveTags(r.path);
113
+ return matchesTagFilter(fileTags, includeTags, excludeTags);
114
+ })
115
+ .slice(0, topK);
116
+
117
+ if (results.length === 0) {
118
+ const hint = tagFilterActive && includeTags && includeTags.length > 0
119
+ ? " (include_tags is active — untagged files are excluded; broaden the filter or use exclude_tags instead)"
120
+ : "";
121
+ return textResult(`No semantic code search results found.${hint}`, { results: [] });
122
+ }
123
+ const text = results
124
+ .map((r, i) => `${i + 1}. ${r.path}:${r.startLine}-${r.endLine} score=${r.score.toFixed(3)}${r.symbol ? ` symbol=${r.symbol}` : ""}\n${snippet(r.content)}`)
125
+ .join("\n\n");
126
+
127
+ // Inline tag hint: show when tag filter is not active, the project has .index_tag files,
128
+ // and at least one result has tags (so the hint is relevant to this query).
129
+ let inlineHint = "";
130
+ if (!tagFilterActive && tagResolver.hasTags) {
131
+ const anyTagged = results.some((r) => tagResolver.resolveTags(r.path).size > 0);
132
+ if (anyTagged) {
133
+ const filePaths = Object.keys(manifest.files);
134
+ const stats = computeTagStats(filePaths, (p) => tagResolver.resolveTags(p));
135
+ const total = stats.total || 1;
136
+ // Sort by count descending for the inline summary.
137
+ const sorted = [...stats.perTag.entries()].sort(([, a], [, b]) => b - a);
138
+ const tagSummary = sorted.map(([t, n]) => `${t}(${Math.round((n / total) * 100)}%)`).join(" · ");
139
+ inlineHint = `\nℹ tags available: ${tagSummary} — pass include_tags/exclude_tags to filter`;
140
+ }
141
+ }
142
+
143
+ return textResult(text + inlineHint, { results });
144
+ },
145
+ });
146
+ }
package/src/types.ts ADDED
@@ -0,0 +1,146 @@
1
+ export type ProviderId = "voyage" | "openrouter" | "local" | "custom";
2
+
3
+ export type ApiKeySource = "env" | "stored" | "none";
4
+
5
+ export interface ProviderPreset {
6
+ id: ProviderId;
7
+ label: string;
8
+ baseUrl: string;
9
+ model: string;
10
+ apiKeyEnv?: string;
11
+ embeddingDim?: number;
12
+ pricePerMillionTokens?: number;
13
+ }
14
+
15
+ export interface GlobalConfig {
16
+ provider: ProviderId;
17
+ baseUrl?: string;
18
+ model?: string;
19
+ apiKeyEnv?: string;
20
+ embeddingDim?: number;
21
+ batchSize: number;
22
+ requestConcurrency: number;
23
+ timeoutMs: number;
24
+ chunkLines: number;
25
+ chunkOverlap: number;
26
+ maxFileBytes: number;
27
+ maxChunkChars: number;
28
+ watcherDebounceMs: number;
29
+ watcherBulkThreshold: number;
30
+ largeRepoConfirmChunks: number;
31
+ pricePerMillionTokens?: number;
32
+ annIndexThreshold: number;
33
+ maxTopK: number;
34
+ scoreThreshold: number;
35
+ chunkOverlapChars: number;
36
+ excludeDirs: string[];
37
+ }
38
+
39
+ export interface ProjectState {
40
+ enabled: boolean;
41
+ model?: string;
42
+ baseUrl?: string;
43
+ apiKeyEnv?: string;
44
+ excludeDirs?: string[];
45
+ chunkLines?: number;
46
+ chunkOverlap?: number;
47
+ maxFileBytes?: number;
48
+ lastIndexedAt?: string;
49
+ lastError?: string;
50
+ dataEgressConfirmed?: boolean;
51
+ }
52
+
53
+ export interface ResolvedConfig extends GlobalConfig {
54
+ providerPreset: ProviderPreset;
55
+ baseUrl: string;
56
+ model: string;
57
+ apiKeyEnv?: string;
58
+ apiKeyPresent: boolean;
59
+ apiKeySource: ApiKeySource;
60
+ apiKey?: string;
61
+ }
62
+
63
+ export interface ProjectInfo {
64
+ cwd: string;
65
+ root: string;
66
+ hash: string;
67
+ statePath: string;
68
+ indexDir: string;
69
+ manifestPath: string;
70
+ safe: boolean;
71
+ reason?: string;
72
+ }
73
+
74
+ export interface SourceFile {
75
+ path: string;
76
+ absPath: string;
77
+ language: string;
78
+ content: string;
79
+ size: number;
80
+ mtimeMs: number;
81
+ fileHash: string;
82
+ }
83
+
84
+ export interface CodeChunk {
85
+ id: string;
86
+ projectRoot: string;
87
+ path: string;
88
+ language: string;
89
+ symbol?: string;
90
+ startLine: number;
91
+ endLine: number;
92
+ content: string;
93
+ embeddedText: string;
94
+ contentHash: string;
95
+ fileHash: string;
96
+ mtimeMs: number;
97
+ size: number;
98
+ vector?: number[];
99
+ }
100
+
101
+ export interface ManifestFileEntry {
102
+ path: string;
103
+ fileHash: string;
104
+ mtimeMs: number;
105
+ size: number;
106
+ chunkIds: string[];
107
+ }
108
+
109
+ export interface Manifest {
110
+ version: number;
111
+ projectRoot: string;
112
+ baseUrl: string;
113
+ model: string;
114
+ embeddingDim: number;
115
+ indexParams?: Record<string, number>;
116
+ createdAt: string;
117
+ updatedAt: string;
118
+ chunkCount: number;
119
+ fileCount: number;
120
+ annIndexBuilt?: boolean;
121
+ files: Record<string, ManifestFileEntry>;
122
+ }
123
+
124
+ export interface IndexEstimate {
125
+ files: number;
126
+ chunks: number;
127
+ estimatedTokens: number;
128
+ estimatedCost?: number;
129
+ model: string;
130
+ baseUrl: string;
131
+ }
132
+
133
+ export type FooterState = "off" | "not-indexed" | "indexing" | "ready" | "stale" | "error" | "bulk-pending";
134
+
135
+ export interface RuntimeStatus {
136
+ state: FooterState;
137
+ message?: string;
138
+ filesDone?: number;
139
+ filesTotal?: number;
140
+ chunks?: number;
141
+ lastError?: string;
142
+ }
143
+
144
+ // Bumped to 2: chunk embeddedText format changed (line numbers moved out of the embedded text, so
145
+ // contentHash is now content-stable). Existing v1 indexes are reported stale and prompt a reindex.
146
+ export const INDEX_VERSION = 2;
package/src/ui.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { IndexEstimate, RuntimeStatus } from "./types.ts";
3
+
4
+ export function updateFooter(ctx: ExtensionContext, status: RuntimeStatus): void {
5
+ const t = ctx.ui.theme;
6
+ let text: string;
7
+ switch (status.state) {
8
+ case "off":
9
+ text = t.fg("dim", "off");
10
+ break;
11
+ case "not-indexed":
12
+ text = t.fg("warning", "not indexed");
13
+ break;
14
+ case "indexing": {
15
+ const progress = status.filesTotal ? ` ${status.filesDone ?? 0}/${status.filesTotal}` : "";
16
+ const chunks = status.chunks !== undefined ? ` ${status.chunks} chunks` : "";
17
+ text = t.fg("accent", `indexing${progress}${chunks}`);
18
+ break;
19
+ }
20
+ case "ready":
21
+ text = t.fg("success", `ready${status.chunks !== undefined ? ` ${status.chunks} chunks` : ""}`);
22
+ break;
23
+ case "stale":
24
+ text = t.fg("warning", `stale${status.message ? ` ${status.message}` : ""}`);
25
+ break;
26
+ case "bulk-pending":
27
+ text = t.fg("warning", status.message ?? "changes pending · run /index update");
28
+ break;
29
+ case "error":
30
+ text = t.fg("error", "error");
31
+ break;
32
+ }
33
+ ctx.ui.setStatus("code-index", text);
34
+ }
35
+
36
+ export function estimateText(estimate: IndexEstimate): string {
37
+ const cost = estimate.estimatedCost === undefined ? "unknown" : `$${estimate.estimatedCost.toFixed(4)}`;
38
+ return [`Index estimate:`, `- files: ${estimate.files}`, `- chunks: ${estimate.chunks}`, `- estimated input tokens: ${estimate.estimatedTokens.toLocaleString()}`, `- model: ${estimate.model}`, `- estimated cost: ${cost}`].join("\n");
39
+ }
40
+
41
+ export async function confirmEstimate(ctx: ExtensionContext, estimate: IndexEstimate, shouldConfirm: boolean): Promise<boolean> {
42
+ if (!ctx.hasUI) return true;
43
+ if (!shouldConfirm) return true;
44
+ return ctx.ui.confirm("Confirm code indexing", `${estimateText(estimate)}\n\nSource code will be sent to the configured embedding provider unless using a local preset. Proceed?`);
45
+ }
package/src/watcher.ts ADDED
@@ -0,0 +1,168 @@
1
+ import chokidar, { type FSWatcher } from "chokidar";
2
+ import { relative } from "node:path";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import type { ProjectInfo, ResolvedConfig } from "./types.ts";
6
+ import { buildIgnoreMatcher, isPathIndexable, isSecretPath } from "./filtering.ts";
7
+ import { deleteFileChunks, loadManifest, manifestCompatible, saveManifest } from "./store.ts";
8
+ import { updateChangedFile } from "./indexer.ts";
9
+
10
+ const execFileAsync = promisify(execFile);
11
+
12
+ async function isGitRepo(root: string): Promise<boolean> {
13
+ try {
14
+ await execFileAsync("git", ["-C", root, "rev-parse", "--git-dir"], { timeout: 5_000 });
15
+ return true;
16
+ } catch {
17
+ return false;
18
+ }
19
+ }
20
+
21
+ export interface WatcherCallbacks {
22
+ onIndexing?: (path: string) => void;
23
+ onReady?: () => void;
24
+ onBulkPending?: (count: number) => void;
25
+ onError?: (error: unknown) => void;
26
+ }
27
+
28
+ export class CodeIndexWatcher {
29
+ private watcher?: FSWatcher;
30
+ private timer?: NodeJS.Timeout;
31
+ private pending = new Set<string>();
32
+ // When the debounce window accumulates more than watcherBulkThreshold changes, auto-embed is
33
+ // suspended. The watcher sets this flag and fires onBulkPending; /index update clears it.
34
+ private bulkPending = false;
35
+ // Cumulative count of files seen while in bulk-pending state (displayed in footer).
36
+ private bulkCount = 0;
37
+ // Serialize flushes: a debounce that fires while a flush is still awaiting embeddings must not
38
+ // start a second concurrent flush (they would race on the manifest and orphan rows).
39
+ private flushing: Promise<void> = Promise.resolve();
40
+ private stopped = true;
41
+ private abortController = new AbortController();
42
+
43
+ private project: ProjectInfo;
44
+ private config: ResolvedConfig;
45
+ private callbacks: WatcherCallbacks;
46
+
47
+ constructor(project: ProjectInfo, config: ResolvedConfig, callbacks: WatcherCallbacks = {}) {
48
+ this.project = project;
49
+ this.config = config;
50
+ this.callbacks = callbacks;
51
+ }
52
+
53
+ // Called when startup reconciliation finds too many out-of-band changes to auto-embed.
54
+ markBulkPending(count: number): void {
55
+ if (this.stopped) return;
56
+ this.bulkPending = true;
57
+ this.bulkCount = count;
58
+ this.callbacks.onBulkPending?.(this.bulkCount);
59
+ }
60
+
61
+ // Called by /index update after a successful update to clear the bulk-pending state.
62
+ clearPending(): void {
63
+ this.bulkPending = false;
64
+ this.bulkCount = 0;
65
+ }
66
+
67
+ async start(): Promise<void> {
68
+ if (this.watcher) return;
69
+ this.stopped = false;
70
+ this.abortController = new AbortController();
71
+ const gitRepo = await isGitRepo(this.project.root);
72
+ if (this.stopped) return;
73
+ const ig = await buildIgnoreMatcher(this.project, this.config, gitRepo);
74
+ if (this.stopped) return;
75
+ this.watcher = chokidar.watch(this.project.root, {
76
+ ignoreInitial: true,
77
+ persistent: true,
78
+ followSymlinks: false,
79
+ ignored: (path) => {
80
+ const rel = relative(this.project.root, path).replaceAll("\\", "/");
81
+ if (!rel || rel.startsWith("..")) return false;
82
+ if (ig.ignores(rel)) return true;
83
+ if (isSecretPath(rel)) return true;
84
+ // Keep all non-ignored files watched; unknown readable files are indexed as plain text.
85
+ return false;
86
+ },
87
+ });
88
+ this.watcher.on("add", (p) => this.enqueue(p));
89
+ this.watcher.on("change", (p) => this.enqueue(p));
90
+ this.watcher.on("unlink", (p) => this.enqueue(p, true));
91
+ }
92
+
93
+ private enqueue(absPath: string, deleted = false): void {
94
+ if (this.stopped) return;
95
+ const rel = relative(this.project.root, absPath).replaceAll("\\", "/");
96
+ if (!rel || rel.startsWith("..")) return;
97
+ this.pending.add(deleted ? `!${rel}` : rel);
98
+ if (this.timer) clearTimeout(this.timer);
99
+ this.timer = setTimeout(() => {
100
+ this.flushing = this.flushing.then(() => this.flush(), () => this.flush());
101
+ }, this.config.watcherDebounceMs);
102
+ }
103
+
104
+ private async flush(): Promise<void> {
105
+ if (this.stopped) {
106
+ this.pending.clear();
107
+ return;
108
+ }
109
+ const items = [...this.pending];
110
+ this.pending.clear();
111
+ if (items.length === 0) return;
112
+
113
+ // If the debounce window accumulated more changes than the bulk threshold, suspend auto-embed
114
+ // and notify the caller to show a warning. The user must run /index update manually.
115
+ const threshold = this.config.watcherBulkThreshold;
116
+ if (items.length > threshold) {
117
+ this.bulkPending = true;
118
+ this.bulkCount += items.length;
119
+ if (!this.stopped) this.callbacks.onBulkPending?.(this.bulkCount);
120
+ return;
121
+ }
122
+
123
+ // If already in bulk-pending state, keep accumulating without auto-embedding until cleared.
124
+ if (this.bulkPending) {
125
+ this.bulkCount += items.length;
126
+ if (!this.stopped) this.callbacks.onBulkPending?.(this.bulkCount);
127
+ return;
128
+ }
129
+
130
+ for (const item of items) {
131
+ if (this.stopped || this.abortController.signal.aborted) return;
132
+ try {
133
+ const deleted = item.startsWith("!");
134
+ const rel = deleted ? item.slice(1) : item;
135
+ this.callbacks.onIndexing?.(rel);
136
+ const manifest = await loadManifest(this.project);
137
+ const compatible = manifestCompatible(manifest, this.config);
138
+ if (!manifest || !compatible.ok) {
139
+ if (!this.stopped) this.callbacks.onReady?.();
140
+ continue;
141
+ }
142
+ if (deleted) {
143
+ await deleteFileChunks(this.project, rel, manifest);
144
+ await saveManifest(this.project, manifest);
145
+ } else if (await isPathIndexable(this.project, this.config, rel)) {
146
+ await updateChangedFile(this.project, this.config, rel, this.abortController.signal);
147
+ } else {
148
+ await deleteFileChunks(this.project, rel, manifest);
149
+ await saveManifest(this.project, manifest);
150
+ }
151
+ if (!this.stopped) this.callbacks.onReady?.();
152
+ } catch (error) {
153
+ if (!this.stopped && !this.abortController.signal.aborted) this.callbacks.onError?.(error);
154
+ }
155
+ }
156
+ }
157
+
158
+ async stop(): Promise<void> {
159
+ this.stopped = true;
160
+ this.abortController.abort();
161
+ if (this.timer) clearTimeout(this.timer);
162
+ this.timer = undefined;
163
+ this.pending.clear();
164
+ if (this.watcher) await this.watcher.close();
165
+ this.watcher = undefined;
166
+ await this.flushing.catch(() => undefined); // let any in-flight flush finish writing
167
+ }
168
+ }