opencode-rag-plugin 2.13.2 → 2.13.4

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.
@@ -8,9 +8,46 @@ export const BEGIN_MARKER = "<!-- BEGIN opencode-rag -->";
8
8
  /** Sentinel marker that closes the managed section. */
9
9
  export const END_MARKER = "<!-- END opencode-rag -->";
10
10
  /**
11
- * The always-on mandatory guidance lines — tool list, decision tree,
12
- * proactive triggers, and anti-patterns. Used verbatim by the runtime
13
- * system prompt injector.
11
+ * The positional rules that actually move behaviour. Measured on a live
12
+ * workspace (2026-11-11): a flat wall of ~40 MUST/NEVER lines produced exactly
13
+ * one mandated search in the first turn and abandonment afterwards (47 of 130
14
+ * searching sessions called it once; 43 % of editing sessions never called it),
15
+ * while a single ordering rule - the search goes IN the first tool batch - put
16
+ * 78 % of first searches into user turn 1. Order is therefore stated before the
17
+ * tool list, and this block is the only guidance text the compact AGENTS.md
18
+ * directive carries. Shared verbatim by both carriers, so neither can drift.
19
+ */
20
+ export const FIRST_MOVE_LINES = [
21
+ "First move, every task: `search_semantic` goes IN the first tool batch - an orientation call may share that batch, it never precedes it.",
22
+ "Re-search when the working area changes: one search per area, not one per task.",
23
+ "Authoritative elsewhere? When another system owns the current copy (source control, an MCP server, a database, an API), fetch it there first - `search_semantic` covers the local mirror and cross-cutting questions.",
24
+ "A weak result is a lead, not an answer: read the printed relevance, then verify with `read` before concluding.",
25
+ ];
26
+ /** One-line pointer used by the compact AGENTS.md directive. */
27
+ export const FULL_PROTOCOL_POINTER = "The full protocol (decision tree, proactive triggers, anti-patterns) is injected into the system prompt by the plugin - `openCode.injectSystemPrompt`. Do not restate it here.";
28
+ /**
29
+ * Resolve a configured detail level into a concrete one.
30
+ *
31
+ * An unset level stays `"full"` so callers that know nothing about the injector
32
+ * keep the standalone file they always produced.
33
+ *
34
+ * @param detail - The configured level.
35
+ * @param injectedAtRuntime - Whether `openCode.injectSystemPrompt` will put the
36
+ * full protocol into the system prompt of sessions that have the tools.
37
+ * @returns `"full"` or `"compact"`.
38
+ */
39
+ export function resolveAgentsMdDetail(detail, injectedAtRuntime) {
40
+ if (detail === "full" || detail === "compact")
41
+ return detail;
42
+ if (detail === "auto")
43
+ return injectedAtRuntime ? "compact" : "full";
44
+ return "full";
45
+ }
46
+ /**
47
+ * The always-on mandatory guidance lines - tool list, decision tree,
48
+ * proactive triggers, and anti-patterns. The runtime system prompt injector
49
+ * uses these verbatim and additionally puts {@link FIRST_MOVE_LINES} first, so
50
+ * the ordering rule is never buried under the list it governs.
14
51
  */
