@nerviq/cli 0.0.1 → 0.9.0-beta.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 (148) hide show
  1. package/CHANGELOG.md +181 -0
  2. package/LICENSE +21 -0
  3. package/README.md +447 -0
  4. package/bin/cli.js +749 -0
  5. package/content/case-study-template.md +91 -0
  6. package/content/claims-governance.md +37 -0
  7. package/content/claude-code/audit-repo/SKILL.md +20 -0
  8. package/content/claude-native-integration.md +60 -0
  9. package/content/devto-article.json +9 -0
  10. package/content/launch-posts.md +226 -0
  11. package/content/pilot-rollout-kit.md +30 -0
  12. package/content/release-checklist.md +31 -0
  13. package/package.json +53 -4
  14. package/src/activity.js +529 -0
  15. package/src/aider/activity.js +226 -0
  16. package/src/aider/config-parser.js +166 -0
  17. package/src/aider/context.js +158 -0
  18. package/src/aider/deep-review.js +316 -0
  19. package/src/aider/domain-packs.js +278 -0
  20. package/src/aider/freshness.js +168 -0
  21. package/src/aider/governance.js +253 -0
  22. package/src/aider/interactive.js +334 -0
  23. package/src/aider/mcp-packs.js +98 -0
  24. package/src/aider/patch.js +214 -0
  25. package/src/aider/plans.js +186 -0
  26. package/src/aider/premium.js +360 -0
  27. package/src/aider/setup.js +404 -0
  28. package/src/aider/techniques.js +1323 -0
  29. package/src/analyze.js +821 -0
  30. package/src/audit.js +1003 -0
  31. package/src/badge.js +13 -0
  32. package/src/benchmark.js +339 -0
  33. package/src/claudex-sync.json +7 -0
  34. package/src/codex/activity.js +324 -0
  35. package/src/codex/config-parser.js +183 -0
  36. package/src/codex/context.js +221 -0
  37. package/src/codex/deep-review.js +493 -0
  38. package/src/codex/domain-packs.js +372 -0
  39. package/src/codex/freshness.js +167 -0
  40. package/src/codex/governance.js +192 -0
  41. package/src/codex/interactive.js +618 -0
  42. package/src/codex/mcp-packs.js +660 -0
  43. package/src/codex/patch.js +209 -0
  44. package/src/codex/plans.js +251 -0
  45. package/src/codex/premium.js +614 -0
  46. package/src/codex/setup.js +603 -0
  47. package/src/codex/techniques.js +2649 -0
  48. package/src/context.js +272 -0
  49. package/src/copilot/activity.js +309 -0
  50. package/src/copilot/config-parser.js +226 -0
  51. package/src/copilot/context.js +197 -0
  52. package/src/copilot/deep-review.js +346 -0
  53. package/src/copilot/domain-packs.js +350 -0
  54. package/src/copilot/freshness.js +197 -0
  55. package/src/copilot/governance.js +222 -0
  56. package/src/copilot/interactive.js +406 -0
  57. package/src/copilot/mcp-packs.js +572 -0
  58. package/src/copilot/patch.js +238 -0
  59. package/src/copilot/plans.js +253 -0
  60. package/src/copilot/premium.js +450 -0
  61. package/src/copilot/setup.js +488 -0
  62. package/src/copilot/techniques.js +1822 -0
  63. package/src/cursor/activity.js +301 -0
  64. package/src/cursor/config-parser.js +265 -0
  65. package/src/cursor/context.js +236 -0
  66. package/src/cursor/deep-review.js +334 -0
  67. package/src/cursor/domain-packs.js +346 -0
  68. package/src/cursor/freshness.js +214 -0
  69. package/src/cursor/governance.js +229 -0
  70. package/src/cursor/interactive.js +391 -0
  71. package/src/cursor/mcp-packs.js +571 -0
  72. package/src/cursor/patch.js +243 -0
  73. package/src/cursor/plans.js +254 -0
  74. package/src/cursor/premium.js +468 -0
  75. package/src/cursor/setup.js +488 -0
  76. package/src/cursor/techniques.js +1786 -0
  77. package/src/deep-review.js +345 -0
  78. package/src/domain-packs.js +364 -0
  79. package/src/formatters/sarif.js +115 -0
  80. package/src/gemini/activity.js +402 -0
  81. package/src/gemini/config-parser.js +275 -0
  82. package/src/gemini/context.js +221 -0
  83. package/src/gemini/deep-review.js +559 -0
  84. package/src/gemini/domain-packs.js +371 -0
  85. package/src/gemini/freshness.js +204 -0
  86. package/src/gemini/governance.js +201 -0
  87. package/src/gemini/interactive.js +860 -0
  88. package/src/gemini/mcp-packs.js +658 -0
  89. package/src/gemini/patch.js +229 -0
  90. package/src/gemini/plans.js +269 -0
  91. package/src/gemini/premium.js +759 -0
  92. package/src/gemini/setup.js +692 -0
  93. package/src/gemini/techniques.js +2084 -0
  94. package/src/governance.js +523 -0
  95. package/src/harmony/advisor.js +383 -0
  96. package/src/harmony/audit.js +303 -0
  97. package/src/harmony/canon.js +444 -0
  98. package/src/harmony/cli.js +331 -0
  99. package/src/harmony/drift.js +401 -0
  100. package/src/harmony/governance.js +313 -0
  101. package/src/harmony/memory.js +238 -0
  102. package/src/harmony/sync.js +458 -0
  103. package/src/harmony/watch.js +336 -0
  104. package/src/index.js +256 -0
  105. package/src/insights.js +119 -0
  106. package/src/interactive.js +118 -0
  107. package/src/mcp-packs.js +597 -0
  108. package/src/opencode/activity.js +286 -0
  109. package/src/opencode/config-parser.js +109 -0
  110. package/src/opencode/context.js +247 -0
  111. package/src/opencode/deep-review.js +313 -0
  112. package/src/opencode/domain-packs.js +240 -0
  113. package/src/opencode/freshness.js +158 -0
  114. package/src/opencode/governance.js +159 -0
  115. package/src/opencode/interactive.js +392 -0
  116. package/src/opencode/mcp-packs.js +474 -0
  117. package/src/opencode/patch.js +184 -0
  118. package/src/opencode/plans.js +231 -0
  119. package/src/opencode/premium.js +413 -0
  120. package/src/opencode/setup.js +449 -0
  121. package/src/opencode/techniques.js +1713 -0
  122. package/src/plans.js +655 -0
  123. package/src/secret-patterns.js +30 -0
  124. package/src/setup.js +1274 -0
  125. package/src/synergy/adaptive.js +261 -0
  126. package/src/synergy/compensation.js +156 -0
  127. package/src/synergy/evidence.js +193 -0
  128. package/src/synergy/learning.js +184 -0
  129. package/src/synergy/patterns.js +227 -0
  130. package/src/synergy/ranking.js +83 -0
  131. package/src/synergy/report.js +163 -0
  132. package/src/synergy/routing.js +152 -0
  133. package/src/techniques.js +1354 -0
  134. package/src/watch.js +229 -0
  135. package/src/windsurf/activity.js +302 -0
  136. package/src/windsurf/config-parser.js +267 -0
  137. package/src/windsurf/context.js +249 -0
  138. package/src/windsurf/deep-review.js +337 -0
  139. package/src/windsurf/domain-packs.js +348 -0
  140. package/src/windsurf/freshness.js +215 -0
  141. package/src/windsurf/governance.js +231 -0
  142. package/src/windsurf/interactive.js +388 -0
  143. package/src/windsurf/mcp-packs.js +535 -0
  144. package/src/windsurf/patch.js +231 -0
  145. package/src/windsurf/plans.js +247 -0
  146. package/src/windsurf/premium.js +467 -0
  147. package/src/windsurf/setup.js +471 -0
  148. package/src/windsurf/techniques.js +1758 -0
