@myrialabs/clopen 0.4.31 → 0.4.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +31 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -13,14 +13,30 @@ export interface GitExecResult {
13
13
  exitCode: number;
14
14
  }
15
15
 
16
+ export interface GitExecOptions {
17
+ /** Milliseconds before the process is killed. */
18
+ timeout?: number;
19
+ /** Piped to the command's stdin (e.g. `check-ignore --stdin` path lists). */
20
+ stdin?: string;
21
+ /**
22
+ * Exit codes that are a normal answer rather than a failure, so they are
23
+ * not logged as one — `check-ignore` exits 1 to say "nothing matched".
24
+ */
25
+ okExitCodes?: number[];
26
+ }
27
+
16
28
  /**
17
- * Execute a git command in the given working directory
29
+ * Execute a git command in the given working directory.
30
+ * The third argument accepts a timeout in ms (legacy form) or an options object.
18
31
  */
19
32
  export async function execGit(
20
33
  args: string[],
21
34
  cwd: string,
22
- timeout = 30000
35
+ timeoutOrOptions: number | GitExecOptions = 30000
23
36
  ): Promise<GitExecResult> {
37
+ const options: GitExecOptions =
38
+ typeof timeoutOrOptions === 'number' ? { timeout: timeoutOrOptions } : timeoutOrOptions;
39
+ const { timeout = 30000, stdin, okExitCodes = [] } = options;
24
40
  debug.log('git', `Executing: git ${args.join(' ')} in ${cwd}`);
25
41
 
26
42
  const gitPath = resolveBinary('git');
@@ -29,6 +45,9 @@ export async function execGit(
29
45
  const safeCwd = cwd.replace(/\\/g, '/');
30
46
  const proc = Bun.spawn([gitPath, '-c', `safe.directory=${safeCwd}`, ...args], {
31
47
  cwd,
48
+ // Commands that read a path list (`check-ignore --stdin`) get it here —
49
+ // far safer than argv, which has a length limit and quoting pitfalls.
50
+ stdin: stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin),
32
51
  stdout: 'pipe',
33
52
  stderr: 'pipe',
34
53
  env: {
@@ -63,7 +82,7 @@ export async function execGit(
63
82
  const exitCode = await proc.exited;
64
83
  clearTimeout(timeoutId);
65
84
 
66
- if (exitCode !== 0) {
85
+ if (exitCode !== 0 && !okExitCodes.includes(exitCode)) {
67
86
  debug.warn('git', `Command failed (exit ${exitCode}): git ${args.join(' ')}\n${stderr}`);
68
87
  }
69
88
 
@@ -36,7 +36,7 @@ import {
36
36
  assertSafeGitRevish,
37
37
  assertSafeGitShowRef
38
38
  } from './git-spawn-validation';
39
- import { findNestedRepoPaths, findSubmodulePaths } from '../snapshot/gitignore';
39
+ import { findNestedRepoPaths, findSubmodulePaths } from './nested-repos';
40
40
  import path from 'node:path';
41
41
 
42
42
  export class GitService {
@@ -0,0 +1,224 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
2
+ import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { execGit } from './git-executor';
6
+ import { findNestedRepoPaths, findRepoForFile } from './nested-repos';
7
+
8
+ /**
9
+ * Sub-repo detection used to walk the whole tree and report every directory
10
+ * with a `.git` inside it — on an iOS project, Swift Package Manager's
11
+ * `build/…/SourcePackages/checkouts/*` put thousands of foreign changes in the
12
+ * Changes tab. Pruning by directory name fixed that case and nothing more:
13
+ * `plugins/` is where tmux clones its packages *and* where a WordPress
14
+ * developer keeps their own plugin repos, so no denylist can be right on both
15
+ * sides. The policy these tests pin down is structural instead — inside a tree
16
+ * the project ignores, a sub-repo is reported only if it holds local work or
17
+ * is a declared submodule.
18
+ */
19
+
20
+ let root: string;
21
+
22
+ async function git(cwd: string, ...args: string[]) {
23
+ const result = await execGit(args, cwd);
24
+ if (result.exitCode !== 0 && args[0] !== 'check-ignore') {
25
+ throw new Error(`git ${args.join(' ')}: ${result.stderr}`);
26
+ }
27
+ return result.stdout;
28
+ }
29
+
30
+ async function initRepo(dir: string) {
31
+ await mkdir(dir, { recursive: true });
32
+ await git(dir, 'init', '-b', 'main', '.');
33
+ await git(dir, 'config', 'user.email', 'test@example.com');
34
+ await git(dir, 'config', 'user.name', 'Test');
35
+ await git(dir, 'config', 'commit.gpgsign', 'false');
36
+ }
37
+
38
+ /**
39
+ * Give a repo something the Git panel could show. An untracked file is what an
40
+ * agent writing into a sub-repo produces, and it is what tells a repo the user
41
+ * works in apart from a package manager's pristine checkout.
42
+ */
43
+ async function addLocalWork(dir: string) {
44
+ await writeFile(path.join(dir, 'index.php'), '<?php // edited\n');
45
+ }
46
+
47
+ /** Paths relative to the project root, for readable assertions. */
48
+ async function detected(): Promise<string[]> {
49
+ const paths = await findNestedRepoPaths(root);
50
+ return paths.map((p) => path.relative(root, p).replace(/\\/g, '/')).sort();
51
+ }
52
+
53
+ beforeEach(async () => {
54
+ root = await mkdtemp(path.join(tmpdir(), 'clopen-nested-'));
55
+ await initRepo(root);
56
+ });
57
+
58
+ afterEach(async () => {
59
+ await rm(root, { recursive: true, force: true });
60
+ });
61
+
62
+ describe('findNestedRepoPaths', () => {
63
+ test('ignores package-manager checkouts under an ignored build dir', async () => {
64
+ await writeFile(path.join(root, '.gitignore'), 'build/\n');
65
+ for (const name of ['abseil-cpp-binary', 'firebase-ios-sdk', 'leveldb']) {
66
+ await initRepo(path.join(root, 'build/ios/SourcePackages/checkouts', name));
67
+ }
68
+
69
+ expect(await detected()).toEqual([]);
70
+ });
71
+
72
+ test('ignores dependency dirs by name even when they are committed', async () => {
73
+ // No .gitignore at all — the name alone must be enough.
74
+ await initRepo(path.join(root, 'node_modules/some-pkg'));
75
+ await initRepo(path.join(root, 'ios/Pods/SomePod'));
76
+ await initRepo(path.join(root, '.build/checkouts/some-dep'));
77
+
78
+ expect(await detected()).toEqual([]);
79
+ });
80
+
81
+ test('detects a repo embedded in the project tree', async () => {
82
+ await initRepo(path.join(root, 'packages/widget'));
83
+
84
+ expect(await detected()).toEqual(['packages/widget']);
85
+ });
86
+
87
+ test('detects a repo the outer repo ignores', async () => {
88
+ await writeFile(path.join(root, '.gitignore'), 'wp-content/themes/mytheme/\n');
89
+ await initRepo(path.join(root, 'wp-content/themes/mytheme'));
90
+
91
+ expect(await detected()).toEqual(['wp-content/themes/mytheme']);
92
+ });
93
+
94
+ test('detects a worked-in repo sitting directly under an ignored parent', async () => {
95
+ await writeFile(path.join(root, '.gitignore'), 'themes/\n');
96
+ await initRepo(path.join(root, 'themes/mytheme'));
97
+ await addLocalWork(path.join(root, 'themes/mytheme'));
98
+
99
+ expect(await detected()).toEqual(['themes/mytheme']);
100
+ });
101
+
102
+ test('leaves a pristine repo under an ignored parent out until it changes', async () => {
103
+ // The deliberate trade-off: with nothing to show, a repo inside an
104
+ // ignored tree is indistinguishable from a package checkout. It comes
105
+ // back the moment there is a change — which is when the panel needs it.
106
+ await writeFile(path.join(root, '.gitignore'), 'themes/\n');
107
+ await initRepo(path.join(root, 'themes/mytheme'));
108
+
109
+ expect(await detected()).toEqual([]);
110
+
111
+ await addLocalWork(path.join(root, 'themes/mytheme'));
112
+ expect(await detected()).toEqual(['themes/mytheme']);
113
+ });
114
+
115
+ test.each([
116
+ ['elixir mix', '/deps/\n', ['deps/daisyui', 'deps/heroicons']],
117
+ ['openwrt feeds', 'feeds/\n', ['feeds/packages', 'feeds/luci']],
118
+ ['vim pathogen', 'bundle/\n', ['bundle/vim-fugitive']],
119
+ ['tmux tpm', 'plugins/\n', ['plugins/tpm']],
120
+ ['ansible galaxy', 'roles/\n', ['roles/geerlingguy.nginx']],
121
+ ['puppet librarian', 'modules/\n', ['modules/stdlib']],
122
+ ['chef berkshelf', 'berks-cookbooks/\n', ['berks-cookbooks/nginx']],
123
+ ['zephyr west', 'west-modules/\n', ['west-modules/hal_stm32']],
124
+ ['composer source install', 'vendor/\n', ['vendor/acme/lib']],
125
+ ['cmake fetchcontent', 'build/\n', ['build/_deps/googletest-src']]
126
+ ])(
127
+ 'ignores %s checkouts inside an ignored tree',
128
+ async (_name, gitignore, repos) => {
129
+ // Every one of these clones into an ignored directory, several of
130
+ // them exactly one level down where the peek looks. They are all
131
+ // pristine, which is the only thing the policy needs to know —
132
+ // `plugins/` and `modules/` appear on the user's side of the fence
133
+ // too, so their names cannot be the signal.
134
+ await writeFile(path.join(root, '.gitignore'), gitignore);
135
+ for (const repo of repos) await initRepo(path.join(root, repo));
136
+
137
+ expect(await detected()).toEqual([]);
138
+ }
139
+ );
140
+
141
+ test('reports the user plugin repo under an ignored dir that tmux also uses', async () => {
142
+ // Same directory name as the tmux case above, opposite verdict.
143
+ await writeFile(path.join(root, '.gitignore'), 'wp-content/plugins/\n');
144
+ await initRepo(path.join(root, 'wp-content/plugins/my-plugin'));
145
+ await addLocalWork(path.join(root, 'wp-content/plugins/my-plugin'));
146
+
147
+ expect(await detected()).toEqual(['wp-content/plugins/my-plugin']);
148
+ });
149
+
150
+ test('reports a declared submodule inside an ignored tree even when pristine', async () => {
151
+ // `.gitmodules` is the user naming the sub-repo themselves, which
152
+ // outranks anything its working tree could tell us.
153
+ await writeFile(path.join(root, '.gitignore'), 'themes/\n');
154
+ await writeFile(
155
+ path.join(root, '.gitmodules'),
156
+ '[submodule "themes/mytheme"]\n\tpath = themes/mytheme\n\turl = https://example.com/t.git\n'
157
+ );
158
+ await initRepo(path.join(root, 'themes/mytheme'));
159
+
160
+ expect(await detected()).toEqual(['themes/mytheme']);
161
+ });
162
+
163
+ test('a repo inside a rejected checkout cannot launder itself', async () => {
164
+ // Entering a repo resets the ignore budget, so without inheriting the
165
+ // "inside an ignored tree" flag the vendored repo would be treated as
166
+ // part of `pkg`'s own tracked structure and reported unconditionally.
167
+ await writeFile(path.join(root, '.gitignore'), '/deps/\n');
168
+ const pkg = path.join(root, 'deps/pkg');
169
+ await initRepo(pkg);
170
+ // Committed, so `pkg` itself stays pristine — otherwise the vendored
171
+ // directory would show up as untracked work and this would test nothing.
172
+ await writeFile(path.join(pkg, '.gitignore'), 'vendored/\n');
173
+ await git(pkg, 'add', '-A');
174
+ await git(pkg, 'commit', '-m', 'init');
175
+ await initRepo(path.join(pkg, 'vendored'));
176
+
177
+ expect(await detected()).toEqual([]);
178
+ });
179
+
180
+ test('still reports an ignored build dir that is itself a repo', async () => {
181
+ // A `dist/` deploy worktree is a repo the user works in; only the
182
+ // contents of a dependency-named dir are off limits, not the dir itself.
183
+ await writeFile(path.join(root, '.gitignore'), 'dist/\n');
184
+ await initRepo(path.join(root, 'dist'));
185
+
186
+ expect(await detected()).toEqual(['dist']);
187
+ });
188
+
189
+ test('does not report repos generated deep inside an ignored tree', async () => {
190
+ await writeFile(path.join(root, '.gitignore'), 'themes/\n');
191
+ await initRepo(path.join(root, 'themes/mytheme'));
192
+ await addLocalWork(path.join(root, 'themes/mytheme'));
193
+ await initRepo(path.join(root, 'themes/cache/vendor/dep/checkout'));
194
+ await addLocalWork(path.join(root, 'themes/cache/vendor/dep/checkout'));
195
+
196
+ expect(await detected()).toEqual(['themes/mytheme']);
197
+ });
198
+
199
+ test('a nested repo is judged by its own ignore rules', async () => {
200
+ await initRepo(path.join(root, 'packages/widget'));
201
+ await writeFile(path.join(root, 'packages/widget/.gitignore'), 'build/\n');
202
+ await initRepo(path.join(root, 'packages/widget/build/x/y/dep'));
203
+ await initRepo(path.join(root, 'packages/widget/plugins/helper'));
204
+
205
+ expect(await detected()).toEqual(['packages/widget', 'packages/widget/plugins/helper']);
206
+ });
207
+ });
208
+
209
+ describe('findRepoForFile', () => {
210
+ test('routes a file to the deepest owning repo', async () => {
211
+ await initRepo(path.join(root, 'packages/widget'));
212
+ await initRepo(path.join(root, 'packages/widget/plugins/helper'));
213
+
214
+ const owner = await findRepoForFile(root, 'packages/widget/plugins/helper/src/a.ts');
215
+ expect(owner?.repoPath).toBe(path.join(root, 'packages/widget/plugins/helper'));
216
+ expect(owner?.relativeFilePath).toBe('src/a.ts');
217
+ });
218
+
219
+ test('leaves outer-repo files alone', async () => {
220
+ await initRepo(path.join(root, 'packages/widget'));
221
+
222
+ expect(await findRepoForFile(root, 'src/main.ts')).toBeNull();
223
+ });
224
+ });
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Nested git repo discovery — the single source of truth for "which sub-repos
3
+ * live inside this project".
4
+ *
5
+ * Used by the Git panel (status/branches/conflicts aggregation), by the file
6
+ * handlers that must run git inside the owning repo, and by the snapshot
7
+ * scanner. Every caller MUST go through `findNestedRepoPaths` so they all agree
8
+ * on what counts as a sub-repo.
9
+ *
10
+ * ## What counts as a sub-repo
11
+ *
12
+ * A directory with its own `.git` that the user actually works in — a theme or
13
+ * plugin extracted into its own repo, a submodule, a worktree.
14
+ *
15
+ * What does NOT count: the hundreds of repos a package manager clones into a
16
+ * build or cache directory (Swift Package Manager's
17
+ * `build/…/SourcePackages/checkouts/*`, Carthage, Go module caches, …). They
18
+ * are machine-generated, the user never commits them, and listing them floods
19
+ * the Changes tab with thousands of foreign files.
20
+ *
21
+ * Names alone cannot separate the two. `plugins/` holds tmux's cloned packages
22
+ * and a WordPress developer's own plugin repos; `modules/` holds Puppet's
23
+ * librarian checkouts and hand-written modules. Any denylist of directory
24
+ * names is wrong on one side of those, and every new package manager adds
25
+ * another name to chase. So the policy leans on structure instead:
26
+ *
27
+ * 1. **Name, for cost only** — `HARD_SKIP_DIRS` are caches so large that
28
+ * walking them is wasteful. Pruning them is an optimisation, not the policy.
29
+ * 2. **Ignore state** — a directory the enclosing repo ignores is not part of
30
+ * the project's own structure. We still peek `IGNORED_DESCENT_LEVELS` level
31
+ * into it, because an embedded repo is commonly placed directly under an
32
+ * ignored parent (`wp-content/plugins/` ignored, the plugin repo inside it).
33
+ * 3. **Local work** — a repo found inside an ignored tree is reported only if
34
+ * it has something to show: uncommitted changes, or a `.gitmodules` entry
35
+ * declaring it. A package manager's checkout is pristine by construction —
36
+ * it is a clone at a pinned ref that nobody edits — so this drops Mix's
37
+ * `deps/*`, OpenWrt's `feeds/*`, Vim's `bundle/*` and every future
38
+ * equivalent without naming any of them. A repo the user actually works in
39
+ * appears the moment there is a change to see, which is exactly when the
40
+ * Changes tab needs it.
41
+ *
42
+ * Repos in the project's own tracked structure are never subject to (3): they
43
+ * are listed whether or not they are clean. That includes a repo whose own
44
+ * path is ignored while its parents are tracked — a directory that is itself a
45
+ * repo is recognised before its ignore state is ever consulted.
46
+ *
47
+ * A repo found this way resets the ignore budget: its own contents are then
48
+ * judged by its own `.gitignore`, not the outer repo's.
49
+ */
50
+
51
+ import fs from 'fs/promises';
52
+ import path from 'path';
53
+ import { debug } from '$shared/utils/logger';
54
+ import { execGit } from './git-executor';
55
+
56
+ /**
57
+ * Directories large enough that walking them is pure waste — VCS internals and
58
+ * the big dependency caches. Pruned by name at any depth, whether or not the
59
+ * enclosing repo ignores them. This list is a cost guard, not the policy: what
60
+ * keeps package checkouts out of the panel is rule (3) above, so a name
61
+ * missing from here costs a little walking, not a wrong answer.
62
+ */
63
+ const HARD_SKIP_DIRS = new Set([
64
+ '.git', '.svn', '.hg',
65
+ 'node_modules', 'bower_components', '.yarn', '.pnpm-store',
66
+ 'Pods', 'Carthage', 'DerivedData', 'SourcePackages', '.build',
67
+ '.gradle', '.m2', '.cargo', '.pub-cache', '.dart_tool', '.expo',
68
+ '.venv', 'venv', '__pycache__', '.tox', '.stack-work',
69
+ '.next', '.nuxt', '.svelte-kit', '.turbo', '.angular', '.parcel-cache',
70
+ '.terraform', '.serverless', '.vercel', '.netlify', '.cache'
71
+ ]);
72
+
73
+ /** How many levels below an ignored directory we still look for a repo. */
74
+ const IGNORED_DESCENT_LEVELS = 1;
75
+
76
+ /** Depth limit below the project root — a runaway walk helps nobody. */
77
+ const MAX_DEPTH = 12;
78
+
79
+ /**
80
+ * Upper bound on reported sub-repos. A project with more than this is either
81
+ * pathological or hit a detection hole; either way the UI cannot usefully show
82
+ * them, so we stop and log instead of flooding it.
83
+ */
84
+ const MAX_REPOS = 50;
85
+
86
+ /** One directory queued for inspection during the breadth-first walk. */
87
+ interface WalkEntry {
88
+ /** Absolute path of the directory whose children we will inspect. */
89
+ dirPath: string;
90
+ /** Absolute path of the nearest enclosing git repo (for ignore checks). */
91
+ repoRoot: string;
92
+ /**
93
+ * Remaining levels we may descend while inside an ignored tree, or `null`
94
+ * when this directory is part of the enclosing repo's own structure.
95
+ */
96
+ ignoredBudget: number | null;
97
+ /**
98
+ * True once the walk has crossed into a tree the project ignores. Repos
99
+ * found from here on must prove they hold local work before being
100
+ * reported, and the flag is inherited so a repo nested inside a rejected
101
+ * package checkout does not slip through on its own clean ignore state.
102
+ */
103
+ insideIgnored: boolean;
104
+ }
105
+
106
+ /**
107
+ * Ask the enclosing repo which of `relPaths` it ignores. Returns the ignored
108
+ * subset. Batched so a walk costs one git call per repo per depth level, not
109
+ * one per directory.
110
+ */
111
+ async function filterIgnored(repoRoot: string, relPaths: string[]): Promise<Set<string>> {
112
+ const ignored = new Set<string>();
113
+ if (relPaths.length === 0) return ignored;
114
+
115
+ try {
116
+ // Paths go in over stdin: no argv limit, no quoting rules. Exit 1 just
117
+ // means "none of these are ignored" — not a failure.
118
+ const result = await execGit(['check-ignore', '-z', '--stdin'], repoRoot, {
119
+ stdin: relPaths.join('\0'),
120
+ okExitCodes: [1]
121
+ });
122
+ if (result.exitCode === 0) {
123
+ for (const p of result.stdout.split('\0')) {
124
+ if (p) ignored.add(p.replace(/\\/g, '/'));
125
+ }
126
+ }
127
+ } catch {
128
+ // Not a repo, or git unavailable — treat as "nothing ignored" and let
129
+ // the name-based prune carry the walk.
130
+ }
131
+
132
+ return ignored;
133
+ }
134
+
135
+ /**
136
+ * Whether `repoPath` has anything the Git panel could show — staged, unstaged,
137
+ * untracked or conflicted entries. This is what separates a repo the user
138
+ * works in from a package manager's checkout, which is a clone at a pinned ref
139
+ * that nobody edits and so reports nothing.
140
+ *
141
+ * A repo we cannot read is reported as having work: hiding a sub-repo the user
142
+ * edits is a far worse failure than showing one they do not care about.
143
+ */
144
+ async function hasLocalWork(repoPath: string): Promise<boolean> {
145
+ try {
146
+ const result = await execGit(['status', '--porcelain', '-z'], repoPath, { timeout: 15000 });
147
+ if (result.exitCode !== 0) return true;
148
+ return result.stdout.length > 0;
149
+ } catch {
150
+ return true;
151
+ }
152
+ }
153
+
154
+ /** Whether `dirPath` is a git repo (`.git` is a dir for clones, a file for worktrees/submodules). */
155
+ async function isRepoDir(dirPath: string): Promise<boolean> {
156
+ try {
157
+ await fs.access(path.join(dirPath, '.git'));
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Find every nested git repo under `rootPath`, skipping dependency caches and
166
+ * ignored trees (see the module comment for the exact policy). Does NOT scan
167
+ * the repos — just returns their absolute paths, sorted for stable UI order.
168
+ */
169
+ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
170
+ const found: string[] = [];
171
+ /** Repos found inside an ignored tree — reported only if they prove local work. */
172
+ const provisional: string[] = [];
173
+ let level: WalkEntry[] = [
174
+ { dirPath: rootPath, repoRoot: rootPath, ignoredBudget: null, insideIgnored: false }
175
+ ];
176
+ let truncated = false;
177
+
178
+ for (let depth = 0; depth < MAX_DEPTH && level.length > 0 && !truncated; depth++) {
179
+ // Collect this level's candidate children, grouped by enclosing repo so
180
+ // the ignore check can be batched per repo.
181
+ const candidates: Array<{ parent: WalkEntry; fullPath: string; relPath: string }> = [];
182
+ for (const entry of level) {
183
+ let entries;
184
+ try {
185
+ entries = await fs.readdir(entry.dirPath, { withFileTypes: true });
186
+ } catch {
187
+ continue; // unreadable dir — skip, never fail the whole walk
188
+ }
189
+ for (const child of entries) {
190
+ // `isDirectory()` is false for symlinks, which also keeps the
191
+ // walk free of symlink cycles.
192
+ if (!child.isDirectory()) continue;
193
+ if (HARD_SKIP_DIRS.has(child.name)) continue;
194
+ const fullPath = path.join(entry.dirPath, child.name);
195
+ candidates.push({
196
+ parent: entry,
197
+ fullPath,
198
+ relPath: path.relative(entry.repoRoot, fullPath).replace(/\\/g, '/')
199
+ });
200
+ }
201
+ }
202
+ if (candidates.length === 0) break;
203
+
204
+ // Ignore state is only needed for candidates that are not repos
205
+ // themselves and whose parent isn't already inside an ignored tree.
206
+ const repoFlags = await Promise.all(candidates.map((c) => isRepoDir(c.fullPath)));
207
+ const needIgnoreCheck = new Map<string, string[]>();
208
+ candidates.forEach((c, i) => {
209
+ if (repoFlags[i] || c.parent.ignoredBudget !== null) return;
210
+ const list = needIgnoreCheck.get(c.parent.repoRoot) ?? [];
211
+ list.push(c.relPath);
212
+ needIgnoreCheck.set(c.parent.repoRoot, list);
213
+ });
214
+ const ignoredByRepo = new Map<string, Set<string>>();
215
+ for (const [repoRoot, relPaths] of needIgnoreCheck) {
216
+ ignoredByRepo.set(repoRoot, await filterIgnored(repoRoot, relPaths));
217
+ }
218
+
219
+ const next: WalkEntry[] = [];
220
+ candidates.forEach((c, i) => {
221
+ if (repoFlags[i]) {
222
+ if (c.parent.insideIgnored) {
223
+ // Candidates from an ignored tree get their own budget, so a
224
+ // directory full of package checkouts bounds the `git status`
225
+ // work without blinding the rest of the walk to real sub-repos.
226
+ if (provisional.length >= MAX_REPOS) return;
227
+ provisional.push(c.fullPath);
228
+ } else {
229
+ if (found.length >= MAX_REPOS) {
230
+ truncated = true;
231
+ return;
232
+ }
233
+ found.push(c.fullPath);
234
+ }
235
+ // Inside a repo, its own ignore rules apply from scratch — but a
236
+ // repo buried in an ignored tree cannot launder its children.
237
+ next.push({
238
+ dirPath: c.fullPath,
239
+ repoRoot: c.fullPath,
240
+ ignoredBudget: null,
241
+ insideIgnored: c.parent.insideIgnored
242
+ });
243
+ return;
244
+ }
245
+
246
+ let budget = c.parent.ignoredBudget;
247
+ if (budget === null) {
248
+ const ignored = ignoredByRepo.get(c.parent.repoRoot);
249
+ if (!ignored?.has(c.relPath)) {
250
+ // Part of the project's own structure — descend freely.
251
+ next.push({
252
+ dirPath: c.fullPath,
253
+ repoRoot: c.parent.repoRoot,
254
+ ignoredBudget: null,
255
+ insideIgnored: c.parent.insideIgnored
256
+ });
257
+ return;
258
+ }
259
+ budget = IGNORED_DESCENT_LEVELS;
260
+ } else {
261
+ budget -= 1;
262
+ }
263
+ // Inside an ignored tree: keep looking only while the budget lasts.
264
+ if (budget > 0) {
265
+ next.push({
266
+ dirPath: c.fullPath,
267
+ repoRoot: c.parent.repoRoot,
268
+ ignoredBudget: budget,
269
+ insideIgnored: true
270
+ });
271
+ }
272
+ });
273
+
274
+ level = next;
275
+ }
276
+
277
+ if (truncated) {
278
+ debug.warn('git', `Nested repo scan of ${rootPath} stopped at ${MAX_REPOS} repos`);
279
+ }
280
+
281
+ if (provisional.length > 0) {
282
+ // A submodule is the user declaring the sub-repo themselves, which
283
+ // outranks anything we could infer from its working tree.
284
+ const submodulePaths = await findSubmodulePaths(rootPath);
285
+ const isDeclared = (repoPath: string) =>
286
+ submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
287
+ const verdicts = await Promise.all(
288
+ provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(repoPath)))
289
+ );
290
+ provisional.forEach((repoPath, i) => {
291
+ if (verdicts[i]) found.push(repoPath);
292
+ });
293
+ }
294
+
295
+ found.sort();
296
+ return found;
297
+ }
298
+
299
+ /**
300
+ * Read the outer repo's `.gitmodules` file and return the set of relative
301
+ * submodule paths. Returns an empty set when the file is missing or unreadable
302
+ * (e.g. the project isn't a git repo at all, or has no submodules).
303
+ *
304
+ * The format is INI-like:
305
+ * [submodule "vendor/foo"]
306
+ * path = vendor/foo
307
+ * url = git@example.com:vendor/foo.git
308
+ *
309
+ * The `path =` value is what we return — the directory inside the project root
310
+ * where the submodule is checked out. If a section omits `path =`, git falls
311
+ * back to the section name; we mirror that.
312
+ */
313
+ export async function findSubmodulePaths(rootPath: string): Promise<Set<string>> {
314
+ const out = new Set<string>();
315
+ let raw: string;
316
+ try {
317
+ raw = await fs.readFile(path.join(rootPath, '.gitmodules'), 'utf8');
318
+ } catch {
319
+ return out; // file missing → no submodules
320
+ }
321
+
322
+ // Two-pass parse: collect per-section { name, path? } then resolve.
323
+ // Single-pass is simpler but needs careful handling of the implicit
324
+ // section-name fallback; the two-pass version reads more clearly.
325
+ const sections: Array<{ name: string; path?: string }> = [];
326
+ let current: { name: string; path?: string } | null = null;
327
+ for (const line of raw.split(/\r?\n/)) {
328
+ const trimmed = line.trim();
329
+ if (!trimmed || trimmed.startsWith('#')) continue;
330
+
331
+ const sectionMatch = trimmed.match(/^\[submodule\s+"([^"]+)"\]\s*$/);
332
+ if (sectionMatch) {
333
+ if (current) sections.push(current);
334
+ current = { name: sectionMatch[1] };
335
+ continue;
336
+ }
337
+ if (!current) continue;
338
+
339
+ const pathMatch = trimmed.match(/^path\s*=\s*(.+?)\s*$/);
340
+ if (pathMatch) current.path = pathMatch[1].replace(/\\/g, '/');
341
+ }
342
+ if (current) sections.push(current);
343
+
344
+ for (const s of sections) {
345
+ out.add(s.path ?? s.name);
346
+ }
347
+ return out;
348
+ }
349
+
350
+ /**
351
+ * Given a file path relative to the project root, find the deepest nested
352
+ * git repo that contains it. Returns the repo's absolute path and the file
353
+ * path relative to that repo, or `null` if the file lives in the outer repo.
354
+ *
355
+ * Used by git staging/discard handlers so that `git add` / `git restore` /
356
+ * `git rm` run inside the correct repo (the outer repo's `git` would skip
357
+ * or fail on files that are tracked by a nested repo).
358
+ */
359
+ export async function findRepoForFile(
360
+ projectPath: string,
361
+ filePath: string
362
+ ): Promise<{ repoPath: string; relativeFilePath: string } | null> {
363
+ const normalizedFilePath = filePath.replace(/\\/g, '/');
364
+ const nestedRepoPaths = await findNestedRepoPaths(projectPath);
365
+
366
+ let bestMatch: { repoPath: string; relativeFilePath: string } | null = null;
367
+ let bestRepoRelLen = -1;
368
+
369
+ for (const repoPath of nestedRepoPaths) {
370
+ const repoRel = path.relative(projectPath, repoPath).replace(/\\/g, '/');
371
+ // File is inside this repo if its path starts with `repoRel/`
372
+ if (normalizedFilePath === repoRel || normalizedFilePath.startsWith(repoRel + '/')) {
373
+ if (repoRel.length > bestRepoRelLen) {
374
+ bestMatch = {
375
+ repoPath,
376
+ relativeFilePath: normalizedFilePath === repoRel
377
+ ? ''
378
+ : normalizedFilePath.substring(repoRel.length + 1)
379
+ };
380
+ bestRepoRelLen = repoRel.length;
381
+ }
382
+ }
383
+ }
384
+
385
+ return bestMatch;
386
+ }