15
52
  export const MANDATORY_GUIDANCE_LINES = [
16
53
  "MANDATORY: OpenCodeRAG tools MUST be used before any code task:",
@@ -97,6 +134,9 @@ export function buildShellBackgroundGuidanceLines(shell) {
97
134
  }
98
135
  export function buildSystemGuidanceLines(opts) {
99
136
  const lines = [...MANDATORY_GUIDANCE_LINES];
137
+ // Positional rules go directly under the headline: the injector used to lead
138
+ // with a 40-line list, and the ordering rule got skimmed (see FIRST_MOVE_LINES).
139
+ lines.splice(1, 0, "", ...FIRST_MOVE_LINES);
100
140
  if (opts.decisionEnabled) {
101
141
  const decisionLines = [...DECISION_GUIDANCE_LINES];
102
142
  if (opts.routeBeforeAsking) {
@@ -133,12 +173,13 @@ const DECISION_AGENTS_SECTION_LINES = [
133
173
  /** Extra directive bullet, only when `decision.routeBeforeAsking` is enabled. */
134
174
  const DECISION_ROUTING_AGENTS_LINE = "- With `decision.routeBeforeAsking` enabled: route option choices through `make_decision` before asking the user; ask the user only when the model is undecided (low confidence) or the choice is preference-based.";
135
175
  /**
136
- * Build the markdown-formatted AGENTS.md directive section, wrapped in sentinel
137
- * markers so `mergeAgentsMdContent` can replace it in place on re-runs.
176
+ * The complete `AGENTS.md` directive body, without sentinel markers. This is the
177
+ * standalone form and repeats the runtime protocol on purpose: a file that has to
178
+ * work without the plugin (agents that do not load it, CI, a human reading the
179
+ * repo) must carry the whole thing.
138
180
  */
139
- export function buildAgentsMdDirective(opts) {
181
+ export function buildFullAgentsMdLines(opts) {
140
182
  const lines = [
141
- BEGIN_MARKER,
142
183
  "## Code Navigation",
143
184
  "",
144
185
  "ALWAYS use OpenCodeRAG tools before reading or editing:",
@@ -201,7 +242,52 @@ export function buildAgentsMdDirective(opts) {
201
242
  if (shellLines.length > 0) {
202
243
  lines.push("", "### Long-running commands", ...shellLines.filter((l) => l.trim().length > 0));
203
244
  }
204
- lines.push(END_MARKER);
205
- return lines.join("\n");
245
+ return lines;
246
+ }
247
+ /**
248
+ * The short `AGENTS.md` directive body: the positional rules plus a tool index
249
+ * and a pointer. Used when the runtime injector already ships the full protocol,
250
+ * so the same ~40 lines do not arrive twice in one request.
251
+ */
252
+ export function buildCompactAgentsMdLines(opts) {
253
+ const lines = [
254
+ "## Code Navigation",
255
+ "",
256
+ "OpenCodeRAG indexes this workspace.",
257
+ "",
258
+ ...FIRST_MOVE_LINES.map((line) => `- ${line}`),
259
+ "",
260
+ "Tools: `search_semantic` finds code by meaning - use it before grep; `get_file_skeleton` before reading a file; `find_usages` before editing a symbol; `describe_image` for images, never raw bytes; `recall_quirks` / `add_quirk` / `update_quirk` / `delete_quirk` for experiential memory. Signatures live in the tool schema, not here.",
261
+ "",
262
+ "A search that returns nothing useful usually means the workspace is not indexed: run `opencode-rag index` (or `opencode-rag status` to check).",
263
+ ];
264
+ if (opts.decisionEnabled) {
265
+ lines.push("", opts.routeBeforeAsking
266
+ ? "`make_decision(state, questions)` classifies/routes/scores short text with the local decision model; with `decision.routeBeforeAsking` set, route option choices through it before asking the user."
267
+ : "`make_decision(state, questions)` classifies/routes/scores short text with the local decision model; never as the only check for a high-stakes decision.");
268
+ }
269
+ if (opts.promptEnforcement) {
270
+ lines.push("", "Quirks: call `add_quirk` after resolving a failed build/test/type-check, an undocumented constraint, or a gotcha that cost more than one attempt; `update_quirk`/`delete_quirk` instead of storing a contradicting duplicate.");
271
+ }
272
+ const shellLines = buildShellBackgroundGuidanceLines(opts.shell);
273
+ if (shellLines.length > 0) {
274
+ // Same heading as the full form; the plain in-list title is dropped.
275
+ lines.push("", "### Long-running commands", ...shellLines.filter((l) => l.trim().length > 0).slice(1));
276
+ }
277
+ lines.push("", FULL_PROTOCOL_POINTER);
278
+ return lines;
279
+ }
280
+ /**
281
+ * Build the markdown-formatted `AGENTS.md` directive section, wrapped in sentinel
282
+ * markers so `mergeAgentsMdContent` can replace it in place on re-runs.
283
+ *
284
+ * @param opts - Section switches plus `agentsMdDetail` (default `"auto"`: compact
285
+ * when the runtime injector is on, full when it is off).
286
+ * @returns The marker-delimited section, without a trailing newline.
287
+ */
288
+ export function buildAgentsMdDirective(opts) {
289
+ const detail = resolveAgentsMdDetail(opts.agentsMdDetail, opts.injectedAtRuntime !== false);
290
+ const body = detail === "compact" ? buildCompactAgentsMdLines(opts) : buildFullAgentsMdLines(opts);
291
+ return [BEGIN_MARKER, ...body, END_MARKER].join("\n");
206
292
  }
207
293
  //# sourceMappingURL=system-guidance.js.map
package/dist/plugin.js CHANGED
@@ -36,6 +36,7 @@ import { detectOutputError, detectSessionError, extractExitCode, } from "./quirk
36
36
  import { createToolErrorInjectionState, recallToolErrorQuirks, formatToolErrorQuirkBlock, toToolErrorCaptureEntry, } from "./quirks/tool-error-recall.js";
37
37
  import { buildToolErrorQuirkContent, classifyToolErrorCause, createToolErrorCreateState, createToolErrorQuirk, formatToolGotchaBlock, hasEquivalentToolGotcha, selectToolGotchas, TOOL_ERROR_CREATE_DEFAULTS, TOOL_ERROR_QUIRK_TAG, } from "./quirks/tool-error-create.js";
38
38
  import { buildSystemGuidanceLines } from "./opencode/system-guidance.js";
39
+ import { weakHitAdvisory } from "./opencode/read-format.js";
39
40
  import { describeAutoInjectSelection, formatAutoInjectBlock, selectAutoInjectQuirksWithinBudget, } from "./quirks/auto-inject.js";
40
41
  import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from "node:fs";
41
42
  import path from "node:path";
@@ -417,13 +418,25 @@ export function createLiveEmbedder(getConfig, create, initial) {
417
418
  /**
418
419
  * Format retrieval results into a Markdown context block for LLM injection.
419
420
  * Includes per-chunk file paths, line numbers, relevance scores, and descriptions.
421
+ *
422
+ * A block whose average relevance sits under `weakHitThreshold` is labelled
423
+ * inline. Without the label a mandated search that returns near-noise reads as an
424
+ * answer, which is how the tool earns a reputation it does not deserve (measured
425
+ * on one workspace: 11 % of searches came back under 0.35 and the agent stopped
426
+ * calling the tool, not because it failed but because it looked pointless).
427
+ *
428
+ * @param results - Retrieval results, best first.
429
+ * @param weakHitThreshold - Average-relevance floor for the label; `0` disables it.
420
430
  */
421
- function formatContext(results) {
431
+ function formatContext(results, weakHitThreshold = 0.5) {
422
432
  if (results.length === 0)
423
433
  return "";
424
434
  const avgScore = results.reduce((sum, r) => sum + r.score, 0) / results.length;
425
435
  const parts = [];
426
436
  parts.push(`\n**${CONTEXT_MARKER}** _(context: ${results.length} chunks, avg relevance: ${avgScore.toFixed(2)})_\n`);
437
+ const advisory = weakHitAdvisory(avgScore, weakHitThreshold);
438
+ if (advisory)
439
+ parts.push(`${advisory}\n`);
427
440
  parts.push("---\n");
428
441
  for (const r of results) {
429
442
  const m = r.chunk.metadata;
@@ -771,9 +784,10 @@ export function createRagHooks(options) {
771
784
  }
772
785
  const retrievalTool = tool({
773
786
  description: "Search the indexed codebase by meaning, not just keywords. " +
774
- "ESSENTIAL before any code task — replaces blind reading with targeted retrieval. " +
775
- "Call when the user asks 'how does X work?', 'where is Y?', references files/functions you haven't read, " +
776
- "or you need to understand code behavior. Returns the most relevant code snippets with file paths, line numbers, and relevance scores.",
787
+ "Call it IN the first tool batch of any code task - before planning, reading, or answering - and again when the working area changes. " +
788
+ "Prefer it over grep for 'where is X' / 'how does X work' questions; grep stays right for an exact identifier you already have. " +
789
+ "Exception: when another system owns the current copy (source control, an MCP server, a database, an API), fetch it there first - this index covers the local mirror. " +
790
+ "Returns the most relevant code snippets with file paths, line numbers, and relevance scores; a low average score means the query was wrong, not that the code is missing.",
777
791
  args: {
778
792
  query: tool.schema.string().min(1, "A retrieval query is required."),
779
793
  pathHints: tool.schema.array(tool.schema.string().min(1)).max(10).optional(),
@@ -832,7 +846,7 @@ export function createRagHooks(options) {
832
846
  },
833
847
  };
834
848
  }
835
- const output = formatContext(results);
849
+ const output = formatContext(results, getEffectiveCfg().openCode.weakHitThreshold ?? 0.5);
836
850
  appendVerboseLog(options.logFilePath, CONTEXT_TOOL_NAME, "retrieval completed successfully", {
837
851
  query,
838
852
  pathHints: args.pathHints ?? [],
@@ -24,8 +24,32 @@ export interface ResolvedClickHouseOptions {
24
24
  }
25
25
  /** Sanitize a namespace so it is safe as a table suffix. */
26
26
  export declare function sanitizeNamespace(raw: string): string;
27
- /** Derive a stable namespace from a workspace path (name + path hash). */
27
+ /**
28
+ * Canonical form of a workspace path for namespace derivation.
29
+ *
30
+ * On Windows `path.resolve()` keeps the drive letter exactly as the caller
31
+ * spelled it, so `C:\repo` and `c:\repo` derived two different namespaces and one
32
+ * repository got indexed twice - one copy quietly going stale (measured
33
+ * 2026-11-11: `chunks_SLVSCODE_b2041fa6` current, `chunks_SLVSCODE_722a9877` five
34
+ * days behind and still serving a config file the repository had deleted). Windows
35
+ * paths are case-insensitive, so the drive letter is canonicalized here. The rest
36
+ * of the path is deliberately NOT lowercased: that would re-hash every existing
37
+ * deployment and silently orphan a populated index. A directory segment spelled
38
+ * differently still lands in its own namespace - `opencode-rag status` and
39
+ * `clickhouse adopt` surface those siblings instead of guessing.
40
+ */
41
+ export declare function canonicalizeWorkspacePath(workspaceDir: string): string;
42
+ /** Derive a stable namespace from a workspace path (name + canonical path hash). */
28
43
  export declare function deriveNamespace(workspaceDir: string): string;
44
+ /**
45
+ * Namespaces this workspace COULD have been indexed under before the drive letter
46
+ * was canonicalized. Lets a tool tell the operator "your index is alive, under
47
+ * this other name - adopt it" instead of starting from zero.
48
+ *
49
+ * @param workspaceDir - The workspace path as the caller has it.
50
+ * @returns Namespace strings, canonical form excluded, deduplicated.
51
+ */
52
+ export declare function legacyNamespaceVariants(workspaceDir: string): string[];
29
53
  /** Resolve a full ClickHouse config block (with defaults) for a workspace. */
30
54
  export declare function resolveClickHouseOptions(config: RagConfig, workspaceDir: string): ResolvedClickHouseOptions;
31
55
  /**
@@ -39,13 +39,55 @@ export function sanitizeNamespace(raw) {
39
39
  .slice(0, 40);
40
40
  return cleaned.length > 0 ? cleaned : "default";
41
41
  }
42
- /** Derive a stable namespace from a workspace path (name + path hash). */
43
- export function deriveNamespace(workspaceDir) {
42
+ /**
43
+ * Canonical form of a workspace path for namespace derivation.
44
+ *
45
+ * On Windows `path.resolve()` keeps the drive letter exactly as the caller
46
+ * spelled it, so `C:\repo` and `c:\repo` derived two different namespaces and one
47
+ * repository got indexed twice - one copy quietly going stale (measured
48
+ * 2026-11-11: `chunks_SLVSCODE_b2041fa6` current, `chunks_SLVSCODE_722a9877` five
49
+ * days behind and still serving a config file the repository had deleted). Windows
50
+ * paths are case-insensitive, so the drive letter is canonicalized here. The rest
51
+ * of the path is deliberately NOT lowercased: that would re-hash every existing
52
+ * deployment and silently orphan a populated index. A directory segment spelled
53
+ * differently still lands in its own namespace - `opencode-rag status` and
54
+ * `clickhouse adopt` surface those siblings instead of guessing.
55
+ */
56
+ export function canonicalizeWorkspacePath(workspaceDir) {
44
57
  const absolute = path.resolve(workspaceDir);
58
+ if (process.platform !== "win32")
59
+ return absolute;
60
+ return absolute.replace(/^([a-z])(:)/, (_m, drive, sep) => drive.toUpperCase() + sep);
61
+ }
62
+ /** Derive a stable namespace from a workspace path (name + canonical path hash). */
63
+ export function deriveNamespace(workspaceDir) {
64
+ const absolute = canonicalizeWorkspacePath(workspaceDir);
45
65
  const base = path.basename(absolute) || "workspace";
46
66
  const hash = createHash("sha1").update(absolute).digest("hex").slice(0, 8);
47
67
  return sanitizeNamespace(`${base}_${hash}`);
48
68
  }
69
+ /**
70
+ * Namespaces this workspace COULD have been indexed under before the drive letter
71
+ * was canonicalized. Lets a tool tell the operator "your index is alive, under
72
+ * this other name - adopt it" instead of starting from zero.
73
+ *
74
+ * @param workspaceDir - The workspace path as the caller has it.
75
+ * @returns Namespace strings, canonical form excluded, deduplicated.
76
+ */
77
+ export function legacyNamespaceVariants(workspaceDir) {
78
+ const canonical = deriveNamespace(workspaceDir);
79
+ const raw = path.resolve(workspaceDir);
80
+ const spellings = new Set([raw, raw.charAt(0).toLowerCase() + raw.slice(1), raw.charAt(0).toUpperCase() + raw.slice(1)]);
81
+ const out = [];
82
+ for (const spelling of spellings) {
83
+ const base = path.basename(spelling) || "workspace";
84
+ const hash = createHash("sha1").update(spelling).digest("hex").slice(0, 8);
85
+ const ns = sanitizeNamespace(`${base}_${hash}`);
86
+ if (ns !== canonical && !out.includes(ns))
87
+ out.push(ns);
88
+ }
89
+ return out;
90
+ }
49
91
  /** Resolve a full ClickHouse config block (with defaults) for a workspace. */
50
92
  export function resolveClickHouseOptions(config, workspaceDir) {
51
93
  const ch = config.vectorStore.clickhouse;