-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathworktree.ts
More file actions
1215 lines (1066 loc) · 36.8 KB
/
Copy pathworktree.ts
File metadata and controls
1215 lines (1066 loc) · 36.8 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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* OCX Worktree Plugin
*
* Creates isolated git worktrees for AI development sessions with
* seamless terminal spawning across macOS, Windows, and Linux.
*
* Inspired by opencode-worktree-session by Felix Anhalt
* https://github.com/felixAnhalt/opencode-worktree-session
* License: MIT
*
* Rewritten for OCX with production-proven patterns.
*/
import type { Database } from "bun:sqlite"
import { constants as fsConstants } from "node:fs"
import { access, copyFile, cp, lstat, mkdir, realpath, rm, stat, symlink } from "node:fs/promises"
import * as os from "node:os"
import * as path from "node:path"
import { type Plugin, tool } from "@opencode-ai/plugin"
import type { Event } from "@opencode-ai/sdk"
import type { OpencodeClient } from "./kdco-primitives/types"
/** Logger interface for structured logging */
interface Logger {
debug: (msg: string) => void
info: (msg: string) => void
warn: (msg: string) => void
error: (msg: string) => void
}
import { parse as parseJsonc } from "jsonc-parser"
import { z } from "zod"
import { getProjectId } from "./kdco-primitives/get-project-id"
import {
type ActiveLaunchContext,
buildSessionLaunchArgv,
parseActiveLaunchContext,
serializePersistedLaunchMetadata,
toPersistedLaunchMetadata,
} from "./worktree/launch-context"
import {
addSession,
clearPendingDelete,
getPendingDelete,
getSession,
getWorktreePath,
initStateDb,
removeSession,
setPendingDelete,
} from "./worktree/state"
import { openTerminal, type TerminalResult } from "./worktree/terminal"
/** Maximum retries for database initialization */
const DB_MAX_RETRIES = 3
/** Delay between retry attempts in milliseconds */
const DB_RETRY_DELAY_MS = 100
/** Maximum depth to traverse session parent chain */
const MAX_SESSION_CHAIN_DEPTH = 10
// =============================================================================
// TYPES & SCHEMAS
// =============================================================================
/** Result type for fallible operations */
interface OkResult<T> {
readonly ok: true
readonly value: T
}
interface ErrResult<E> {
readonly ok: false
readonly error: E
}
type Result<T, E> = OkResult<T> | ErrResult<E>
const Result = {
ok: <T>(value: T): OkResult<T> => ({ ok: true, value }),
err: <E>(error: E): ErrResult<E> => ({ ok: false, error }),
}
/**
* Git branch name validation - blocks invalid refs and shell metacharacters
* Characters blocked: control chars (0x00-0x1f, 0x7f), ~^:?*[]\\, and shell metacharacters
*/
function isValidBranchName(name: string): boolean {
// Check for control characters
for (let i = 0; i < name.length; i++) {
const code = name.charCodeAt(i)
if (code <= 0x1f || code === 0x7f) return false
}
// Check for invalid git ref characters and shell metacharacters
if (/[~^:?*[\]\\;&|`$()]/.test(name)) return false
return true
}
const branchNameSchema = z
.string()
.min(1, "Branch name cannot be empty")
.refine((name) => !name.startsWith("-"), {
message: "Branch name cannot start with '-' (prevents option injection)",
})
.refine((name) => !name.startsWith("/") && !name.endsWith("/"), {
message: "Branch name cannot start or end with '/'",
})
.refine((name) => !name.includes("//"), {
message: "Branch name cannot contain '//'",
})
.refine((name) => !name.includes("@{"), {
message: "Branch name cannot contain '@{' (git reflog syntax)",
})
.refine((name) => !name.includes(".."), {
message: "Branch name cannot contain '..'",
})
// biome-ignore lint/suspicious/noControlCharactersInRegex: Control character detection is intentional for security
.refine((name) => !/[\x00-\x1f\x7f ~^:?*[\]\\]/.test(name), {
message: "Branch name contains invalid characters",
})
.max(255, "Branch name too long")
.refine((name) => isValidBranchName(name), "Contains invalid git ref characters")
.refine((name) => !name.startsWith(".") && !name.endsWith("."), "Cannot start or end with dot")
.refine((name) => !name.endsWith(".lock"), "Cannot end with .lock")
/**
* Worktree plugin configuration schema.
* Config file: .opencode/worktree.jsonc
*/
const worktreeConfigSchema = z.object({
/** Custom base path for worktree storage. Supports ~ for home directory. */
worktreePath: z.string().optional(),
sync: z
.object({
/** Files to copy from main worktree (relative paths only) */
copyFiles: z.array(z.string()).default([]),
/** Directories to symlink from main worktree (saves disk space) */
symlinkDirs: z.array(z.string()).default([]),
/** Patterns to exclude from copying (reserved for future use) */
exclude: z.array(z.string()).default([]),
})
.default(() => ({ copyFiles: [], symlinkDirs: [], exclude: [] })),
hooks: z
.object({
/** Commands to run after worktree creation */
postCreate: z.array(z.string()).default([]),
/** Commands to run before worktree deletion */
preDelete: z.array(z.string()).default([]),
})
.default(() => ({ postCreate: [], preDelete: [] })),
})
type WorktreeConfig = z.infer<typeof worktreeConfigSchema>
// =============================================================================
// ERROR TYPES
// =============================================================================
class WorktreeError extends Error {
constructor(
message: string,
public readonly operation: string,
public readonly cause?: unknown,
) {
super(`${operation}: ${message}`)
this.name = "WorktreeError"
}
}
type ResolveExecutable = (command: string) => string | null | undefined
type ValidateProfileAvailability = (
ocxBin: string,
profile: string,
) => Promise<Result<void, string>>
interface LaunchExecutableValidationOptions {
resolveExecutable?: ResolveExecutable
pathExists?: (absolutePath: string) => Promise<boolean>
}
function isPathLikeCommand(command: string): boolean {
return command.includes("/") || command.includes("\\")
}
function resolveStableLaunchBinaryPath(
ocxBin: string,
baseDirectory: string,
resolveExecutable: ResolveExecutable,
): Result<string, string> {
if (isPathLikeCommand(ocxBin)) {
const resolvedPath = path.isAbsolute(ocxBin) ? ocxBin : path.resolve(baseDirectory, ocxBin)
return Result.ok(resolvedPath)
}
const resolvedFromPath = resolveExecutable(ocxBin)
if (!resolvedFromPath) {
return Result.err(`Configured OCX binary "${ocxBin}" is not available in PATH.`)
}
const resolvedPath = path.isAbsolute(resolvedFromPath)
? resolvedFromPath
: path.resolve(baseDirectory, resolvedFromPath)
return Result.ok(resolvedPath)
}
async function pathPointsToLaunchableBinary(absolutePath: string): Promise<boolean> {
try {
const stats = await stat(absolutePath)
if (stats.isDirectory()) {
return false
}
await access(absolutePath, fsConstants.X_OK)
return true
} catch {
return false
}
}
async function ensureLaunchContextExecutable(
launchContext: ActiveLaunchContext,
baseDirectory: string,
options: LaunchExecutableValidationOptions = {},
): Promise<ActiveLaunchContext> {
if (launchContext.mode === "plain") {
return launchContext
}
const { ocxBin, profile } = launchContext
const resolveExecutable = options.resolveExecutable ?? ((command: string) => Bun.which(command))
const pathExists = options.pathExists ?? pathPointsToLaunchableBinary
const resolvedPathResult = resolveStableLaunchBinaryPath(ocxBin, baseDirectory, resolveExecutable)
if (!resolvedPathResult.ok) {
throw new WorktreeError(
`${resolvedPathResult.error} Repair the parent OCX profile (${profile}) and recreate this worktree session.`,
"launch",
)
}
const resolvedPath = resolvedPathResult.value
const isLaunchable = await pathExists(resolvedPath)
if (!isLaunchable) {
throw new WorktreeError(
`Configured OCX binary "${ocxBin}" resolved to "${resolvedPath}" but is missing or stale. Repair the parent OCX profile (${profile}) and recreate this worktree session.`,
"launch",
)
}
return {
mode: "ocx",
ocxBin: resolvedPath,
profile,
}
}
async function validateOcxProfileAvailability(
ocxBin: string,
profile: string,
): Promise<Result<void, string>> {
try {
const proc = Bun.spawn([ocxBin, "profile", "show", profile, "--global", "--json"], {
stdout: "pipe",
stderr: "pipe",
})
const [exitCode, stdout, stderr] = await Promise.all([
proc.exited,
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
])
if (exitCode === 0) {
return Result.ok(undefined)
}
const detail = stderr.trim() || stdout.trim() || `exit ${exitCode}`
return Result.err(detail)
} catch (error) {
return Result.err(error instanceof Error ? error.message : String(error))
}
}
async function ensureLaunchContextProfile(
launchContext: ActiveLaunchContext,
validateProfileAvailability: ValidateProfileAvailability = validateOcxProfileAvailability,
): Promise<void> {
if (launchContext.mode === "plain") {
return
}
const validationResult = await validateProfileAvailability(
launchContext.ocxBin,
launchContext.profile,
)
if (validationResult.ok) {
return
}
throw new WorktreeError(
`Configured OCX profile "${launchContext.profile}" is missing or stale. ${validationResult.error} Repair the parent OCX profile and recreate this worktree session.`,
"launch",
)
}
// =============================================================================
// SESSION FORKING HELPERS
// =============================================================================
/**
* Check if a path exists, distinguishing ENOENT from other errors (Law 4)
*/
async function pathExists(filePath: string): Promise<boolean> {
try {
await access(filePath)
return true
} catch (e: unknown) {
if (e && typeof e === "object" && "code" in e && e.code === "ENOENT") {
return false
}
throw e // Re-throw permission errors, etc.
}
}
/**
* Copy file if source exists. Returns true if copied, false if source doesn't exist.
* Throws on copy failure (Law 4: Fail Loud)
*/
async function copyIfExists(src: string, dest: string): Promise<boolean> {
if (!(await pathExists(src))) return false
await copyFile(src, dest)
return true
}
/**
* Copy directory contents if source exists.
* @param src - Source directory path
* @param dest - Destination directory path
* @returns true if copy was performed, false if source doesn't exist
*/
async function copyDirIfExists(src: string, dest: string): Promise<boolean> {
if (!(await pathExists(src))) return false
await cp(src, dest, { recursive: true })
return true
}
interface ForkResult {
forkedSession: { id: string }
rootSessionId: string
planCopied: boolean
delegationsCopied: boolean
}
interface FinalizeWorktreeLaunchOptions {
database: Database
worktreePath: string
launchArgv: string[]
branch: string
forkedSessionId: string
sessionRecord: {
id: string
branch: string
path: string
createdAt: string
launchMode: "plain" | "ocx"
profile: string | null
ocxBin: string | null
}
log: Logger
openTerminalFn?: (cwd: string, argv?: string[], windowName?: string) => Promise<TerminalResult>
addSessionFn?: typeof addSession
deleteForkedSessionFn?: (sessionId: string) => Promise<void>
}
async function finalizeWorktreeLaunch(
options: FinalizeWorktreeLaunchOptions,
): Promise<TerminalResult> {
const openTerminalFn = options.openTerminalFn ?? openTerminal
const addSessionFn = options.addSessionFn ?? addSession
const deleteForkedSessionFn =
options.deleteForkedSessionFn ??
(async (_sessionId: string) => {
// Default no-op for tests without cleanup side effects.
})
const terminalResult = await openTerminalFn(
options.worktreePath,
options.launchArgv,
options.branch,
)
if (!terminalResult.success) {
await deleteForkedSessionFn(options.forkedSessionId).catch((cleanupError) => {
options.log.warn(
`[worktree] Failed to clean up forked session ${options.forkedSessionId} after launch failure: ${cleanupError}`,
)
})
return terminalResult
}
addSessionFn(options.database, options.sessionRecord)
return terminalResult
}
/**
* Fork a session and copy associated plans/delegations.
* Cleans up forked session on failure (atomic operation).
*/
async function forkWithContext(
client: OpencodeClient,
sessionId: string,
projectId: string,
getRootSessionIdFn: (sessionId: string) => Promise<string>,
): Promise<ForkResult> {
// Guard clauses (Law 1)
if (!client) throw new WorktreeError("client is required", "forkWithContext")
if (!sessionId) throw new WorktreeError("sessionId is required", "forkWithContext")
if (!projectId) throw new WorktreeError("projectId is required", "forkWithContext")
// Get root session ID with error wrapping
let rootSessionId: string
try {
rootSessionId = await getRootSessionIdFn(sessionId)
} catch (e) {
throw new WorktreeError("Failed to get root session ID", "forkWithContext", e)
}
// Fork session
const forkedSessionResponse = await client.session.fork({
path: { id: sessionId },
body: {},
})
const forkedSession = forkedSessionResponse.data
if (!forkedSession?.id) {
throw new WorktreeError("Failed to fork session: no session data returned", "forkWithContext")
}
// Copy data with cleanup on failure
let planCopied = false
let delegationsCopied = false
try {
const workspaceBase = path.join(os.homedir(), ".local", "share", "opencode", "workspace")
const delegationsBase = path.join(os.homedir(), ".local", "share", "opencode", "delegations")
const destWorkspaceDir = path.join(workspaceBase, projectId, forkedSession.id)
const destDelegationsDir = path.join(delegationsBase, projectId, forkedSession.id)
await mkdir(destWorkspaceDir, { recursive: true })
await mkdir(destDelegationsDir, { recursive: true })
// Copy plan
const srcPlan = path.join(workspaceBase, projectId, rootSessionId, "plan.md")
const destPlan = path.join(destWorkspaceDir, "plan.md")
planCopied = await copyIfExists(srcPlan, destPlan)
// Copy delegations
const srcDelegations = path.join(delegationsBase, projectId, rootSessionId)
delegationsCopied = await copyDirIfExists(srcDelegations, destDelegationsDir)
} catch (error) {
client.app
.log({
body: {
service: "worktree",
level: "error",
message: `forkWithContext: Copy failed, cleaning up forked session: ${error}`,
},
})
.catch(() => {})
// Clean up orphaned directories
const workspaceBase = path.join(os.homedir(), ".local", "share", "opencode", "workspace")
const delegationsBase = path.join(os.homedir(), ".local", "share", "opencode", "delegations")
const destWorkspaceDir = path.join(workspaceBase, projectId, forkedSession.id)
const destDelegationsDir = path.join(delegationsBase, projectId, forkedSession.id)
await rm(destWorkspaceDir, { recursive: true, force: true }).catch((e) => {
client.app
.log({
body: {
service: "worktree",
level: "error",
message: `forkWithContext: Failed to clean up workspace dir ${destWorkspaceDir}: ${e}`,
},
})
.catch(() => {})
})
await rm(destDelegationsDir, { recursive: true, force: true }).catch((e) => {
client.app
.log({
body: {
service: "worktree",
level: "error",
message: `forkWithContext: Failed to clean up delegations dir ${destDelegationsDir}: ${e}`,
},
})
.catch(() => {})
})
await client.session.delete({ path: { id: forkedSession.id } }).catch((e) => {
client.app
.log({
body: {
service: "worktree",
level: "error",
message: `forkWithContext: Failed to clean up forked session ${forkedSession.id}: ${e}`,
},
})
.catch(() => {})
})
throw new WorktreeError(
`Failed to copy session data: ${error instanceof Error ? error.message : String(error)}`,
"forkWithContext",
error,
)
}
return { forkedSession, rootSessionId, planCopied, delegationsCopied }
}
// =============================================================================
// MODULE-LEVEL STATE
// =============================================================================
/** Database instance - initialized once per plugin lifecycle */
let db: Database | null = null
/** Project root path - stored on first initialization */
let projectRoot: string | null = null
/** Flag to prevent duplicate cleanup handler registration */
let cleanupRegistered = false
/**
* Register process cleanup handlers for graceful database shutdown.
* Ensures WAL checkpoint and proper close on process termination.
*
* NOTE: process.once() is an EventEmitter method that never throws.
* The boolean guard is defense-in-depth for idempotency, not error recovery.
*
* @param database - The database instance to clean up
*/
function registerCleanupHandlers(database: Database): void {
if (cleanupRegistered) return // Early exit guard
cleanupRegistered = true
const cleanup = () => {
try {
database.exec("PRAGMA wal_checkpoint(TRUNCATE)")
database.close()
} catch {
// Best effort cleanup - process is exiting anyway
}
}
process.once("SIGTERM", cleanup)
process.once("SIGINT", cleanup)
process.once("beforeExit", cleanup)
}
/**
* Get the database instance, initializing if needed.
* Includes retry logic for transient initialization failures.
*
* @returns Database instance
* @throws {Error} if initialization fails after all retries
*/
async function getDb(log: Logger): Promise<Database> {
if (db) return db
if (!projectRoot) {
throw new Error("Database not initialized: projectRoot not set. Call initDb() first.")
}
let lastError: Error | null = null
for (let attempt = 1; attempt <= DB_MAX_RETRIES; attempt++) {
try {
db = await initStateDb(projectRoot)
registerCleanupHandlers(db)
return db
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error))
log.warn(`Database init attempt ${attempt}/${DB_MAX_RETRIES} failed: ${lastError.message}`)
if (attempt < DB_MAX_RETRIES) {
Bun.sleepSync(DB_RETRY_DELAY_MS)
}
}
}
throw new Error(
`Failed to initialize database after ${DB_MAX_RETRIES} attempts: ${lastError?.message}`,
)
}
/**
* Initialize the database with the project root path.
* Must be called once before any getDb() calls.
*/
async function initDb(root: string, log: Logger): Promise<Database> {
projectRoot = root
return getDb(log)
}
// =============================================================================
// GIT MODULE
// =============================================================================
/**
* Execute a git command safely using Bun.spawn with explicit array.
* Avoids shell interpolation entirely by passing args as array.
*/
async function git(args: string[], cwd: string): Promise<Result<string, string>> {
try {
const proc = Bun.spawn(["git", ...args], {
cwd,
stdout: "pipe",
stderr: "pipe",
})
const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
])
if (exitCode !== 0) {
return Result.err(stderr.trim() || `git ${args[0]} failed`)
}
return Result.ok(stdout.trim())
} catch (error) {
return Result.err(error instanceof Error ? error.message : String(error))
}
}
async function branchExists(cwd: string, branch: string): Promise<boolean> {
const result = await git(["rev-parse", "--verify", branch], cwd)
return result.ok
}
async function createWorktree(
repoRoot: string,
branch: string,
baseBranch?: string,
basePath?: string,
): Promise<Result<string, string>> {
const worktreePath = await getWorktreePath(repoRoot, branch, basePath)
// Ensure parent directory exists
await mkdir(path.dirname(worktreePath), { recursive: true })
const exists = await branchExists(repoRoot, branch)
if (exists) {
// Checkout existing branch into worktree
const result = await git(["worktree", "add", worktreePath, branch], repoRoot)
return result.ok ? Result.ok(worktreePath) : result
} else {
// Create new branch from base
const base = baseBranch ?? "HEAD"
const result = await git(["worktree", "add", "-b", branch, worktreePath, base], repoRoot)
return result.ok ? Result.ok(worktreePath) : result
}
}
async function removeWorktree(
repoRoot: string,
worktreePath: string,
): Promise<Result<void, string>> {
const result = await git(["worktree", "remove", "--force", worktreePath], repoRoot)
return result.ok ? Result.ok(undefined) : Result.err(result.error)
}
// =============================================================================
// FILE SYNC MODULE
// =============================================================================
/**
* Validate that a path is safe (no escape from base directory)
*/
function isPathSafe(filePath: string, baseDir: string, log: Logger): boolean {
// Reject absolute paths
if (path.isAbsolute(filePath)) {
log.warn(`[worktree] Rejected absolute path: ${filePath}`)
return false
}
// Reject obvious path traversal
if (filePath.includes("..")) {
log.warn(`[worktree] Rejected path traversal: ${filePath}`)
return false
}
// Verify resolved path stays within base directory
const resolved = path.resolve(baseDir, filePath)
if (!resolved.startsWith(baseDir + path.sep) && resolved !== baseDir) {
log.warn(`[worktree] Path escapes base directory: ${filePath}`)
return false
}
return true
}
function isWithinRealRoot(rootRealPath: string, candidateRealPath: string): boolean {
const relative = path.relative(rootRealPath, candidateRealPath)
return relative === "" || (!!relative && !relative.startsWith("..") && !path.isAbsolute(relative))
}
async function resolveExistingPathWithinRoot(
rootDir: string,
relativePath: string,
log: Logger,
): Promise<string | null> {
const rootRealPath = await realpath(rootDir).catch(() => null)
if (!rootRealPath) {
log.warn(`[worktree] Failed to resolve worktree root: ${rootDir}`)
return null
}
const candidatePath = path.resolve(rootDir, relativePath)
const candidateRealPath = await realpath(candidatePath).catch(() => null)
if (!candidateRealPath) return null
if (!isWithinRealRoot(rootRealPath, candidateRealPath)) {
log.warn(`[worktree] Rejected path escaping worktree via symlink: ${relativePath}`)
return null
}
return candidateRealPath
}
async function ensureDirectoryWithinRoot(
rootDir: string,
relativeDir: string,
log: Logger,
): Promise<string | null> {
const rootRealPath = await realpath(rootDir).catch(() => null)
if (!rootRealPath) {
log.warn(`[worktree] Failed to resolve worktree root: ${rootDir}`)
return null
}
const rootPath = path.resolve(rootDir)
const targetDir = path.resolve(rootDir, relativeDir)
const resolvedRootRelative = path.relative(rootPath, targetDir)
if (
resolvedRootRelative !== "" &&
(resolvedRootRelative.startsWith("..") || path.isAbsolute(resolvedRootRelative))
) {
log.warn(`[worktree] Rejected path escaping worktree: ${relativeDir}`)
return null
}
const rootRelative = path.relative(rootDir, targetDir)
const parts = rootRelative.split(path.sep).filter(Boolean)
let cursor = rootDir
for (const part of parts) {
cursor = path.join(cursor, part)
const entry = await lstat(cursor).catch(() => null)
if (entry?.isSymbolicLink()) {
log.warn(`[worktree] Rejected symlinked target parent: ${relativeDir}`)
return null
}
if (entry && !entry.isDirectory()) {
log.warn(`[worktree] Rejected non-directory target parent: ${relativeDir}`)
return null
}
if (!entry) {
await mkdir(cursor)
}
}
const finalRealPath = await realpath(targetDir).catch(() => null)
if (!finalRealPath || !isWithinRealRoot(rootRealPath, finalRealPath)) {
log.warn(`[worktree] Rejected path escaping worktree via symlink: ${relativeDir}`)
return null
}
return targetDir
}
/**
* Copy files from source directory to target directory.
* Skips missing files silently (production pattern).
*/
async function copyFiles(
sourceDir: string,
targetDir: string,
files: string[],
log: Logger,
): Promise<void> {
for (const file of files) {
if (!isPathSafe(file, sourceDir, log)) continue
const sourcePath = await resolveExistingPathWithinRoot(sourceDir, file, log)
if (!sourcePath) continue
const targetPath = path.join(targetDir, file)
try {
const sourceFile = Bun.file(sourcePath)
if (!(await sourceFile.exists())) {
log.debug(`[worktree] Skipping missing file: ${file}`)
continue
}
// Ensure target directory exists
const targetFileDir = path.dirname(targetPath)
const targetFileRelativeDir = path.relative(targetDir, targetFileDir)
if (!(await ensureDirectoryWithinRoot(targetDir, targetFileRelativeDir, log))) continue
const existingTarget = await lstat(targetPath).catch(() => null)
if (existingTarget?.isSymbolicLink()) {
log.warn(`[worktree] Rejected symlinked target file: ${file}`)
continue
}
// Copy file
await Bun.write(targetPath, sourceFile)
log.info(`[worktree] Copied: ${file}`)
} catch (error) {
const isNotFound =
error instanceof Error &&
(error.message.includes("ENOENT") || error.message.includes("no such file"))
if (isNotFound) {
log.debug(`[worktree] Skipping missing: ${file}`)
} else {
log.warn(`[worktree] Failed to copy ${file}: ${error}`)
}
}
}
}
/**
* Create symlinks for directories from source to target.
* Uses absolute paths for symlink targets.
*/
async function symlinkDirs(
sourceDir: string,
targetDir: string,
dirs: string[],
log: Logger,
): Promise<void> {
for (const dir of dirs) {
if (!isPathSafe(dir, sourceDir, log)) continue
const sourcePath = await resolveExistingPathWithinRoot(sourceDir, dir, log)
if (!sourcePath) continue
const targetPath = path.join(targetDir, dir)
try {
// Check if source directory exists
const fileStat = await stat(sourcePath).catch(() => null)
if (!fileStat?.isDirectory()) {
log.debug(`[worktree] Skipping missing directory: ${dir}`)
continue
}
// Ensure parent directory exists
const targetParentDir = path.dirname(targetPath)
const targetParentRelativeDir = path.relative(targetDir, targetParentDir)
if (!(await ensureDirectoryWithinRoot(targetDir, targetParentRelativeDir, log))) continue
const existingTarget = await lstat(targetPath).catch(() => null)
if (existingTarget?.isSymbolicLink()) {
log.warn(`[worktree] Rejected symlinked target: ${dir}`)
continue
}
// Remove existing target if it exists (might be empty dir from git)
await rm(targetPath, { recursive: true, force: true })
// Create symlink (use absolute path for source)
await symlink(sourcePath, targetPath, "dir")
log.info(`[worktree] Symlinked: ${dir}`)
} catch (error) {
log.warn(`[worktree] Failed to symlink ${dir}: ${error}`)
}
}
}
/**
* Run hook commands in the worktree directory.
*/
async function runHooks(cwd: string, commands: string[], log: Logger): Promise<void> {
for (const command of commands) {
log.info(`[worktree] Running hook: ${command}`)
try {
// Use shell to properly handle quoted arguments and complex commands
const result = Bun.spawnSync(["bash", "-c", command], {
cwd,
stdout: "inherit",
stderr: "pipe",
})
if (result.exitCode !== 0) {
const stderr = result.stderr?.toString() || ""
log.warn(
`[worktree] Hook failed (exit ${result.exitCode}): ${command}${stderr ? `\n${stderr}` : ""}`,
)
}
} catch (error) {
log.warn(`[worktree] Hook error: ${error}`)
}
}
}
/**
* Resolve a path that may contain a leading `~` to the user's home directory.
*/
function resolveHomePath(p: string): string {
if (p === "~" || p.startsWith("~/") || p.startsWith("~\\")) {
return path.join(os.homedir(), p.slice(1))
}
return p
}
/**
* Load worktree-specific configuration from .opencode/worktree.jsonc
* Auto-creates config file with helpful defaults if it doesn't exist.
*/
async function loadWorktreeConfig(directory: string, log: Logger): Promise<WorktreeConfig> {
const configPath = path.join(directory, ".opencode", "worktree.jsonc")
try {
const file = Bun.file(configPath)
if (!(await file.exists())) {
// Auto-create config with helpful defaults and comments
const defaultConfig = `{
"$schema": "https://registry.kdco.dev/schemas/worktree.json",
// Worktree plugin configuration
// Documentation: https://github.com/kdcokenny/ocx
// Custom base path for worktree storage (supports ~)
// Default: ~/.local/share/opencode/worktree
// "worktreePath": "~/my-worktrees",
"sync": {
// Files to copy from main worktree to new worktrees
// Example: [".env", ".env.local", "dev.sqlite"]
"copyFiles": [],
// Directories to symlink (saves disk space)
// Example: ["node_modules"]
"symlinkDirs": [],
// Patterns to exclude from copying
"exclude": []
},
"hooks": {
// Commands to run after worktree creation
// Example: ["pnpm install", "docker compose up -d"]
"postCreate": [],
// Commands to run before worktree deletion
// Example: ["docker compose down"]
"preDelete": []
}
}
`
// Ensure .opencode directory exists
await mkdir(path.join(directory, ".opencode"), { recursive: true })
await Bun.write(configPath, defaultConfig)
log.info(`[worktree] Created default config: ${configPath}`)
return worktreeConfigSchema.parse({})
}
const content = await file.text()
// Use proper JSONC parser (handles comments in strings correctly)
const parsed = parseJsonc(content)
if (parsed === undefined) {
log.error(`[worktree] Invalid worktree.jsonc syntax`)
return worktreeConfigSchema.parse({})
}
const config = worktreeConfigSchema.parse(parsed)
if (config.worktreePath) {
config.worktreePath = resolveHomePath(config.worktreePath)
}
return config
} catch (error) {
log.warn(`[worktree] Failed to load config: ${error}`)
return worktreeConfigSchema.parse({})
}
}
// =============================================================================
// PLUGIN ENTRY
// =============================================================================
const WorktreePlugin: Plugin = async (ctx) => {
const { directory, client } = ctx
const log = {
debug: (msg: string) =>
client.app
.log({ body: { service: "worktree", level: "debug", message: msg } })
.catch(() => {}),
info: (msg: string) =>
client.app
.log({ body: { service: "worktree", level: "info", message: msg } })
.catch(() => {}),
warn: (msg: string) =>
client.app
.log({ body: { service: "worktree", level: "warn", message: msg } })
.catch(() => {}),
error: (msg: string) =>