@myrialabs/clopen 0.4.34 → 0.4.36
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.
- package/backend/artifacts/sync.test.ts +63 -0
- package/backend/artifacts/sync.ts +56 -3
- package/backend/auth/permissions.ts +7 -0
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +1 -0
- package/backend/database/queries/session-queries.ts +50 -11
- package/backend/database/queries/worktree-queries.ts +148 -0
- package/backend/engine/adapters/opencode/server.ts +389 -83
- package/backend/engine/adapters/opencode/stream.ts +14 -14
- package/backend/engine/hot-reload.ts +25 -10
- package/backend/files/file-watcher.test.ts +105 -0
- package/backend/files/file-watcher.ts +80 -10
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/host/metrics.test.ts +110 -0
- package/backend/host/metrics.ts +235 -0
- package/backend/{ports → host}/runner.ts +19 -10
- package/backend/index.ts +16 -4
- package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
- package/backend/ports/attribute.test.ts +3 -2
- package/backend/ports/attribute.ts +6 -45
- package/backend/ports/kill.ts +1 -1
- package/backend/ports/monitor.ts +1 -1
- package/backend/ports/processes.ts +1 -1
- package/backend/ports/scan-host.ts +77 -8
- package/backend/ports/scan.test.ts +1 -1
- package/backend/ports/scan.ts +1 -1
- package/backend/ports/ssh-lineage.ts +1 -1
- package/backend/preview/browser/browser-pool.ts +81 -0
- package/backend/preview/browser/browser-preview-service.ts +142 -32
- package/backend/preview/browser/browser-tab-manager.ts +350 -113
- package/backend/preview/browser/browser-video-capture.ts +84 -31
- package/backend/preview/browser/types.ts +9 -0
- package/backend/projects/project-cleanup.integration.test.ts +1 -1
- package/backend/projects/project-cleanup.ts +7 -1
- package/backend/projects/shell-ownership.ts +65 -0
- package/backend/snapshot/snapshot-service.ts +6 -2
- package/backend/terminal/ptykit.ts +35 -6
- package/backend/utils/ws.ts +21 -1
- package/backend/worktrees/clone.ts +222 -0
- package/backend/worktrees/index.ts +29 -0
- package/backend/worktrees/merge.test.ts +93 -0
- package/backend/worktrees/merge.ts +232 -0
- package/backend/worktrees/paths.test.ts +60 -0
- package/backend/worktrees/paths.ts +60 -0
- package/backend/worktrees/resolve.ts +67 -0
- package/backend/worktrees/service.ts +315 -0
- package/backend/worktrees/tree.ts +59 -0
- package/backend/ws/access.ts +18 -0
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/chat/stream.ts +9 -2
- package/backend/ws/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- package/backend/ws/files/panel-state-scope.test.ts +102 -0
- package/backend/ws/files/path-access.test.ts +93 -1
- package/backend/ws/files/path-access.ts +54 -5
- package/backend/ws/files/read.ts +15 -10
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/state.ts +70 -8
- package/backend/ws/files/watch.ts +16 -14
- package/backend/ws/git/branch-name.ts +3 -3
- package/backend/ws/git/branch.ts +15 -15
- package/backend/ws/git/commit-message.ts +3 -3
- package/backend/ws/git/commit.ts +17 -17
- package/backend/ws/git/conflict.ts +10 -10
- package/backend/ws/git/diff.ts +9 -9
- package/backend/ws/git/ignored.ts +9 -9
- package/backend/ws/git/log.ts +6 -4
- package/backend/ws/git/remote.ts +43 -43
- package/backend/ws/git/staging.ts +16 -16
- package/backend/ws/git/status.ts +47 -37
- package/backend/ws/index.ts +6 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- package/backend/ws/preview/access.ts +11 -3
- package/backend/ws/projects/index.ts +5 -1
- package/backend/ws/projects/info.test.ts +54 -0
- package/backend/ws/projects/info.ts +398 -0
- package/backend/ws/sessions/crud.ts +21 -6
- package/backend/ws/snapshot/restore.ts +11 -14
- package/backend/ws/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +70 -96
- package/backend/ws/worktrees/crud.ts +187 -0
- package/backend/ws/worktrees/index.ts +33 -0
- package/backend/ws/worktrees/transfer.ts +88 -0
- package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
- package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
- package/dist/assets/main-9G7IpQpK.css +1 -0
- package/dist/assets/main-BofFsH8E.js +1085 -0
- package/dist/index.html +2 -2
- package/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/database/schema.ts +26 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/port.ts +47 -9
- package/shared/utils/logger.ts +3 -0
- package/shared/utils/workspace-scope.test.ts +80 -0
- package/shared/utils/workspace-scope.ts +57 -0
- package/shared/utils/ws-client.ts +92 -17
- package/shared/utils/ws-server.ts +83 -16
- package/dist/assets/main-CYCMEbXB.css +0 -1
- package/dist/assets/main-ZCojSzvW.js +0 -1060
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Materialising a worktree from the main tree.
|
|
3
|
+
*
|
|
4
|
+
* Preferred path is a copy-on-write clone (`COPYFILE_FICLONE`): on APFS, btrfs
|
|
5
|
+
* and reflink-capable XFS this is near-instant and costs no extra disk until a
|
|
6
|
+
* file is written, so the worktree can carry everything the project needs to
|
|
7
|
+
* actually run — `.git`, `node_modules`, `.env` — not just tracked files.
|
|
8
|
+
*
|
|
9
|
+
* Where reflink is unavailable (different volume, ext4 without reflink, NTFS)
|
|
10
|
+
* a real byte copy of that much data would be unacceptable, so the clone falls
|
|
11
|
+
* back to gitignore-eligible files plus `.git` and the caller is told to run a
|
|
12
|
+
* setup command for dependencies.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from 'fs/promises';
|
|
16
|
+
import { constants as fsConstants, type Dirent } from 'fs';
|
|
17
|
+
import path from 'path';
|
|
18
|
+
import type { WorktreeCloneMode } from '$shared/types/database/schema';
|
|
19
|
+
import { debug } from '$shared/utils/logger';
|
|
20
|
+
import { getSnapshotFiles } from '../snapshot/gitignore';
|
|
21
|
+
|
|
22
|
+
/** Above this many entries a full-tree walk is refused and the lean clone is used. */
|
|
23
|
+
const MAX_FULL_CLONE_ENTRIES = 200_000;
|
|
24
|
+
|
|
25
|
+
/** Never copied — process-local state that must not be shared between trees. */
|
|
26
|
+
const NEVER_CLONE = new Set(['.DS_Store', '.clopen-reflink-probe']);
|
|
27
|
+
|
|
28
|
+
export interface CloneResult {
|
|
29
|
+
mode: WorktreeCloneMode;
|
|
30
|
+
fileCount: number;
|
|
31
|
+
/** True when ignored files (dependencies, .env) were carried over. */
|
|
32
|
+
carriedIgnoredFiles: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Probe whether `targetDir` can hold reflinks of files from `sourceDir`.
|
|
37
|
+
* Uses a real file from the project so the answer accounts for both filesystems.
|
|
38
|
+
*/
|
|
39
|
+
export async function probeReflinkSupport(sourceDir: string, targetDir: string): Promise<boolean> {
|
|
40
|
+
const probeSource = await findProbeFile(sourceDir);
|
|
41
|
+
if (!probeSource) return false;
|
|
42
|
+
|
|
43
|
+
const probeTarget = path.join(targetDir, '.clopen-reflink-probe');
|
|
44
|
+
try {
|
|
45
|
+
await fs.copyFile(probeSource, probeTarget, fsConstants.COPYFILE_FICLONE_FORCE);
|
|
46
|
+
return true;
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
} finally {
|
|
50
|
+
await fs.rm(probeTarget, { force: true }).catch(() => {});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Find a small regular file to probe with; returns null for an empty project. */
|
|
55
|
+
async function findProbeFile(dirPath: string): Promise<string | null> {
|
|
56
|
+
let entries: Dirent[];
|
|
57
|
+
try {
|
|
58
|
+
entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
59
|
+
} catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
if (!entry.isFile()) continue;
|
|
65
|
+
const full = path.join(dirPath, entry.name);
|
|
66
|
+
try {
|
|
67
|
+
const stat = await fs.stat(full);
|
|
68
|
+
if (stat.size > 0 && stat.size < 1024 * 1024) return full;
|
|
69
|
+
} catch {
|
|
70
|
+
// Unreadable — try the next one
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// No usable file at the top level; one level down is enough to decide.
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
if (!entry.isDirectory() || entry.name === '.git') continue;
|
|
77
|
+
const nested = await findProbeFile(path.join(dirPath, entry.name));
|
|
78
|
+
if (nested) return nested;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Clone `sourceRoot` into `targetRoot`.
|
|
86
|
+
* `targetRoot` must already exist and be empty.
|
|
87
|
+
*/
|
|
88
|
+
export async function cloneTree(sourceRoot: string, targetRoot: string): Promise<CloneResult> {
|
|
89
|
+
const canReflink = await probeReflinkSupport(sourceRoot, targetRoot);
|
|
90
|
+
|
|
91
|
+
if (canReflink) {
|
|
92
|
+
const entries = await enumerateFullTree(sourceRoot);
|
|
93
|
+
if (entries !== null) {
|
|
94
|
+
const fileCount = await copyEntries(sourceRoot, targetRoot, entries);
|
|
95
|
+
debug.log('worktree', `Cloned ${fileCount} entries via reflink: ${targetRoot}`);
|
|
96
|
+
return { mode: 'reflink', fileCount, carriedIgnoredFiles: true };
|
|
97
|
+
}
|
|
98
|
+
debug.warn('worktree', `Tree too large for a full clone, falling back to tracked files: ${sourceRoot}`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const lean = await enumerateLeanTree(sourceRoot);
|
|
102
|
+
const fileCount = await copyEntries(sourceRoot, targetRoot, lean);
|
|
103
|
+
debug.log('worktree', `Cloned ${fileCount} tracked files: ${targetRoot}`);
|
|
104
|
+
return { mode: canReflink ? 'reflink' : 'copy', fileCount, carriedIgnoredFiles: false };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Relative paths of everything under a root, split by kind. */
|
|
108
|
+
interface TreeEntries {
|
|
109
|
+
dirs: string[];
|
|
110
|
+
files: string[];
|
|
111
|
+
symlinks: string[];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Walk everything under `root`, including ignored files and `.git`.
|
|
116
|
+
* Returns null when the tree exceeds `MAX_FULL_CLONE_ENTRIES`.
|
|
117
|
+
*/
|
|
118
|
+
async function enumerateFullTree(root: string): Promise<TreeEntries | null> {
|
|
119
|
+
const entries: TreeEntries = { dirs: [], files: [], symlinks: [] };
|
|
120
|
+
const queue: string[] = [''];
|
|
121
|
+
let total = 0;
|
|
122
|
+
|
|
123
|
+
while (queue.length > 0) {
|
|
124
|
+
const relativeDir = queue.pop() as string;
|
|
125
|
+
let dirEntries: Dirent[];
|
|
126
|
+
try {
|
|
127
|
+
dirEntries = await fs.readdir(path.join(root, relativeDir), { withFileTypes: true });
|
|
128
|
+
} catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
for (const entry of dirEntries) {
|
|
133
|
+
if (NEVER_CLONE.has(entry.name)) continue;
|
|
134
|
+
const relativePath = relativeDir ? path.join(relativeDir, entry.name) : entry.name;
|
|
135
|
+
|
|
136
|
+
if (++total > MAX_FULL_CLONE_ENTRIES) return null;
|
|
137
|
+
|
|
138
|
+
if (entry.isSymbolicLink()) {
|
|
139
|
+
entries.symlinks.push(relativePath);
|
|
140
|
+
} else if (entry.isDirectory()) {
|
|
141
|
+
entries.dirs.push(relativePath);
|
|
142
|
+
queue.push(relativePath);
|
|
143
|
+
} else if (entry.isFile()) {
|
|
144
|
+
entries.files.push(relativePath);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return entries;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Tracked/untracked-not-ignored files, plus `.git` so the Git panel still works. */
|
|
153
|
+
async function enumerateLeanTree(root: string): Promise<TreeEntries> {
|
|
154
|
+
const entries: TreeEntries = { dirs: [], files: [], symlinks: [] };
|
|
155
|
+
const dirs = new Set<string>();
|
|
156
|
+
|
|
157
|
+
const snapshotFiles = await getSnapshotFiles(root);
|
|
158
|
+
for (const absolute of snapshotFiles) {
|
|
159
|
+
const relativePath = path.relative(root, absolute);
|
|
160
|
+
if (!relativePath || relativePath.startsWith('..')) continue;
|
|
161
|
+
entries.files.push(relativePath);
|
|
162
|
+
collectParentDirs(relativePath, dirs);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const gitDir = await enumerateFullTree(path.join(root, '.git'));
|
|
166
|
+
if (gitDir) {
|
|
167
|
+
dirs.add('.git');
|
|
168
|
+
for (const dir of gitDir.dirs) dirs.add(path.join('.git', dir));
|
|
169
|
+
for (const file of gitDir.files) entries.files.push(path.join('.git', file));
|
|
170
|
+
for (const link of gitDir.symlinks) entries.symlinks.push(path.join('.git', link));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
entries.dirs = [...dirs].sort((a, b) => a.length - b.length);
|
|
174
|
+
return entries;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function collectParentDirs(relativePath: string, into: Set<string>): void {
|
|
178
|
+
let parent = path.dirname(relativePath);
|
|
179
|
+
while (parent && parent !== '.' && parent !== path.sep) {
|
|
180
|
+
into.add(parent);
|
|
181
|
+
parent = path.dirname(parent);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Create the directories, then clone files and re-create symlinks. */
|
|
186
|
+
async function copyEntries(sourceRoot: string, targetRoot: string, entries: TreeEntries): Promise<number> {
|
|
187
|
+
for (const relativeDir of entries.dirs) {
|
|
188
|
+
await fs.mkdir(path.join(targetRoot, relativeDir), { recursive: true });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
let copied = 0;
|
|
192
|
+
|
|
193
|
+
for (const relativeFile of entries.files) {
|
|
194
|
+
const source = path.join(sourceRoot, relativeFile);
|
|
195
|
+
const target = path.join(targetRoot, relativeFile);
|
|
196
|
+
try {
|
|
197
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
198
|
+
// FICLONE (not FORCE): reflink where the filesystem supports it,
|
|
199
|
+
// plain copy where it does not, without a second code path.
|
|
200
|
+
await fs.copyFile(source, target, fsConstants.COPYFILE_FICLONE);
|
|
201
|
+
copied++;
|
|
202
|
+
} catch (error) {
|
|
203
|
+
debug.warn('worktree', `Skipped ${relativeFile}: ${error}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Symlinks are re-created, never followed — following them would duplicate
|
|
208
|
+
// whatever they point at and break links that are relative by design.
|
|
209
|
+
for (const relativeLink of entries.symlinks) {
|
|
210
|
+
try {
|
|
211
|
+
const linkTarget = await fs.readlink(path.join(sourceRoot, relativeLink));
|
|
212
|
+
const target = path.join(targetRoot, relativeLink);
|
|
213
|
+
await fs.mkdir(path.dirname(target), { recursive: true });
|
|
214
|
+
await fs.symlink(linkTarget, target);
|
|
215
|
+
copied++;
|
|
216
|
+
} catch (error) {
|
|
217
|
+
debug.warn('worktree', `Skipped symlink ${relativeLink}: ${error}`);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return copied;
|
|
222
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worktrees — isolated copies of a project that chat sessions can run in.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export {
|
|
6
|
+
createWorktree,
|
|
7
|
+
countPendingChanges,
|
|
8
|
+
executeTransfer,
|
|
9
|
+
getWorktreeDiskUsage,
|
|
10
|
+
previewTransfer,
|
|
11
|
+
removeProjectWorktrees,
|
|
12
|
+
removeWorktree,
|
|
13
|
+
type TransferDirection,
|
|
14
|
+
type TransferPreview,
|
|
15
|
+
type TransferResult,
|
|
16
|
+
type WorktreeChange,
|
|
17
|
+
type WorktreeConflictPreview,
|
|
18
|
+
type WorktreeCreateResult
|
|
19
|
+
} from './service';
|
|
20
|
+
|
|
21
|
+
export {
|
|
22
|
+
resolveSessionPath,
|
|
23
|
+
resolveSessionRoot,
|
|
24
|
+
resolveWorktreeRoot,
|
|
25
|
+
type SessionRoot
|
|
26
|
+
} from './resolve';
|
|
27
|
+
|
|
28
|
+
export { planMerge, type MergeEntry, type MergePlan, type MergeResolution } from './merge';
|
|
29
|
+
export { getProjectWorktreesDir, getWorktreePath, getWorktreesRootDir, isPathInside, slugifyWorktreeName, uniqueWorktreeSlug } from './paths';
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { planMerge } from './merge';
|
|
3
|
+
|
|
4
|
+
const HASH_A = 'aaaa';
|
|
5
|
+
const HASH_B = 'bbbb';
|
|
6
|
+
const HASH_C = 'cccc';
|
|
7
|
+
|
|
8
|
+
describe('planMerge', () => {
|
|
9
|
+
test('carries a file the source added', () => {
|
|
10
|
+
const plan = planMerge({}, { 'new.ts': HASH_A }, {});
|
|
11
|
+
|
|
12
|
+
expect(plan.entries).toHaveLength(1);
|
|
13
|
+
expect(plan.entries[0]).toMatchObject({
|
|
14
|
+
path: 'new.ts',
|
|
15
|
+
status: 'added',
|
|
16
|
+
conflict: false
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('carries a file the source modified', () => {
|
|
21
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, { 'a.ts': HASH_A });
|
|
22
|
+
|
|
23
|
+
expect(plan.entries[0]).toMatchObject({ path: 'a.ts', status: 'modified', conflict: false });
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test('carries a file the source deleted', () => {
|
|
27
|
+
const plan = planMerge({ 'a.ts': HASH_A }, {}, { 'a.ts': HASH_A });
|
|
28
|
+
|
|
29
|
+
expect(plan.entries[0]).toMatchObject({ path: 'a.ts', status: 'deleted', conflict: false });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('ignores files the source never touched', () => {
|
|
33
|
+
// The target moved on alone — a transfer must not drag it back to the base.
|
|
34
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_A }, { 'a.ts': HASH_B });
|
|
35
|
+
|
|
36
|
+
expect(plan.entries).toHaveLength(0);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test('ignores files where both sides made the same change', () => {
|
|
40
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, { 'a.ts': HASH_B });
|
|
41
|
+
|
|
42
|
+
expect(plan.entries).toHaveLength(0);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('flags a file both sides changed differently', () => {
|
|
46
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, { 'a.ts': HASH_C });
|
|
47
|
+
|
|
48
|
+
expect(plan.conflicts).toHaveLength(1);
|
|
49
|
+
expect(plan.conflicts[0]).toMatchObject({
|
|
50
|
+
path: 'a.ts',
|
|
51
|
+
status: 'modified',
|
|
52
|
+
conflict: true,
|
|
53
|
+
baseHash: HASH_A,
|
|
54
|
+
sourceHash: HASH_B,
|
|
55
|
+
targetHash: HASH_C
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('flags a source edit against a target deletion', () => {
|
|
60
|
+
const plan = planMerge({ 'a.ts': HASH_A }, { 'a.ts': HASH_B }, {});
|
|
61
|
+
|
|
62
|
+
expect(plan.conflicts[0]).toMatchObject({
|
|
63
|
+
path: 'a.ts',
|
|
64
|
+
status: 'modified',
|
|
65
|
+
conflict: true,
|
|
66
|
+
targetHash: null
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('treats an add on both sides with different content as a conflict', () => {
|
|
71
|
+
const plan = planMerge({}, { 'a.ts': HASH_A }, { 'a.ts': HASH_B });
|
|
72
|
+
|
|
73
|
+
expect(plan.conflicts[0]).toMatchObject({ path: 'a.ts', status: 'added', conflict: true });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('leaves an empty plan when nothing diverged', () => {
|
|
77
|
+
const tree = { 'a.ts': HASH_A, 'b.ts': HASH_B };
|
|
78
|
+
const plan = planMerge(tree, { ...tree }, { ...tree });
|
|
79
|
+
|
|
80
|
+
expect(plan.entries).toHaveLength(0);
|
|
81
|
+
expect(plan.conflicts).toHaveLength(0);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test('returns entries in a stable path order', () => {
|
|
85
|
+
const plan = planMerge(
|
|
86
|
+
{},
|
|
87
|
+
{ 'z.ts': HASH_A, 'a.ts': HASH_A, 'm.ts': HASH_A },
|
|
88
|
+
{}
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
expect(plan.entries.map((entry) => entry.path)).toEqual(['a.ts', 'm.ts', 'z.ts']);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Three-way merge between a worktree and the main tree.
|
|
3
|
+
*
|
|
4
|
+
* The merge base is the tree recorded when the worktree was cloned, so a file
|
|
5
|
+
* is only in play when the source side actually changed it. When the target
|
|
6
|
+
* side changed the same file the entry is a conflict — resolvable line-by-line
|
|
7
|
+
* through `git merge-file` when both sides are text, and whole-file otherwise.
|
|
8
|
+
*
|
|
9
|
+
* `source` and `target` are direction-agnostic: applying runs worktree → main,
|
|
10
|
+
* syncing runs main → worktree, and both use this same planner.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import fs from 'fs/promises';
|
|
14
|
+
import os from 'os';
|
|
15
|
+
import path from 'path';
|
|
16
|
+
import type { TreeMap } from '../snapshot/blob-store';
|
|
17
|
+
import { execGit } from '../git/git-executor';
|
|
18
|
+
import { resolveBinary } from '../utils/cli';
|
|
19
|
+
import { debug } from '$shared/utils/logger';
|
|
20
|
+
import { readBlobText } from './tree';
|
|
21
|
+
|
|
22
|
+
export type MergeEntryStatus = 'added' | 'modified' | 'deleted';
|
|
23
|
+
|
|
24
|
+
/** What to do with one file: take the source side, keep the target, or merge both. */
|
|
25
|
+
export type MergeResolution = 'source' | 'target' | 'merge';
|
|
26
|
+
|
|
27
|
+
export interface MergeEntry {
|
|
28
|
+
path: string;
|
|
29
|
+
status: MergeEntryStatus;
|
|
30
|
+
baseHash: string | null;
|
|
31
|
+
sourceHash: string | null;
|
|
32
|
+
targetHash: string | null;
|
|
33
|
+
/** Target also moved away from the base, so taking the source would discard work. */
|
|
34
|
+
conflict: boolean;
|
|
35
|
+
/** A clean line-level merge of both sides is available. */
|
|
36
|
+
autoMergeable: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface MergePlan {
|
|
40
|
+
entries: MergeEntry[];
|
|
41
|
+
conflicts: MergeEntry[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Decide which files transfer from source to target.
|
|
46
|
+
*
|
|
47
|
+
* Pure: the three trees are all it reads, which is what makes the interesting
|
|
48
|
+
* cases (both sides identical, both sides deleted, target-only edits) testable
|
|
49
|
+
* without touching a disk.
|
|
50
|
+
*/
|
|
51
|
+
export function planMerge(base: TreeMap, source: TreeMap, target: TreeMap): MergePlan {
|
|
52
|
+
const paths = new Set<string>([
|
|
53
|
+
...Object.keys(base),
|
|
54
|
+
...Object.keys(source),
|
|
55
|
+
...Object.keys(target)
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
const entries: MergeEntry[] = [];
|
|
59
|
+
|
|
60
|
+
for (const filePath of [...paths].sort()) {
|
|
61
|
+
const baseHash = base[filePath] ?? null;
|
|
62
|
+
const sourceHash = source[filePath] ?? null;
|
|
63
|
+
const targetHash = target[filePath] ?? null;
|
|
64
|
+
|
|
65
|
+
// The source side never touched this file — nothing to carry over.
|
|
66
|
+
if (sourceHash === baseHash) continue;
|
|
67
|
+
|
|
68
|
+
// Both sides landed on the same content; the transfer is already done.
|
|
69
|
+
if (sourceHash === targetHash) continue;
|
|
70
|
+
|
|
71
|
+
const status: MergeEntryStatus =
|
|
72
|
+
sourceHash === null ? 'deleted' : baseHash === null ? 'added' : 'modified';
|
|
73
|
+
|
|
74
|
+
entries.push({
|
|
75
|
+
path: filePath,
|
|
76
|
+
status,
|
|
77
|
+
baseHash,
|
|
78
|
+
sourceHash,
|
|
79
|
+
targetHash,
|
|
80
|
+
conflict: targetHash !== baseHash,
|
|
81
|
+
autoMergeable: false
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return { entries, conflicts: entries.filter((entry) => entry.conflict) };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Mark conflicts that `git merge-file` can resolve on its own.
|
|
90
|
+
* Runs before the user is asked anything, so the dialog only shows the files
|
|
91
|
+
* that genuinely need a decision.
|
|
92
|
+
*/
|
|
93
|
+
export async function markAutoMergeable(
|
|
94
|
+
plan: MergePlan,
|
|
95
|
+
sourceRoot: string,
|
|
96
|
+
targetRoot: string
|
|
97
|
+
): Promise<MergePlan> {
|
|
98
|
+
if (!resolveBinary('git')) return plan;
|
|
99
|
+
|
|
100
|
+
for (const entry of plan.conflicts) {
|
|
101
|
+
// A deletion on either side has no text to merge.
|
|
102
|
+
if (entry.status === 'deleted' || entry.targetHash === null) continue;
|
|
103
|
+
const merged = await mergeFileContents(entry, sourceRoot, targetRoot);
|
|
104
|
+
entry.autoMergeable = merged !== null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return plan;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Three-way merge one file's text. Returns null when it cannot be merged
|
|
112
|
+
* cleanly — conflicting edits, a missing base blob, or binary content.
|
|
113
|
+
*/
|
|
114
|
+
export async function mergeFileContents(
|
|
115
|
+
entry: MergeEntry,
|
|
116
|
+
sourceRoot: string,
|
|
117
|
+
targetRoot: string
|
|
118
|
+
): Promise<string | null> {
|
|
119
|
+
if (entry.baseHash === null || entry.sourceHash === null || entry.targetHash === null) {
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const baseText = await readBlobText(entry.baseHash);
|
|
124
|
+
if (baseText === null) return null;
|
|
125
|
+
|
|
126
|
+
const sourceText = await readText(path.join(sourceRoot, entry.path));
|
|
127
|
+
const targetText = await readText(path.join(targetRoot, entry.path));
|
|
128
|
+
if (sourceText === null || targetText === null) return null;
|
|
129
|
+
|
|
130
|
+
const scratch = await fs.mkdtemp(path.join(os.tmpdir(), 'clopen-merge-'));
|
|
131
|
+
try {
|
|
132
|
+
const currentFile = path.join(scratch, 'current');
|
|
133
|
+
const baseFile = path.join(scratch, 'base');
|
|
134
|
+
const otherFile = path.join(scratch, 'other');
|
|
135
|
+
|
|
136
|
+
await Promise.all([
|
|
137
|
+
fs.writeFile(currentFile, targetText),
|
|
138
|
+
fs.writeFile(baseFile, baseText),
|
|
139
|
+
fs.writeFile(otherFile, sourceText)
|
|
140
|
+
]);
|
|
141
|
+
|
|
142
|
+
// `-p` prints the result instead of rewriting `current`; a non-zero exit
|
|
143
|
+
// is the conflict count, not a failure to run.
|
|
144
|
+
const result = await execGit(
|
|
145
|
+
['merge-file', '-p', currentFile, baseFile, otherFile],
|
|
146
|
+
scratch,
|
|
147
|
+
{ okExitCodes: [1] }
|
|
148
|
+
);
|
|
149
|
+
|
|
150
|
+
return result.exitCode === 0 ? result.stdout : null;
|
|
151
|
+
} catch (error) {
|
|
152
|
+
debug.warn('worktree', `merge-file failed for ${entry.path}: ${error}`);
|
|
153
|
+
return null;
|
|
154
|
+
} finally {
|
|
155
|
+
await fs.rm(scratch, { recursive: true, force: true }).catch(() => {});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Read a file as text, or null when it is missing or contains a NUL byte. */
|
|
160
|
+
async function readText(filePath: string): Promise<string | null> {
|
|
161
|
+
try {
|
|
162
|
+
const buffer = await fs.readFile(filePath);
|
|
163
|
+
if (buffer.includes(0)) return null;
|
|
164
|
+
return buffer.toString('utf-8');
|
|
165
|
+
} catch {
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface MergeApplyResult {
|
|
171
|
+
written: string[];
|
|
172
|
+
deleted: string[];
|
|
173
|
+
skipped: string[];
|
|
174
|
+
failed: string[];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Carry the planned changes into `targetRoot`.
|
|
179
|
+
*
|
|
180
|
+
* `resolutions` only has to cover conflicts; clean entries default to taking
|
|
181
|
+
* the source side, which is the whole point of the transfer.
|
|
182
|
+
*/
|
|
183
|
+
export async function applyMergePlan(
|
|
184
|
+
plan: MergePlan,
|
|
185
|
+
sourceRoot: string,
|
|
186
|
+
targetRoot: string,
|
|
187
|
+
resolutions: Record<string, MergeResolution> = {}
|
|
188
|
+
): Promise<MergeApplyResult> {
|
|
189
|
+
const result: MergeApplyResult = { written: [], deleted: [], skipped: [], failed: [] };
|
|
190
|
+
|
|
191
|
+
for (const entry of plan.entries) {
|
|
192
|
+
const resolution: MergeResolution = entry.conflict
|
|
193
|
+
? resolutions[entry.path] ?? 'target'
|
|
194
|
+
: 'source';
|
|
195
|
+
|
|
196
|
+
if (resolution === 'target') {
|
|
197
|
+
result.skipped.push(entry.path);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const targetPath = path.join(targetRoot, entry.path);
|
|
202
|
+
|
|
203
|
+
try {
|
|
204
|
+
if (resolution === 'merge') {
|
|
205
|
+
const merged = await mergeFileContents(entry, sourceRoot, targetRoot);
|
|
206
|
+
if (merged === null) {
|
|
207
|
+
result.failed.push(entry.path);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
await fs.mkdir(path.dirname(targetPath), { recursive: true });
|
|
211
|
+
await fs.writeFile(targetPath, merged);
|
|
212
|
+
result.written.push(entry.path);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (entry.status === 'deleted') {
|
|
217
|
+
await fs.rm(targetPath, { force: true });
|
|
218
|
+
result.deleted.push(entry.path);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
await fs.mkdir(path.dirname(targetPath), { recursive: true });
|
|
223
|
+
await fs.copyFile(path.join(sourceRoot, entry.path), targetPath);
|
|
224
|
+
result.written.push(entry.path);
|
|
225
|
+
} catch (error) {
|
|
226
|
+
debug.warn('worktree', `Failed to transfer ${entry.path}: ${error}`);
|
|
227
|
+
result.failed.push(entry.path);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
return result;
|
|
232
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { isPathInside, slugifyWorktreeName, uniqueWorktreeSlug } from './paths';
|
|
4
|
+
|
|
5
|
+
describe('slugifyWorktreeName', () => {
|
|
6
|
+
test('lowercases and hyphenates', () => {
|
|
7
|
+
expect(slugifyWorktreeName('Refactor Auth')).toBe('refactor-auth');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('strips characters that cannot be a directory name', () => {
|
|
11
|
+
expect(slugifyWorktreeName('fix/../etc passwd')).toBe('fix-etc-passwd');
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('trims leading and trailing separators', () => {
|
|
15
|
+
expect(slugifyWorktreeName(' --hello-- ')).toBe('hello');
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
test('returns empty when nothing usable survives', () => {
|
|
19
|
+
expect(slugifyWorktreeName('///')).toBe('');
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test('caps the length', () => {
|
|
23
|
+
expect(slugifyWorktreeName('a'.repeat(200)).length).toBe(48);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
describe('uniqueWorktreeSlug', () => {
|
|
28
|
+
test('uses the plain slug when free', () => {
|
|
29
|
+
expect(uniqueWorktreeSlug('Feature X', new Set())).toBe('feature-x');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('suffixes on collision', () => {
|
|
33
|
+
expect(uniqueWorktreeSlug('Feature X', new Set(['feature-x']))).toBe('feature-x-2');
|
|
34
|
+
expect(uniqueWorktreeSlug('Feature X', new Set(['feature-x', 'feature-x-2']))).toBe('feature-x-3');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('falls back to a default stem for unusable names', () => {
|
|
38
|
+
expect(uniqueWorktreeSlug('///', new Set())).toBe('worktree');
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
describe('isPathInside', () => {
|
|
43
|
+
const root = path.join('/tmp', 'clopen-root');
|
|
44
|
+
|
|
45
|
+
test('accepts the root itself', () => {
|
|
46
|
+
expect(isPathInside(root, root)).toBe(true);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('accepts a nested path', () => {
|
|
50
|
+
expect(isPathInside(root, path.join(root, 'src', 'index.ts'))).toBe(true);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('rejects an escape', () => {
|
|
54
|
+
expect(isPathInside(root, path.join(root, '..', 'elsewhere'))).toBe(false);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('rejects a sibling with a shared prefix', () => {
|
|
58
|
+
expect(isPathInside(root, `${root}-other`)).toBe(false);
|
|
59
|
+
});
|
|
60
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worktree location and naming.
|
|
3
|
+
*
|
|
4
|
+
* Worktrees live outside the project directory. Inside it they would be picked
|
|
5
|
+
* up as nested repos by the Git panel, walked by the file watcher, and shown to
|
|
6
|
+
* the agent as part of its own tree.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { getClopenDir } from '../utils/paths';
|
|
11
|
+
|
|
12
|
+
/** Root that holds every worktree of every project. */
|
|
13
|
+
export function getWorktreesRootDir(): string {
|
|
14
|
+
return path.join(getClopenDir(), 'worktrees');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Directory that holds one project's worktrees. */
|
|
18
|
+
export function getProjectWorktreesDir(projectId: string): string {
|
|
19
|
+
return path.join(getWorktreesRootDir(), projectId);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Absolute path of a single worktree. */
|
|
23
|
+
export function getWorktreePath(projectId: string, slug: string): string {
|
|
24
|
+
return path.join(getProjectWorktreesDir(projectId), slug);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Turn a display name into a directory-safe slug.
|
|
29
|
+
* Returns an empty string when nothing usable survives — callers substitute one.
|
|
30
|
+
*/
|
|
31
|
+
export function slugifyWorktreeName(name: string): string {
|
|
32
|
+
return name
|
|
33
|
+
.toLowerCase()
|
|
34
|
+
.normalize('NFKD')
|
|
35
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
36
|
+
.replace(/^-+|-+$/g, '')
|
|
37
|
+
.slice(0, 48);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Pick a slug not already used by this project.
|
|
42
|
+
* `taken` is the set of existing slugs; a numeric suffix is added on collision.
|
|
43
|
+
*/
|
|
44
|
+
export function uniqueWorktreeSlug(name: string, taken: Set<string>): string {
|
|
45
|
+
const base = slugifyWorktreeName(name) || 'worktree';
|
|
46
|
+
if (!taken.has(base)) return base;
|
|
47
|
+
|
|
48
|
+
for (let suffix = 2; suffix < 1000; suffix++) {
|
|
49
|
+
const candidate = `${base}-${suffix}`;
|
|
50
|
+
if (!taken.has(candidate)) return candidate;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return `${base}-${Date.now()}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether `candidate` sits inside `root` (or is `root` itself). */
|
|
57
|
+
export function isPathInside(root: string, candidate: string): boolean {
|
|
58
|
+
const relative = path.relative(path.resolve(root), path.resolve(candidate));
|
|
59
|
+
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
60
|
+
}
|