@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.
Files changed (125) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/auth/permissions.ts +7 -0
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  20. package/backend/database/migrations/index.ts +7 -0
  21. package/backend/database/queries/index.ts +1 -0
  22. package/backend/database/queries/session-queries.ts +50 -11
  23. package/backend/database/queries/worktree-queries.ts +148 -0
  24. package/backend/engine/adapters/opencode/server.ts +389 -83
  25. package/backend/engine/adapters/opencode/stream.ts +14 -14
  26. package/backend/engine/hot-reload.ts +25 -10
  27. package/backend/files/file-watcher.test.ts +105 -0
  28. package/backend/files/file-watcher.ts +80 -10
  29. package/backend/git/git-service.test.ts +33 -0
  30. package/backend/git/git-service.ts +7 -3
  31. package/backend/git/nested-repos.test.ts +292 -1
  32. package/backend/git/nested-repos.ts +330 -17
  33. package/backend/host/metrics.test.ts +110 -0
  34. package/backend/host/metrics.ts +235 -0
  35. package/backend/{ports → host}/runner.ts +19 -10
  36. package/backend/index.ts +16 -4
  37. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  38. package/backend/ports/attribute.test.ts +3 -2
  39. package/backend/ports/attribute.ts +6 -45
  40. package/backend/ports/kill.ts +1 -1
  41. package/backend/ports/monitor.ts +1 -1
  42. package/backend/ports/processes.ts +1 -1
  43. package/backend/ports/scan-host.ts +77 -8
  44. package/backend/ports/scan.test.ts +1 -1
  45. package/backend/ports/scan.ts +1 -1
  46. package/backend/ports/ssh-lineage.ts +1 -1
  47. package/backend/preview/browser/browser-pool.ts +81 -0
  48. package/backend/preview/browser/browser-preview-service.ts +142 -32
  49. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  50. package/backend/preview/browser/browser-video-capture.ts +84 -31
  51. package/backend/preview/browser/types.ts +9 -0
  52. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  53. package/backend/projects/project-cleanup.ts +7 -1
  54. package/backend/projects/shell-ownership.ts +65 -0
  55. package/backend/snapshot/snapshot-service.ts +6 -2
  56. package/backend/terminal/ptykit.ts +35 -6
  57. package/backend/utils/ws.ts +21 -1
  58. package/backend/worktrees/clone.ts +222 -0
  59. package/backend/worktrees/index.ts +29 -0
  60. package/backend/worktrees/merge.test.ts +93 -0
  61. package/backend/worktrees/merge.ts +232 -0
  62. package/backend/worktrees/paths.test.ts +60 -0
  63. package/backend/worktrees/paths.ts +60 -0
  64. package/backend/worktrees/resolve.ts +67 -0
  65. package/backend/worktrees/service.ts +315 -0
  66. package/backend/worktrees/tree.ts +59 -0
  67. package/backend/ws/access.ts +18 -0
  68. package/backend/ws/artifacts/generate.ts +2 -2
  69. package/backend/ws/chat/stream.ts +9 -2
  70. package/backend/ws/containers/actions.ts +156 -0
  71. package/backend/ws/containers/index.ts +43 -0
  72. package/backend/ws/containers/list.ts +146 -0
  73. package/backend/ws/containers/logs.ts +43 -0
  74. package/backend/ws/containers/tunnel.ts +101 -0
  75. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  76. package/backend/ws/files/path-access.test.ts +93 -1
  77. package/backend/ws/files/path-access.ts +54 -5
  78. package/backend/ws/files/read.ts +15 -10
  79. package/backend/ws/files/search.ts +7 -7
  80. package/backend/ws/files/state.ts +70 -8
  81. package/backend/ws/files/watch.ts +16 -14
  82. package/backend/ws/git/branch-name.ts +3 -3
  83. package/backend/ws/git/branch.ts +15 -15
  84. package/backend/ws/git/commit-message.ts +3 -3
  85. package/backend/ws/git/commit.ts +17 -17
  86. package/backend/ws/git/conflict.ts +10 -10
  87. package/backend/ws/git/diff.ts +9 -9
  88. package/backend/ws/git/ignored.ts +9 -9
  89. package/backend/ws/git/log.ts +6 -4
  90. package/backend/ws/git/remote.ts +43 -43
  91. package/backend/ws/git/staging.ts +16 -16
  92. package/backend/ws/git/status.ts +47 -37
  93. package/backend/ws/index.ts +6 -0
  94. package/backend/ws/message-rate-limiter.test.ts +45 -0
  95. package/backend/ws/message-rate-limiter.ts +34 -3
  96. package/backend/ws/preview/access.ts +11 -3
  97. package/backend/ws/projects/index.ts +5 -1
  98. package/backend/ws/projects/info.test.ts +54 -0
  99. package/backend/ws/projects/info.ts +398 -0
  100. package/backend/ws/sessions/crud.ts +21 -6
  101. package/backend/ws/snapshot/restore.ts +11 -14
  102. package/backend/ws/ssh/connections.ts +8 -0
  103. package/backend/ws/system/device-info.ts +70 -96
  104. package/backend/ws/worktrees/crud.ts +187 -0
  105. package/backend/ws/worktrees/index.ts +33 -0
  106. package/backend/ws/worktrees/transfer.ts +88 -0
  107. package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
  108. package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
  109. package/dist/assets/main-9G7IpQpK.css +1 -0
  110. package/dist/assets/main-BofFsH8E.js +1085 -0
  111. package/dist/index.html +2 -2
  112. package/dist/manifest.json +9 -2
  113. package/package.json +1 -1
  114. package/shared/types/containers/container.ts +366 -0
  115. package/shared/types/containers/index.ts +5 -0
  116. package/shared/types/database/schema.ts +26 -0
  117. package/shared/types/host/index.ts +18 -0
  118. package/shared/types/ports/port.ts +47 -9
  119. package/shared/utils/logger.ts +3 -0
  120. package/shared/utils/workspace-scope.test.ts +80 -0
  121. package/shared/utils/workspace-scope.ts +57 -0
  122. package/shared/utils/ws-client.ts +92 -17
  123. package/shared/utils/ws-server.ts +83 -16
  124. package/dist/assets/main-CYCMEbXB.css +0 -1
  125. package/dist/assets/main-ZCojSzvW.js +0 -1060
