opencode-rag-plugin 2.5.3 → 2.7.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.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * @fileoverview Tool-error → quirk creation: when a tool call fails and NO
3
+ * existing quirk covers the failure, record a new one so future sessions can
4
+ * recall it.
5
+ *
6
+ * Design notes:
7
+ * - Pure and dependency-injected: the caller passes an `add` function (the plugin
8
+ * binds `addQuirk`), so this module has no store/embedder dependencies and is
9
+ * cheap to unit-test.
10
+ * - Deterministic content: no LLM is involved. The quirk is a template built
11
+ * from the tool name and the error text, plus an optional deterministic cause
12
+ * for a handful of well-known error classes. This keeps the path available
13
+ * even when `description.enabled` is false (the LLM-based auto-capture
14
+ * pipeline is inert then) and keeps it off the critical latency path.
15
+ * - Bounded: a per-session budget and a per-error-signature cooldown cap how
16
+ * many quirks a failing session can write. Cross-session duplication is
17
+ * prevented by the semantic recall that runs BEFORE creation — the quirk
18
+ * written for a failure is recalled on the next occurrence of that failure.
19
+ * - The trust monitor is NOT bypassed. A rejected quirk (e.g. an error text
20
+ * that contains `rm -rf`) is reported as "not created" with a reason; the
21
+ * caller logs it.
22
+ */
23
+ import type { Quirk, QuirkInput } from "./types.js";
24
+ import { type ToolErrorInfo } from "./tool-error-recall.js";
25
+ /** Tag every auto-created tool-error quirk carries. */
26
+ export declare const TOOL_ERROR_QUIRK_TAG = "tool-error";
27
+ /** Second tag marking the quirk as machine-created (not agent-authored). */
28
+ export declare const TOOL_ERROR_AUTO_TAG = "auto-created";
29
+ /** Defaults for the tool-error creation path. */
30
+ export declare const TOOL_ERROR_CREATE_DEFAULTS: {
31
+ /**
32
+ * Minimum raw similarity for a candidate to count as "an equivalent quirk
33
+ * already exists" (and therefore suppress creation). Default 0.6 — below
34
+ * the 0.7 injection bar, so a probable match still blocks a duplicate.
35
+ */
36
+ readonly minScore: 0.6;
37
+ /** Maximum quirks created per session. Default 2. */
38
+ readonly maxPerSession: 2;
39
+ /** Cooldown per normalized error signature in ms. Default 10 minutes. */
40
+ readonly cooldownMs: 600000;
41
+ /** Error text is truncated to this length before it becomes quirk content. */
42
+ readonly maxErrorChars: 400;
43
+ /** Hard cap on the generated quirk content. */
44
+ readonly maxContentChars: 300;
45
+ /** Confidence assigned to an auto-created quirk. */
46
+ readonly confidence: 0.6;
47
+ /** Errors shorter than this carry no information — nothing is recorded. */
48
+ readonly minErrorChars: 15;
49
+ };
50
+ /**
51
+ * Classify an error message into a short, deterministic cause.
52
+ *
53
+ * Returns `undefined` for unknown errors — the raw text is then the whole
54
+ * story.
55
+ */
56
+ export declare function classifyToolError(error: string): string | undefined;
57
+ /**
58
+ * Build the quirk content for a failed tool call.
59
+ *
60
+ * The tool name and the error text are embedded verbatim (whitespace
61
+ * collapsed, truncated) on purpose: a later occurrence of the same failure
62
+ * must share tokens with this content (the lexical recall gate) and embed
63
+ * close to it (the semantic gate), otherwise the creation path would fire
64
+ * again and again for the same error.
65
+ */
66
+ export declare function buildToolErrorQuirkContent(info: ToolErrorInfo): string;
67
+ /** True when the error carries enough information to be worth recording. */
68
+ export declare function isWorthRecordingToolError(info: ToolErrorInfo): boolean;
69
+ /** Tunables for the per-session creation state. */
70
+ export interface ToolErrorCreateOptions {
71
+ /** Maximum quirks created per session. Default 2. */
72
+ maxPerSession?: number;
73
+ /** Cooldown per normalized error signature in ms. Default 600000 (10 min). */
74
+ cooldownMs?: number;
75
+ }
76
+ /** Per-session creation bookkeeping (budget, cooldown, created signatures). */
77
+ export interface ToolErrorCreateState {
78
+ /** True when a new quirk may be created (budget left, signature not cooling down). */
79
+ shouldCreate(info: ToolErrorInfo, now?: number): boolean;
80
+ /** Record the attempt. Always refreshes the cooldown; consumes budget only when `created` is true. */
81
+ record(info: ToolErrorInfo, created: boolean, now?: number): void;
82
+ /** Normalized error signatures that already produced a quirk in this session. */
83
+ readonly createdSignatures: ReadonlySet<string>;
84
+ /** Number of quirks actually created in this session. */
85
+ creationCount(): number;
86
+ }
87
+ /** Create the per-session creation state. */
88
+ export declare function createToolErrorCreateState(options?: ToolErrorCreateOptions): ToolErrorCreateState;
89
+ /** The function that persists a quirk; injected so the module stays testable. */
90
+ export type ToolErrorQuirkAddFn = (input: QuirkInput) => Promise<Quirk>;
91
+ /** Dependencies for the creation path. */
92
+ export interface ToolErrorQuirkDeps {
93
+ /** Persists the quirk. The plugin binds `addQuirk` to the quirk store deps. */
94
+ add: ToolErrorQuirkAddFn;
95
+ }
96
+ /** The outcome of a creation attempt. */
97
+ export interface ToolErrorQuirkCreateResult {
98
+ /** True when a quirk was written. */
99
+ created: boolean;
100
+ /** The new quirk's id (only when `created`). */
101
+ id?: string;
102
+ /** Why nothing was created (e.g. trust-monitor rejection, error too short). */
103
+ reason?: string;
104
+ }
105
+ /**
106
+ * Create and persist a quirk for a failed tool call.
107
+ *
108
+ * Never throws: a trust-monitor rejection or a store failure is reported as
109
+ * `created: false` with a reason so the caller can log it and carry on.
110
+ */
111
+ export declare function createToolErrorQuirk(deps: ToolErrorQuirkDeps, info: ToolErrorInfo, content?: string): Promise<ToolErrorQuirkCreateResult>;
@@ -0,0 +1,173 @@
1
+ /**
2
+ * @fileoverview Tool-error → quirk creation: when a tool call fails and NO
3
+ * existing quirk covers the failure, record a new one so future sessions can
4
+ * recall it.
5
+ *
6
+ * Design notes:
7
+ * - Pure and dependency-injected: the caller passes an `add` function (the plugin
8
+ * binds `addQuirk`), so this module has no store/embedder dependencies and is
9
+ * cheap to unit-test.
10
+ * - Deterministic content: no LLM is involved. The quirk is a template built
11
+ * from the tool name and the error text, plus an optional deterministic cause
12
+ * for a handful of well-known error classes. This keeps the path available
13
+ * even when `description.enabled` is false (the LLM-based auto-capture
14
+ * pipeline is inert then) and keeps it off the critical latency path.
15
+ * - Bounded: a per-session budget and a per-error-signature cooldown cap how
16
+ * many quirks a failing session can write. Cross-session duplication is
17
+ * prevented by the semantic recall that runs BEFORE creation — the quirk
18
+ * written for a failure is recalled on the next occurrence of that failure.
19
+ * - The trust monitor is NOT bypassed. A rejected quirk (e.g. an error text
20
+ * that contains `rm -rf`) is reported as "not created" with a reason; the
21
+ * caller logs it.
22
+ */
23
+ import { normalizeToolErrorSignature } from "./tool-error-recall.js";
24
+ /** Tag every auto-created tool-error quirk carries. */
25
+ export const TOOL_ERROR_QUIRK_TAG = "tool-error";
26
+ /** Second tag marking the quirk as machine-created (not agent-authored). */
27
+ export const TOOL_ERROR_AUTO_TAG = "auto-created";
28
+ /** Defaults for the tool-error creation path. */
29
+ export const TOOL_ERROR_CREATE_DEFAULTS = {
30
+ /**
31
+ * Minimum raw similarity for a candidate to count as "an equivalent quirk
32
+ * already exists" (and therefore suppress creation). Default 0.6 — below
33
+ * the 0.7 injection bar, so a probable match still blocks a duplicate.
34
+ */
35
+ minScore: 0.6,
36
+ /** Maximum quirks created per session. Default 2. */
37
+ maxPerSession: 2,
38
+ /** Cooldown per normalized error signature in ms. Default 10 minutes. */
39
+ cooldownMs: 600_000,
40
+ /** Error text is truncated to this length before it becomes quirk content. */
41
+ maxErrorChars: 400,
42
+ /** Hard cap on the generated quirk content. */
43
+ maxContentChars: 300,
44
+ /** Confidence assigned to an auto-created quirk. */
45
+ confidence: 0.6,
46
+ /** Errors shorter than this carry no information — nothing is recorded. */
47
+ minErrorChars: 15,
48
+ };
49
+ /** Known error classes with a deterministic, actionable cause. */
50
+ const ERROR_CAUSES = [
51
+ {
52
+ pattern: /unknown tool|no such tool|tool .*not found|not a registered tool/i,
53
+ cause: "the tool name may be wrong, or the tool is not available in this session",
54
+ },
55
+ {
56
+ pattern: /enoent|no such file or directory|cannot find module/i,
57
+ cause: "the path or module name may be wrong",
58
+ },
59
+ {
60
+ pattern: /eacces|permission denied/i,
61
+ cause: "the path may need different permissions",
62
+ },
63
+ {
64
+ pattern: /expected .*(received|but got)|invalid argument|invalid type|schema|must be (a|an|string|number|boolean|object|array)/i,
65
+ cause: "the arguments do not match the tool's schema",
66
+ },
67
+ {
68
+ pattern: /\b429\b|rate limit|too many requests/i,
69
+ cause: "the request was rate limited — retry later",
70
+ },
71
+ {
72
+ pattern: /timed? ?out|timeout|etimedout/i,
73
+ cause: "the operation timed out",
74
+ },
75
+ ];
76
+ /**
77
+ * Classify an error message into a short, deterministic cause.
78
+ *
79
+ * Returns `undefined` for unknown errors — the raw text is then the whole
80
+ * story.
81
+ */
82
+ export function classifyToolError(error) {
83
+ for (const { pattern, cause } of ERROR_CAUSES) {
84
+ if (pattern.test(error))
85
+ return cause;
86
+ }
87
+ return undefined;
88
+ }
89
+ /**
90
+ * Build the quirk content for a failed tool call.
91
+ *
92
+ * The tool name and the error text are embedded verbatim (whitespace
93
+ * collapsed, truncated) on purpose: a later occurrence of the same failure
94
+ * must share tokens with this content (the lexical recall gate) and embed
95
+ * close to it (the semantic gate), otherwise the creation path would fire
96
+ * again and again for the same error.
97
+ */
98
+ export function buildToolErrorQuirkContent(info) {
99
+ const error = info.error
100
+ .replace(/\s+/g, " ")
101
+ .trim()
102
+ .slice(0, TOOL_ERROR_CREATE_DEFAULTS.maxErrorChars);
103
+ const cause = classifyToolError(info.error);
104
+ const base = `Tool \`${info.tool}\` failed: ${error}`;
105
+ const content = cause ? `${base} — ${cause}` : base;
106
+ return content.slice(0, TOOL_ERROR_CREATE_DEFAULTS.maxContentChars);
107
+ }
108
+ /** True when the error carries enough information to be worth recording. */
109
+ export function isWorthRecordingToolError(info) {
110
+ return info.error.replace(/\s+/g, " ").trim().length >= TOOL_ERROR_CREATE_DEFAULTS.minErrorChars;
111
+ }
112
+ /** Create the per-session creation state. */
113
+ export function createToolErrorCreateState(options) {
114
+ const cooldownMs = options?.cooldownMs ?? TOOL_ERROR_CREATE_DEFAULTS.cooldownMs;
115
+ const maxPerSession = options?.maxPerSession ?? TOOL_ERROR_CREATE_DEFAULTS.maxPerSession;
116
+ const lastAttemptAt = new Map();
117
+ const createdSignatures = new Set();
118
+ let creations = 0;
119
+ return {
120
+ shouldCreate(info, now = Date.now()) {
121
+ if (creations >= maxPerSession)
122
+ return false;
123
+ const signature = normalizeToolErrorSignature(info);
124
+ const last = lastAttemptAt.get(signature);
125
+ if (last !== undefined && now - last < cooldownMs)
126
+ return false;
127
+ return true;
128
+ },
129
+ record(info, created, now = Date.now()) {
130
+ const signature = normalizeToolErrorSignature(info);
131
+ lastAttemptAt.set(signature, now);
132
+ if (!created)
133
+ return;
134
+ creations += 1;
135
+ createdSignatures.add(signature);
136
+ },
137
+ get createdSignatures() {
138
+ return createdSignatures;
139
+ },
140
+ creationCount() {
141
+ return creations;
142
+ },
143
+ };
144
+ }
145
+ /**
146
+ * Create and persist a quirk for a failed tool call.
147
+ *
148
+ * Never throws: a trust-monitor rejection or a store failure is reported as
149
+ * `created: false` with a reason so the caller can log it and carry on.
150
+ */
151
+ export async function createToolErrorQuirk(deps, info, content) {
152
+ if (!isWorthRecordingToolError(info)) {
153
+ return { created: false, reason: "error text too short to record" };
154
+ }
155
+ const text = (content ?? buildToolErrorQuirkContent(info)).trim();
156
+ if (!text) {
157
+ return { created: false, reason: "empty quirk content" };
158
+ }
159
+ try {
160
+ const quirk = await deps.add({
161
+ content: text,
162
+ quirkType: "gotcha",
163
+ tags: [TOOL_ERROR_QUIRK_TAG, TOOL_ERROR_AUTO_TAG, `tool:${info.tool}`],
164
+ confidence: TOOL_ERROR_CREATE_DEFAULTS.confidence,
165
+ sourceRef: `tool-error:${info.tool}`,
166
+ });
167
+ return { created: true, id: quirk.id };
168
+ }
169
+ catch (err) {
170
+ return { created: false, reason: err instanceof Error ? err.message : String(err) };
171
+ }
172
+ }
173
+ //# sourceMappingURL=tool-error-create.js.map
@@ -13,6 +13,12 @@
13
13
  * - A failed recall still counts as an attempt (cooldown), so a repeatedly failing
