opencode-rag-plugin 2.3.0 → 2.4.1

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.
Files changed (71) hide show
  1. package/ReadMe.md +73 -8
  2. package/dist/chunker/skeleton.js +1 -1
  3. package/dist/cli/commands/decide.d.ts +25 -0
  4. package/dist/cli/commands/decide.js +160 -0
  5. package/dist/cli/commands/eval.d.ts +23 -0
  6. package/dist/cli/commands/eval.js +331 -1
  7. package/dist/cli/commands/index-command.js +28 -10
  8. package/dist/cli/commands/index.d.ts +2 -1
  9. package/dist/cli/commands/index.js +2 -1
  10. package/dist/cli/commands/init-helpers.d.ts +20 -2
  11. package/dist/cli/commands/init-helpers.js +139 -22
  12. package/dist/cli/commands/init.js +42 -5
  13. package/dist/cli/commands/setup.js +43 -12
  14. package/dist/cli/commands/status.js +14 -8
  15. package/dist/cli/commands/update.d.ts +3 -2
  16. package/dist/cli/commands/update.js +7 -3
  17. package/dist/cli/format.d.ts +50 -0
  18. package/dist/cli/format.js +122 -0
  19. package/dist/cli/index.js +4 -1
  20. package/dist/cli/types.d.ts +2 -0
  21. package/dist/core/bootstrap.js +1 -0
  22. package/dist/core/config.d.ts +54 -2
  23. package/dist/core/config.js +36 -3
  24. package/dist/core/interfaces.d.ts +69 -0
  25. package/dist/core/package-manager.d.ts +69 -0
  26. package/dist/core/package-manager.js +250 -0
  27. package/dist/core/setup-runtime.d.ts +7 -4
  28. package/dist/core/setup-runtime.js +33 -31
  29. package/dist/core/version-check.d.ts +19 -11
  30. package/dist/core/version-check.js +30 -11
  31. package/dist/decision/factory.d.ts +17 -0
  32. package/dist/decision/factory.js +17 -0
  33. package/dist/decision/format.d.ts +14 -0
  34. package/dist/decision/format.js +53 -0
  35. package/dist/decision/systemone.d.ts +76 -0
  36. package/dist/decision/systemone.js +234 -0
  37. package/dist/decision/validate.d.ts +26 -0
  38. package/dist/decision/validate.js +74 -0
  39. package/dist/eval/decide-calibration.d.ts +112 -0
  40. package/dist/eval/decide-calibration.js +185 -0
  41. package/dist/eval/golden-gate.d.ts +65 -0
  42. package/dist/eval/golden-gate.js +61 -0
  43. package/dist/eval/golden-set.d.ts +81 -0
  44. package/dist/eval/golden-set.js +155 -0
  45. package/dist/eval/rerank-eval.js +10 -125
  46. package/dist/index.d.ts +6 -2
  47. package/dist/index.js +4 -0
  48. package/dist/indexer/pipeline.d.ts +0 -10
  49. package/dist/indexer/pipeline.js +1 -0
  50. package/dist/mcp/handlers.d.ts +17 -1
  51. package/dist/mcp/handlers.js +30 -0
  52. package/dist/mcp/server.d.ts +9 -1
  53. package/dist/mcp/server.js +47 -3
  54. package/dist/opencode/system-guidance.d.ts +11 -0
  55. package/dist/opencode/system-guidance.js +53 -0
  56. package/dist/opencode/tools.d.ts +24 -1
  57. package/dist/opencode/tools.js +101 -0
  58. package/dist/plugin.js +21 -3
  59. package/dist/quirks/quirk-store.d.ts +2 -0
  60. package/dist/quirks/quirk-store.js +33 -4
  61. package/dist/tui.js +21 -2
  62. package/dist/v2/v2-adapter.d.ts +20 -0
  63. package/dist/v2/v2-adapter.js +36 -8
  64. package/dist/vectorstore/lancedb.js +54 -5
  65. package/dist/watcher.d.ts +26 -1
  66. package/dist/watcher.js +71 -9
  67. package/dist/web/ui/assets/index-CWcp0jNf.css +2 -0
  68. package/dist/web/ui/index.html +2 -2
  69. package/package.json +5 -2
  70. package/dist/web/ui/assets/index-Dp009QCQ.css +0 -1
  71. /package/dist/web/ui/assets/{index-C0QXKA-b.js → index-DbXFrn53.js} +0 -0
@@ -21,6 +21,10 @@ import { extractSkeleton, getExtension } from "../chunker/skeleton.js";
21
21
  import { readFileSync } from "node:fs";
22
22
  import { resolveWorkspacePath } from "./tool-args.js";
23
23
  import { addQuirk, updateQuirk, removeQuirk, recallQuirks } from "../quirks/quirk-store.js";