@@ -76,6 +76,221 @@ const IGNORED_DESCENT_LEVELS = 1;
76
76
  /** Depth limit below the project root — a runaway walk helps nobody. */
77
77
  const MAX_DEPTH = 12;
78
78
 
79
+ /**
80
+ * Discovery caching, and who is allowed to decide it is stale.
81
+ *
82
+ * Every `git:status` / `git:branches` used to re-answer "which directories
83
+ * under this root are repos" from scratch: an `fs.readdir` over the whole tree
84
+ * plus a `git check-ignore` spawn per repo per depth level, then one
85
+ * `git status` per repo sitting inside an ignored tree. Measured on a real
86
+ * project that is 132ms and 7 spawns for the walk alone, and the panel fires it
87
+ * three or four times a second while staging. On Windows every spawn and every
88
+ * readdir also pays for Defender, which is what made Stage All look frozen.
89
+ *
90
+ * The answer barely ever changes, and the file watcher already knows exactly
91
+ * when it does. So the watcher, not a clock, is the invalidation authority:
92
+ *
93
+ * - `beginWatchedDiscovery` / `endWatchedDiscovery` — a root is "watched"
94
+ * while a live watcher is feeding it signals.
95
+ * - `invalidateRepoSet` — a `.git` appeared or vanished, or `.gitignore` /
96
+ * `.gitmodules` changed. The set of repos may be different.
97
+ * - `invalidateLocalWork` — something was written inside one repo, so only
98
+ * that repo's "does it have work to show" verdict is suspect.
99
+ *
100
+ * THE SAFETY RULE, which every change here must preserve: **the watcher only
101
+ * ever makes an answer fresher, never staler.** A TTL is always the floor, so
102
+ * losing every signal degrades to re-walking on a timer — never to an answer
103
+ * that is wrong forever. That failure mode is not hypothetical: `resolveGitDirs`
104
+ * decides which git dirs get watched at all and rejects unaccounted-for ones
105
+ * permanently, so one stale walk there took a sub-repo out of the panel for the
106
+ * whole session.
107
+ *
108
+ * The two halves have different exposure, so they are cached separately:
109
+ *
110
+ * - The WALK (which dirs hold a `.git`) is stable, and the signal for it —
111
+ * a `.git` entry appearing — is one the watcher sees reliably on every
112
+ * platform, because the repo's parent directory is watched. Long floor.
113
+ * - LOCAL WORK (whether a repo inside an ignored tree has anything to show)
114
+ * changes with ordinary file writes, and the watcher is blind inside the
115
+ * directories it prunes by name. Cached ONLY for watched roots, where a
116
+ * write lands as an invalidation; an unwatched caller (the snapshot
117
+ * scanner, a CLI path) still probes live, exactly as before. Hiding a
118
+ * sub-repo the user edits is the worst failure this module can produce, so
119
+ * it does not get cached on a guess.
120
+ *
121
+ * What is never cached, at any point: file status. Staged, unstaged, untracked
122
+ * and conflicted entries come from a live `git status` per repo on every call.
123
+ * The Changes tab cannot go stale through this module.
124
+ */
125
+
126
+ /** Floor for a root nobody is invalidating — the clock is the only signal. */
127
+ const UNWATCHED_TTL_MS = process.platform === 'win32' ? 5000 : 3000;
128
+
129
+ /**
130
+ * Floor for a watched root. Long, because the watcher normally invalidates
131
+ * within milliseconds; this only bounds the damage if a signal is ever missed
132
+ * (a platform that drops an event, a watcher that faulted and is restarting).
133
+ */
134
+ const WATCHED_TTL_MS = 60_000;
135
+
136
+ interface WalkEntryCache {
137
+ found: string[];
138
+ provisional: string[];
139
+ expiresAt: number;
140
+ }
141
+
142
+ /** Whether a sub-repo has anything the panel could show. Watched roots only. */
143
+ interface LocalWorkCache {
144
+ hasWork: boolean;
145
+ expiresAt: number;
146
+ }
147
+
148
+ const nestedRepoWalkCache = new Map<string, WalkEntryCache>();
149
+ const nestedRepoInflight = new Map<string, Promise<string[]>>();
150
+ const localWorkCache = new Map<string, LocalWorkCache>();
151
+
152
+ /**
153
+ * Project roots a live file watcher is feeding signals for, and how many
154
+ * watchers are doing so. Refcounted because two projects can be opened at the
155
+ * same directory: without it the first one to close would revoke the claim
156
+ * while the second is still reporting, and discovery would quietly go back to
157
+ * the clock while a perfectly good signal source was still running.
158
+ */
159
+ const watchedRoots = new Map<string, number>();
160
+
161
+ /**
162
+ * The key every cache and the watched-root set is stored under. Callers reach
163
+ * this module from both sides of a `path.normalize()` — the watcher normalises
164
+ * the project path before registering, `git:status` passes `project.path`
165
+ * straight through — and on Windows those differ by separator alone. Keying on
166
+ * the raw string would put them in two entries: the watcher would invalidate
167
+ * one while the panel read the other, silently turning the signal off.
168
+ * Values keep their native separators; only keys are folded.
169
+ */
170
+ function cacheKey(inputPath: string): string {
171
+ return inputPath.replace(/\\/g, '/').replace(/\/+$/, '');
172
+ }
173
+
174
+ /** Whether `candidate` is `base` or sits underneath it. */
175
+ function isUnder(base: string, candidate: string): boolean {
176
+ const baseKey = cacheKey(base);
177
+ const candidateKey = cacheKey(candidate);
178
+ return candidateKey === baseKey || candidateKey.startsWith(baseKey + '/');
179
+ }
180
+
181
+ function isWatched(rootPath: string): boolean {
182
+ return (watchedRoots.get(cacheKey(rootPath)) ?? 0) > 0;
183
+ }
184
+
185
+ function ttlFor(rootPath: string): number {
186
+ return isWatched(rootPath) ? WATCHED_TTL_MS : UNWATCHED_TTL_MS;
187
+ }
188
+
189
+ /**
190
+ * Declare that a live file watcher will report changes for `rootPath`. Until
191
+ * `endWatchedDiscovery`, discovery may lean on those signals instead of the
192
+ * short clock — and `hasLocalWork` verdicts become cacheable at all.
193
+ */
194
+ export function beginWatchedDiscovery(rootPath: string): void {
195
+ const key = cacheKey(rootPath);
196
+ watchedRoots.set(key, (watchedRoots.get(key) ?? 0) + 1);
197
+ }
198
+
199
+ /**
200
+ * The watcher for `rootPath` is gone. Drop everything that was only safe
201
+ * because it was being invalidated, so the next call re-probes live.
202
+ */
203
+ export function endWatchedDiscovery(rootPath: string): void {
204
+ const key = cacheKey(rootPath);
205
+ const remaining = (watchedRoots.get(key) ?? 0) - 1;
206
+ if (remaining > 0) {
207
+ watchedRoots.set(key, remaining);
208
+ return;
209
+ }
210
+ watchedRoots.delete(key);
211
+ nestedRepoWalkCache.delete(key);
212
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
213
+ if (isUnder(rootPath, cachedRepoKey)) localWorkCache.delete(cachedRepoKey);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * The set of repos under `rootPath` may have changed — a `.git` appeared or
219
+ * vanished, or the rules that decide what counts (`.gitignore`, `.gitmodules`)
220
+ * were edited. Forces a fresh walk on the next call.
221
+ */
222
+ export function invalidateRepoSet(rootPath: string): void {
223
+ nestedRepoWalkCache.delete(cacheKey(rootPath));
224
+ }
225
+
226
+ /**
227
+ * Whether a changed path is one that can change WHICH repos are reported, as
228
+ * opposed to what is inside one.
229
+ *
230
+ * These live here rather than in the watcher on purpose. They are facts about
231
+ * the sub-repo policy at the top of this file, not about filesystem events, so
232
+ * extending that policy has to mean editing one place. Splitting them across
233
+ * the two files is what let discovery and its invalidation drift apart in the
234
+ * first place.
235
+ */
236
+ function isRepoSetRule(changedPath: string): boolean {
237
+ const segments = cacheKey(changedPath).split('/');
238
+ const basename = segments[segments.length - 1];
239
+
240
+ // The repository itself appearing or vanishing.
241
+ if (basename === '.git') return true;
242
+
243
+ // Rule (2) and rule (3): what the project ignores, and what it declares.
244
+ if (basename === '.gitignore' || basename === '.gitmodules') return true;
245
+
246
+ // `.git/info/exclude` is a per-repo ignore file `git check-ignore` obeys
247
+ // exactly like `.gitignore`, so it moves the same boundary. The watcher
248
+ // filters it out of the panel's git-state events — correctly, the panel has
249
+ // nothing to show for it — which is precisely why discovery has to ask for
250
+ // it by name instead of riding along with those.
251
+ return (
252
+ basename === 'exclude' &&
253
+ segments[segments.length - 2] === 'info' &&
254
+ segments[segments.length - 3] === '.git'
255
+ );
256
+ }
257
+
258
+ /**
259
+ * A path under `rootPath` changed. The single entry point the file watcher
260
+ * uses: it forwards raw paths and this module decides what each one means, so
261
+ * no caller has to carry a copy of the sub-repo policy.
262
+ *
263
+ * Ignored entirely for a root nobody claimed — an unwatched root caches
264
+ * nothing that a signal could correct, and answering it here would only hide
265
+ * that fact.
266
+ */
267
+ export function notifyPathChanged(rootPath: string, changedPath: string): void {
268
+ if (!isWatched(rootPath)) return;
269
+ if (isRepoSetRule(changedPath)) invalidateRepoSet(rootPath);
270
+ dropLocalWorkUnder(changedPath);
271
+ }
272
+
273
+ /**
274
+ * Something at or under `changedPath` moved, so the "has work to show" verdict
275
+ * of every cached repo containing it is suspect.
276
+ *
277
+ * Matching by containment rather than taking a repo path directly is what makes
278
+ * the important case work. A pristine sub-repo inside an ignored tree is NOT in
279
+ * the watcher's repo list — it is deliberately unreported until it has
280
+ * something to show, so the watcher has never resolved a git dir for it. The
281
+ * transition that must be caught is exactly the first write into it, and at
282
+ * that moment the only place it is known by name is this cache, holding the
283
+ * `false` verdict that is about to become wrong.
284
+ *
285
+ * Still scoped: a write in one sub-repo says nothing about its siblings, and
286
+ * re-probing all of them is the cost this cache exists to avoid.
287
+ */
288
+ function dropLocalWorkUnder(changedPath: string): void {
289
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
290
+ if (isUnder(cachedRepoKey, changedPath)) localWorkCache.delete(cachedRepoKey);
291
+ }
292
+ }
293
+
79
294
  /**
80
295
  * Upper bound on reported sub-repos. A project with more than this is either
81
296
  * pathological or hit a detection hole; either way the UI cannot usefully show
@@ -141,7 +356,7 @@ async function filterIgnored(repoRoot: string, relPaths: string[]): Promise<Set<
141
356
  * A repo we cannot read is reported as having work: hiding a sub-repo the user
142
357
  * edits is a far worse failure than showing one they do not care about.
143
358
  */
