kibi-opencode 0.9.0 → 0.10.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.
Files changed (51) hide show
  1. package/README.md +36 -12
  2. package/dist/brief-intent.d.ts +15 -4
  3. package/dist/brief-intent.js +63 -25
  4. package/dist/briefing-runtime.js +2 -1
  5. package/dist/config.d.ts +3 -0
  6. package/dist/config.js +9 -0
  7. package/dist/e2e-coverage-signals.d.ts +6 -0
  8. package/dist/e2e-coverage-signals.js +186 -0
  9. package/dist/file-entity-links.d.ts +15 -0
  10. package/dist/file-entity-links.js +254 -0
  11. package/dist/file-operation-reminders.d.ts +24 -0
  12. package/dist/file-operation-reminders.js +55 -0
  13. package/dist/file-operation-state.d.ts +29 -0
  14. package/dist/file-operation-state.js +113 -0
  15. package/dist/idle-brief-audit.d.ts +36 -0
  16. package/dist/idle-brief-audit.js +186 -0
  17. package/dist/idle-brief-paths.d.ts +6 -0
  18. package/dist/idle-brief-paths.js +120 -0
  19. package/dist/idle-brief-reader.d.ts +25 -0
  20. package/dist/idle-brief-reader.js +142 -0
  21. package/dist/idle-brief-runtime.d.ts +48 -0
  22. package/dist/idle-brief-runtime.js +443 -0
  23. package/dist/idle-brief-store.d.ts +96 -0
  24. package/dist/idle-brief-store.js +209 -0
  25. package/dist/index.d.ts +14 -1
  26. package/dist/index.js +626 -50
  27. package/dist/init-kibi-alias.d.ts +14 -0
  28. package/dist/init-kibi-alias.js +38 -0
  29. package/dist/init-kibi-capability.d.ts +32 -0
  30. package/dist/init-kibi-capability.js +202 -0
  31. package/dist/logger.js +9 -3
  32. package/dist/plugin-startup.d.ts +1 -0
  33. package/dist/plugin-startup.js +11 -2
  34. package/dist/prompt.d.ts +15 -3
  35. package/dist/prompt.js +103 -33
  36. package/dist/reconcile-engine.d.ts +15 -0
  37. package/dist/reconcile-engine.js +112 -0
  38. package/dist/scheduler.d.ts +1 -0
  39. package/dist/scheduler.js +37 -1
  40. package/dist/session-edit-state.d.ts +25 -0
  41. package/dist/session-edit-state.js +177 -0
  42. package/dist/session-fingerprint.d.ts +11 -0
  43. package/dist/session-fingerprint.js +21 -0
  44. package/dist/source-linked-guidance.d.ts +1 -2
  45. package/dist/source-linked-guidance.js +5 -168
  46. package/dist/startup-notifier.js +42 -31
  47. package/dist/toast.d.ts +21 -22
  48. package/dist/toast.js +36 -14
  49. package/dist/tui-brief-delivery.d.ts +47 -0
  50. package/dist/tui-brief-delivery.js +138 -0
  51. package/package.json +4 -3
package/README.md CHANGED
@@ -113,13 +113,11 @@ The plugin injects guidance into OpenCode sessions to improve agent grounding. U
113
113
 