@@ -0,0 +1,286 @@
1
+ /**
2
+ * OpenCode Repeat-Usage Surfaces — 6 repeat-usage surfaces
3
+ *
4
+ * Adapts the shared activity/snapshot backend for OpenCode platform.
5
+ * Provides: history, compare, trend, watch, feedback, insights.
6
+ *
7
+ * OpenCode snapshots are stored alongside Claude snapshots in
8
+ * .claude/claudex-setup/snapshots/ but filtered by platform='opencode'.
9
+ */
10
+
11
+ const path = require('path');
12
+ const {
13
+ readSnapshotIndex,
14
+ writeSnapshotArtifact,
15
+ exportTrendReport: sharedExportTrendReport,
16
+ recordRecommendationOutcome,
17
+ readOutcomeIndex,
18
+ summarizeOutcomeEntries,
19
+ } = require('../activity');
20
+ const { version } = require('../../package.json');
21
+
22
+ // --- History ---
23
+
24
+ function getOpenCodeHistory(dir, limit = 20) {
25
+ const entries = readSnapshotIndex(dir);
26
+ return entries
27
+ .filter(e => e.snapshotKind === 'audit' && (e.platform === 'opencode' || e.summary?.platform === 'opencode'))
28
+ .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
29
+ .slice(0, limit);
30
+ }
31
+
32
+ function formatOpenCodeHistory(dir) {
33
+ const history = getOpenCodeHistory(dir, 10);
34
+ if (history.length === 0) {
35
+ return 'No OpenCode snapshots found. Run `npx nerviq --platform opencode --snapshot` to save one.';
36
+ }
37
+
38
+ const lines = ['OpenCode Score History (most recent first):', ''];
39
+ for (const entry of history) {
40
+ const date = entry.createdAt?.split('T')[0] || 'unknown';
41
+ const score = entry.summary?.score ?? '?';
42
+ const passed = entry.summary?.passed ?? '?';
43
+ const total = entry.summary?.checkCount ?? '?';
44
+ lines.push(` ${date} ${score}/100 (${passed}/${total} passing)`);
45
+ }
46
+
47
+ const comparison = compareOpenCodeLatest(dir);
48
+ if (comparison) {
49
+ lines.push('');
50
+ const sign = comparison.delta.score >= 0 ? '+' : '';
51
+ lines.push(` Trend: ${comparison.trend} (${sign}${comparison.delta.score} since previous)`);
52
+ if (comparison.improvements.length > 0) lines.push(` Fixed: ${comparison.improvements.join(', ')}`);
53
+ if (comparison.regressions.length > 0) lines.push(` New gaps: ${comparison.regressions.join(', ')}`);
54
+ }
55
+
56
+ return lines.join('\n');
57
+ }
58
+
59
+ // --- Compare ---
60
+
61
+ function compareOpenCodeLatest(dir) {
62
+ const audits = getOpenCodeHistory(dir, 2);
63
+ if (audits.length < 2) return null;
64
+
65
+ const current = audits[0];
66
+ const previous = audits[1];
67
+
68
+ const delta = {
69
+ score: (current.summary?.score || 0) - (previous.summary?.score || 0),
70
+ organic: (current.summary?.organicScore || 0) - (previous.summary?.organicScore || 0),
71
+ passed: (current.summary?.passed || 0) - (previous.summary?.passed || 0),
72
+ };
73
+
74
+ const regressions = [];
75
+ const improvements = [];
76
+ const prevKeys = new Set(previous.summary?.topActionKeys || []);
77
+ const currKeys = new Set(current.summary?.topActionKeys || []);
78
+ for (const key of currKeys) { if (!prevKeys.has(key)) regressions.push(key); }
79
+ for (const key of prevKeys) { if (!currKeys.has(key)) improvements.push(key); }
80
+
81
+ return {
82
+ platform: 'opencode',
83
+ current: { date: current.createdAt, score: current.summary?.score, passed: current.summary?.passed },
84
+ previous: { date: previous.createdAt, score: previous.summary?.score, passed: previous.summary?.passed },
85
+ delta,
86
+ regressions,
87
+ improvements,
88
+ trend: delta.score > 0 ? 'improving' : delta.score < 0 ? 'regressing' : 'stable',
89
+ };
90
+ }
91
+
92
+ // --- Trend ---
93
+
94
+ function exportOpenCodeTrendReport(dir) {
95
+ const history = getOpenCodeHistory(dir, 50);
96
+ if (history.length === 0) return null;
97
+
98
+ const comparison = compareOpenCodeLatest(dir);
99
+ const lines = [
100
+ '# OpenCode Setup Trend Report',
101
+ '',
102
+ `**Project:** ${path.basename(dir)}`,
103
+ '**Platform:** OpenCode',
104
+ `**Generated:** ${new Date().toISOString().split('T')[0]}`,
105
+ `**Snapshots:** ${history.length}`,
106
+ '',
107
+ '## Score History',
108
+ '',
109
+ '| Date | Score | Passed | Checks |',
110
+ '|------|-------|--------|--------|',
111
+ ];
112
+
113
+ for (const entry of history) {
114
+ const date = entry.createdAt?.split('T')[0] || '?';
115
+ lines.push(`| ${date} | ${entry.summary?.score ?? '?'}/100 | ${entry.summary?.passed ?? '?'} | ${entry.summary?.checkCount ?? '?'} |`);
116
+ }
117
+
118
+ if (comparison) {
119
+ lines.push('');
120
+ lines.push('## Latest Comparison');
121
+ lines.push('');
122
+ lines.push(`- **Previous:** ${comparison.previous.score}/100 (${comparison.previous.date?.split('T')[0]})`);
123
+ lines.push(`- **Current:** ${comparison.current.score}/100 (${comparison.current.date?.split('T')[0]})`);
124
+ lines.push(`- **Delta:** ${comparison.delta.score >= 0 ? '+' : ''}${comparison.delta.score} points`);
125
+ lines.push(`- **Trend:** ${comparison.trend}`);
126
+ if (comparison.improvements.length > 0) lines.push(`- **Fixed:** ${comparison.improvements.join(', ')}`);
127
+ if (comparison.regressions.length > 0) lines.push(`- **New gaps:** ${comparison.regressions.join(', ')}`);
128
+ }
129
+
130
+ if (history.length >= 3) {
131
+ lines.push('');
132
+ lines.push('## Trend Chart');
133
+ lines.push('');
134
+ lines.push('```');
135
+ const scores = history.slice().reverse().map(e => e.summary?.score ?? 0);
136
+ const max = Math.max(...scores, 100);
137
+ const chartHeight = 10;
138
+ for (let row = chartHeight; row >= 0; row--) {
139
+ const threshold = (row / chartHeight) * max;
140
+ const rowLabel = String(Math.round(threshold)).padStart(3);
141
+ const bar = scores.map(s => s >= threshold ? '#' : ' ').join('');
142
+ lines.push(`${rowLabel} |${bar}`);
143
+ }
144
+ lines.push(` +${'─'.repeat(scores.length)}`);
145
+ lines.push('```');
146
+ }
147
+
148
+ lines.push('');
149
+ lines.push('---');
150
+ lines.push(`*Generated by nerviq v${version} for OpenCode*`);
151
+ return lines.join('\n');
152
+ }
153
+
154
+ // --- Feedback ---
155
+
156
+ function recordOpenCodeFeedback(dir, payload) {
157
+ return recordRecommendationOutcome(dir, {
158
+ ...payload,
159
+ source: payload.source || 'opencode-cli',
160
+ platform: 'opencode',
161
+ });
162
+ }
163
+
164
+ function getOpenCodeFeedbackSummary(dir) {
165
+ const entries = readOutcomeIndex(dir)
166
+ .filter(e => e.source === 'opencode-cli' || e.platform === 'opencode');
167
+ return summarizeOutcomeEntries(entries);
168
+ }
169
+
170
+ function formatOpenCodeFeedback(dir) {
171
+ const summary = getOpenCodeFeedbackSummary(dir);
172
+ if (!summary || Object.keys(summary).length === 0) {
173
+ return 'No OpenCode feedback recorded yet.';
174
+ }
175
+
176
+ const lines = ['OpenCode Recommendation Feedback:', ''];
177
+ const entries = Array.isArray(summary) ? summary : Object.values(summary);
178
+ for (const entry of entries) {
179
+ const key = entry.key || 'unknown';
180
+ const accepted = entry.accepted || 0;
181
+ const rejected = entry.rejected || 0;
182
+ const total = entry.total || 0;
183
+ lines.push(` ${key}: ${accepted} accepted, ${rejected} rejected (${total} total)`);
184
+ }
185
+ return lines.join('\n');
186
+ }
187
+
188
+ // --- Insights ---
189
+
190
+ function generateOpenCodeInsights(dir) {
191
+ const history = getOpenCodeHistory(dir, 50);
192
+ const feedback = getOpenCodeFeedbackSummary(dir);
193
+ const insights = [];
194
+
195
+ if (history.length >= 3) {
196
+ const recentFailKeys = new Map();
197
+ for (const entry of history.slice(0, 5)) {
198
+ for (const key of (entry.summary?.topActionKeys || [])) {
199
+ recentFailKeys.set(key, (recentFailKeys.get(key) || 0) + 1);
200
+ }
201
+ }
202
+ for (const [key, count] of recentFailKeys) {
203
+ if (count >= 3) {
204
+ insights.push({
205
+ type: 'persistent-failure',
206
+ severity: 'high',
207
+ key,
208
+ message: `Check ${key} has failed in ${count} of the last ${Math.min(history.length, 5)} audits.`,
209
+ });
210
+ }
211
+ }
212
+ }
213
+
214
+ if (history.length >= 2) {
215
+ const scores = history.map(e => e.summary?.score ?? 0);
216
+ if (scores[0] < scores[1]) {
217
+ insights.push({
218
+ type: 'regression-pattern',
219
+ severity: 'medium',
220
+ message: `Score dropped from ${scores[1]} to ${scores[0]} in the most recent audit.`,
221
+ delta: scores[0] - scores[1],
222
+ });
223
+ }
224
+ }
225
+
226
+ if (history.length >= 5) {
227
+ const recentScores = history.slice(0, 5).map(e => e.summary?.score ?? 0);
228
+ const range = Math.max(...recentScores) - Math.min(...recentScores);
229
+ if (range <= 2) {
230
+ insights.push({
231
+ type: 'velocity-stall',
232
+ severity: 'low',
233
+ message: `Score has been flat (range: ${range} points) over the last 5 audits.`,
234
+ });
235
+ }
236
+ }
237
+
238
+ const feedbackEntries = Array.isArray(feedback) ? feedback : Object.values(feedback || {});
239
+ for (const entry of feedbackEntries) {
240
+ if (entry.rejected > entry.accepted && entry.total >= 2) {
241
+ insights.push({
242
+ type: 'feedback-signal',
243
+ severity: 'medium',
244
+ key: entry.key,
245
+ message: `Recommendation ${entry.key} has been rejected more than accepted (${entry.rejected}/${entry.total}).`,
246
+ });
247
+ }
248
+ }
249
+
250
+ return {
251
+ platform: 'opencode',
252
+ generatedAt: new Date().toISOString(),
253
+ snapshotCount: history.length,
254
+ feedbackCount: feedbackEntries.length,
255
+ insights,
256
+ summary: insights.length === 0
257
+ ? 'No actionable insights detected. Keep running audits to build pattern data.'
258
+ : `${insights.length} insight(s) detected across ${history.length} snapshots.`,
259
+ };
260
+ }
261
+
262
+ function formatOpenCodeInsights(dir) {
263
+ const result = generateOpenCodeInsights(dir);
264
+ if (result.insights.length === 0) return result.summary;
265
+
266
+ const lines = ['OpenCode Insights:', ''];
267
+ for (const insight of result.insights) {
268
+ const severity = insight.severity.toUpperCase();
269
+ lines.push(` [${severity}] ${insight.message}`);
270
+ }
271
+ lines.push('');
272
+ lines.push(result.summary);
273
+ return lines.join('\n');
274
+ }
275
+
276
+ module.exports = {
277
+ getOpenCodeHistory,
278
+ formatOpenCodeHistory,
279
+ compareOpenCodeLatest,
280
+ exportOpenCodeTrendReport,
281
+ recordOpenCodeFeedback,
282
+ getOpenCodeFeedbackSummary,
283
+ formatOpenCodeFeedback,
284
+ generateOpenCodeInsights,
285
+ formatOpenCodeInsights,
286
+ };
@@ -0,0 +1,109 @@
1
+ /**
2
+ * OpenCode JSONC Parser
3
+ *
4
+ * Parses JSONC (JSON with Comments) format used by opencode.json / opencode.jsonc.
5
+ * Strips single-line (//) and multi-line comments before parsing.
6
+ */
7
+
8
+ function stripJsoncComments(content) {
9
+ let result = '';
10
+ let inString = false;
11
+ let inSingleLineComment = false;
12
+ let inMultiLineComment = false;
13
+
14
+ for (let i = 0; i < content.length; i++) {
15
+ const char = content[i];
16
+ const next = i + 1 < content.length ? content[i + 1] : '';
17
+ const prev = i > 0 ? content[i - 1] : '';
18
+
19
+ if (inSingleLineComment) {
20
+ if (char === '\n') {
21
+ inSingleLineComment = false;
22
+ result += char;
23
+ }
24
+ continue;
25
+ }
26
+
27
+ if (inMultiLineComment) {
28
+ if (char === '*' && next === '/') {
29
+ inMultiLineComment = false;
30
+ i++; // skip closing /
31
+ } else if (char === '\n') {
32
+ result += char; // preserve newlines for line counting
33
+ }
34
+ continue;
35
+ }
36
+
37
+ if (inString) {
38
+ result += char;
39
+ if (char === '"' && prev !== '\\') {
40
+ inString = false;
41
+ }
42
+ continue;
43
+ }
44
+
45
+ // Not in string or comment
46
+ if (char === '"') {
47
+ inString = true;
48
+ result += char;
49
+ continue;
50
+ }
51
+
52
+ if (char === '/' && next === '/') {
53
+ inSingleLineComment = true;
54
+ i++; // skip second /
55
+ continue;
56
+ }
57
+
58
+ if (char === '/' && next === '*') {
59
+ inMultiLineComment = true;
60
+ i++; // skip *
61
+ continue;
62
+ }
63
+
64
+ result += char;
65
+ }
66
+
67
+ return result;
68
+ }
69
+
70
+ /**
71
+ * Strip trailing commas from JSON (common in JSONC).
72
+ */
73
+ function stripTrailingCommas(content) {
74
+ return content.replace(/,\s*([\]}])/g, '$1');
75
+ }
76
+
77
+ function parseJsonc(content) {
78
+ const stripped = stripTrailingCommas(stripJsoncComments(content));
79
+ return JSON.parse(stripped);
80
+ }
81
+
82
+ function tryParseJsonc(content) {
83
+ try {
84
+ return { ok: true, data: parseJsonc(content), error: null };
85
+ } catch (error) {
86
+ return { ok: false, data: null, error: error.message };
87
+ }
88
+ }
89
+
90
+ function getValueByPath(obj, dottedPath) {
91
+ if (!obj) return undefined;
92
+ const parts = dottedPath.split('.').filter(Boolean);
93
+ let cursor = obj;
94
+ for (const part of parts) {
95
+ if (cursor == null || typeof cursor !== 'object' || !(part in cursor)) {
96
+ return undefined;
97
+ }
98
+ cursor = cursor[part];
99
+ }
100
+ return cursor;
101
+ }
102
+
103
+ module.exports = {
104
+ stripJsoncComments,
105
+ stripTrailingCommas,
106
+ parseJsonc,
107
+ tryParseJsonc,
108
+ getValueByPath,
109
+ };
@@ -0,0 +1,247 @@
1
+ /**
2
+ * OpenCode Project Context
3
+ *
4
+ * Reads and caches OpenCode-specific project surfaces:
5
+ * - opencode.json / opencode.jsonc (JSONC config)
6
+ * - AGENTS.md (shared with Codex/Copilot)
7
+ * - Permission configuration
8
+ * - Plugin system
9
+ * - 6-level config merge hierarchy
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const os = require('os');
14
+ const path = require('path');
15
+ const { spawnSync } = require('child_process');
16
+ const { ProjectContext } = require('../context');
17
+ const { tryParseJsonc, getValueByPath } = require('./config-parser');
18
+
19
+ let opencodeVersionCache = null;
20
+
21
+ function detectOpencodeVersion() {
22
+ if (opencodeVersionCache !== null) {
23
+ return opencodeVersionCache;
24
+ }
25
+
26
+ try {
27
+ const result = spawnSync('opencode', ['--version'], { encoding: 'utf8' });
28
+ const output = `${result.stdout || ''} ${result.stderr || ''}`.trim();
29
+ const match = output.match(/opencode\s+v?([^\s]+)/i);
30
+ opencodeVersionCache = match ? match[1] : (output || null);
31
+ return opencodeVersionCache;
32
+ } catch {
33
+ opencodeVersionCache = null;
34
+ return null;
35
+ }
36
+ }
37
+
38
+ function listDirs(fullPath) {
39
+ try {
40
+ return fs.readdirSync(fullPath, { withFileTypes: true }).filter(entry => entry.isDirectory());
41
+ } catch {
42
+ return [];
43
+ }
44
+ }
45
+
46
+ class OpenCodeProjectContext extends ProjectContext {
47
+ configContent() {
48
+ return this.fileContent('opencode.json') || this.fileContent('opencode.jsonc');
49
+ }
50
+
51
+ configFileName() {
52
+ if (this.fileContent('opencode.json')) return 'opencode.json';
53
+ if (this.fileContent('opencode.jsonc')) return 'opencode.jsonc';
54
+ return null;
55
+ }
56
+
57
+ globalConfigContent() {
58
+ const homeDir = os.homedir();
59
+ const globalPaths = [
60
+ path.join(homeDir, '.config', 'opencode', 'opencode.json'),
61
+ path.join(homeDir, '.config', 'opencode', 'opencode.jsonc'),
62
+ ];
63
+ for (const globalPath of globalPaths) {
64
+ try {
65
+ return fs.readFileSync(globalPath, 'utf8');
66
+ } catch {
67
+ // continue
68
+ }
69
+ }
70
+ return null;
71
+ }
72
+
73
+ agentsMdContent() {
74
+ const direct = this.fileContent('AGENTS.md');
75
+ if (direct) return direct;
76
+
77
+ // OpenCode fallback: CLAUDE.md if no AGENTS.md
78
+ const claudeMd = this.fileContent('CLAUDE.md');
79
+ if (claudeMd) return claudeMd;
80
+
81
+ return null;
82
+ }
83
+
84
+ agentsMdPath() {
85
+ if (this.fileContent('AGENTS.md')) return 'AGENTS.md';
86
+ if (this.fileContent('CLAUDE.md')) return 'CLAUDE.md';
87
+ return null;
88
+ }
89
+
90
+ hasAgentsMdAndClaudeMd() {
91
+ return Boolean(this.fileContent('AGENTS.md')) && Boolean(this.fileContent('CLAUDE.md'));
92
+ }
93
+
94
+ globalAgentsMdContent() {
95
+ const homeDir = os.homedir();
96
+ const paths = [
97
+ path.join(homeDir, '.config', 'opencode', 'AGENTS.md'),
98
+ path.join(homeDir, '.claude', 'CLAUDE.md'),
99
+ ];
100
+ for (const p of paths) {
101
+ try {
102
+ return fs.readFileSync(p, 'utf8');
103
+ } catch {
104
+ // continue
105
+ }
106
+ }
107
+ return null;
108
+ }
109
+
110
+ configJson() {
111
+ const content = this.configContent();
112
+ if (!content) {
113
+ return { ok: false, data: null, error: 'missing project config', source: this.configFileName() || 'opencode.json' };
114
+ }
115
+ const parsed = tryParseJsonc(content);
116
+ return { ...parsed, source: this.configFileName() };
117
+ }
118
+
119
+ globalConfigJson() {
120
+ const content = this.globalConfigContent();
121
+ if (!content) {
122
+ return { ok: false, data: null, error: 'missing global config', source: '~/.config/opencode/opencode.json' };
123
+ }
124
+ const parsed = tryParseJsonc(content);
125
+ return { ...parsed, source: '~/.config/opencode/opencode.json' };
126
+ }
127
+
128
+ configValue(dottedPath) {
129
+ // 6-level merge: project wins over global
130
+ const project = this.configJson();
131
+ if (project.ok) {
132
+ const projectValue = getValueByPath(project.data, dottedPath);
133
+ if (projectValue !== undefined) return projectValue;
134
+ }
135
+
136
+ const globalConfig = this.globalConfigJson();
137
+ if (globalConfig.ok) {
138
+ return getValueByPath(globalConfig.data, dottedPath);
139
+ }
140
+
141
+ return undefined;
142
+ }
143
+
144
+ permissions() {
145
+ const config = this.configJson();
146
+ if (!config.ok || !config.data) return {};
147
+ return config.data.permissions || {};
148
+ }
149
+
150
+ toolPermissions() {
151
+ const perms = this.permissions();
152
+ return perms.tools || {};
153
+ }
154
+
155
+ plugins() {
156
+ const config = this.configJson();
157
+ if (!config.ok || !config.data) return [];
158
+ return config.data.plugins || [];
159
+ }
160
+
161
+ pluginFiles() {
162
+ const pluginsDir = path.join(this.dir, '.opencode', 'plugins');
163
+ try {
164
+ return fs.readdirSync(pluginsDir).filter(f => /\.(js|ts|mjs)$/.test(f));
165
+ } catch {
166
+ return [];
167
+ }
168
+ }
169
+
170
+ tuiConfigContent() {
171
+ return this.fileContent('tui.json') || this.fileContent('tui.jsonc') ||
172
+ this.fileContent('.opencode/tui.json') || this.fileContent('.opencode/tui.jsonc');
173
+ }
174
+
175
+ tuiConfigJson() {
176
+ const content = this.tuiConfigContent();
177
+ if (!content) return { ok: false, data: null, error: 'missing tui config' };
178
+ return tryParseJsonc(content);
179
+ }
180
+
181
+ mcpServers() {
182
+ return this.configValue('mcp') || {};
183
+ }
184
+
185
+ customAgents() {
186
+ const config = this.configJson();
187
+ if (!config.ok || !config.data) return {};
188
+ return config.data.agents || {};
189
+ }
190
+
191
+ commandDirs() {
192
+ const commandsDir = path.join(this.dir, '.opencode', 'commands');
193
+ return listDirs(commandsDir).map(entry => entry.name);
194
+ }
195
+
196
+ commandFiles() {
197
+ const commandsDir = path.join(this.dir, '.opencode', 'commands');
198
+ try {
199
+ return fs.readdirSync(commandsDir).filter(f => /\.(md|yaml|yml)$/.test(f));
200
+ } catch {
201
+ return [];
202
+ }
203
+ }
204
+
205
+ skillDirs() {
206
+ const skillsDir = path.join(this.dir, '.opencode', 'commands');
207
+ return listDirs(skillsDir).map(entry => entry.name);
208
+ }
209
+
210
+ skillMetadata(name) {
211
+ return this.fileContent(path.join('.opencode', 'commands', name, 'SKILL.md'));
212
+ }
213
+
214
+ themeFiles() {
215
+ const themesDir = path.join(this.dir, '.opencode', 'themes');
216
+ try {
217
+ return fs.readdirSync(themesDir).filter(f => f.endsWith('.json'));
218
+ } catch {
219
+ return [];
220
+ }
221
+ }
222
+
223
+ instructionsArray() {
224
+ return this.configValue('instructions') || [];
225
+ }
226
+
227
+ workflowFiles() {
228
+ return this.dirFiles('.github/workflows')
229
+ .filter(file => /\.ya?ml$/i.test(file))
230
+ .map(file => path.join('.github', 'workflows', file).replace(/\\/g, '/'));
231
+ }
232
+
233
+ static isOpenCodeRepo(dir) {
234
+ try {
235
+ return fs.existsSync(path.join(dir, 'opencode.json')) ||
236
+ fs.existsSync(path.join(dir, 'opencode.jsonc')) ||
237
+ fs.existsSync(path.join(dir, '.opencode'));
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+ }
243
+
244
+ module.exports = {
245
+ OpenCodeProjectContext,
246
+ detectOpencodeVersion,
247
+ };