144
- async function hasLocalWork(repoPath: string): Promise<boolean> {
359
+ async function probeLocalWork(repoPath: string): Promise<boolean> {
145
360
  try {
146
361
  const result = await execGit(['status', '--porcelain', '-z'], repoPath, { timeout: 15000 });
147
362
  if (result.exitCode !== 0) return true;
@@ -151,6 +366,29 @@ async function hasLocalWork(repoPath: string): Promise<boolean> {
151
366
  }
152
367
  }
153
368
 
369
+ /**
370
+ * `probeLocalWork` with the verdict remembered — but only under a root the
371
+ * watcher is invalidating, where a write inside the repo lands as an
372
+ * `invalidateLocalWork` before anyone can read a stale answer. Unwatched roots
373
+ * probe live every time: this is the verdict that decides whether a sub-repo is
374
+ * shown at all, and a cached "nothing to show" with no signal behind it would
375
+ * hide a repo the user is working in.
376
+ */
377
+ async function hasLocalWork(rootPath: string, repoPath: string): Promise<boolean> {
378
+ if (!isWatched(rootPath)) return probeLocalWork(repoPath);
379
+
380
+ const cached = localWorkCache.get(cacheKey(repoPath));
381
+ if (cached && Date.now() < cached.expiresAt) return cached.hasWork;
382
+
383
+ const hasWork = await probeLocalWork(repoPath);
384
+ // Re-read the flag: the watcher may have stopped while the probe ran, and a
385
+ // verdict nobody will invalidate must not be left behind.
386
+ if (isWatched(rootPath)) {
387
+ localWorkCache.set(cacheKey(repoPath), { hasWork, expiresAt: Date.now() + WATCHED_TTL_MS });
388
+ }
389
+ return hasWork;
390
+ }
391
+
154
392
  /** Whether `dirPath` is a git repo (`.git` is a dir for clones, a file for worktrees/submodules). */
155
393
  async function isRepoDir(dirPath: string): Promise<boolean> {
156
394
  try {
@@ -165,8 +403,76 @@ async function isRepoDir(dirPath: string): Promise<boolean> {
165
403
  * Find every nested git repo under `rootPath`, skipping dependency caches and
166
404
  * ignored trees (see the module comment for the exact policy). Does NOT scan
167
405
  * the repos — just returns their absolute paths, sorted for stable UI order.
406
+ *
407
+ * The filesystem walk is cached for a few seconds (longer on Windows) and
408
+ * concurrent callers for the same root share a single walk via inflight
409
+ * deduplication. The provisional → found filtering is re-run on every call
410
+ * so a newly-dirtied repo appears immediately.
168
411
  */
169
412
  export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
413
+ const cachedWalk = nestedRepoWalkCache.get(cacheKey(rootPath));
414
+ if (cachedWalk && Date.now() < cachedWalk.expiresAt) {
415
+ return resolveProvisional(rootPath, cachedWalk.found, cachedWalk.provisional);
416
+ }
417
+
418
+ // A caller that arrives while a walk is running shares it instead of
419
+ // starting a second one, but gets its own copy of the result: the array
420
+ // goes out to unrelated call sites, and one of them mutating it in place
421
+ // would corrupt the others.
422
+ const inflight = nestedRepoInflight.get(cacheKey(rootPath));
423
+ if (inflight) return [...(await inflight)];
424
+
425
+ const promise = (async (): Promise<string[]> => {
426
+ const walk = await walkNestedRepos(rootPath);
427
+ nestedRepoWalkCache.set(cacheKey(rootPath), {
428
+ found: walk.found,
429
+ provisional: walk.provisional,
430
+ expiresAt: Date.now() + ttlFor(rootPath)
431
+ });
432
+ return resolveProvisional(rootPath, walk.found, walk.provisional);
433
+ })();
434
+
435
+ nestedRepoInflight.set(cacheKey(rootPath), promise);
436
+ try {
437
+ return await promise;
438
+ } finally {
439
+ nestedRepoInflight.delete(cacheKey(rootPath));
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Decide which provisional repos (those found inside an ignored tree) earn a
445
+ * place in the result, and return the sorted list. Deliberately outside the
446
+ * WALK cache: a repo qualifies the moment it gains local work, so a cached walk
447
+ * must never carry a cached verdict with it. The verdicts have their own,
448
+ * signal-backed cache — see `hasLocalWork`.
449
+ */
450
+ async function resolveProvisional(rootPath: string, found: string[], provisional: string[]): Promise<string[]> {
451
+ if (provisional.length === 0) {
452
+ const out = [...found];
453
+ out.sort();
454
+ return out;
455
+ }
456
+ const submodulePaths = await findSubmodulePaths(rootPath);
457
+ const isDeclared = (repoPath: string) =>
458
+ submodulePaths.has(path.relative(rootPath, repoPath).replace(/\\/g, '/'));
459
+ const verdicts = await Promise.all(
460
+ provisional.map(async (repoPath) => isDeclared(repoPath) || (await hasLocalWork(rootPath, repoPath)))
461
+ );
462
+ const out = [...found];
463
+ provisional.forEach((repoPath, i) => {
464
+ if (verdicts[i]) out.push(repoPath);
465
+ });
466
+ out.sort();
467
+ return out;
468
+ }
469
+
470
+ /**
471
+ * The raw, uncached filesystem walk. Returns repos split into those reportable
472
+ * on structure alone and those still needing to prove local work — the split
473
+ * `findNestedRepoPaths` caches, because only the first half is stable.
474
+ */
475
+ async function walkNestedRepos(rootPath: string): Promise<{ found: string[]; provisional: string[] }> {
170
476
  const found: string[] = [];
171
477
  /** Repos found inside an ignored tree — reported only if they prove local work. */
172
478
  const provisional: string[] = [];
@@ -278,22 +584,7 @@ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
278
584
  debug.warn('git', `Nested repo scan of ${rootPath} stopped at ${MAX_REPOS} repos`);
279
585
  }
280
586
 
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;
587
+ return { found, provisional };
297
588
  }
298
589
 
299
590
  /**
@@ -347,6 +638,28 @@ export async function findSubmodulePaths(rootPath: string): Promise<Set<string>>
347
638
  return out;
348
639
  }
349
640
 
641
+ /**
642
+ * Drop every cached answer so the next call re-scans and re-probes. Exists for
643
+ * tests, which mutate a project's layout far faster than any TTL and would
644
+ * otherwise assert against the previous fixture. Production code should reach
645
+ * for the targeted `invalidateRepoSet` / `invalidateLocalWork` instead, so one
646
+ * repo's churn does not throw away every other repo's answer.
647
+ */
648
+ export function clearNestedRepoCache(rootPath?: string): void {
649
+ if (rootPath) {
650
+ nestedRepoWalkCache.delete(cacheKey(rootPath));
651
+ nestedRepoInflight.delete(cacheKey(rootPath));
652
+ for (const cachedRepoKey of Array.from(localWorkCache.keys())) {
653
+ if (isUnder(rootPath, cachedRepoKey)) localWorkCache.delete(cachedRepoKey);
654
+ }
655
+ } else {
656
+ nestedRepoWalkCache.clear();
657
+ nestedRepoInflight.clear();
658
+ localWorkCache.clear();
659
+ watchedRoots.clear();
660
+ }
661
+ }
662
+
350
663
  /**
351
664
  * Given a file path relative to the project root, find the deepest nested
352
665
  * git repo that contains it. Returns the repo's absolute path and the file
@@ -0,0 +1,110 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { collectProcessTree, cpuCapacityFactor, getHostFacts, withTimeout } from './metrics';
3
+
4
+ function proc(pid: number, parentPid: number) {
5
+ return { pid, parentPid };
6
+ }
7
+
8
+ describe('collectProcessTree', () => {
9
+ it('keeps the roots even when the table does not list them', () => {
10
+ expect([...collectProcessTree([], [42])]).toEqual([42]);
11
+ });
12
+
13
+ it('excludes processes outside the roots', () => {
14
+ const tree = collectProcessTree([proc(100, 1), proc(200, 1), proc(201, 200)], [200]);
15
+ expect([...tree].sort((a, b) => a - b)).toEqual([200, 201]);
16
+ });
17
+
18
+ it('reaches past the depth a bounded pass count would stop at', () => {
19
+ // shell → 15 nested children, listed child-before-parent so a
20
+ // repeated-pass matcher would only pick up one level per pass.
21
+ const list = [];
22
+ for (let depth = 15; depth >= 1; depth--) list.push(proc(1000 + depth, 1000 + depth - 1));
23
+ const tree = collectProcessTree(list, [1000]);
24
+ expect(tree.size).toBe(16);
25
+ expect(tree.has(1015)).toBe(true);
26
+ });
27
+
28
+ it('collects several roots at once', () => {
29
+ const list = [proc(11, 10), proc(21, 20), proc(31, 30)];
30
+ const tree = collectProcessTree(list, [10, 20]);
31
+ expect([...tree].sort((a, b) => a - b)).toEqual([10, 11, 20, 21]);
32
+ });
33
+
34
+ it('terminates on a parent cycle', () => {
35
+ const tree = collectProcessTree([proc(2, 1), proc(1, 2)], [1]);
36
+ expect([...tree].sort((a, b) => a - b)).toEqual([1, 2]);
37
+ });
38
+
39
+ it('ignores a process that claims to be its own parent', () => {
40
+ const tree = collectProcessTree([proc(5, 5), proc(6, 5)], [5]);
41
+ expect([...tree].sort((a, b) => a - b)).toEqual([5, 6]);
42
+ });
43
+ });
44
+
45
+ describe('cpuCapacityFactor', () => {
46
+ it('passes Linux through once a delta exists', () => {
47
+ expect(cpuCapacityFactor('linux', 8, 0.5, true)).toBe(1);
48
+ });
49
+
50
+ it('has no answer for Linux before the second sample', () => {
51
+ expect(cpuCapacityFactor('linux', 8, 0.5, false)).toBeNull();
52
+ });
53
+
54
+ it('divides the per-core macOS reading by the core count', () => {
55
+ expect(cpuCapacityFactor('darwin', 8, null, false)).toBe(1 / 8);
56
+ });
57
+
58
+ it('treats the BSDs like macOS', () => {
59
+ expect(cpuCapacityFactor('freebsd', 4, null, true)).toBe(1 / 4);
60
+ });
61
+
62
+ it('scales Windows by the machine busy fraction', () => {
63
+ expect(cpuCapacityFactor('win32', 8, 0.25, true)).toBe(0.25);
64
+ });
65
+
66
+ it('has no answer for Windows without a busy fraction', () => {
67
+ expect(cpuCapacityFactor('win32', 8, null, true)).toBeNull();
68
+ expect(cpuCapacityFactor('win32', 8, 0.25, false)).toBeNull();
69
+ });
70
+
71
+ it('refuses to divide by a missing core count', () => {
72
+ expect(cpuCapacityFactor('darwin', 0, null, true)).toBeNull();
73
+ });
74
+ });
75
+
76
+ describe('withTimeout', () => {
77
+ it('passes a value through when it beats the deadline', async () => {
78
+ expect(await withTimeout(Promise.resolve(7), 1000)).toBe(7);
79
+ });
80
+
81
+ it('resolves null on timeout when no fallback is given', async () => {
82
+ expect(await withTimeout(new Promise(() => {}), 10)).toBeNull();
83
+ });
84
+
85
+ it('resolves the fallback on timeout when one is given', async () => {
86
+ expect(await withTimeout(new Promise<number>(() => {}), 10, -1)).toBe(-1);
87
+ });
88
+
89
+ it('treats a rejection like a timeout rather than propagating it', async () => {
90
+ expect(await withTimeout(Promise.reject(new Error('nope')), 1000)).toBeNull();
91
+ });
92
+ });
93
+
94
+ describe('getHostFacts', () => {
95
+ it('probes once and hands every caller the same object', async () => {
96
+ const [a, b] = await Promise.all([getHostFacts(), getHostFacts()]);
97
+ expect(a).toBe(b);
98
+ });
99
+
100
+ it('always answers with a usable core count and installed RAM', async () => {
101
+ // Both are denominators: the core count normalises per-process CPU on
102
+ // macOS/BSD, and the RAM total is what "percent of host memory" divides
103
+ // by in Project Info. A zero from a failed probe would poison both.
104
+ const facts = await getHostFacts();
105
+ expect(facts.logicalCores).toBeGreaterThan(0);
106
+ expect(facts.totalMemBytes).toBeGreaterThan(0);
107
+ expect(facts.platform).toBeTruthy();
108
+ expect(facts.arch).toBeTruthy();
109
+ });
110
+ });