114
114
  OpenCode exposes Kibi MCP prompts as slash commands. The \`/init-kibi\` command triggers the \`kb_autopilot_generate\` workflow to assist in retroactive bootstrap using only public MCP tools.
115
115
 
116
- ### Start-Task Briefing
116
+ When the plugin detects an authoritative risky edit (`behavior_candidate` or `traceability_candidate` risk class), it automatically renders a Kibi briefing before the prompt. The plugin uses two complementary paths: the `file.edited` event hook as a fast-path hint, and prompt-cycle reconciliation as an authoritative fallback for programmatic edits that bypass the event bus. Briefings are rendered directly into the prompt to ensure immediate visibility.
117
117
 
118
- When the plugin detects an authoritative risky edit (`behavior_candidate` or `traceability_candidate` risk class), it automatically fetches a Kibi briefing from a background worker session via the `file.edited` event path. Auto-briefing is no longer deferred and provides immediate project context before you act.
119
-
120
- - **Automatic delivery**: Briefings appear in a toast notification and inside the guidance block headed `🧠 **Kibi briefing available**`.
121
- - **Contextual richness**: The briefing includes a summary and key source-linked bullets generated by the `kb_briefing_generate` MCP tool.
122
- - **TL;DR fallback**: If a full briefing is unavailable, a summary is provided with a cue to use the manual command.
118
+ - **Immediate delivery**: Briefings are rendered-first into the prompt guidance block headed `🧠 **Kibi briefing available**` and TUI toasts titled `Kibi Knowledge Update`.
119
+ - **Narrative structure**: Delivery favors user-facing prose with `What changed` and `Why it matters`, plus conditional `Project knowledge impact` / `Interpretation note` sections when evidence or caveats exist.
120
+ - **TL;DR fallback**: If a full briefing is unavailable, fallback output still preserves `What changed` / `Why it matters` framing while keeping the manual command cue available.
123
121
  - **Manual command**: Use `/brief-kibi` at any time to trigger an on-demand briefing if auto-delivery is skipped or fails.
124
122
 
125
123
  ### Discovery-first MCP guidance
@@ -142,7 +140,7 @@ Internal maintenance automatically syncs the knowledge base after relevant file
142
140
  ### Non-Blocking UX
143
141
 
144
142
  - Sync runs in background, never blocks OpenCode
145
- - Failures reported via console logs only, never as blocking UI elements
143
+ - **Non-blocking toast delivery**: Toast transport is best-effort. The plugin detects available OpenCode TUI capabilities (`client.tui.toast` or `client.tui.showToast`) and uses the official SDK contract. Toast failures resolve to structured `SendToastResult` objects (`delivered`, `unavailable`, `failed`) rather than throwing or falling back to raw HTTP requests.
146
144
 
147
145
  ## Configuration
148
146
 
@@ -166,6 +164,8 @@ Config files (project overrides global):
166
164
  | `ux.toastFailures` | boolean | `true` | Show failure toasts for sync/check issues |
167
165
  | `ux.toastSuccesses` | boolean | `false` | Show success toasts for sync/check completion |
168
166
  | `ux.toastCooldownMs` | number | `10000` | Cooldown between repeated UX toasts |
167
+ | `ux.briefs.autoSubmit` | boolean | `true` | **Deprecated/No-op**: Auto-submission is no longer needed with render-first briefing |
168
+ PP|| `guidance.dynamic` | boolean | `true` | Enable dynamic contextual guidance |
169
169
  | `guidance.dynamic` | boolean | `true` | Enable dynamic contextual guidance |
170
170
  | `guidance.warnOnKbEdits` | boolean | `true` | Enable loud warnings for .kb/** edits |
171
171
  | `guidance.factFirstDomainRouting` | boolean | `true` | Enable FACT-first domain routing suggestions |
@@ -195,21 +195,31 @@ The plugin follows a **silent-except-operational-errors** policy for terminal ou
195
195
 
196
196
  | Classification | Examples | Surface | Terminal | Structured |
197
197
  |---------------|----------|---------|----------|------------|
198
- | **Advisory (background)** | scheduler check failures, degraded-mode latches | `errorStructuredOnly()` | No | Yes, via `client.app.log()` |
199
- | **Operational (plugin)** | bootstrap-needed, sync failure, hook/init failure | `error()` | Yes, via `console.error` | Yes, via `client.app.log()` |
198
+ | **Advisory (background)** | routine `info()`, `warn()`, scheduler check failures, degraded-mode latches, `errorStructuredOnly()` | `client.app.log()` | No | Yes, via `client.app.log()` |
199
+ | **Operational (plugin)** | bootstrap-needed, sync failure, hook/init failure | `error()` | Yes, exactly one prefixed `console.error` (`[kibi-opencode]`) | Yes, via `client.app.log()` |
200
200
  | **Authoritative external** | git hooks, CLI checks | Outside plugin surface | N/A | N/A |
201
201
 
202
202
  ### Failure Routing Contract
203
203
 
204
204
  The logger exposes two error-level surfaces with distinct routing semantics:
205
205
 
206
- - **`error(msg, metadata?)`** — Operational plugin failures. Always emits to `console.error` for terminal visibility, plus `client.app.log()` when a client is bound. Use for bootstrap-needed, hook/init failures, and sync failures that require developer attention.
207
- - **`errorStructuredOnly(msg, metadata?)`** — Advisory background maintenance failures. Routes through `client.app.log()` only when a client is bound; completely silent when no client is bound (no `console.error` fallback). Use for scheduler check failures and degraded-mode latches.
206
+ - **`error(msg, metadata?)`** — Operational plugin failures. Emits exactly one prefixed `console.error` (`[kibi-opencode]`) for terminal visibility, plus `client.app.log()` when a client is bound. Structured log rejection does not emit secondary console noise. Use for bootstrap-needed, hook/init failures, and sync failures that require developer attention.
207
+ - **`errorStructuredOnly(msg, metadata?)`** — Advisory background maintenance failures. Routes through `client.app.log()` only when a client is bound and remains terminal-silent even when the structured transport rejects. Use for scheduler check failures and degraded-mode latches.
208
208
 
209
- **Contract rule:** Once `client` is bound (after `setClient()`), advisory logging MUST use `errorStructuredOnly()`. When no client is bound, `errorStructuredOnly()` is completely silent it does not fall back to `console.error`.
209
+ **Contract rule:** Once `client` is bound (after `setClient()`), advisory paths (`info()`, `warn()`, `errorStructuredOnly()`) MUST stay on `client.app.log()` and remain terminal-silent. Operational failures use `error()` for a single prefixed terminal emission without duplicating console output when structured logging rejects.
210
210
 
211
211
  Routine diagnostics route through [`client.app.log()`](https://opencode.ai/docs/plugins/) and never appear in the terminal. Only operational error-class events break terminal silence. This keeps the developer's workspace clean while preserving full visibility in structured logs for debugging.
212
212
 
213
+ ### Toast Transport Contract
214
+
215
+ The plugin uses the official OpenCode toast APIs with automatic capability detection:
216
+
217
+ 1. **Legacy transport**: `client.tui.toast(payload)` — used when available in plugin context
218
+ 2. **SDK transport**: `client.tui.showToast({ body: payload })` — used as fallback
219
+ 3. **No capability**: Returns `{ status: "unavailable", reason: "missing-capability" }`
220
+
221
+ All toast delivery is best-effort and non-blocking. The `sendToast` helper returns a discriminated `SendToastResult` union and never throws. There is no raw HTTP fallback.
222
+
213
223
  The `experimental.chat.system.transform` hook handles prompt injection (see [Hook Policy](#hook-policy)). The `chat.params` hook is compatibility-only and never carries prompt text.
214
224
 
215
225
  ### Hook Modes
@@ -275,6 +285,20 @@ A proposed enhancement would inject Kibi context hints into file-read results (e
275
285
 
276
286
  Current workaround: static system prompt guidance directs agents to query Kibi explicitly.
277
287
 
288
+ ### File-Context Guidance
289
+
290
+ The plugin provides proactive guidance when agents perform file operations:
291
+
292
+ - **File-create/edit guidance**: When an agent creates or edits a source file, the plugin may inject reminders to check Kibi for that path if e2e evidence exists.
293
+
294
+ - **File-delete safety guidance**: When an agent attempts to delete a file, the plugin injects a safety check reminding the agent to verify if the file implements any Kibi requirements before removal.
295
+
296
+ - **E2e reminder evidence**: File-operation reminders use exact Kibi graph evidence first (`covered_by` links to `[e2e]`-tagged entities or `/e2e/`-sourced entities) and narrow path heuristics second. Package-level e2e tests do not trigger "authoritative evidence" flags at the file level.
297
+
298
+ - **Session suppression**: To minimize prompt noise, this guidance is suppressed after the first occurrence per path per session.
299
+
300
+ - **Current-host scope**: This feature uses host-side event monitoring to detect intent; it does not intercept or modify actual file content returned by the Read tool.
301
+
278
302
  ## License
279
303
 
280
304
  AGPL-3.0-or-later
@@ -6,7 +6,8 @@ export interface BriefIntentParams {
6
6
  maintenanceDegraded: boolean;
7
7
  workspaceRoot: string;
8
8
  branch: string;
9
- editedFilePath: string | undefined;
9
+ sourceFiles: string[];
10
+ focusFilePath?: string;
10
11
  seedIds?: string[];
11
12
  }
12
13
  export interface BriefIntentResult {
@@ -22,9 +23,19 @@ export interface BriefIntentInputs {
22
23
  maintenanceDegraded: boolean;
23
24
  worktreeRoot: string;
24
25
  branch: string;
25
- editedFile: string | undefined;
26
+ sourceFiles: string[];
27
+ focusFilePath?: string;
26
28
  seedIds?: string[];
27
29
  }
28
30
  export declare function deriveBriefIntent(params: BriefIntentParams): BriefIntentResult;
29
- export declare function computeBriefIntent(// implements REQ-opencode-kibi-briefing-v2
30
- inputs: BriefIntentInputs): BriefIntentResult;
31
+ export declare function computeBriefIntent(inputs: BriefIntentInputs): BriefIntentResult;
32
+ export interface BriefingContextParams {
33
+ sourceFiles: string[];
34
+ seedIds?: string[];
35
+ changedEntityIds?: string[];
36
+ }
37
+ export interface BriefingContextResult {
38
+ sourceFiles: string[];
39
+ seedIds: string[];
40
+ }
41
+ export declare function buildBriefingContext(params: BriefingContextParams): BriefingContextResult;
@@ -1,5 +1,4 @@
1
1
  // implements REQ-opencode-kibi-briefing-v2, REQ-opencode-smart-enforcement-v1
2
- import * as path from "node:path";
3
2
  import { getSourceLinkedRequirementIds } from "./source-linked-guidance.js";
4
3
  const ELIGIBLE_RISK_CLASSES = new Set([
5
4
  "behavior_candidate",
@@ -9,35 +8,37 @@ const STRICT_ELIGIBLE_POSTURES = new Set([
9
8
  "root_active",
10
9
  "hybrid_root_plus_vendored",
11
10
  ]);
12
- function hasEditedFilePath(editedFilePath) {
13
- return typeof editedFilePath === "string" && editedFilePath.length > 0;
11
+ function sortAndDedup(files) {
12
+ return [...new Set(files)].sort();
14
13
  }
15
14
  function deriveSeedIds(params) {
16
- if (!hasEditedFilePath(params.editedFilePath)) {
17
- return [];
15
+ if (params.seedIds !== undefined && params.seedIds.length > 0) {
16
+ return buildBriefingContext({
17
+ sourceFiles: params.sourceFiles,
18
+ seedIds: params.seedIds,
19
+ }).seedIds.slice(0, 3);
18
20
  }
19
- if (params.seedIds !== undefined) {
20
- return params.seedIds.slice(0, 3);
21
+ const focusFile = params.focusFilePath ?? params.sourceFiles[0];
22
+ if (!focusFile) {
23
+ return [];
21
24
  }
22
- const absoluteEditedPath = path.isAbsolute(params.editedFilePath)
23
- ? params.editedFilePath
24
- : path.join(params.workspaceRoot, params.editedFilePath);
25
- return getSourceLinkedRequirementIds(params.workspaceRoot, absoluteEditedPath).slice(0, 3);
25
+ return buildBriefingContext({
26
+ sourceFiles: params.sourceFiles,
27
+ seedIds: getSourceLinkedRequirementIds(params.workspaceRoot, focusFile),
28
+ }).seedIds.slice(0, 3);
26
29
  }
27
30
  // implements REQ-opencode-kibi-briefing-v2, REQ-opencode-smart-enforcement-v1
28
31
  export function deriveBriefIntent(params) {
29
- const fingerprint = `brief:${params.workspaceRoot}\0${params.branch}\0${params.editedFilePath ?? ""}\0${params.riskClass}`;
30
- const sourceFiles = hasEditedFilePath(params.editedFilePath)
31
- ? [params.editedFilePath]
32
- : [];
32
+ const sortedSourceFiles = sortAndDedup(params.sourceFiles);
33
+ const fingerprint = `brief:${params.workspaceRoot}\0${params.branch}\0${params.riskClass}\0${sortedSourceFiles.join("\0")}`;
33
34
  const seedIds = deriveSeedIds(params);
34
- if (!hasEditedFilePath(params.editedFilePath)) {
35
+ if (sortedSourceFiles.length === 0) {
35
36
  return {
36
37
  eligible: false,
37
- reason: "Ineligible: edited file path is missing",
38
+ reason: "Ineligible: no source files in session",
38
39
  fingerprint,
39
- sourceFiles,
40
- seedIds,
40
+ sourceFiles: sortedSourceFiles,
41
+ seedIds: [],
41
42
  };
42
43
  }
43
44
  if (!ELIGIBLE_RISK_CLASSES.has(params.riskClass)) {
@@ -45,7 +46,7 @@ export function deriveBriefIntent(params) {
45
46
  eligible: false,
46
47
  reason: `Ineligible: riskClass ${params.riskClass} is not auto-brief eligible`,
47
48
  fingerprint,
48
- sourceFiles,
49
+ sourceFiles: sortedSourceFiles,
49
50
  seedIds,
50
51
  };
51
52
  }
@@ -54,7 +55,7 @@ export function deriveBriefIntent(params) {
54
55
  eligible: false,
55
56
  reason: `Ineligible: posture ${params.posture} is not authoritative`,
56
57
  fingerprint,
57
- sourceFiles,
58
+ sourceFiles: sortedSourceFiles,
58
59
  seedIds,
59
60
  };
60
61
  }
@@ -63,7 +64,7 @@ export function deriveBriefIntent(params) {
63
64
  eligible: false,
64
65
  reason: "Ineligible: maintenance is degraded",
65
66
  fingerprint,
66
- sourceFiles,
67
+ sourceFiles: sortedSourceFiles,
67
68
  seedIds,
68
69
  };
69
70
  }
@@ -71,11 +72,12 @@ export function deriveBriefIntent(params) {
71
72
  eligible: true,
72
73
  reason: "Eligible for auto-briefing",
73
74
  fingerprint,
74
- sourceFiles,
75
+ sourceFiles: sortedSourceFiles,
75
76
  seedIds,
76
77
  };
77
78
  }
78
- export function computeBriefIntent(// implements REQ-opencode-kibi-briefing-v2
79
+ export function computeBriefIntent(
80
+ // implements REQ-opencode-kibi-briefing-v2
79
81
  inputs) {
80
82
  return deriveBriefIntent({
81
83
  riskClass: inputs.riskClass,
@@ -83,7 +85,43 @@ inputs) {
83
85
  maintenanceDegraded: inputs.maintenanceDegraded,
84
86
  workspaceRoot: inputs.worktreeRoot,
85
87
  branch: inputs.branch,
86
- editedFilePath: inputs.editedFile,
88
+ sourceFiles: inputs.sourceFiles,
89
+ ...(inputs.focusFilePath !== undefined
90
+ ? { focusFilePath: inputs.focusFilePath }
91
+ : {}),
87
92
  ...(inputs.seedIds !== undefined ? { seedIds: inputs.seedIds } : {}),
88
93
  });
89
94
  }
95
+ export function buildBriefingContext(
96
+ // implements REQ-opencode-kibi-briefing-v6
97
+ params) {
98
+ const sourceFiles = [...new Set(params.sourceFiles)].sort();
99
+ const seen = new Set();
100
+ const seeds = [];
101
+ // Take first 3 changed entity IDs in original order, dedupe, sort
102
+ if (params.changedEntityIds) {
103
+ for (const id of params.changedEntityIds.slice(0, 3)) {
104
+ if (!seen.has(id)) {
105
+ seeds.push(id);
106
+ seen.add(id);
107
+ }
108
+ }
109
+ }
110
+ // Fill remaining slots from seedIds in original order
111
+ if (params.seedIds) {
112
+ for (const id of params.seedIds) {
113
+ if (seeds.length >= 5)
114
+ break;
115
+ if (!seen.has(id)) {
116
+ seeds.push(id);
117
+ seen.add(id);
118
+ }
119
+ }
120
+ }
121
+ // Sort final seedIds alphabetically
122
+ seeds.sort((a, b) => a.localeCompare(b));
123
+ return {
124
+ sourceFiles,
125
+ seedIds: seeds,
126
+ };
127
+ }
@@ -4,6 +4,7 @@ const WORKER_TITLE = "Kibi Auto Brief Worker";
4
4
  const READY_TOAST = "Kibi brief ready — summary added to guidance.";
5
5
  const TLDR_FALLBACK_TOAST = "Kibi brief summary added — use /brief-kibi for full details.";
6
6
  const UNAVAILABLE_TOAST = "Kibi brief unavailable — keeping /brief-kibi manual path.";
7
+ const DEFAULT_WHY_IT_MATTERS = "This update changes how current project knowledge should be interpreted.";
7
8
  const PROMPT_INSTRUCTION = "Call only kb_briefing_generate once with the provided sourceFiles and seedIds. If briefingState is ready, copy only cited fields. If briefingState is no_briefing, return empty promptBlock/citations and keep manual cue availability. Never invent claims.";
8
9
  const PROMPT_FORMAT = {
9
10
  type: "json_schema",
@@ -140,7 +141,7 @@ function normalizeResult(payload) {
140
141
  if (briefingState === "ready" && tldr) {
141
142
  return {
142
143
  state: "tldr_fallback",
143
- promptBlock: `- ${tldr}\n- Full details: run /brief-kibi.`,
144
+ promptBlock: `- What changed: ${tldr}\n- Why it matters: ${DEFAULT_WHY_IT_MATTERS}`,
144
145
  tldr,
145
146
  citations: [],
146
147
  showManualCue: true,
package/dist/config.d.ts CHANGED
@@ -15,6 +15,9 @@ export interface KibiConfig {
15
15
  toastFailures: boolean;
16
16
  toastSuccesses: boolean;
17
17
  toastCooldownMs: number;
18
+ briefs?: {
19
+ autoSubmit: boolean;
20
+ };
18
21
  };
19
22
  guidance: {
20
23
  dynamic: boolean;
package/dist/config.js CHANGED
@@ -11,6 +11,9 @@ const DEFAULTS = {
11
11
  toastFailures: true,
12
12
  toastSuccesses: false,
13
13
  toastCooldownMs: 10000,
14
+ briefs: {
15
+ autoSubmit: true,
16
+ },
14
17
  },
15
18
  guidance: {
16
19
  dynamic: true,
@@ -100,6 +103,12 @@ export function validateAndMerge(obj) {
100
103
  out.ux.toastSuccesses = u.toastSuccesses;
101
104
  if (typeof u.toastCooldownMs === "number")
102
105
  out.ux.toastCooldownMs = u.toastCooldownMs;
106
+ if (u.briefs && typeof u.briefs === "object") {
107
+ const b = u.briefs;
108
+ out.ux.briefs = { autoSubmit: true };
109
+ if (typeof b.autoSubmit === "boolean")
110
+ out.ux.briefs.autoSubmit = b.autoSubmit;
111
+ }
103
112
  }
104
113
  if (typeof src.logLevel === "string")
105
114
  out.logLevel = src.logLevel;
@@ -0,0 +1,6 @@
1
+ export interface E2eCoverageSignal {
2
+ level: "exact" | "heuristic" | "none";
3
+ evidence: string[];
4
+ reminderText: string | null;
5
+ }
6
+ export declare function getE2eCoverageSignal(worktree: string, filePath: string): E2eCoverageSignal;
@@ -0,0 +1,186 @@
1
+ // implements REQ-opencode-file-context-guidance-v1
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import * as path from "node:path";
4
+ import { getFileLinkedTargetsByType } from "./file-entity-links.js";
5
+ // ── TEST doc reader ──────────────────────────────────────────────
6
+ //
7
+ // Reads a TEST-*.md file from documentation/tests/ and extracts
8
+ // frontmatter tags, source, and body.
9
+ function readTestDoc(worktree, testId) {
10
+ // Try common locations for TEST docs
11
+ const candidates = [
12
+ `documentation/tests/${testId}.md`,
13
+ `documentation/tests/${testId.toLowerCase()}.md`,
14
+ ];
15
+ for (const rel of candidates) {
16
+ const fullPath = path.join(worktree, rel);
17
+ if (existsSync(fullPath)) {
18
+ try {
19
+ const content = readFileSync(fullPath, "utf8");
20
+ return parseTestDoc(content, testId);
21
+ }
22
+ catch {
23
+ continue;
24
+ }
25
+ }
26
+ }
27
+ return null;
28
+ }
29
+ function parseTestDoc(content, id) {
30
+ const result = { id, title: id };
31
+ // Extract frontmatter
32
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
33
+ if (!fmMatch || fmMatch[1] === undefined) {
34
+ result.body = content;
35
+ return result;
36
+ }
37
+ const frontmatter = fmMatch[1];
38
+ // Parse title
39
+ const titleMatch = frontmatter.match(/^title:\s*(.+)$/m);
40
+ if (titleMatch && titleMatch[1] !== undefined) {
41
+ result.title = titleMatch[1].trim();
42
+ }
43
+ // Parse status
44
+ const statusMatch = frontmatter.match(/^status:\s*(.+)$/m);
45
+ if (statusMatch && statusMatch[1] !== undefined) {
46
+ result.status = statusMatch[1].trim();
47
+ }
48
+ // Parse source
49
+ const sourceMatch = frontmatter.match(/^source:\s*(.+)$/m);
50
+ if (sourceMatch && sourceMatch[1] !== undefined) {
51
+ result.source = sourceMatch[1].trim();
52
+ }
53
+ // Parse tags
54
+ const tagsMatch = frontmatter.match(/^tags:\s*$/m);
55
+ if (tagsMatch) {
56
+ const afterTags = frontmatter.slice(frontmatter.indexOf("tags:") + "tags:".length);
57
+ const tagLines = afterTags.match(/^\s+-\s+(.+)$/gm);
58
+ if (tagLines) {
59
+ result.tags = tagLines.map((l) => l.replace(/^\s+-\s+/, "").trim());
60
+ }
61
+ }
62
+ // Extract body (after frontmatter)
63
+ const bodyMatch = content.match(/^---\n[\s\S]*?\n---\n([\s\S]*)$/);
64
+ if (bodyMatch && bodyMatch[1] !== undefined) {
65
+ result.body = bodyMatch[1];
66
+ }
67
+ return result;
68
+ }
69
+ // ── E2e detection predicates ─────────────────────────────────────
70
+ const E2E_SOURCE_PREFIXES = [
71
+ "documentation/tests/e2e/",
72
+ "documentation/tests/e2e/packed/",
73
+ ];
74
+ function isExactE2eEvidence(doc) {
75
+ // (a) has e2e tag
76
+ if (doc.tags?.includes("e2e"))
77
+ return true;
78
+ // (b) source points into e2e directories
79
+ if (doc.source) {
80
+ for (const prefix of E2E_SOURCE_PREFIXES) {
81
+ if (doc.source.startsWith(prefix))
82
+ return true;
83
+ }
84
+ }
85
+ return false;
86
+ }
87
+ function isPackageLevelUmbrellaDoc(testId) {
88
+ // Package-level umbrella docs like TEST-opencode-kibi-plugin-v1
89
+ // These are broad test manifests, not file-specific e2e evidence
90
+ return /^TEST-opencode-.*-plugin-v\d+$/.test(testId);
91
+ }
92
+ function docNamesPath(doc, queryRelPath, distRelPath, srcCorrespondingPath) {
93
+ const body = doc.body ?? "";
94
+ return (body.includes(queryRelPath) ||
95
+ (distRelPath !== null && body.includes(distRelPath)) ||
96
+ (srcCorrespondingPath !== null && body.includes(srcCorrespondingPath)));
97
+ }
98
+ // ── Main exported function ───────────────────────────────────────
99
+ const EXACT_REMINDER = "- This file has existing e2e coverage. Check whether the e2e tests and linked TEST entities need updates.";
100
+ const HEURISTIC_REMINDER = "- This file may have related e2e coverage. Check the linked e2e tests if this change affects behavior.";
101
+ // implements REQ-opencode-file-context-guidance-v1
102
+ export function getE2eCoverageSignal(worktree, filePath) {
103
+ // Compute relative paths for heuristic matching
104
+ const srcRelPath = path
105
+ .relative(worktree, filePath)
106
+ .split(path.sep)
107
+ .join("/");
108
+ // For dist/ files, compute the matching src/ path
109
+ let distRelPath = null;
110
+ let srcCorrespondingPath = null;
111
+ if (srcRelPath.startsWith("packages/opencode/dist/")) {
112
+ distRelPath = srcRelPath;
113
+ // Derive the src/ path: packages/opencode/dist/toast.js → packages/opencode/src/toast.ts
114
+ const distSuffix = srcRelPath.slice("packages/opencode/dist/".length);
115
+ const baseName = distSuffix.replace(/\.js$/, ".ts");
116
+ srcCorrespondingPath = `packages/opencode/src/${baseName}`;
117
+ }
118
+ // Step 1: Get linked TEST-* targets via symbols.yaml relationships
119
+ // Try the actual file path first, then also try the src/ corresponding path for dist/ files
120
+ let linkedTargets = getFileLinkedTargetsByType(worktree, filePath, [
121
+ "covered_by",
122
+ "executable_for",
123
+ ]);
124
+ if (linkedTargets.length === 0 && srcCorrespondingPath) {
125
+ const srcAbsPath = path.join(worktree, srcCorrespondingPath);
126
+ linkedTargets = getFileLinkedTargetsByType(worktree, srcAbsPath, [
127
+ "covered_by",
128
+ "executable_for",
129
+ ]);
130
+ }
131
+ // Track exact and heuristic evidence
132
+ const exactEvidence = [];
133
+ const heuristicEvidence = [];
134
+ for (const targetId of linkedTargets) {
135
+ if (!targetId.startsWith("TEST-"))
136
+ continue;
137
+ const doc = readTestDoc(worktree, targetId);
138
+ if (!doc)
139
+ continue;
140
+ const isUmbrella = isPackageLevelUmbrellaDoc(targetId);
141
+ const hasExactE2e = isExactE2eEvidence(doc);
142
+ const namesPath = docNamesPath(doc, srcRelPath, distRelPath, srcCorrespondingPath);
143
+ if (isUmbrella) {
144
+ // Package-level umbrella docs are demoted to heuristic at most
145
+ // and only if they explicitly name the path
146
+ if (namesPath) {
147
+ heuristicEvidence.push(`${targetId} (umbrella doc names path: ${srcRelPath})`);
148
+ }
149
+ // Never exact for umbrella docs
150
+ continue;
151
+ }
152
+ if (hasExactE2e) {
153
+ exactEvidence.push(targetId);
154
+ }
155
+ else if (namesPath) {
156
+ // Heuristic: non-e2e doc that explicitly names the source path
157
+ heuristicEvidence.push(`${targetId} (doc names path: ${srcRelPath})`);
158
+ }
159
+ }
160
+ // Step 2: Also check heuristic path rules when no exact evidence
161
+ if (exactEvidence.length === 0 && heuristicEvidence.length === 0) {
162
+ // Narrow heuristic: file under packages/opencode/src/ and a test doc body names it
163
+ // This is already covered by the linked targets loop above since we check docNamesPath
164
+ // No additional scanning needed - we only inspect linked docs
165
+ }
166
+ // Step 3: Resolve level
167
+ if (exactEvidence.length > 0) {
168
+ return {
169
+ level: "exact",
170
+ evidence: exactEvidence,
171
+ reminderText: EXACT_REMINDER,
172
+ };
173
+ }
174
+ if (heuristicEvidence.length > 0) {
175
+ return {
176
+ level: "heuristic",
177
+ evidence: heuristicEvidence,
178
+ reminderText: HEURISTIC_REMINDER,
179
+ };
180
+ }
181
+ return {
182
+ level: "none",
183
+ evidence: [],
184
+ reminderText: null,
185
+ };
186
+ }
@@ -0,0 +1,15 @@
1
+ export type SymbolsManifestRow = {
2
+ id?: string;
3
+ sourceFile?: string;
4
+ links?: string[];
5
+ relationships?: Array<{
6
+ type: string;
7
+ target: string;
8
+ }>;
9
+ };
10
+ export declare function parseSymbolsYaml(content: string): SymbolsManifestRow[];
11
+ export declare function getFileLinkedEntityIds(worktree: string, filePath: string): {
12
+ ids: string[];
13
+ source: "symbols" | "doc-path" | "none";
14
+ };
15
+ export declare function getFileLinkedTargetsByType(worktree: string, filePath: string, relationshipTypes: string[]): string[];