24
+ import { createDecisionProvider } from "../decision/factory.js";
25
+ import { validateDecisionRequest } from "../decision/validate.js";
26
+ import { formatDecisionAnswers } from "../decision/format.js";
27
+ import { SYSTEMONE_MAX_QUESTIONS } from "../decision/systemone.js";
24
28
  // Skeleton configuration (extension → grammar + node types) and extraction
25
29
  // live in ../chunker/skeleton.ts, shared with the MCP server so both surfaces
26
30
  // honor `chunking.parsers` overrides identically.
@@ -624,4 +628,101 @@ export function createDeleteQuirkTool(options) {
624
628
  },
625
629
  });
626
630
  }
631
+ /**
632
+ * Create the `make_decision` tool.
633
+ *
634
+ * Answers classification/decision questions against a short text using the
635
+ * configured decision model (tev1 via Ollama's `/v1/systemone`). The model is
636
+ * NOT a chat model — `state` is scored against named questions of type
637
+ * `choice`, `noul`, or `score`, and answers carry probabilities.
638
+ *
639
+ * Registered by the plugin only when `decision.enabled` is true; the tool
640
+ * re-checks the flag at execution time so runtime config changes degrade to a
641
+ * clear error instead of a stale provider call.
642
+ *
643
+ * @param options - Resolved config and an optional injected provider.
644
+ * @returns A tool definition suitable for OpenCode plugin registration.
645
+ */
646
+ export function createMakeDecisionTool(options) {
647
+ const { config, provider } = options;
648
+ return tool({
649
+ description: "Classify, route, or score a short text with a local decision model (tev1 via Ollama /v1/systemone). " +
650
+ "Provide `state` (the text to judge) and 1-64 named `questions`. " +
651
+ "Question types: `choice` (pick one of 2-24 options — `criteria` maps option → description; include a \"none\" option when no listed option may fit), " +
652
+ "`noul` (true/false probability; optional criteria {\"true\": \"...\", \"false\": \"...\"}), " +
653
+ "and `score` (`criteria` is an ordered array of 2-24 level descriptions, lowest first). " +
654
+ "Returns the chosen option, verdict, or level with probabilities. Keep `state` short — the model's effective context is ~2k tokens. " +
655
+ "Use for fast classification and policy checks; never as the only check for a high-stakes decision.",
656
+ args: {
657
+ state: tool.schema.string().min(1, "A state text is required."),
658
+ questions: tool.schema
659
+ .array(tool.schema.object({
660
+ id: tool.schema.string().min(1, "A question id is required."),
661
+ type: tool.schema.enum(["choice", "noul", "score"]),
662
+ instructions: tool.schema.string().min(1, "Question instructions are required."),
663
+ criteria: tool.schema
664
+ .union([
665
+ tool.schema.record(tool.schema.string(), tool.schema.string()),
666
+ tool.schema.array(tool.schema.string()),
667
+ tool.schema.object({
668
+ true: tool.schema.string().optional(),
669
+ false: tool.schema.string().optional(),
670
+ }),
671
+ ])
672
+ .optional(),
673
+ }))
674
+ .min(1)
675
+ .max(SYSTEMONE_MAX_QUESTIONS),
676
+ },
677
+ async execute(args, _context) {
678
+ try {
679
+ const decisionConfig = config.decision;
680
+ if (!decisionConfig?.enabled) {
681
+ return {
682
+ title: "Make decision",
683
+ output: "Decision model is not enabled in config (decision.enabled).",
684
+ metadata: { tool: "make_decision", error: "disabled" },
685
+ };
686
+ }
687
+ const validationError = validateDecisionRequest({
688
+ state: args.state,
689
+ questions: args.questions,
690
+ maxStateChars: decisionConfig.maxStateChars,
691
+ });
692
+ if (validationError) {
693
+ return {
694
+ title: "Make decision",
695
+ output: `Invalid decision request: ${validationError}`,
696
+ metadata: { tool: "make_decision", error: "invalid_request" },
697
+ };
698
+ }
699
+ const decisionProvider = provider ?? createDecisionProvider(decisionConfig);
700
+ const result = await decisionProvider.decide({
701
+ state: args.state,
702
+ questions: args.questions,
703
+ });
704
+ return {
705
+ title: `Decision (${result.answers.length} question${result.answers.length === 1 ? "" : "s"})`,
706
+ output: formatDecisionAnswers(result.answers, {
707
+ provider: decisionProvider.name,
708
+ model: decisionConfig.model,
709
+ }),
710
+ metadata: {
711
+ tool: "make_decision",
712
+ provider: decisionProvider.name,
713
+ model: decisionConfig.model,
714
+ answers: result.answers,
715
+ },
716
+ };
717
+ }
718
+ catch (err) {
719
+ return {
720
+ title: "Make decision",
721
+ output: `Decision failed: ${err instanceof Error ? err.message : String(err)}`,
722
+ metadata: { tool: "make_decision", error: String(err) },
723
+ };
724
+ }
725
+ },
726
+ });
727
+ }
627
728
  //# sourceMappingURL=tools.js.map
