-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.js
More file actions
executable file
·308 lines (278 loc) · 9.12 KB
/
Copy pathinstall.js
File metadata and controls
executable file
·308 lines (278 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#!/usr/bin/env node
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 EvoMap
'use strict';
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const PLUGIN_FILE_NAME = 'evolver.js';
const PLUGIN_HEADER = '// _evolver_managed: true (do not remove this line)';
const EVOLVER_MARKER = '<!-- evolver-opencode-evolution-memory -->';
const EVOLVER_END_MARKER = '<!-- /evolver-opencode-evolution-memory -->';
const HOOK_SCRIPTS = ['session-start.js', 'signal-detect.js', 'session-end.js'];
function usage() {
return `Usage: evolver-opencode-plugin [--install|--verify|--uninstall] [--config-root <dir>] [--force]
Installs the local-file OpenCode plugin into <config-root>/.opencode/plugins.
For npm-based OpenCode installs, add "evolver-opencode-plugin" to opencode.json
instead; no CLI install step is required.
`;
}
function parseArgs(argv) {
const args = {
action: 'install',
configRoot: process.cwd(),
force: false,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '--install') args.action = 'install';
else if (arg === '--verify') args.action = 'verify';
else if (arg === '--uninstall') args.action = 'uninstall';
else if (arg === '--force') args.force = true;
else if (arg === '--help' || arg === '-h') args.action = 'help';
else if (arg === '--config-root') {
i += 1;
args.configRoot = argv[i] || args.configRoot;
} else if (arg.startsWith('--config-root=')) {
args.configRoot = arg.slice('--config-root='.length);
} else {
throw new Error(`unknown argument: ${arg}`);
}
}
args.configRoot = path.resolve(args.configRoot);
return args;
}
function packageRoot() {
return path.resolve(__dirname, '..');
}
function pluginSource() {
const serverPath = path.join(packageRoot(), 'server.js');
return `${PLUGIN_HEADER}
// Auto-generated by evolver-opencode-plugin.
// This file delegates to the package server plugin entrypoint.
module.exports = require(${JSON.stringify(serverPath)});
`;
}
function paths(configRoot) {
const opencodeDir = path.join(configRoot, '.opencode');
const pluginsDir = path.join(opencodeDir, 'plugins');
const pluginPath = path.join(pluginsDir, PLUGIN_FILE_NAME);
const agentsMdPath = path.join(configRoot, 'AGENTS.md');
return { opencodeDir, pluginsDir, pluginPath, agentsMdPath };
}
function isManaged(filePath) {
try {
return fs.readFileSync(filePath, 'utf8').includes('_evolver_managed: true');
} catch (_err) {
return false;
}
}
function atomicWrite(filePath, content) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const tmp = path.join(
path.dirname(filePath),
`.${path.basename(filePath)}.${process.pid}.tmp`
);
fs.writeFileSync(tmp, content, 'utf8');
fs.renameSync(tmp, filePath);
}
function appendAgentsSection(filePath) {
const section = `${EVOLVER_MARKER}
## Evolution Memory (Evolver)
This project uses Evolver for self-evolution. OpenCode plugin hooks automatically:
1. Prepare recent evolution memory for OpenCode context compaction
2. Detect evolution signals during file edits
3. Record outcomes when the OpenCode session is deleted
For substantive tasks, use successful prior approaches when the plugin surfaces them, and avoid repeating failed patterns.
${EVOLVER_END_MARKER}`;
let existing = '';
try {
existing = fs.readFileSync(filePath, 'utf8');
} catch (_err) {
// new file
}
if (existing.includes(EVOLVER_MARKER)) return false;
const separator = existing.length === 0
? ''
: existing.endsWith('\n')
? '\n'
: '\n\n';
atomicWrite(filePath, existing + separator + section + '\n');
return true;
}
function removeAgentsSection(filePath) {
try {
let content = fs.readFileSync(filePath, 'utf8');
if (!content.includes(EVOLVER_MARKER)) return false;
const idx = content.indexOf(EVOLVER_MARKER);
const endMarker = content.indexOf(EVOLVER_END_MARKER, idx);
let endIdx;
if (endMarker !== -1) {
const afterEndMarker = endMarker + EVOLVER_END_MARKER.length;
const lineBreak = content.indexOf('\n', afterEndMarker);
endIdx = lineBreak === -1 ? content.length : lineBreak + 1;
} else {
// Legacy installs had no end marker. Skip the managed heading itself,
// then remove until the following markdown section or EOF.
const ownHeading = content.indexOf('\n## ', idx);
const nextSection = ownHeading === -1
? -1
: content.indexOf('\n## ', ownHeading + 1);
endIdx = nextSection === -1 ? content.length : nextSection;
}
content = content.slice(0, idx).trimEnd() + content.slice(endIdx);
atomicWrite(filePath, `${content.trimEnd()}\n`);
return true;
} catch (_err) {
return false;
}
}
function install({ configRoot, force }) {
const p = paths(configRoot);
if (fs.existsSync(p.pluginPath) && !isManaged(p.pluginPath) && !force) {
return {
ok: false,
error: `refusing to overwrite user-owned plugin: ${p.pluginPath}`,
};
}
fs.mkdirSync(p.pluginsDir, { recursive: true });
atomicWrite(p.pluginPath, pluginSource());
appendAgentsSection(p.agentsMdPath);
return {
ok: true,
action: 'install',
plugin_path: p.pluginPath,
config_root: configRoot,
};
}
function verify({ configRoot }) {
const p = paths(configRoot);
const checks = [];
const pluginExists = fs.existsSync(p.pluginPath);
checks.push({
id: 'plugin_file_present',
ok: pluginExists,
detail: pluginExists ? p.pluginPath : `missing: ${p.pluginPath}`,
});
const managed = pluginExists && isManaged(p.pluginPath);
checks.push({
id: 'plugin_managed_marker',
ok: managed,
detail: managed ? 'contains _evolver_managed: true' : 'plugin file is absent or user-owned',
});
let loadable = false;
let loadError = null;
if (pluginExists) {
try {
delete require.cache[require.resolve(p.pluginPath)];
const mod = require(p.pluginPath);
loadable = typeof (mod && (mod.Evolver || mod.default)) === 'function';
if (!loadable) loadError = 'missing Evolver/default function export';
} catch (err) {
loadError = (err && err.message) || String(err);
}
}
checks.push({
id: 'plugin_loadable',
ok: loadable,
detail: loadable ? 'require() succeeded and exports Evolver()' : `require() failed: ${loadError || 'unknown'}`,
});
const missingHooks = HOOK_SCRIPTS.filter((name) => !fs.existsSync(path.join(packageRoot(), 'hooks', name)));
checks.push({
id: 'package_hooks_present',
ok: missingHooks.length === 0,
detail: missingHooks.length === 0
? 'all package hook scripts present'
: `missing from package: ${missingHooks.join(', ')}`,
});
let hasAgents = false;
try {
hasAgents = fs.readFileSync(p.agentsMdPath, 'utf8').includes(EVOLVER_MARKER);
} catch (_err) {
hasAgents = false;
}
checks.push({
id: 'agents_md_section',
ok: hasAgents,
detail: hasAgents ? 'AGENTS.md contains Evolver OpenCode section' : 'AGENTS.md section not installed',
});
return {
ok: checks.every((check) => check.ok),
action: 'verify',
plugin_path: p.pluginPath,
config_root: configRoot,
checks,
};
}
function uninstall({ configRoot }) {
const p = paths(configRoot);
let changed = false;
if (isManaged(p.pluginPath)) {
fs.unlinkSync(p.pluginPath);
changed = true;
}
if (removeAgentsSection(p.agentsMdPath)) changed = true;
return {
ok: true,
action: 'uninstall',
removed: changed,
plugin_path: p.pluginPath,
config_root: configRoot,
};
}
function printReport(report) {
if (report.action === 'verify') {
console.log(`[opencode] Verify ${report.ok ? 'passed' : 'failed'}`);
console.log(`[opencode] plugin path : ${report.plugin_path}`);
console.log(`[opencode] config root : ${report.config_root}`);
for (const check of report.checks) {
console.log(`[opencode] ${check.ok ? '[OK] ' : '[FAIL]'} ${check.id} -- ${check.detail}`);
}
return;
}
if (report.ok) {
const verb = report.action === 'uninstall' ? 'Uninstalled' : 'Installed';
console.log(`[opencode] ${verb} Evolver plugin at ${report.plugin_path}`);
if (report.action === 'install') {
console.log('[opencode] Restart OpenCode for the plugin to take effect.');
console.log('[opencode] For npm installs, prefer adding "evolver-opencode-plugin" to opencode.json.');
}
} else {
console.error(`[opencode] ${report.error || 'operation failed'}`);
}
}
function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (err) {
console.error((err && err.message) || String(err));
console.error(usage());
process.exit(2);
}
if (args.action === 'help') {
process.stdout.write(usage());
return;
}
let report;
if (args.action === 'verify') report = verify(args);
else if (args.action === 'uninstall') report = uninstall(args);
else report = install(args);
printReport(report);
if (!report.ok) process.exit(1);
}
if (require.main === module) {
main();
}
module.exports = {
parseArgs,
pluginSource,
isManaged,
install,
verify,
uninstall,
paths,
packageRoot,
EVOLVER_MARKER,
EVOLVER_END_MARKER,
};