@floydous/pi-agent-kernel 0.3.1 → 0.3.3
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/AGENT_KERNEL_SYS_PROMPT.md +10 -0
- package/CHANGELOG.md +44 -10
- package/README.md +61 -78
- package/config.toml +8 -2
- package/package.json +3 -1
- package/src/config/kernel_config.ts +24 -6
- package/src/editing/auto_heal.ts +232 -0
- package/src/editing/patch.ts +214 -17
- package/src/editing/post_edit_verification.ts +3 -2
- package/src/editing/smart_anchor.ts +420 -0
- package/src/index.ts +212 -152
- package/src/retrieval/repomap.ts +2 -1
- package/src/retrieval/search_bm25.ts +14 -1
- package/src/retrieval/search_chunker.ts +69 -3
- package/src/retrieval/search_config.ts +5 -6
- package/src/retrieval/search_index.ts +208 -82
- package/src/retrieval/symbol_reader.ts +34 -4
- package/src/safety/epistemic_guard.ts +304 -38
- package/src/safety/output_clamper.ts +28 -4
- package/src/tools/ast_search_tool.ts +19 -8
- package/src/tools/code_search_tool.ts +43 -29
- package/src/tools/edit_tool.ts +510 -197
- package/src/tools/read_tool.ts +265 -28
- package/src/ui/footer.ts +45 -19
- package/src/dedup/content_store.ts +0 -365
- package/src/dedup/recall_tool.ts +0 -155
package/src/index.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as path from "path";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
|
+
import * as child_process from "node:child_process";
|
|
3
4
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
5
|
import { computeRepoMap, evaluateCodebaseMetrics } from "./retrieval/repomap";
|
|
5
6
|
import { HybridSearchIndex } from "./retrieval/search_index";
|
|
@@ -47,6 +48,8 @@ function getSessionId(ctx: any): string {
|
|
|
47
48
|
const PI_DOCS_START =
|
|
48
49
|
"Pi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):";
|
|
49
50
|
const PI_DOCS_END = /\n- Always read pi \.md files completely[^\n]*/;
|
|
51
|
+
const KERNEL_GUIDANCE_MARKER = "## Agent Kernel Guidance";
|
|
52
|
+
let kernelGuidance: string | null | undefined;
|
|
50
53
|
const piDocsEnabledBySession = new Map<string, boolean>();
|
|
51
54
|
const codebaseProfileBySession = new Map<string, "auto" | "light" | "heavy">();
|
|
52
55
|
|
|
@@ -65,11 +68,30 @@ function withoutPiDocumentation(systemPrompt: string): string {
|
|
|
65
68
|
function piDocsEnabled(ctx: any): boolean {
|
|
66
69
|
return piDocsEnabledBySession.get(getSessionId(ctx)) ?? true;
|
|
67
70
|
}
|
|
71
|
+
|
|
72
|
+
function loadKernelGuidance(): string {
|
|
73
|
+
if (kernelGuidance !== undefined) return kernelGuidance ?? "";
|
|
74
|
+
|
|
75
|
+
try {
|
|
76
|
+
const instructionPath = path.join(__dirname, "..", "AGENT_KERNEL_SYS_PROMPT.md");
|
|
77
|
+
const contents = fs.readFileSync(instructionPath, "utf8").trim();
|
|
78
|
+
kernelGuidance = contents || null;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
kernelGuidance = null;
|
|
81
|
+
kernelDebug(error);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return kernelGuidance ?? "";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function appendKernelGuidance(systemPrompt: string, guidance: string): string {
|
|
88
|
+
if (!guidance || systemPrompt.includes(guidance)) return systemPrompt;
|
|
89
|
+
const base = systemPrompt.trimEnd();
|
|
90
|
+
return `${base ? `${base}\n\n` : ""}${KERNEL_GUIDANCE_MARKER}\n${guidance}`;
|
|
91
|
+
}
|
|
68
92
|
import { clampCommandOutput } from "./safety/output_clamper";
|
|
69
93
|
import { sanitizeSessionFiles } from "./context/session_repair";
|
|
70
|
-
import { renderFooter } from "./ui/footer";
|
|
71
|
-
import { DedupStore } from "./dedup/content_store";
|
|
72
|
-
import { registerRecallTool } from "./dedup/recall_tool";
|
|
94
|
+
import { formatSearchEngineTag, renderFooter } from "./ui/footer";
|
|
73
95
|
import {
|
|
74
96
|
LspManager,
|
|
75
97
|
LspControlModal,
|
|
@@ -93,13 +115,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
93
115
|
kernelDebug(e);
|
|
94
116
|
}
|
|
95
117
|
|
|
96
|
-
// 0b. Dedup store: shared across all sessions in this process. Per-session
|
|
97
|
-
// state is keyed by sessionId. A single instance lets the dedup store
|
|
98
|
-
// benefit from cross-session LRU and lets the recall tool look up refs
|
|
99
|
-
// from any active session.
|
|
100
|
-
const dedupStore = new DedupStore();
|
|
101
|
-
const getDedupStore = () => dedupStore;
|
|
102
|
-
|
|
103
118
|
// 3. Slash Commands: /repomap, /engine, /lsp, /pi-docs
|
|
104
119
|
let activeTui: any = null;
|
|
105
120
|
const configByWorkspace = new Map<
|
|
@@ -126,7 +141,27 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
126
141
|
return index;
|
|
127
142
|
};
|
|
128
143
|
|
|
129
|
-
// Helper: Background index synchronization with
|
|
144
|
+
// Helper: Background index synchronization with statusline indicator
|
|
145
|
+
const syncRetrievalStatus = (ctx: any, customText?: string) => {
|
|
146
|
+
if (!ctx?.ui?.setStatus) return;
|
|
147
|
+
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
148
|
+
const index = getSearchIndex(cwd);
|
|
149
|
+
const eff = index.getEffectiveProfile();
|
|
150
|
+
if (eff === "off") {
|
|
151
|
+
ctx.ui.setStatus("retrieval", "");
|
|
152
|
+
activeTui?.requestRender?.();
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (customText !== undefined) {
|
|
157
|
+
ctx.ui.setStatus("retrieval", customText);
|
|
158
|
+
} else {
|
|
159
|
+
const tag = formatSearchEngineTag(index, true);
|
|
160
|
+
ctx.ui.setStatus("retrieval", tag);
|
|
161
|
+
}
|
|
162
|
+
activeTui?.requestRender?.();
|
|
163
|
+
};
|
|
164
|
+
|
|
130
165
|
const triggerBackgroundIndexing = (
|
|
131
166
|
index: HybridSearchIndex,
|
|
132
167
|
ctx: any,
|
|
@@ -134,76 +169,73 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
134
169
|
) => {
|
|
135
170
|
const eff = index.getEffectiveProfile();
|
|
136
171
|
if (eff === "off") {
|
|
137
|
-
ctx
|
|
138
|
-
return;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
if (eff === "lean") {
|
|
142
|
-
ctx.ui?.setWidget?.("engine-progress", undefined);
|
|
143
|
-
ctx.ui?.notify?.(
|
|
144
|
-
`Lean mode active (${index.getStatus().chunkCount} chunks ready in RAM)`,
|
|
145
|
-
"info",
|
|
146
|
-
);
|
|
172
|
+
syncRetrievalStatus(ctx);
|
|
147
173
|
return;
|
|
148
174
|
}
|
|
149
175
|
|
|
150
|
-
const
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
};
|
|
176
|
+
const engineTag = formatSearchEngineTag(index, true);
|
|
177
|
+
const streamArrow = "\x1b[38;2;155;210;170m⇢\x1b[0m";
|
|
178
|
+
syncRetrievalStatus(
|
|
179
|
+
ctx,
|
|
180
|
+
`${engineTag} ${streamArrow} \x1b[38;2;165;175;190m(indexing...)\x1b[0m`,
|
|
181
|
+
);
|
|
157
182
|
|
|
158
183
|
const runSync = async () => {
|
|
159
|
-
if (isVectorProfile) {
|
|
160
|
-
updateWidget("\x1b[38;5;244mEngine: Loading embedding model...\x1b[0m");
|
|
161
|
-
await index.preloadModel((msg: string) => {
|
|
162
|
-
updateWidget(`\x1b[38;5;244mEngine: ${msg.slice(0, 40)}\x1b[0m`);
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
184
|
return await index.syncWorkspace(
|
|
166
185
|
isFullSync,
|
|
167
186
|
(msg: string) => {
|
|
168
187
|
const pctMatch = msg.match(/(\d+)%/);
|
|
188
|
+
const speedMatch = msg.match(/([\d.]+\s*chunk\/s)/);
|
|
189
|
+
const countMatch = msg.match(/\((\d+)\/(\d+)/);
|
|
190
|
+
|
|
169
191
|
if (pctMatch) {
|
|
170
192
|
const pct = parseInt(pctMatch[1], 10);
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
193
|
+
let info = "";
|
|
194
|
+
if (countMatch && speedMatch) {
|
|
195
|
+
info = ` \x1b[38;2;165;175;190m(${countMatch[1]}/${countMatch[2]} • ${speedMatch[1]})\x1b[0m`;
|
|
196
|
+
} else if (countMatch) {
|
|
197
|
+
info = ` \x1b[38;2;165;175;190m(${countMatch[1]}/${countMatch[2]})\x1b[0m`;
|
|
198
|
+
} else if (msg.includes("Downloading")) {
|
|
199
|
+
info = ` \x1b[38;2;165;175;190m(downloading weights)\x1b[0m`;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
syncRetrievalStatus(
|
|
203
|
+
ctx,
|
|
204
|
+
`${engineTag} ${streamArrow} \x1b[38;2;155;210;170m${pct}%\x1b[0m${info}`,
|
|
182
205
|
);
|
|
183
206
|
} else {
|
|
184
|
-
|
|
207
|
+
syncRetrievalStatus(
|
|
208
|
+
ctx,
|
|
209
|
+
`${engineTag} ${streamArrow} \x1b[38;2;165;175;190m(${msg.slice(0, 35)})\x1b[0m`,
|
|
210
|
+
);
|
|
185
211
|
}
|
|
186
212
|
},
|
|
187
213
|
);
|
|
188
214
|
};
|
|
189
215
|
|
|
190
|
-
// Keep profile changes responsive:
|
|
191
|
-
//
|
|
216
|
+
// Keep profile changes responsive: indexing runs in the background
|
|
217
|
+
// while progress stays cleanly reported on the statusline.
|
|
192
218
|
void runSync()
|
|
193
219
|
.then((result) => {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
)
|
|
220
|
+
syncRetrievalStatus(ctx); // Reset to clean idle tag on status line
|
|
221
|
+
if (
|
|
222
|
+
(result.indexedCount !== undefined ? result.indexedCount > 0 : false) ||
|
|
223
|
+
isFullSync
|
|
224
|
+
) {
|
|
225
|
+
ctx.ui?.notify?.(
|
|
226
|
+
`Search index ready (${result.chunkCount} chunks in ${result.fileCount} files)`,
|
|
227
|
+
"info",
|
|
228
|
+
);
|
|
229
|
+
}
|
|
199
230
|
})
|
|
200
231
|
.catch((err: any) => {
|
|
201
|
-
|
|
232
|
+
syncRetrievalStatus(ctx);
|
|
202
233
|
ctx.ui?.notify?.(`Indexing error: ${err.message}`, "error");
|
|
203
234
|
});
|
|
204
235
|
};
|
|
205
236
|
|
|
206
237
|
const setupUnifiedFooter = (ctx: any) => {
|
|
238
|
+
syncRetrievalStatus(ctx);
|
|
207
239
|
if (ctx.hasUI && ctx.ui?.setFooter) {
|
|
208
240
|
ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
|
|
209
241
|
activeTui = tui;
|
|
@@ -261,9 +293,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
261
293
|
await TreeSitterEngine.getInstance().init();
|
|
262
294
|
const budget = args ? parseInt(args, 10) : 1024;
|
|
263
295
|
const map = computeRepoMap(
|
|
264
|
-
ctx.cwd,
|
|
296
|
+
ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd(),
|
|
265
297
|
Number.isNaN(budget)
|
|
266
|
-
? getConfig(ctx.cwd).retrieval.repo_map_budget
|
|
298
|
+
? getConfig(ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd()).retrieval.repo_map_budget
|
|
267
299
|
: budget,
|
|
268
300
|
);
|
|
269
301
|
ctx.ui?.notify?.("Repository Map Generated", "info");
|
|
@@ -302,8 +334,9 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
302
334
|
return;
|
|
303
335
|
}
|
|
304
336
|
|
|
305
|
-
const
|
|
306
|
-
const
|
|
337
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
338
|
+
const current = codebaseProfileBySession.get(sessionId) ?? getConfig(currentCwd).retrieval.codebase_profile;
|
|
339
|
+
const metrics = evaluateCodebaseMetrics(currentCwd);
|
|
307
340
|
const detected = metrics.isLight ? "light" : "heavy";
|
|
308
341
|
const effective = current === "auto" ? detected : current;
|
|
309
342
|
const statusMsg = `Profile: ${current} (effective: ${effective})\nMetrics: ${metrics.implFiles} impl files (${Math.round(metrics.implBytes / 1024)} KB), ${metrics.testFiles} test files (${Math.round(metrics.testBytes / 1024)} KB)`;
|
|
@@ -635,9 +668,10 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
635
668
|
pi.on("session_start", async (_event: any, ctx: any) => {
|
|
636
669
|
setupUnifiedFooter(ctx);
|
|
637
670
|
try {
|
|
638
|
-
const
|
|
671
|
+
const cwd = ctx.sessionManager?.getCwd?.() || ctx.cwd || process.cwd();
|
|
672
|
+
const index = getSearchIndex(cwd);
|
|
639
673
|
if (index.getEffectiveProfile() !== "off") {
|
|
640
|
-
index
|
|
674
|
+
triggerBackgroundIndexing(index, ctx, false);
|
|
641
675
|
}
|
|
642
676
|
} catch (e) {
|
|
643
677
|
kernelDebug(e);
|
|
@@ -652,7 +686,6 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
652
686
|
const sessionId = getSessionId(ctx);
|
|
653
687
|
piDocsEnabledBySession.delete(sessionId);
|
|
654
688
|
globalEpistemicGuard.resetSession(sessionId);
|
|
655
|
-
dedupStore.clearSession(sessionId);
|
|
656
689
|
try {
|
|
657
690
|
await LspManager.getInstance().stopAll();
|
|
658
691
|
} catch (e) {
|
|
@@ -660,29 +693,25 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
660
693
|
}
|
|
661
694
|
});
|
|
662
695
|
|
|
663
|
-
//
|
|
664
|
-
//
|
|
665
|
-
//
|
|
666
|
-
pi.on("session_before_compact", async (_event: any, ctx: any) => {
|
|
667
|
-
const sessionId = getSessionId(ctx);
|
|
668
|
-
dedupStore.onCompaction(sessionId);
|
|
669
|
-
});
|
|
670
|
-
pi.on("session_compact", async (_event: any, ctx: any) => {
|
|
671
|
-
const sessionId = getSessionId(ctx);
|
|
672
|
-
dedupStore.onCompaction(sessionId);
|
|
673
|
-
});
|
|
674
|
-
|
|
675
|
-
// 4-8. Tools: repo map, AST search, code search, read, edit, LSP
|
|
676
|
-
registerRepoMapTool(pi);
|
|
696
|
+
// 4-8. Tools: Core tools (read, edit) and code_search are registered.
|
|
697
|
+
// Speculative AST dump and heavy daemon tools (ast_search, repo_map, lsp) remain optional
|
|
698
|
+
// to avoid prompt bloat on routine tasks.
|
|
677
699
|
const invalidateSearchFile = (cwd: string, filePath: string) => {
|
|
678
700
|
getSearchIndex(cwd).invalidateFile(filePath);
|
|
679
701
|
};
|
|
680
|
-
registerAstSearchTool(pi, { getSessionId, getConfig });
|
|
681
|
-
registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
|
|
682
702
|
registerReadTool(pi, { getSessionId, getConfig });
|
|
683
703
|
registerEditTool(pi, { getSessionId, getConfig, invalidateSearchFile });
|
|
684
|
-
|
|
685
|
-
|
|
704
|
+
registerCodeSearchTool(pi, { getSessionId, getSearchIndex, getConfig });
|
|
705
|
+
|
|
706
|
+
const enableSpeculativeTools = process.env.PI_ENABLE_ALL_RETRIEVAL_TOOLS === "1" ||
|
|
707
|
+
process.env.PI_ENABLE_ALL_RETRIEVAL_TOOLS === "true" ||
|
|
708
|
+
getConfig(process.cwd()).retrieval.enable_tools === true;
|
|
709
|
+
|
|
710
|
+
if (enableSpeculativeTools) {
|
|
711
|
+
registerRepoMapTool(pi);
|
|
712
|
+
registerAstSearchTool(pi, { getSessionId, getConfig });
|
|
713
|
+
registerLspTool(pi, { getSessionId, getConfig });
|
|
714
|
+
}
|
|
686
715
|
|
|
687
716
|
// 9a. Block host writes before the host tool can create parent directories
|
|
688
717
|
// or overwrite the target. Bash read evidence is recorded after a successful
|
|
@@ -729,12 +758,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
729
758
|
|
|
730
759
|
// 9. Tool Result Interceptor: Syntax Validation & Output Clamping (ACI)
|
|
731
760
|
pi.on("tool_result", async (event: any, ctx: any) => {
|
|
732
|
-
|
|
761
|
+
const isBash = event.toolName === "bash";
|
|
762
|
+
if (event.isError && !isBash) return;
|
|
733
763
|
|
|
734
|
-
const toolName = event.toolName;
|
|
735
764
|
// resultContent === undefined means "no transformation, return event.content as-is".
|
|
736
|
-
|
|
737
|
-
// at the end runs on whichever form is set.
|
|
765
|
+
const toolName = event.toolName;
|
|
738
766
|
let resultContent: any = undefined;
|
|
739
767
|
let didBail = false;
|
|
740
768
|
|
|
@@ -769,6 +797,11 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
769
797
|
.map((c: any) => c.text)
|
|
770
798
|
.join(""),
|
|
771
799
|
);
|
|
800
|
+
if (event.isError) {
|
|
801
|
+
return resultContent !== undefined
|
|
802
|
+
? { content: resultContent, isError: true }
|
|
803
|
+
: undefined;
|
|
804
|
+
}
|
|
772
805
|
}
|
|
773
806
|
|
|
774
807
|
// 9b. Preserve the host write-tool compatibility path. The custom edit
|
|
@@ -859,88 +892,108 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
859
892
|
}
|
|
860
893
|
}
|
|
861
894
|
|
|
862
|
-
// 9c. Dedup pass: hash the rendered text + tool name + input params;
|
|
863
|
-
// if it's a byte-equal duplicate (same tool, same params, same text)
|
|
864
|
-
// of one already in this session's current (uncompacted) context,
|
|
865
|
-
// replace with a [=rN,sizeB,tool,paramsKey] reference. Bail
|
|
866
|
-
// branches (didBail) skip dedup; errors are filtered at the top.
|
|
867
|
-
// The `recall` tool is exempt: its entire purpose is to break the
|
|
868
|
-
// dedup chain by emitting the original bytes; if we dedup'd its
|
|
869
|
-
// output, the LLM would get a reference instead of the bytes it
|
|
870
|
-
// asked for.
|
|
871
|
-
if (!didBail && toolName !== "recall") {
|
|
872
|
-
const contentForLLM = resultContent !== undefined ? resultContent : (event.content || []);
|
|
873
|
-
const hasOnlyTextContent = (contentForLLM as any[]).every(
|
|
874
|
-
(c: any) => c.type === "text" && typeof c.text === "string",
|
|
875
|
-
);
|
|
876
|
-
const finalText = hasOnlyTextContent
|
|
877
|
-
? (contentForLLM as any[]).map((c: any) => c.text).join("")
|
|
878
|
-
: "";
|
|
879
|
-
if (hasOnlyTextContent && Buffer.byteLength(finalText, "utf8") > 0) {
|
|
880
|
-
const sessionId = getSessionId(ctx);
|
|
881
|
-
const compactionCounter = dedupStore.getCompactionCounter(sessionId);
|
|
882
|
-
const inputParams = event.input || {};
|
|
883
|
-
const decision = dedupStore.record(
|
|
884
|
-
sessionId,
|
|
885
|
-
event.toolCallId || "",
|
|
886
|
-
toolName,
|
|
887
|
-
inputParams,
|
|
888
|
-
finalText,
|
|
889
|
-
false,
|
|
890
|
-
compactionCounter,
|
|
891
|
-
);
|
|
892
|
-
if (decision.isDuplicate) {
|
|
893
|
-
// Recall the prior entry's metadata so the notice names
|
|
894
|
-
// the tool and paramsKey. The LLM can use this to
|
|
895
|
-
// decide whether to recall or run a fresh tool call.
|
|
896
|
-
const prior = dedupStore.get(sessionId, decision.shortRef);
|
|
897
|
-
const priorTool = prior?.toolName ?? toolName;
|
|
898
|
-
const priorParamsKey = prior?.paramsKey ?? "";
|
|
899
|
-
resultContent = [
|
|
900
|
-
{
|
|
901
|
-
type: "text",
|
|
902
|
-
text: `[=${decision.shortRef},${Buffer.byteLength(finalText, "utf8")}B,${priorTool},${priorParamsKey}]`,
|
|
903
|
-
},
|
|
904
|
-
];
|
|
905
|
-
}
|
|
906
|
-
// For first occurrence, the dedup store has the entry, but we
|
|
907
|
-
// don't need to return anything; Pi will use event.content as-is.
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
|
|
911
895
|
if (didBail) return;
|
|
912
896
|
if (resultContent !== undefined) {
|
|
913
897
|
return { content: resultContent };
|
|
914
898
|
}
|
|
915
899
|
});
|
|
916
900
|
|
|
917
|
-
// 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching)
|
|
901
|
+
// 10. Dynamic Runtime Context Injection (Repo Map with in-memory caching & Turn 1 Grounding)
|
|
918
902
|
// Notice: Custom user instructions (AGENT.md / prompt templates) are respected as the primary authority.
|
|
919
903
|
// Only runtime operational metadata (repo map) is dynamically attached and cached per session/cwd.
|
|
920
904
|
let cachedRepoMap = "";
|
|
921
905
|
let cachedRepoMapCwd = "";
|
|
922
906
|
let lastRepoMapCheck = 0;
|
|
907
|
+
const sessionGroundingDone = new Set<string>();
|
|
908
|
+
const sessionGroundingText = new Map<string, string>();
|
|
909
|
+
|
|
910
|
+
function getPreFlightGrounding(cwd: string, sessionId: string): string {
|
|
911
|
+
if (sessionGroundingDone.has(sessionId)) {
|
|
912
|
+
return sessionGroundingText.get(sessionId) || "";
|
|
913
|
+
}
|
|
914
|
+
sessionGroundingDone.add(sessionId);
|
|
915
|
+
|
|
916
|
+
try {
|
|
917
|
+
const statusRaw = child_process.execFileSync(
|
|
918
|
+
"git",
|
|
919
|
+
["status", "--porcelain"],
|
|
920
|
+
{ cwd, encoding: "utf8", timeout: 1000, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 1024 * 1024 },
|
|
921
|
+
).trim();
|
|
922
|
+
|
|
923
|
+
if (!statusRaw) {
|
|
924
|
+
sessionGroundingText.set(sessionId, "");
|
|
925
|
+
return "";
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
let diffRaw = "";
|
|
929
|
+
try {
|
|
930
|
+
diffRaw = child_process.execFileSync(
|
|
931
|
+
"git",
|
|
932
|
+
["diff", "HEAD", "-U3"],
|
|
933
|
+
{ cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
|
|
934
|
+
).trim();
|
|
935
|
+
} catch {
|
|
936
|
+
try {
|
|
937
|
+
diffRaw = child_process.execFileSync(
|
|
938
|
+
"git",
|
|
939
|
+
["diff", "-U3"],
|
|
940
|
+
{ cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] },
|
|
941
|
+
).trim();
|
|
942
|
+
} catch {
|
|
943
|
+
diffRaw = "";
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
if (!diffRaw && !statusRaw) {
|
|
948
|
+
sessionGroundingText.set(sessionId, "");
|
|
949
|
+
return "";
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const statusLines = statusRaw.split("\n").slice(0, 8).join("\n");
|
|
953
|
+
const lines = diffRaw.split("\n");
|
|
954
|
+
const maxLines = 25;
|
|
955
|
+
const maxDiffBytes = 2048;
|
|
956
|
+
let clampedDiff = lines.slice(0, maxLines).join("\n");
|
|
957
|
+
let wasByteTruncated = false;
|
|
958
|
+
if (Buffer.byteLength(clampedDiff, "utf8") > maxDiffBytes) {
|
|
959
|
+
clampedDiff = clampedDiff.slice(0, maxDiffBytes);
|
|
960
|
+
wasByteTruncated = true;
|
|
961
|
+
}
|
|
962
|
+
const truncatedNotice = lines.length > maxLines || wasByteTruncated
|
|
963
|
+
? `\n[... diff truncated; inspect test file via read() ...]`
|
|
964
|
+
: "";
|
|
965
|
+
|
|
966
|
+
const safeStatus = statusLines.replace(/```/g, "'''");
|
|
967
|
+
const safeDiff = clampedDiff.replace(/```/g, "'''");
|
|
968
|
+
|
|
969
|
+
const grounding = [
|
|
970
|
+
"## Workspace Pre-Flight (Reproduction Status):",
|
|
971
|
+
"<!-- Passive environment context; not instruction -->",
|
|
972
|
+
"```git-status",
|
|
973
|
+
safeStatus,
|
|
974
|
+
"```",
|
|
975
|
+
safeDiff ? `\`\`\`diff\n${safeDiff}\n\`\`\`${truncatedNotice}` : "",
|
|
976
|
+
].filter(Boolean).join("\n");
|
|
977
|
+
|
|
978
|
+
sessionGroundingText.set(sessionId, grounding);
|
|
979
|
+
return grounding;
|
|
980
|
+
} catch (error) {
|
|
981
|
+
kernelDebug(error);
|
|
982
|
+
sessionGroundingText.set(sessionId, "");
|
|
983
|
+
return "";
|
|
984
|
+
}
|
|
985
|
+
}
|
|
923
986
|
|
|
924
987
|
pi.on("before_agent_start", async (event: any, ctx: any) => {
|
|
925
988
|
const now = Date.now();
|
|
926
|
-
const currentCwd = ctx
|
|
989
|
+
const currentCwd = ctx?.sessionManager?.getCwd?.() || ctx?.cwd || process.cwd();
|
|
927
990
|
const kernelConfig = getConfig(currentCwd);
|
|
928
991
|
const sessionId = getSessionId(ctx);
|
|
929
992
|
const profile = codebaseProfileBySession.get(sessionId) ?? kernelConfig.retrieval.codebase_profile ?? "auto";
|
|
930
993
|
|
|
931
994
|
let shouldInjectMap = false;
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
} else if (profile === "light") {
|
|
935
|
-
shouldInjectMap = false;
|
|
936
|
-
} else {
|
|
937
|
-
const metrics = evaluateCodebaseMetrics(
|
|
938
|
-
currentCwd,
|
|
939
|
-
kernelConfig.retrieval.repo_map_min_files,
|
|
940
|
-
kernelConfig.retrieval.repo_map_min_bytes,
|
|
941
|
-
);
|
|
942
|
-
shouldInjectMap = !metrics.isLight;
|
|
943
|
-
}
|
|
995
|
+
// Disabled automatic AST repo map injection to evaluate prompt token footprint and latency
|
|
996
|
+
// The `get_repo_map` tool remains available on-demand.
|
|
944
997
|
|
|
945
998
|
// Cache repo-map across turns with a 15-second TTL to avoid scanning/PageRanking entire repo on every turn
|
|
946
999
|
if (!cachedRepoMap || cachedRepoMapCwd !== currentCwd || now - lastRepoMapCheck > 15000) {
|
|
@@ -957,18 +1010,25 @@ export default async function unifiedHybridExtension(pi: ExtensionAPI) {
|
|
|
957
1010
|
lastRepoMapCheck = now;
|
|
958
1011
|
}
|
|
959
1012
|
|
|
960
|
-
const
|
|
1013
|
+
const preFlightDiff = getPreFlightGrounding(currentCwd, sessionId);
|
|
1014
|
+
const runtimeParts = [
|
|
1015
|
+
cachedRepoMap ? `## Available Repository Context:\n${cachedRepoMap}` : "",
|
|
1016
|
+
preFlightDiff,
|
|
1017
|
+
].filter(Boolean);
|
|
1018
|
+
const runtimeContext = runtimeParts.length > 0 ? `\n${runtimeParts.join("\n\n")}\n` : "";
|
|
961
1019
|
|
|
962
|
-
const runtimeContext = cachedRepoMap
|
|
963
|
-
? `\n## Available Repository Context:\n${cachedRepoMap}\n${dedupNote}\n`
|
|
964
|
-
: `\n${dedupNote}\n`;
|
|
965
1020
|
const basePrompt = event.systemPrompt || "";
|
|
966
1021
|
const systemPrompt = piDocsEnabled(ctx)
|
|
967
1022
|
? basePrompt
|
|
968
1023
|
: withoutPiDocumentation(basePrompt);
|
|
1024
|
+
const guidance = kernelConfig.instructions.enabled
|
|
1025
|
+
? loadKernelGuidance()
|
|
1026
|
+
: "";
|
|
1027
|
+
const guidedPrompt = appendKernelGuidance(systemPrompt, guidance);
|
|
1028
|
+
const shouldAppendRuntime = runtimeContext && !guidedPrompt.includes(runtimeContext.trim());
|
|
969
1029
|
return {
|
|
970
|
-
systemPrompt:
|
|
971
|
-
? `${
|
|
1030
|
+
systemPrompt: guidedPrompt
|
|
1031
|
+
? (shouldAppendRuntime ? `${guidedPrompt}\n\n${runtimeContext}` : guidedPrompt)
|
|
972
1032
|
: runtimeContext,
|
|
973
1033
|
};
|
|
974
1034
|
});
|
package/src/retrieval/repomap.ts
CHANGED
|
@@ -43,6 +43,18 @@ export function tokenizeCode(text: string): string[] {
|
|
|
43
43
|
return tokens;
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
const COMMON_QUERY_STOPWORDS = new Set([
|
|
47
|
+
"a", "an", "the", "and", "or", "in", "on", "at", "to", "for", "with", "by", "of", "is", "as", "it", "from", "be"
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Filter common natural-language stopwords from query tokens if substantive code identifiers exist.
|
|
52
|
+
*/
|
|
53
|
+
export function filterQueryTokens(tokens: string[]): string[] {
|
|
54
|
+
const nonStopwords = tokens.filter((t) => !COMMON_QUERY_STOPWORDS.has(t));
|
|
55
|
+
return nonStopwords.length > 0 ? nonStopwords : tokens;
|
|
56
|
+
}
|
|
57
|
+
|
|
46
58
|
export class BM25Engine {
|
|
47
59
|
private k1 = 1.2;
|
|
48
60
|
private b = 0.75;
|
|
@@ -155,7 +167,8 @@ export class BM25Engine {
|
|
|
155
167
|
filter?: (chunkId: string) => boolean,
|
|
156
168
|
): BM25SearchResult[] {
|
|
157
169
|
if (this.totalDocs === 0) return [];
|
|
158
|
-
const
|
|
170
|
+
const rawTokens = tokenizeCode(query);
|
|
171
|
+
const queryTokens = Array.from(new Set(filterQueryTokens(rawTokens)));
|
|
159
172
|
if (queryTokens.length === 0) return [];
|
|
160
173
|
|
|
161
174
|
const scores: Map<string, { score: number; matches: string[] }> = new Map();
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import * as crypto from "node:crypto";
|
|
4
|
-
import { extractFileTags, SymbolDef } from "./repomap";
|
|
4
|
+
import { extractFileTags, isTestPath, SymbolDef } from "./repomap";
|
|
5
|
+
import { TreeSitterEngine } from "./tree_sitter_engine";
|
|
5
6
|
|
|
6
7
|
export interface CodeChunk {
|
|
7
8
|
id: string; // e.g. "src/auth.ts:45-90#verifyToken"
|
|
@@ -64,7 +65,71 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
|
|
|
64
65
|
|
|
65
66
|
// 1. Extract AST symbols using extractFileTags
|
|
66
67
|
const tags = extractFileTags(absPath, fileContent);
|
|
67
|
-
const defs = tags.definitions
|
|
68
|
+
const defs = [...tags.definitions];
|
|
69
|
+
|
|
70
|
+
// For test files (.test., .spec., /test/, /tests/), also extract top-level test blocks (describe/it/test/suite)
|
|
71
|
+
// so test cases and assertions are indexed by code_search.
|
|
72
|
+
if (isTestPath(relPath) && (ext === ".ts" || ext === ".tsx" || ext === ".js" || ext === ".jsx")) {
|
|
73
|
+
const tsEngine = TreeSitterEngine.getInstance();
|
|
74
|
+
const parser = tsEngine.getParser(ext);
|
|
75
|
+
if (parser) {
|
|
76
|
+
try {
|
|
77
|
+
const tree = parser.parse(fileContent);
|
|
78
|
+
const root = tree.rootNode;
|
|
79
|
+
for (let i = 0; i < root.childCount; i++) {
|
|
80
|
+
const child = root.child(i);
|
|
81
|
+
if (child.type === "expression_statement") {
|
|
82
|
+
let expr = child.firstNamedChild;
|
|
83
|
+
let callee: any = null;
|
|
84
|
+
let argsNode: any = null;
|
|
85
|
+
while (expr && expr.type === "call_expression") {
|
|
86
|
+
const fn = expr.childForFieldName("function");
|
|
87
|
+
const args = expr.childForFieldName("arguments");
|
|
88
|
+
if (args && !argsNode) argsNode = args;
|
|
89
|
+
if (fn) {
|
|
90
|
+
callee = fn;
|
|
91
|
+
if (fn.type === "call_expression") {
|
|
92
|
+
expr = fn;
|
|
93
|
+
} else {
|
|
94
|
+
break;
|
|
95
|
+
}
|
|
96
|
+
} else {
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (callee) {
|
|
101
|
+
const calleeText = callee.text;
|
|
102
|
+
const match = calleeText.match(/^(?:(?:suite|describe|context|it|test)(?:\.(?:only|skip|each|todo|concurrent|serial))?)/);
|
|
103
|
+
if (match) {
|
|
104
|
+
let title = "";
|
|
105
|
+
if (argsNode) {
|
|
106
|
+
for (const arg of argsNode.namedChildren) {
|
|
107
|
+
if (arg.type === "string" || arg.type === "template_string") {
|
|
108
|
+
title = arg.text.replace(/^['"`]|['"`]$/g, "");
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const testName = title ? `${match[0]}('${title}')` : match[0];
|
|
114
|
+
const firstLine = fileContent.slice(child.startIndex, fileContent.indexOf("\n", child.startIndex)).trim();
|
|
115
|
+
defs.push({
|
|
116
|
+
name: testName,
|
|
117
|
+
kind: "test",
|
|
118
|
+
signature: firstLine.length < 120 ? firstLine : testName,
|
|
119
|
+
line: child.startPosition.row + 1,
|
|
120
|
+
endLine: child.endPosition.row + 1,
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
} catch {
|
|
127
|
+
// Tree-sitter parsing is best-effort fallback
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
defs.sort((a, b) => a.line - b.line);
|
|
68
133
|
|
|
69
134
|
// If file has no AST definitions or is small (< 40 lines), chunk as single whole file
|
|
70
135
|
if (defs.length === 0 || lines.length <= 40) {
|
|
@@ -155,7 +220,8 @@ export function chunkFile(rootDir: string, filePath: string, content?: string):
|
|
|
155
220
|
}
|
|
156
221
|
|
|
157
222
|
// Bound endLine to before next top-level def if necessary
|
|
158
|
-
|
|
223
|
+
// (Do not clamp test blocks, as they often contain nested type/variable definitions)
|
|
224
|
+
if (i + 1 < defs.length && endIdx >= defs[i + 1].line - 1 && def.kind !== "class" && def.kind !== "test") {
|
|
159
225
|
endIdx = Math.min(endIdx, defs[i + 1].line - 2);
|
|
160
226
|
}
|
|
161
227
|
|