14
14
  * tool does not hammer the embedder every call — but it does not consume the
15
15
  * per-session budget; only actual injections do.
16
+ * - Two similarity bars: the recall FLOOR (`minScore`) decides which quirks are
17
+ * candidates at all, the INJECTION bar (`injectMinScore`) decides which of them
18
+ * are injected. The gap between them is the "probable match" tier — it suppresses
19
+ * quirk creation but is only injected when no confident match exists. The bars are
20
+ * compared against the RAW vector similarity, never against the confidence-
21
+ * discounted `score` (see `rawSimilarity`).
16
22
  */
17
23
  /** A failed tool call as observed by the plugin. */
18
24
  export interface ToolErrorInfo {
@@ -30,9 +36,19 @@ export interface ToolErrorRecallHit {
30
36
  content: string;
31
37
  metadata?: {
32
38
  quirkType?: string;
39
+ tags?: string[];
33
40
  };
34
41
  };
35
42
  score: number;
43
+ /**
44
+ * Raw vector similarity (0-1) — the cosine-mapped similarity WITHOUT the
45
+ * confidence discount that `recallQuirks` applies to `score`
46
+ * (`score = similarity * confidence`). Thresholds must be compared against
47
+ * this field; `score` is not comparable to a similarity threshold because a
48
+ * high-confidence quirk and a low-confidence one with the same similarity get
49
+ * different scores. Falls back to `score` when the caller cannot provide it.
50
+ */
51
+ rawSimilarity?: number;
36
52
  }