package/dist/plugin.js CHANGED
@@ -19,7 +19,7 @@ import { appendDebugLog } from "./core/fileLogger.js";
19
19
  import { loadRuntimeOverrides, applyRuntimeOverrides } from "./core/runtime-overrides.js";
20
20
  import { createBackgroundIndexer } from "./watcher.js";
21
21
  import { createRagReadTool } from "./opencode/create-read-tool.js";
22
- import { createFileSkeletonTool, createFindUsagesTool, createDescribeImageTool, createRecallQuirksTool, createAddQuirkTool, createUpdateQuirkTool, createDeleteQuirkTool, } from "./opencode/tools.js";
22
+ import { createFileSkeletonTool, createFindUsagesTool, createDescribeImageTool, createRecallQuirksTool, createAddQuirkTool, createUpdateQuirkTool, createDeleteQuirkTool, createMakeDecisionTool, } from "./opencode/tools.js";
23
23
  import { resolveApiKey } from "./core/resolve-api-key.js";
24
24
  import { consumePendingRagInjection, peekPendingRagInjection } from "./core/rag-injection-flag.js";
25
25
  import { loadDocProgress, markSubdirectoryDocumented } from "./core/doc-progress.js";
@@ -698,6 +698,24 @@ export function createRagHooks(options) {
698
698
  error: err,
699
699
  });
700
700
  }
701
+ // Decision tool — only when the decision model is explicitly enabled
702
+ // (tev1 requires Ollama >= 0.35 and a pulled model). The tool re-checks
703
+ // `decision.enabled` at execution time.
704
+ if (effectiveCfg.decision?.enabled) {
705
+ try {
706
+ const makeDecisionTool = createMakeDecisionTool({
707
+ config: effectiveCfg,
708
+ });
709
+ tools["make_decision"] = makeDecisionTool;
710
+ }
711
+ catch (err) {
712
+ appendDebugLog(options.logFilePath, {
713
+ scope: "plugin",
714
+ message: "Failed to register make_decision tool",
715
+ error: err,
716
+ });
717
+ }
718
+ }
701
719
  if (readOverride) {
702
720
  const readTool = createRagReadTool({
703
721
  worktree: options.worktree,
@@ -834,7 +852,7 @@ export function createRagHooks(options) {
834
852
  });
835
853
  const cfg = getEffectiveCfg();
836
854
  if (cfg.openCode.injectSystemPrompt !== false) {
837
- const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement });
855
+ const guidance = buildSystemGuidanceLines({ promptEnforcement: !!cfg.memory?.promptEnforcement, decisionEnabled: !!cfg.decision?.enabled, routeBeforeAsking: !!cfg.decision?.routeBeforeAsking });
838
856
  output.system.unshift(guidance.join("\n"));
839
857
  }
840
858
  // Inject a one-time update prompt so the agent asks the user to install.
@@ -1523,7 +1541,7 @@ export const ragPlugin = async (input, _options) => {
1523
1541
  if (r.restoredToStore > 0 || r.addedToKeywordIndex > 0 || r.removedOrphans > 0) {
1524
1542
  appendDebugLog(logFilePath, {
1525
1543
  scope: "plugin",
1526
- message: `Quirk reconcile: restored ${r.restoredToStore} to store, added ${r.addedToKeywordIndex} to keyword index, removed ${r.removedOrphans} orphans`,
1544
+ message: `Quirk reconcile: restored ${r.restoredToStore} to store, deduplicated ${r.deduplicated}, added ${r.addedToKeywordIndex} to keyword index, removed ${r.removedOrphans} orphans`,
1527
1545
  }, logLevel);
1528
1546
  }
1529
1547
  })
@@ -42,6 +42,8 @@ export interface QuirkReconcileResult {
42
42
  addedToKeywordIndex: number;
43
43
  /** Store quirk chunks deleted because their quirks.jsonl entry is gone (past the grace window). */
44
44
  removedOrphans: number;
45
+ /** Quirks that had MULTIPLE rows (cross-cwd and/or same-path duplicates), collapsed to one row re-embedded from the jsonl. */
46
+ deduplicated: number;
45
47
  }
