-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathopencode-sm.ts
More file actions
599 lines (519 loc) · 16.4 KB
/
Copy pathopencode-sm.ts
File metadata and controls
599 lines (519 loc) · 16.4 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#!/usr/bin/env node
/**
* opencode-sm: OpenCode wrapper with StackMemory and worktree integration
* Automatically manages context persistence and instance isolation
*/
import { config as loadDotenv } from 'dotenv';
loadDotenv({ override: true, debug: false });
import { spawn, execSync, execFileSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { program } from 'commander';
import { v4 as uuidv4 } from 'uuid';
import chalk from 'chalk';
import { initializeTracing, trace } from '../core/trace/index.js';
interface OpencodeSMConfig {
defaultWorktree: boolean;
defaultTracing: boolean;
}
interface OpencodeConfig {
instanceId: string;
worktreePath?: string;
useWorktree: boolean;
contextEnabled: boolean;
branch?: string;
task?: string;
tracingEnabled: boolean;
verboseTracing: boolean;
opencodeBin?: string;
sessionStartTime: number;
}
const DEFAULT_SM_CONFIG: OpencodeSMConfig = {
defaultWorktree: false,
defaultTracing: true,
};
function getConfigPath(): string {
return path.join(os.homedir(), '.stackmemory', 'opencode-sm.json');
}
function loadSMConfig(): OpencodeSMConfig {
try {
const configPath = getConfigPath();
if (fs.existsSync(configPath)) {
const content = fs.readFileSync(configPath, 'utf8');
return { ...DEFAULT_SM_CONFIG, ...JSON.parse(content) };
}
} catch {
// Ignore errors, use defaults
}
return { ...DEFAULT_SM_CONFIG };
}
function saveSMConfig(config: OpencodeSMConfig): void {
const configPath = getConfigPath();
const dir = path.dirname(configPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
}
class OpencodeSM {
private config: OpencodeConfig;
private stackmemoryPath: string;
private smConfig: OpencodeSMConfig;
constructor() {
this.smConfig = loadSMConfig();
this.config = {
instanceId: this.generateInstanceId(),
useWorktree: this.smConfig.defaultWorktree,
contextEnabled: true,
tracingEnabled: this.smConfig.defaultTracing,
verboseTracing: false,
sessionStartTime: Date.now(),
};
this.stackmemoryPath = this.findStackMemory();
}
private generateInstanceId(): string {
return uuidv4().substring(0, 8);
}
private findStackMemory(): string {
const possiblePaths = [
path.join(os.homedir(), '.stackmemory', 'bin', 'stackmemory'),
'/usr/local/bin/stackmemory',
'/opt/homebrew/bin/stackmemory',
'stackmemory',
];
for (const smPath of possiblePaths) {
try {
execFileSync('which', [smPath], { stdio: 'ignore' });
return smPath;
} catch {
// Continue searching
}
}
return 'stackmemory';
}
private isGitRepo(): boolean {
try {
execSync('git rev-parse --git-dir', { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
private getCurrentBranch(): string {
try {
return execSync('git rev-parse --abbrev-ref HEAD', {
encoding: 'utf8',
}).trim();
} catch {
return 'main';
}
}
private hasUncommittedChanges(): boolean {
try {
const status = execSync('git status --porcelain', { encoding: 'utf8' });
return status.length > 0;
} catch {
return false;
}
}
private resolveOpencodeBin(): string | null {
if (this.config.opencodeBin && this.config.opencodeBin.trim()) {
return this.config.opencodeBin.trim();
}
const envBin = process.env['OPENCODE_BIN'];
if (envBin && envBin.trim()) return envBin.trim();
// Check common OpenCode locations
const possiblePaths = [
path.join(os.homedir(), '.opencode', 'bin', 'opencode'),
'/usr/local/bin/opencode',
'/opt/homebrew/bin/opencode',
];
for (const binPath of possiblePaths) {
if (fs.existsSync(binPath)) {
return binPath;
}
}
// Try PATH
try {
execSync('which opencode', { stdio: 'ignore' });
return 'opencode';
} catch {
// Not found
}
return null;
}
private setupWorktree(): string | null {
if (!this.config.useWorktree || !this.isGitRepo()) {
return null;
}
console.log(chalk.blue('Setting up isolated worktree...'));
const timestamp = new Date()
.toISOString()
.replace(/[:.]/g, '-')
.substring(0, 19);
const branch =
this.config.branch ||
`opencode-${this.config.task || 'work'}-${timestamp}-${this.config.instanceId}`;
const repoName = path.basename(process.cwd());
const worktreePath = path.join(
path.dirname(process.cwd()),
`${repoName}--${branch}`
);
try {
const cmd = `git worktree add -b "${branch}" "${worktreePath}"`;
execSync(cmd, { stdio: 'inherit' });
console.log(chalk.green(`Worktree created: ${worktreePath}`));
console.log(chalk.gray(`Branch: ${branch}`));
const configPath = path.join(worktreePath, '.opencode-instance.json');
const configData = {
instanceId: this.config.instanceId,
worktreePath,
branch,
task: this.config.task,
created: new Date().toISOString(),
parentRepo: process.cwd(),
};
fs.writeFileSync(configPath, JSON.stringify(configData, null, 2));
// Copy environment files
const envFiles = ['.env', '.env.local', '.mise.toml', '.tool-versions'];
for (const file of envFiles) {
const srcPath = path.join(process.cwd(), file);
if (fs.existsSync(srcPath)) {
fs.copyFileSync(srcPath, path.join(worktreePath, file));
}
}
return worktreePath;
} catch (err: unknown) {
console.error(chalk.red('Failed to create worktree:'), err);
return null;
}
}
private saveContext(
message: string,
metadata: Record<string, unknown> = {}
): void {
if (!this.config.contextEnabled) return;
try {
const contextData = {
message,
metadata: {
...metadata,
instanceId: this.config.instanceId,
worktree: this.config.worktreePath,
timestamp: new Date().toISOString(),
tool: 'opencode',
},
};
const cmd = `${this.stackmemoryPath} context save --json '${JSON.stringify(contextData)}'`;
execSync(cmd, { stdio: 'ignore' });
} catch {
// Silently fail
}
}
private loadContext(): void {
if (!this.config.contextEnabled) return;
try {
console.log(chalk.blue('Loading previous context...'));
const cmd = `${this.stackmemoryPath} context show`;
const output = execSync(cmd, {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'pipe'],
});
const lines = output
.trim()
.split('\n')
.filter((l) => l.trim());
if (lines.length > 3) {
console.log(chalk.gray('Context stack loaded'));
}
} catch {
// Silently continue
}
}
private detectMultipleInstances(): boolean {
try {
const lockDir = path.join(process.cwd(), '.opencode-worktree-locks');
if (!fs.existsSync(lockDir)) return false;
const locks = fs.readdirSync(lockDir).filter((f) => f.endsWith('.lock'));
const activeLocks = locks.filter((lockFile) => {
const lockPath = path.join(lockDir, lockFile);
const lockData = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
const lockAge = Date.now() - new Date(lockData.created).getTime();
return lockAge < 24 * 60 * 60 * 1000;
});
return activeLocks.length > 0;
} catch {
return false;
}
}
private suggestWorktreeMode(): void {
if (this.hasUncommittedChanges()) {
console.log(chalk.yellow('Uncommitted changes detected'));
console.log(chalk.gray('Consider using --worktree to work in isolation'));
}
if (this.detectMultipleInstances()) {
console.log(chalk.yellow('Other OpenCode instances detected'));
console.log(
chalk.gray('Using --worktree is recommended to avoid conflicts')
);
}
}
public async run(args: string[]): Promise<void> {
const opencodeArgs: string[] = [];
let i = 0;
while (i < args.length) {
const arg = args[i];
switch (arg) {
case '--worktree':
case '-w':
this.config.useWorktree = true;
break;
case '--no-worktree':
case '-W':
this.config.useWorktree = false;
break;
case '--no-context':
this.config.contextEnabled = false;
break;
case '--no-trace':
this.config.tracingEnabled = false;
break;
case '--verbose-trace':
this.config.verboseTracing = true;
break;
case '--branch':
case '-b':
i++;
this.config.branch = args[i];
break;
case '--task':
case '-t':
i++;
this.config.task = args[i];
break;
case '--opencode-bin':
i++;
this.config.opencodeBin = args[i];
process.env['OPENCODE_BIN'] = this.config.opencodeBin;
break;
case '--auto':
case '-a':
if (this.isGitRepo()) {
this.config.useWorktree =
this.hasUncommittedChanges() || this.detectMultipleInstances();
}
break;
default:
opencodeArgs.push(arg);
}
i++;
}
// Initialize tracing if enabled
if (this.config.tracingEnabled) {
process.env['DEBUG_TRACE'] = 'true';
process.env['STACKMEMORY_DEBUG'] = 'true';
process.env['TRACE_OUTPUT'] = 'file';
process.env['TRACE_MASK_SENSITIVE'] = 'true';
if (this.config.verboseTracing) {
process.env['TRACE_VERBOSITY'] = 'full';
process.env['TRACE_PARAMS'] = 'true';
process.env['TRACE_RESULTS'] = 'true';
process.env['TRACE_MEMORY'] = 'true';
} else {
process.env['TRACE_VERBOSITY'] = 'summary';
process.env['TRACE_PARAMS'] = 'true';
process.env['TRACE_RESULTS'] = 'false';
}
initializeTracing();
trace.command(
'opencode-sm',
{
instanceId: this.config.instanceId,
worktree: this.config.useWorktree,
task: this.config.task,
},
async () => {}
);
}
// Show header
console.log(chalk.magenta('OpenCode + StackMemory'));
console.log();
if (this.isGitRepo()) {
const branch = this.getCurrentBranch();
console.log(chalk.gray(`Branch: ${branch}`));
if (!this.config.useWorktree) {
this.suggestWorktreeMode();
}
}
// Setup worktree if requested
if (this.config.useWorktree) {
const worktreePath = this.setupWorktree();
if (worktreePath) {
this.config.worktreePath = worktreePath;
process.chdir(worktreePath);
this.saveContext('Created worktree for OpenCode instance', {
action: 'worktree_created',
path: worktreePath,
branch: this.config.branch,
});
}
}
this.loadContext();
// Setup environment
process.env['OPENCODE_INSTANCE_ID'] = this.config.instanceId;
if (this.config.worktreePath) {
process.env['OPENCODE_WORKTREE_PATH'] = this.config.worktreePath;
}
console.log(chalk.gray(`Instance: ${this.config.instanceId}`));
console.log(chalk.gray(`Working in: ${process.cwd()}`));
if (this.config.tracingEnabled) {
console.log(
chalk.gray(`Tracing enabled (logs to ~/.stackmemory/traces/)`)
);
}
console.log();
console.log(chalk.gray('Starting OpenCode...'));
console.log(chalk.gray('-'.repeat(40)));
const opencodeBin = this.resolveOpencodeBin();
if (!opencodeBin) {
console.error(chalk.red('OpenCode CLI not found.'));
console.log(
chalk.gray(
'Install OpenCode or set an override:\n' +
' export OPENCODE_BIN=/path/to/opencode\n' +
' opencode-sm --help'
)
);
process.exit(1);
return;
}
const opencode = spawn(opencodeBin, opencodeArgs, {
stdio: 'inherit',
env: process.env,
});
opencode.on('error', (err: NodeJS.ErrnoException) => {
console.error(chalk.red('Failed to launch OpenCode CLI.'));
if (err.code === 'ENOENT') {
console.error(
chalk.gray('Not found. Set OPENCODE_BIN or install opencode.')
);
} else {
console.error(chalk.gray(`${err.message}`));
}
process.exit(1);
});
opencode.on('exit', async (code) => {
this.saveContext('OpenCode session ended', {
action: 'session_end',
exitCode: code,
});
if (this.config.tracingEnabled) {
const summary = trace.getExecutionSummary();
console.log();
console.log(chalk.gray('-'.repeat(40)));
console.log(chalk.magenta('Trace Summary:'));
console.log(chalk.gray(summary));
}
if (this.config.worktreePath) {
console.log();
console.log(chalk.gray('-'.repeat(40)));
console.log(chalk.magenta('Session ended in worktree:'));
console.log(chalk.gray(` ${this.config.worktreePath}`));
}
process.exit(code || 0);
});
process.on('SIGINT', () => {
this.saveContext('OpenCode session interrupted', {
action: 'session_interrupt',
});
opencode.kill('SIGINT');
});
process.on('SIGTERM', () => {
this.saveContext('OpenCode session terminated', {
action: 'session_terminate',
});
opencode.kill('SIGTERM');
});
}
}
// CLI interface
program
.name('opencode-sm')
.description('OpenCode with StackMemory context and worktree isolation')
.version('1.0.0');
// Config subcommand
const configCmd = program
.command('config')
.description('Manage opencode-sm defaults');
configCmd
.command('show')
.description('Show current default settings')
.action(() => {
const config = loadSMConfig();
console.log(chalk.magenta('opencode-sm defaults:'));
console.log(
` defaultWorktree: ${config.defaultWorktree ? chalk.green('true') : chalk.gray('false')}`
);
console.log(
` defaultTracing: ${config.defaultTracing ? chalk.green('true') : chalk.gray('false')}`
);
console.log(chalk.gray(`\nConfig: ${getConfigPath()}`));
});
configCmd
.command('set <key> <value>')
.description('Set a default (e.g., set worktree true)')
.action((key: string, value: string) => {
const config = loadSMConfig();
const boolValue = value === 'true' || value === '1' || value === 'on';
const keyMap: Record<string, keyof OpencodeSMConfig> = {
worktree: 'defaultWorktree',
tracing: 'defaultTracing',
};
const configKey = keyMap[key];
if (!configKey) {
console.log(chalk.red(`Unknown key: ${key}`));
console.log(chalk.gray('Valid keys: worktree, tracing'));
process.exit(1);
}
config[configKey] = boolValue;
saveSMConfig(config);
console.log(chalk.green(`Set ${key} = ${boolValue}`));
});
configCmd
.command('worktree-on')
.description('Enable worktree mode by default')
.action(() => {
const config = loadSMConfig();
config.defaultWorktree = true;
saveSMConfig(config);
console.log(chalk.green('Worktree mode enabled by default'));
});
configCmd
.command('worktree-off')
.description('Disable worktree mode by default')
.action(() => {
const config = loadSMConfig();
config.defaultWorktree = false;
saveSMConfig(config);
console.log(chalk.green('Worktree mode disabled by default'));
});
// Main command
program
.option('-w, --worktree', 'Create isolated worktree for this instance')
.option('-W, --no-worktree', 'Disable worktree (override default)')
.option('-a, --auto', 'Automatically detect and apply best settings')
.option('-b, --branch <name>', 'Specify branch name for worktree')
.option('-t, --task <desc>', 'Task description for context')
.option('--opencode-bin <path>', 'Path to opencode CLI (or use OPENCODE_BIN)')
.option('--no-context', 'Disable StackMemory context integration')
.option('--no-trace', 'Disable debug tracing (enabled by default)')
.option('--verbose-trace', 'Enable verbose debug tracing with full details')
.helpOption('-h, --help', 'Display help')
.allowUnknownOption(true)
.action(async (_options) => {
const opencodeSM = new OpencodeSM();
const args = process.argv.slice(2);
await opencodeSM.run(args);
});
program.parse(process.argv);