37
53
  /** Recall function the caller provides (usually a `recallQuirks` wrapper). */
38
54
  export type ToolErrorRecallFn = (query: string, options: {
@@ -45,15 +61,34 @@ export interface ToolErrorQuirkHit {
45
61
  content: string;
46
62
  quirkType?: string;
47
63
  score: number;
64
+ /** Raw vector similarity (0-1) — the value thresholds are compared against. */
65
+ rawSimilarity: number;
48
66
  }
49
67
  /** Tunables for the tool-error quirk path. */
50
68
  export interface ToolErrorRecallOptions {
51
- /** Minimum recall score for a quirk to be injected. Default 0.7. */
69
+ /**
70
+ * Recall floor — the minimum raw similarity a candidate must clear to be
71
+ * returned by the recall at all. Default 0.7.
72
+ */
52
73
  minScore?: number;
74
+ /**
75
+ * Threshold a candidate must clear to be INJECTED. Defaults to `minScore`.
76
+ * A candidate between the floor and this threshold is a "probable match": it
77
+ * suppresses quirk creation but is only injected when no confident match
78
+ * exists.
79
+ */
80
+ injectMinScore?: number;
53
81
  /** Maximum quirks injected per error. Default 2. */
54
82
  topK?: number;
55
83
  /** Minimum shared meaningful words (>=3 chars) between quirk and error. 0 disables. Default 1. */
56
84
  minTokenOverlap?: number;
85
+ /**
86
+ * Whether the per-session injection budget may block the recall outright
87
+ * (default true). Set to `false` when the caller still needs the candidate
88
+ * list even though it may not inject anything — e.g. to decide whether a
89
+ * quirk already exists. The cooldown still applies either way.
90
+ */
91
+ enforceBudget?: boolean;
57
92
  }
58
93
  /** Tunables for the per-session injection state. */
59
94
  export interface ToolErrorInjectionOptions {
@@ -66,6 +101,16 @@ export interface ToolErrorInjectionOptions {
66
101
  export interface ToolErrorInjectionState {
67
102
  /** True when this error may trigger a recall (budget left, signature not cooling down). */
68
103
  shouldInject(info: ToolErrorInfo, now?: number): boolean;
104
+ /**
105
+ * True when the per-signature cooldown blocks this error. Independent of the
106
+ * per-session budget — a cooled-down error must not trigger another recall
107
+ * (that is what stops a repeatedly failing tool from hammering the
108
+ * embedder), while an exhausted budget is a *context* limit that must not
109
+ * also block quirk creation.
110
+ */
111
+ isCoolingDown(info: ToolErrorInfo, now?: number): boolean;
112
+ /** True when the per-session injection budget still has room. */
113
+ hasBudget(): boolean;
69
114
  /** Record an attempt. Always refreshes the cooldown; counts toward the budget only when quirkIds is non-empty. */
70
115
  record(info: ToolErrorInfo, quirkIds: readonly string[], now?: number): void;
71
116
  /** Quirk ids already injected in this session. */
@@ -91,6 +136,34 @@ export declare function normalizeToolErrorSignature(info: ToolErrorInfo): string
91
136
  export declare function buildToolErrorQuery(info: ToolErrorInfo): string;
92
137
  /** Create the per-session injection state. */
93
138
  export declare function createToolErrorInjectionState(options?: ToolErrorInjectionOptions): ToolErrorInjectionState;
139
+ /** The outcome of a single tool-error recall. */
140
+ export interface ToolErrorRecallResult {
141
+ /**
142
+ * Hits that may be injected right now: they cleared the injection bar and
143
+ * were not already injected in this session.
144
+ */
145
+ inject: ToolErrorQuirkHit[];
146
+ /**
147
+ * Every hit that cleared the recall floor, sorted by raw similarity
148
+ * descending. Includes already-injected quirks — the caller uses this to
149
+ * decide whether a quirk ALREADY EXISTS (which suppresses creation) even
150
+ * when it must not be injected again.
151
+ */
152
+ candidates: ToolErrorQuirkHit[];
153
+ /** True when the attempt was blocked by the cooldown or the per-session budget. */
154
+ blocked: boolean;
155
+ }
156
+ /**
157
+ * Recall quirks for a failed tool call and tier them by raw similarity.
158
+ *
159
+ * The recall happens ONCE, at the floor (`minScore`), so the caller can tell
160
+ * "a confident match exists" from "only a probable match exists" from "no
161
+ * match at all" without paying for a second embedding.
162
+ *
163
+ * This function does NOT mutate the injection state — the caller records the
164
+ * attempt (and the injected ids) once it has decided what to inject.
165
+ */
166
+ export declare function recallToolErrorQuirks(recall: ToolErrorRecallFn, info: ToolErrorInfo, state: ToolErrorInjectionState, options?: ToolErrorRecallOptions): Promise<ToolErrorRecallResult>;
94
167
  /**
95
168
  * Select quirks for a failed tool call.
96
169
  *
@@ -100,7 +173,9 @@ export declare function createToolErrorInjectionState(options?: ToolErrorInjecti
100
173
  */
101
174
  export declare function selectToolErrorQuirks(recall: ToolErrorRecallFn, info: ToolErrorInfo, state: ToolErrorInjectionState, options?: ToolErrorRecallOptions): Promise<ToolErrorQuirkHit[]>;
102
175
  /** Format the injection block appended to the next model request. Empty when there are no hits. */
103
- export declare function formatToolErrorQuirkBlock(info: ToolErrorInfo, hits: readonly ToolErrorQuirkHit[]): string;
176
+ export declare function formatToolErrorQuirkBlock(info: ToolErrorInfo, hits: readonly ToolErrorQuirkHit[], options?: {
177
+ heading?: string;
178
+ }): string;
104
179
  /**
105
180
  * Shape a tool error as an entry for the existing auto-capture pipeline
106
181
  * (`CaptureExchange.toolResults`). Feed the returned entry into the session's
@@ -13,6 +13,12 @@
13
13
  * - A failed recall still counts as an attempt (cooldown), so a repeatedly failing
14
14
  * tool does not hammer the embedder every call — but it does not consume the
15
15
  * per-session budget; only actual injections do.
16
+ * - Two similarity bars: the recall FLOOR (`minScore`) decides which quirks are
17
+ * candidates at all, the INJECTION bar (`injectMinScore`) decides which of them
18
+ * are injected. The gap between them is the "probable match" tier — it suppresses
19
+ * quirk creation but is only injected when no confident match exists. The bars are
20
+ * compared against the RAW vector similarity, never against the confidence-
21
+ * discounted `score` (see `rawSimilarity`).
16
22
  */
17
23
  import { sharedWords } from "./quirk-store.js";
18
24
  /** Defaults shared by the state factory and the selector. */
@@ -51,13 +57,17 @@ export function createToolErrorInjectionState(options) {
51
57
  let injections = 0;
52
58
  return {
53
59
  shouldInject(info, now = Date.now()) {
54
- if (injections >= maxPerSession)
60
+ if (!this.hasBudget())
55
61
  return false;
62
+ return !this.isCoolingDown(info, now);
63
+ },
64
+ isCoolingDown(info, now = Date.now()) {
56
65
  const signature = normalizeToolErrorSignature(info);
57
66
  const last = lastAttemptAt.get(signature);
58
- if (last !== undefined && now - last < cooldownMs)
59
- return false;
60
- return true;
67
+ return last !== undefined && now - last < cooldownMs;
68
+ },
69
+ hasBudget() {
70
+ return injections < maxPerSession;
61
71
  },
62
72
  record(info, quirkIds, now = Date.now()) {
63
73
  lastAttemptAt.set(normalizeToolErrorSignature(info), now);
@@ -76,16 +86,25 @@ export function createToolErrorInjectionState(options) {
76
86
  };
77
87
  }
78
88
  /**
79
- * Select quirks for a failed tool call.
89
+ * Recall quirks for a failed tool call and tier them by raw similarity.
80
90
  *
81
- * Returns `[]` when the state blocks the attempt (cooldown/budget) or nothing
82
- * passes the score, dedup, and lexical gates. Records the attempt in the state —
83
- * with cooldown always, with budget only when at least one quirk is returned.
91
+ * The recall happens ONCE, at the floor (`minScore`), so the caller can tell
92
+ * "a confident match exists" from "only a probable match exists" from "no
93
+ * match at all" without paying for a second embedding.
94
+ *
95
+ * This function does NOT mutate the injection state — the caller records the
96
+ * attempt (and the injected ids) once it has decided what to inject.
84
97
  */
85
- export async function selectToolErrorQuirks(recall, info, state, options) {
86
- if (!state.shouldInject(info))
87
- return [];
98
+ export async function recallToolErrorQuirks(recall, info, state, options) {
99
+ const budgetAvailable = state.hasBudget();
100
+ if (state.isCoolingDown(info)) {
101
+ return { inject: [], candidates: [], blocked: true };
102
+ }
103
+ if (!budgetAvailable && options?.enforceBudget !== false) {
104
+ return { inject: [], candidates: [], blocked: true };
105
+ }
88
106
  const minScore = options?.minScore ?? TOOL_ERROR_DEFAULTS.minScore;
107
+ const injectMinScore = options?.injectMinScore ?? minScore;
89
108
  const topK = options?.topK ?? TOOL_ERROR_DEFAULTS.topK;
90
109
  const minTokenOverlap = options?.minTokenOverlap ?? TOOL_ERROR_DEFAULTS.minTokenOverlap;
91
110
  let raw = [];
@@ -94,17 +113,15 @@ export async function selectToolErrorQuirks(recall, info, state, options) {
94
113
  raw = await recall(buildToolErrorQuery(info), { topK: Math.max(topK * 3, 6), minScore });
95
114
  }
96
115
  catch {
97
- // Recall failures must never break tool execution; fall through to recording.
98
- state.record(info, []);
99
- return [];
116
+ // Recall failures must never break tool execution; the caller still
117
+ // records the attempt so the cooldown applies.
118
+ return { inject: [], candidates: [], blocked: false };
100
119
  }
101
120
  // Filter everything first, then sort and slice — otherwise the topK cut
102
121
  // would keep the first raw entries instead of the highest-scoring ones.
103
122
  const candidates = [];
104
123
  for (const hit of raw) {
105
124
  const { id, content } = hit.chunk;
106
- if (state.injectedQuirkIds.has(id))
107
- continue;
108
125
  if (minTokenOverlap > 0 && sharedWords(content, info.error) < minTokenOverlap)
109
126
  continue;
110
127
  candidates.push({
@@ -112,18 +129,37 @@ export async function selectToolErrorQuirks(recall, info, state, options) {
112
129
  content,
113
130
  quirkType: hit.chunk.metadata?.quirkType,
114
131
  score: hit.score,
132
+ rawSimilarity: hit.rawSimilarity ?? hit.score,
115
133
  });
116
134
  }
117
- candidates.sort((a, b) => b.score - a.score);
118
- const hits = candidates.slice(0, topK);
119
- state.record(info, hits.map((h) => h.id));
120
- return hits;
135
+ candidates.sort((a, b) => b.rawSimilarity - a.rawSimilarity);
136
+ const inject = budgetAvailable
137
+ ? candidates
138
+ .filter((c) => c.rawSimilarity >= injectMinScore && !state.injectedQuirkIds.has(c.id))
139
+ .slice(0, topK)
140
+ : [];
141
+ return { inject, candidates, blocked: false };
142
+ }
143
+ /**
144
+ * Select quirks for a failed tool call.
145
+ *
146
+ * Returns `[]` when the state blocks the attempt (cooldown/budget) or nothing
147
+ * passes the score, dedup, and lexical gates. Records the attempt in the state —
148
+ * with cooldown always, with budget only when at least one quirk is returned.
149
+ */
150
+ export async function selectToolErrorQuirks(recall, info, state, options) {
151
+ const result = await recallToolErrorQuirks(recall, info, state, options);
152
+ if (result.blocked)
153
+ return [];
154
+ state.record(info, result.inject.map((h) => h.id));
155
+ return result.inject;
121
156
  }
122
157
  /** Format the injection block appended to the next model request. Empty when there are no hits. */
123
- export function formatToolErrorQuirkBlock(info, hits) {
158
+ export function formatToolErrorQuirkBlock(info, hits, options) {
124
159
  if (hits.length === 0)
125
160
  return "";
126
- const lines = ["", "---", `⚠ **Tool error** \`${info.tool}\` — matching quirk memory:`, ""];
161
+ const heading = options?.heading ?? `⚠ **Tool error** \`${info.tool}\` — matching quirk memory:`;
162
+ const lines = ["", "---", heading, ""];
127
163
  for (const hit of hits) {
128
164
  const badge = hit.quirkType ? `[\`${hit.quirkType}\`] ` : "";
129
165
  lines.push(`- ${badge}${hit.content}`);
@@ -45,6 +45,16 @@ export declare class KeywordIndex {
45
45
  clear(): void;
46
46
  count(): number;
47
47
  hasChunk(id: string): boolean;
48
+ /**
49
+ * Normalized file paths that currently have at least one indexed chunk.
50
+ *
51
+ * The keyword index and the vector store are two independent stores of the
52
+ * same corpus, and nothing keeps them in sync by construction: an
53
+ * incremental index pass only calls {@link addChunks} for the files it
54
+ * reprocessed, so a once-partial index stays partial forever. Comparing
55
+ * this list with the store's file list is how that drift is detected.
56
+ */
57
+ getIndexedFilePaths(): string[];
48
58
  save(storePath?: string): Promise<void>;
49
59
  static load(storePath: string): Promise<KeywordIndex>;
50
60
  static clearFile(storePath: string): Promise<void>;
@@ -276,6 +276,18 @@ export class KeywordIndex {
276
276
  hasChunk(id) {
277
277
  return this.chunkMap.has(id);
278
278
  }
279
+ /**
280
+ * Normalized file paths that currently have at least one indexed chunk.
281
+ *
282
+ * The keyword index and the vector store are two independent stores of the
283
+ * same corpus, and nothing keeps them in sync by construction: an
284
+ * incremental index pass only calls {@link addChunks} for the files it
285
+ * reprocessed, so a once-partial index stays partial forever. Comparing
286
+ * this list with the store's file list is how that drift is detected.
287
+ */
288
+ getIndexedFilePaths() {
289
+ return [...this.fileToIds.keys()];
290
+ }
279
291
  async save(storePath) {
280
292
  const effectiveStorePath = storePath ?? this.storePath;
281
293
  if (!effectiveStorePath)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-rag-plugin",
3
- "version": "2.5.3",
3
+ "version": "2.7.0",
4
4
  "description": "OpenCode plugin for local-first RAG-based semantic code search",
5
5
  "type": "module",
6
6
  "main": "./dist/plugin-entry.js",