46
48
  /**
47
49
  * Reconcile `quirks.jsonl` (the source of truth for quirk memory) into the
@@ -266,14 +266,19 @@ export async function listQuirks(deps) {
266
266
  all.sort((a, b) => b.lastObserved.localeCompare(a.lastObserved));
267
267
  return all;
268
268
  }
269
- // Fallback: scan the store. Stored filePaths are workspace-absolute
270
- // (chunkToRow normalizes), so match quirks on basename, not prefix.
269
+ // Fallback: scan the store. Quirk rows may be stored raw or as legacy
270
+ // workspace-absolute paths (match on basename), and the variant-aware
271
+ // lookup can return the same quirk once per stored form (dedup by id).
271
272
  const filePaths = await deps.store.getFilePaths();
272
273
  const quirkPaths = filePaths.filter((fp) => path.basename(fp).startsWith(QUIRK_FILE_PREFIX));
273
274
  const result = [];
275
+ const seen = new Set();
274
276
  for (const fp of quirkPaths) {
275
277
  const chunks = await deps.store.getChunksByFilePath(fp);
276
278
  for (const c of chunks) {
279
+ if (seen.has(c.id))
280
+ continue;
281
+ seen.add(c.id);
277
282
  result.push({
278
283
  id: c.id,
279
284
  content: c.content,
@@ -337,7 +342,7 @@ const QUIRK_ORPHAN_GRACE_MS = 60 * 60 * 1000;
337
342
  * @returns Counts of what changed (all zero when already consistent).
338
343
  */
339
344
  export async function reconcileQuirks(deps) {
340
- const result = { restoredToStore: 0, addedToKeywordIndex: 0, removedOrphans: 0 };
345
+ const result = { restoredToStore: 0, addedToKeywordIndex: 0, removedOrphans: 0, deduplicated: 0 };
341
346
  if (isMemoryStore(deps.storePath))
342
347
  return result;
343
348
  const jsonlFile = jsonlPath(deps.storePath);
@@ -358,8 +363,30 @@ export async function reconcileQuirks(deps) {
358
363
  }
359
364
  }
360
365
  const storeIds = new Set(quirkRows.map((r) => r.id));
366
+ // 0. Collapse duplicate rows for the same quirk. Legacy rows were keyed by
367
+ // the writing process's cwd (normalizeFilePath = path.resolve), so a quirk
368
+ // touched from two cwds has one row per cwd — and insert-then-NOT-IN dedup
369
+ // cannot remove same-id rows at all. Raw-vs-legacy variants AND same-path
370
+ // double-rows are both hard to see via getFilePaths alone, so count rows
371
+ // per id with the variant-aware lookup. The jsonl content is authoritative:
372
+ // delete every row, re-embed one raw row below.
373
+ const dupIds = [];
374
+ for (const q of quirks) {
375
+ if (!storeIds.has(q.id))
376
+ continue; // absent → the restore path below covers it
377
+ const rows = await deps.store.getChunksByFilePath(QUIRK_FILE_PREFIX + q.id);
378
+ if (rows.length > 1)
379
+ dupIds.push(q.id);
380
+ }
381
+ for (const id of dupIds) {
382
+ // Variant-aware: removes the raw row plus every cwd-prefixed legacy copy.
383
+ await deps.store.deleteByFilePath(QUIRK_FILE_PREFIX + id);
384
+ storeIds.delete(id); // → picked up by the restore path below
385
+ result.deduplicated++;
386
+ }
361
387
  // 1. Restore jsonl quirks the table is missing (the rebuild-wipe direction).
362
388
  const missing = quirks.filter((q) => !storeIds.has(q.id));
389
+ const restoredIds = new Set(missing.map((q) => q.id));
363
390
  if (missing.length > 0) {
364
391
  const prefix = deps.cfg.embedding.documentPrefix ?? "";
365
392
  const embeddings = await deps.embedder.embed(missing.map((q) => prefix + q.content), "document");
@@ -375,10 +402,12 @@ export async function reconcileQuirks(deps) {
375
402
  }
376
403
  // 2. Ensure every jsonl quirk is in the keyword index. Lexical only — the
377
404
  // keyword index never looks at embeddings, so this needs no provider.
405
+ // Restored/deduplicated ids are re-added even when present: their cached
406
+ // content may predate the collapse.
378
407
  let kiDirty = false;
379
408
  if (deps.keywordIndex) {
380
409
  for (const q of quirks) {
381
- if (deps.keywordIndex.hasChunk(q.id))
410
+ if (deps.keywordIndex.hasChunk(q.id) && !restoredIds.has(q.id))
382
411
  continue;
383
412
  deps.keywordIndex.addChunks([quirkChunk(q, [])]);
384
413
  result.addedToKeywordIndex++;
package/dist/tui.js CHANGED
@@ -53,12 +53,22 @@ function loadWatcherStatus(storePath) {
53
53
  return {
54
54
  running: raw.running === true,
55
55
  lastRunAt: typeof raw.lastRunAt === "number" ? raw.lastRunAt : undefined,
56
+ lastSuccessAt: typeof raw.lastSuccessAt === "number" ? raw.lastSuccessAt : undefined,
57
+ lastChangeAt: typeof raw.lastChangeAt === "number" ? raw.lastChangeAt : undefined,
58
+ consecutiveFailures: typeof raw.consecutiveFailures === "number" ? raw.consecutiveFailures : undefined,
59
+ lastError: typeof raw.lastError === "string" ? raw.lastError : undefined,
56
60
  };
57
61
  }
58
62
  catch {
59
63
  return { running: false, lastRunAt: undefined, disabled: true };
60
64
  }
61
65
  }
66
+ /** True when the watched index may be stale (failed passes or pending changes). */
67
+ function watcherIsStale(w) {
68
+ if ((w.consecutiveFailures ?? 0) > 0)
69
+ return true;
70
+ return !!(w.lastChangeAt && (!w.lastSuccessAt || w.lastChangeAt > w.lastSuccessAt));
71
+ }
62
72
  /**
63
73
  * Load the full RAG status for a workspace by reading its config and
64
74
  * vector store manifest.
@@ -163,11 +173,19 @@ function renderSidebar(theme, version, status, tuiConfig, tokenStats) {
163
173
  : "Not indexed";
164
174
  const timeLine = `Indexed ${formatRelativeTime(status.lastIndexedAt)}`;
165
175
  const { watcher } = status;
176
+ const watcherStale = watcherIsStale(watcher);
166
177
  const watcherLine = watcher.disabled
167
178
  ? "Watcher disabled"
168
179
  : watcher.running
169
180
  ? "Watcher running\u2026"
170
- : `Watcher idle \u00B7 last ${formatRelativeTime(watcher.lastRunAt)}`;
181
+ : watcherStale
182
+ ? "Watcher: index may be stale"
183
+ : `Watcher idle \u00B7 last ${formatRelativeTime(watcher.lastSuccessAt ?? watcher.lastRunAt)}`;
184
+ const watcherDetail = watcherStale
185
+ ? (watcher.consecutiveFailures ?? 0) > 0
186
+ ? ` ${watcher.consecutiveFailures}\u00D7 failed: ${(watcher.lastError ?? "unknown error").slice(0, 60)}`
187
+ : " changes after last successful reindex"
188
+ : undefined;
171
189
  const fileListKey = tuiConfig?.fileListKeybinding ?? "ctrl+enter";
172
190
  const chunksKey = tuiConfig?.chunksKeybinding ?? "ctrl+alt+enter";
173
191
  const settingsKey = tuiConfig?.settingsKeybinding ?? "ctrl+shift+r";
@@ -194,7 +212,8 @@ function renderSidebar(theme, version, status, tuiConfig, tokenStats) {
194
212
  ]),
195
213
  text({ fg: theme.text }, [statusLine]),
196
214
  text({ fg: theme.textMuted }, [timeLine]),
197
- text({ fg: watcher.running ? theme.accent : theme.textMuted }, [watcherLine]),
215
+ text({ fg: watcher.running ? theme.accent : watcherStale ? theme.text : theme.textMuted }, [watcherLine]),
216
+ ...(watcherDetail ? [text({ fg: theme.textMuted }, [watcherDetail])] : []),
198
217
  text({ fg: theme.textMuted }, [`${formatKeybinding(settingsKey)} → Settings`]),
199
218
  text({ fg: theme.textMuted }, [`${formatKeybinding(fileListKey)} → Add File List`]),
200
219
  text({ fg: theme.textMuted }, [`${formatKeybinding(chunksKey)} → Add Chunks`]),
@@ -60,6 +60,19 @@ type V2Tool = {
60
60
  name: string;
61
61
  description: string;
62
62
  input: Record<string, unknown>;
63
+ /**
64
+ * Registered tool options. `codemode: false` is REQUIRED for the tool to be
65
+ * offered directly to the agent: in OpenCode v2 (2.0.x) tools registered
66
+ * without an explicit `codemode: false` are only reachable through the Code
67
+ * Mode `execute` runtime's `tools.*` catalog (plugin and MCP tools alike —
68
+ * see `Mcp.LocalConfigEncoded.codemode`), which surfaces as "No tool named
69
+ * ... is currently available" for every direct call. The crosstalk plugin
70
+ * uses the same `options: { codemode: false }` pattern for its top-level
71
+ * tools.
72
+ */
73
+ options: {
74
+ codemode: boolean;
75
+ };
63
76
  execute(input: unknown, context: {
64
77
  sessionID?: string;
65
78
  }): Promise<{
@@ -99,6 +112,13 @@ type V2ContextHookEvent = {
99
112
  text: string;
100
113
  }>;
101
114
  };
115
+ /** Convert a single zod-shaped argument schema into a minimal JSON schema
116
+ * object. Duck-types on zod v3/v4 class names (`constructor.name`) — avoids
117
+ * depending on zod internals (`_def.typeName`) which changed between majors.
118
+ * Exported for tests. */
119
+ export declare function zodArgToJsonSchema(schema: unknown): Record<string, unknown>;
120
+ /** Convert a V1 `args` record (zod raw shape) to a JSON schema object. Exported for tests. */
121
+ export declare function zodShapeToJsonSchema(shape: Record<string, unknown>): Record<string, unknown>;
102
122
  /**
103
123
  * Run the V1 `ragPlugin` factory for the V2 context's location and register
104
124
  * all returned hooks as V2 transforms/hooks. Returns a cleanup function that
@@ -64,12 +64,11 @@ function extractToolErrorText(event) {
64
64
  // ────────────────────────────────────────────────────────────────────────────
65
65
  // V1 tool (`@opencode-ai/plugin/tool`, zod-backed) → V2 Tool.Info converter
66
66
  // ────────────────────────────────────────────────────────────────────────────
67
- /**
68
- * Convert a single zod-shaped argument schema into a minimal JSON schema
67
+ /** Convert a single zod-shaped argument schema into a minimal JSON schema
69
68
  * object. Duck-types on zod v3/v4 class names (`constructor.name`) — avoids
70
69
  * depending on zod internals (`_def.typeName`) which changed between majors.
71
- */
72
- function zodArgToJsonSchema(schema) {
70
+ * Exported for tests. */
71
+ export function zodArgToJsonSchema(schema) {
73
72
  const candidate = schema;
74
73
  // Unwrap optional wrappers (zod v3.23+/v4 expose isOptional()).
75
74
  if (typeof candidate?.isOptional === "function" && candidate.isOptional()) {
@@ -89,13 +88,28 @@ function zodArgToJsonSchema(schema) {
89
88
  }
90
89
  case "ZodObject":
91
90
  return zodShapeToJsonSchema(candidate.shape ?? {});
91
+ case "ZodEnum": {
92
+ const options = Array.isArray(candidate.options)
93
+ ? candidate.options.filter((option) => typeof option === "string")
94
+ : [];
95
+ return options.length > 0 ? { type: "string", enum: options } : { type: "string" };
96
+ }
97
+ case "ZodRecord": {
98
+ // zod v4 exposes `.valueType`; fall back to an unconstrained value.
99
+ const valueType = candidate.valueType;
100
+ return { type: "object", additionalProperties: valueType ? zodArgToJsonSchema(valueType) : {} };
101
+ }
102
+ case "ZodUnion": {
103
+ const options = Array.isArray(candidate.options) ? candidate.options : [];
104
+ return options.length > 0 ? { anyOf: options.map((option) => zodArgToJsonSchema(option)) } : {};
105
+ }
92
106
  default:
93
107
  // Unknown wrapper — expose as unconstrained value rather than failing.
94
108
  return {};
95
109
  }
96
110
  }
97
- /** Convert a V1 `args` record (zod raw shape) to a JSON schema object. */
98
- function zodShapeToJsonSchema(shape) {
111
+ /** Convert a V1 `args` record (zod raw shape) to a JSON schema object. Exported for tests. */
112
+ export function zodShapeToJsonSchema(shape) {
99
113
  const properties = {};
100
114
  const required = [];
101
115
  for (const [key, schema] of Object.entries(shape)) {
@@ -111,8 +125,14 @@ function zodShapeToJsonSchema(shape) {
111
125
  * Convert a V1 tool definition (from `@opencode-ai/plugin/tool`) into a V2
112
126
  * tool definition. V1 executors return `{ title, output, metadata }`; V2
113
127
  * results carry `content`/`output`/`metadata`.
128
+ *
129
+ * @param codemode - When false (default) the tool is exposed directly to the
130
+ * agent; when true it is only reachable through the Code Mode `execute`
131
+ * runtime. Without an explicit `codemode: false` OpenCode v2 (2.0.x) folds
132
+ * plugin tools into the Code Mode catalog, so every RAG tool would be
133
+ * unusable outside `execute`.
114
134
  */
115
- function v1ToolToV2(name, def) {
135
+ function v1ToolToV2(name, def, codemode) {
116
136
  const v1Result = (result) => {
117
137
  const r = result;
118
138
  const metadata = { ...(r?.metadata ?? {}) };
@@ -127,6 +147,7 @@ function v1ToolToV2(name, def) {
127
147
  name,
128
148
  description: def.description ?? "",
129
149
  input: zodShapeToJsonSchema(def.args ?? {}),
150
+ options: { codemode },
130
151
  async execute(input, context) {
131
152
  const fn = def.execute;
132
153
  if (typeof fn !== "function") {
@@ -147,6 +168,13 @@ function v1ToolToV2(name, def) {
147
168
  export async function registerRagPluginV2(ctx) {
148
169
  // The V1 factory only consumes `input.directory`; project/client/$ are unused.
149
170
  const hooks = (await ragPlugin({ directory: ctx.location.directory }, ctx.options));
171
+ // Tool exposure: default to DIRECT tools (`codemode: false`), matching the
172
+ // crosstalk plugin. OpenCode v2 (2.0.x) folds plugin tools without an
173
+ // explicit `codemode: false` into the Code Mode catalog, making them
174
+ // unreachable outside `execute`. Set the plugin option `codemode: true`
175
+ // (via `plugins: [{ "package": "opencode-rag-plugin", "options": { "codemode": true } }]`)
176
+ // to force the previous code-mode-only behavior.
177
+ const codemode = typeof ctx.options?.codemode === "boolean" ? ctx.options.codemode : false;
150
178
  const registrations = [];
151
179
  // ── Tools ────────────────────────────────────────────────────────────────
152
180
  const toolDefs = (hooks.tool ?? {});
@@ -154,7 +182,7 @@ export async function registerRagPluginV2(ctx) {
154
182
  if (toolEntries.length > 0) {
155
183
  const registration = await ctx.tool.transform((editor) => {
156
184
  for (const [name, def] of toolEntries) {
157
- editor.add(v1ToolToV2(name, def));
185
+ editor.add(v1ToolToV2(name, def, codemode));
158
186
  }
159
187
  });
160
188
  registrations.push(registration);
@@ -310,6 +310,36 @@ export async function swapStoreDirectories(tempPath, realPath) {
310
310
  await preserveStoreArtifacts(oldPath, realPath);
311
311
  fs.rm(oldPath, { recursive: true, force: true }).catch(() => { });
312
312
  }
313
+ /**
314
+ * Synthetic filePath prefix for quirk chunks — mirrors QUIRK_FILE_PREFIX in
315
+ * `quirks/quirk-store.ts` (kept local to avoid inverting the module dependency).
316
+ */
317
+ const QUIRK_FILE_PREFIX = "quirk:";
318
+ /**
319
+ * SQL predicate matching every stored form of `filePath`.
320
+ *
321
+ * Workspace files are stored with absolute paths, so `normalizeFilePath`
322
+ * (= `path.resolve`) is a no-op → exact match, as before.
323
+ *
324
+ * Quirk chunks use the synthetic path `quirk:<id>`, which `normalizeFilePath`
325
+ * historically resolved against the cwd of the WRITING process — the same quirk
326
+ * could exist as the raw form (stored raw since 2026-09-22) and as one or more
327
+ * `<cwd>/`-prefixed legacy forms. Match the raw form plus any
328
+ * directory-prefixed variant via suffix LIKE (quirk ids are uuids — no LIKE
329
+ * metacharacters).
330
+ */
331
+ function buildFilePathMatch(filePath) {
332
+ // Quirk detection by BASENAME so callers may pass the raw synthetic path or
333
+ // any legacy cwd-prefixed absolute form — both resolve to the same match.
334
+ const base = path.basename(filePath);
335
+ if (base.startsWith(QUIRK_FILE_PREFIX)) {
336
+ const escBase = base.replace(/'/g, "''");
337
+ // canonical raw form + every directory-prefixed variant (quirk ids are
338
+ // uuids — no LIKE metacharacters; paths never contain quotes unescaped)
339
+ return `(filePath = '${escBase}' OR filePath LIKE '%/${escBase}')`;
340
+ }
341
+ return `filePath = '${normalizeFilePath(filePath).replace(/'/g, "''")}'`;
342
+ }
313
343
  /**
314
344
  * A LanceDB-backed vector store with persistent on-disk storage, vector search,
315
345
  * and chunk metadata queries. Supports automatic corruption recovery by falling
@@ -653,7 +683,12 @@ export class LanceDbStore {
653
683
  content: c.content,
654
684
  description: c.description ?? "",
655
685
  embedding: l2Normalize(c.embedding),
656
- filePath: normalizeFilePath(c.metadata.filePath),
686
+ // Synthetic quirk ids stay RAW: resolving them keyed quirk rows by the
687
+ // cwd of whichever process wrote them (plugin vs CLI), producing
688
+ // cross-cwd duplicates that a cwd-normalized delete could not remove.
689
+ filePath: c.metadata.filePath.startsWith(QUIRK_FILE_PREFIX)
690
+ ? c.metadata.filePath
691
+ : normalizeFilePath(c.metadata.filePath),
657
692
  startLine: c.metadata.startLine,
658
693
  endLine: c.metadata.endLine,
659
694
  language: c.metadata.language,
@@ -685,6 +720,13 @@ export class LanceDbStore {
685
720
  if (rows.length === 0)
686
721
  return;
687
722
  this.assertEmbeddingDimensions(rows);
723
+ // Quirk rows: wipe every stored form of this synthetic path FIRST — raw,
724
+ // legacy cwd-prefixed variants, and prior same-id rows (the NOT IN dedup
725
+ // below cannot remove same-id rows). Safe: quirks.jsonl is the source of
726
+ // truth and reconcileQuirks re-restores if we crash between delete+add.
727
+ for (const p of new Set(rows.filter((r) => r.filePath.startsWith(QUIRK_FILE_PREFIX)).map((r) => r.filePath))) {
728
+ await table.delete(buildFilePathMatch(p));
729
+ }
688
730
  // INSERT FIRST: data is safely stored before any delete
689
731
  await table.add(rows);
690
732
  if (!dedup)
@@ -694,8 +736,11 @@ export class LanceDbStore {
694
736
  // NOT IN clause preserves the newly inserted rows (so multiple new IDs
695
737
  // sharing a startLine never delete each other). Insert-first ordering
696
738
  // keeps an abort between insert and delete from losing data.
739
+ // Quirk paths are skipped — they were fully cleaned above.
697
740
  const byFile = this.rowsByFilePath(rows);
698
741
  for (const [filePath, ids] of byFile) {
742
+ if (filePath.startsWith(QUIRK_FILE_PREFIX))
743
+ continue;
699
744
  const escapedPath = filePath.replace(/'/g, "''");
700
745
  const idList = ids.map((id) => `'${id.replace(/'/g, "''")}'`).join(", ");
701
746
  await table.delete(`filePath = '${escapedPath}' AND id NOT IN (${idList})`);
@@ -727,9 +772,15 @@ export class LanceDbStore {
727
772
  if (allRows.length === 0)
728
773
  return;
729
774
  this.assertEmbeddingDimensions(allRows);
775
+ // Quirk rows: wipe every stored form first (see addChunksInternal).
776
+ for (const p of new Set(allRows.filter((r) => r.filePath.startsWith(QUIRK_FILE_PREFIX)).map((r) => r.filePath))) {
777
+ await table.delete(buildFilePathMatch(p));
778
+ }
730
779
  // INSERT FIRST (single add for the whole batch), then per-file dedup
731
780
  await table.add(allRows);
732
781
  for (const [filePath, ids] of dedupByFile) {
782
+ if (filePath.startsWith(QUIRK_FILE_PREFIX))
783
+ continue;
733
784
  const escapedPath = filePath.replace(/'/g, "''");
734
785
  const idList = ids.map((id) => `'${id.replace(/'/g, "''")}'`).join(", ");
735
786
  await table.delete(`filePath = '${escapedPath}' AND id NOT IN (${idList})`);
@@ -847,10 +898,9 @@ export class LanceDbStore {
847
898
  async getChunksByFilePath(filePath) {
848
899
  return this.withCorruptionRecovery(async () => {
849
900
  const table = await this.getTable();
850
- const normalizedPath = normalizeFilePath(filePath).replace(/'/g, "''");
851
901
  const rows = await table.query()
852
902
  .select(QUERY_COLUMNS)
853
- .where(`filePath = '${normalizedPath}'`)
903
+ .where(buildFilePathMatch(filePath))
854
904
  .toArray();
855
905
  return rows
856
906
  .map((row) => {
@@ -1482,8 +1532,7 @@ export class LanceDbStore {
1482
1532
  if (!tableNames.includes(TABLE_NAME))
1483
1533
  return;
1484
1534
  const table = await this.getTable();
1485
- const normalizedPath = normalizeFilePath(filePath).replace(/'/g, "''");
1486
- await table.delete(`filePath = '${normalizedPath}'`);
1535
+ await table.delete(buildFilePathMatch(filePath));
1487
1536
  }
1488
1537
  /**
1489
1538
  * Verify that data in the store is actually readable.
package/dist/watcher.d.ts CHANGED
@@ -37,8 +37,33 @@ export interface CreateBackgroundIndexerOptions {
37
37
  export type WatcherStatus = {
38
38
  /** Whether an index pass is currently running. */
39
39
  running: boolean;
40
- /** Timestamp (ms since epoch) of the last completed run, or undefined. */
40
+ /** Timestamp (ms since epoch) of the last finished pass (success or failure), or undefined. */
41
41
  lastRunAt: number | undefined;
42
+ /** Timestamp (ms since epoch) of the last pass that finished without an error. */
43
+ lastSuccessAt?: number;
44
+ /** Timestamp (ms since epoch) of the last failed pass. */
45
+ lastErrorAt?: number;
46
+ /** Truncated error message from the last failed pass. */
47
+ lastError?: string;
48
+ /** Consecutive failed passes since the last success (0 after a clean pass). */
49
+ consecutiveFailures?: number;
50
+ /** Timestamp (ms since epoch) of the last filesystem change that triggered a pass. */
51
+ lastChangeAt?: number;
52
+ /** Files/chunks that failed inside the last pass without failing the pass itself. */
53
+ lastPassProblems?: number;
54
+ };
55
+ /**
56
+ * Derive whether the watched index may be stale from the persisted status.
57
+ * Stale when a reindex pass failed (or the embedding provider was unavailable and
58
+ * stored nothing), or when filesystem changes arrived after the last successful pass.
59
+ * Pure function — used by `status` and the TUI so both tell the same story.
60
+ *
61
+ * @param status - The persisted watcher status.
62
+ * @returns `stale` plus a human-readable reason when stale.
63
+ */
64
+ export declare function deriveWatcherHealth(status: WatcherStatus): {
65
+ stale: boolean;
66
+ reason?: string;
42
67
  };
43
68
  /**
44
69
  * Atomically claim the watcher lock for a workspace. Returns true only if