feat(web): preview worktree storage before saving cleanup rules #12604
Closedtris203(GitHub profile, opens in a new tab)wants to merge 18 commits into
main fromrefs/pull/12604/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/settings/DaysNumberField.tsx line 55OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +35,21 @@35+ min={min}36+ max={max}37+ step={1}38+ size="sm"39+ className="w-auto"40+ onValueChange={setDraft}41+ onValueCommitted={(next) => {42+ if (next === null) setDraft(value);43+ else {44+ const days = Math.min(max, Math.max(min, Math.round(next)));45+ setDraft(days);46+ onCommit(days);47+ }48+ }}49+ >50+ <NumberFieldGroup>51+ <NumberFieldDecrement aria-label={`Decrease ${label}`} />52+ <NumberFieldInput53+ aria-label={label}54+ size={new Intl.NumberFormat().format(draft ?? value).length}55+ className="field-sizing-content w-auto min-w-[1ch] grow-0 text-right in-data-[size=sm]:px-1"
- apps/web/src/components/settings/StorageCleanupPreview.tsx lines 157 to 159Resolvedby tris203(GitHub profile, opens in a new tab)@@ -0,0 +111,21 @@111+ const incomplete =112+ data &&113+ (data.unchecked > 0 || data.unavailable > 0 || data.total.measured < data.total.folders);114+115+ return (116+ <div className="overflow-hidden rounded-lg border border-border/60" aria-busy={isPending}>117+ <div className="space-y-4 border-b border-border/50 px-4 py-4">118+ <div className="flex items-center justify-between gap-3">119+ <div className="flex min-w-0 items-center gap-3">120+ <div className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-border/60 bg-muted/40">121+ <HardDriveIcon className="size-5 text-muted-foreground" aria-hidden="true" />122+ </div>123+ <div className="min-w-0">124+ <p className="text-sm font-medium">Worktree storage</p>125+ {initialLoading ? (126+ <Skeleton className="mt-1 h-3 w-28" />127+ ) : (128+ <p className="mt-0.5 text-xs text-muted-foreground">129+ {data130+ ? `${data.projectCount.toLocaleString()} ${environments.length > 1 ? "project checkouts" : "projects"}`131+ : "Storage unavailable"}
- apps/server/src/storageCleanupSize.ts lines 22 to 23OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +3,21 @@3+import * as Effect from "effect/Effect";4+import * as Option from "effect/Option";5+import * as Path from "effect/Path";6+7+/** Estimate allocated bytes without following symlinks or counting externally shared hardlinks. */8+export const measureWorktreeBytes = Effect.fn("measureWorktreeBytes")(function* (root: string) {9+ const path = yield* Path.Path;10+ return yield* Effect.tryPromise({11+ try: async (signal) => {12+ const directories = [root];13+ let entries = 0;14+ let bytes = 0;15+ while (directories.length > 0) {16+ const directory = directories.pop()!;17+ for await (const entry of await NodeFSP.opendir(directory)) {18+ signal.throwIfAborted();19+ if (++entries > 20_000) return null;20+ const target = path.join(directory, entry.name);21+ const stat = await NodeFSP.lstat(target);22+ if (stat.isDirectory()) directories.push(target);23+ else if (stat.nlink === 1) bytes += stat.blocks * 512;apps/server/src/storageCleanup.ts lines 249 to 257Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -186,15 +213,20 @@213+ if (deletedThreads.length > 0 && !preview) {186214 // Read tombstones before taking this fence. A later deletion waits for the187215 // next sweep; every captured deletion must finish stopping its resources.188216 const { snapshotSequence } = yield* snapshots.getSnapshotSequence();189217 yield* threadDeletion.drainThrough(snapshotSequence);190218 }191219 const snapshot = yield* readThreads();192220 const root = yield* fs.realPath(config.worktreesDir);221+ const previewRealPaths = preview ? new Map<string, string>() : undefined;222+ const projectsById = new Map(snapshot.projects.map((project) => [project.id, project]));193223 const refreshedDefaultRefs = new Map<string, Set<string>>();194224 const groups = Map.groupBy(195225 snapshot.threads.filter((thread) => thread.worktreePath !== null),196226 (thread) => path.resolve(thread.worktreePath!),197227 );198228 const candidates = [199- ...[...groups.values()].flatMap((group) => (group.length === 1 ? [group[0]!] : [])),229+ ...[...groups.values()].flatMap((group) =>230+ preview || group.length === 1 ? [group[0]!] : [],231+ ),200232 ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath))),
- apps/server/src/storageCleanupSize.ts line 27OutdatedResolvedby tris203(GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+/** Estimate allocated bytes without following symlinks or counting externally shared hardlinks. */8+export const measureWorktreeBytes = Effect.fn("measureWorktreeBytes")(function* (root: string) {9+ const path = yield* Path.Path;10+ return yield* Effect.tryPromise({11+ try: async (signal) => {12+ const directories = [root];13+ let entries = 0;14+ let bytes = 0;15+ while (directories.length > 0) {16+ const directory = directories.pop()!;17+ const directoryStat = await NodeFSP.lstat(directory);18+ if (!directoryStat.isDirectory()) return null;19+ // Directory links include children and parents, not externally shared file data.20+ bytes += directoryStat.blocks * 512;21+ for await (const entry of await NodeFSP.opendir(directory)) {22+ signal.throwIfAborted();23+ if (++entries > 20_000) return null;24+ const target = path.join(directory, entry.name);25+ const stat = await NodeFSP.lstat(target);26+ if (stat.isDirectory()) directories.push(target);27+ else if (stat.nlink === 1) bytes += stat.blocks * 512;
- apps/server/src/storageCleanupSize.ts lines 11 to 14OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,14 @@1+import * as Context from "effect/Context";2+import * as Effect from "effect/Effect";3+import * as Layer from "effect/Layer";4+import * as Option from "effect/Option";5+import * as Pull from "effect/Pull";6+import * as Schema from "effect/Schema";7+import * as Stream from "effect/Stream";8+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";9+import { ResourceMonitorBinary } from "./resourceTelemetry/ResourceMonitorBinary.ts";10+11+export class WorktreeMeasurementError extends Schema.TaggedError<WorktreeMeasurementError>()(12+ "WorktreeMeasurementError",13+ { cause: Schema.Defect() },14+) {}
- apps/server/src/storageCleanup.ts line 759OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -367,0 +739,21 @@739+ settings,740+ at: now,741+ running: true,742+ previous: previewCache.findLast(743+ (entry) => entry.input.projectId === input.projectId && entry.result !== undefined,744+ )?.result,745+ scan: {746+ input,747+ total: undefined,748+ examined: 0,749+ skippedMeasurements: 0,750+ checked: 0,751+ unavailable: 0,752+ folders: [],753+ discovered: false,754+ onFolder: (folder, activity) => measure(folder, activity, input.refreshKey),755+ progress: publish,756+ onDiscovery: publishImmediately,757+ },758+ };759+ if (previewCache.length >= 8) {native/resource-monitor/src/storage_scan.rs line 148OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +128,21 @@128+struct Worker {129+ current: Option<ReadDir>,130+ // A hardlinked file only contributes once all of its links were found in this worktree.131+ linked: HashMap<(u64, u128), (u64, u64, u64)>,132+ bytes: u64,133+}134+135+impl Worker {136+ fn step(137+ &mut self,138+ pending: &Mutex<Vec<PathBuf>>,139+ limit: usize,140+ deadline: Instant,141+ ) -> io::Result<()> {142+ for _ in 0..limit {143+ if let Some(entries) = &mut self.current {144+ if let Some(entry) = entries.next() {145+ let entry = entry?;146+ let path = entry.path();147+ if directory_entry(&entry)? {148+ pending.lock().unwrap().push(path);@@ -367,0 +771,21 @@771+ : {772+ progress: {773+ total: entry.scan.total * 3,774+ completed:775+ entry.scan.examined +776+ entry.scan.skippedMeasurements +777+ entry.scan.checked +778+ entry.scan.folders.filter((folder) => measurements.get(folder.path)?.done).length,779+ },780+ };781+ if (entry.running && !entry.scan.discovered && entry.previous) {782+ const { progress: _progress, ...previous } = entry.previous;783+ return { ...previous, scanning: true, ...progress };784+ }785+ const total = { folders: 0, measured: 0, bytes: 0 };786+ const kinds = ["deleted", "inactive", "merged", "unchanged", "kept", "unchecked"] as const;787+ const categories = kinds.map((kind) => ({ kind, folders: 0, measured: 0, bytes: 0 }));788+ const projectIds = new Set<ProjectId>();789+ let scanning = entry.running;790+ for (const folder of entry.scan.folders) {791+ const inactiveAfterDays =
- apps/server/src/storageCleanupSize.ts line 16OutdatedResolvedby tris203(GitHub profile, opens in a new tab)@@ -0,0 +1,16 @@1+import * as Context from "effect/Context";2+import * as Effect from "effect/Effect";3+import * as Layer from "effect/Layer";4+import * as Option from "effect/Option";5+import * as Pull from "effect/Pull";6+import * as Schema from "effect/Schema";7+import * as Stream from "effect/Stream";8+import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";9+import { ResourceMonitorBinary } from "./resourceTelemetry/ResourceMonitorBinary.ts";10+11+export class WorktreeMeasurementError extends Schema.TaggedError<WorktreeMeasurementError>()(12+ "WorktreeMeasurementError",13+ { cause: Schema.Defect() },14+) {}15+16+const isWorktreeMeasurementError = Schema.is(WorktreeMeasurementError);
- native/resource-monitor/src/storage_scan.rs lines 166 to 199OutdatedResolvedby tris203(GitHub profile, opens in a new tab)@@ -0,0 +179,21 @@179+ .or_insert((0, info.links, info.bytes))180+ .0 += 1;181+ }182+ }183+ } else {184+ self.current = None;185+ }186+ } else {187+ let directory = pending.lock().unwrap().pop();188+ let Some(directory) = directory else {189+ break;190+ };191+ let info = file_info(&directory)?;192+ if !info.directory {193+ return Err(io::Error::other(194+ "queued directory is no longer a directory",195+ ));196+ }197+ directories.lock().unwrap().visit(info.identity)?;198+ self.bytes += info.bytes;199+ self.current = Some(fs::read_dir(directory)?);
- @@ -19,3 +23,5 @@1923 import * as Option from "effect/Option";2024 import * as Path from "effect/Path";2125 import type { PlatformError } from "effect/PlatformError";26+import * as Semaphore from "effect/Semaphore";27+import * as StorageCleanupGit from "./storageCleanupGit.ts";
- apps/server/src/orchestration/PullRequestSyncReactor.ts lines 181 to 191OutdatedResolvedby tris203(GitHub profile, opens in a new tab)@@ -164,0 +171,21 @@171+ for (const thread of [...snapshot.threads, ...archived.threads]) {172+ if (thread.archivedAt !== null && thread.worktreePath === null) continue;173+ const links = [...visibleThreadPullRequests(thread.pullRequests)];174+ const legacy = thread.branchPullRequest;175+ const identity = legacy ? parseChangeRequestUrl(legacy.url) : null;176+ if (177+ legacy &&178+ identity &&179+ !thread.pullRequests.some((link) => threadPullRequestKeysEqual(link, identity))180+ ) {181+ const uuid = yield* crypto.randomUUIDv4;182+ yield* engine.dispatch({183+ type: "thread.pull-request.link",184+ commandId: CommandId.make(`server:legacy-pr-link:${thread.id}:${uuid}`),185+ threadId: thread.id,186+ host: identity.host,187+ repository: identity.repository,188+ number: identity.number,189+ url: legacy.url,190+ source: "agent",191+ });
- native/resource-monitor/src/storage_scan.rs line 186OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +166,21 @@166+ &mut self,167+ pending: &Mutex<Vec<PathBuf>>,168+ directories: &Mutex<Directories>,169+ limit: usize,170+ deadline: Instant,171+ ) -> io::Result<()> {172+ for _ in 0..limit {173+ if Instant::now() >= deadline {174+ break;175+ }176+ if let Some(entries) = &mut self.current {177+ if let Some(entry) = entries.next() {178+ let Some(entry) = skip_missing(entry)? else {179+ continue;180+ };181+ let path = entry.path();182+ let Some(is_directory) = skip_missing(directory_entry(&entry))? else {183+ continue;184+ };185+ if is_directory {186+ pending.lock().unwrap().push(path);native/resource-monitor/src/storage_scan.rs line 152Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +112,21 @@112+ use std::os::windows::fs::MetadataExt;113+ use windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;114+ return Ok(entry.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT.0 == 0);115+ }116+ #[cfg(unix)]117+ Ok(true)118+}119+120+// Files can disappear while a live worktree is being measured.121+fn skip_missing<T>(result: io::Result<T>) -> io::Result<Option<T>> {122+ match result {123+ Ok(value) => Ok(Some(value)),124+ Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),125+ Err(error) => Err(error),126+ }127+}128+129+#[derive(Debug, Serialize)]130+struct Progress {131+ version: u32,132+ bytes: u64,
- @@ -2142,4 +2145,8 @@21422145 });21432146 const branchPullRequest: GitManager["Service"]["branchPullRequest"] = Effect.fn(21442147 "branchPullRequest",2145- )(function* ({ cwd, branch }, options) {2148+ )(function* ({ cwd, branch, reference }, options) {2149+ if (reference !== undefined) {2150+ // Cleanup reads an identified PR afresh, rather than selecting a reused branch's PR.2151+ const latest = toPullRequestInfo(2152+ yield* (yield* sourceControlProvider(cwd)).getChangeRequest({ cwd, reference }),
- apps/server/src/orchestration/PullRequestSyncReactor.ts lines 293 to 297Resolvedby tris203(GitHub profile, opens in a new tab)@@ -242,5 +284,6 @@242284 number: first.link.number,243285 };244286 const generation = requested.get(key);245- if (generation !== undefined) yield* pullRequests.invalidate({ reference: ref });246- const summary = yield* pullRequests.summary(ref, { recoverTransientFailure: false });287+ const needsHeadEvidence = entries.some(288+ (entry) => entry.link.snapshot?.state === "merged" && !entry.link.snapshot.headSha,289+ );apps/server/src/orchestration/PullRequestSyncReactor.ts line 150Resolvedby tris203(GitHub profile, opens in a new tab)@@ -138,4 +140,7 @@138140 const isDue = (key: string, entries: ReadonlyArray<LinkEntry>, nowMs: number): boolean => {139141 if (requested.has(key) || retryStacks.has(key)) return true;140142 if (entries.some((entry) => entry.link.snapshot === null)) return true;141- if (entries.every((entry) => entry.link.snapshot?.state === "merged")) return false;143+ if (entries.every((entry) => entry.link.snapshot?.state === "merged")) {144+ const last = lastSyncedAt.get(key);145+ return (146+ entries.some((entry) => !entry.link.snapshot?.headSha) &&
Sign in to join this conversation.
Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This XXL PR introduces a new production storage-preview workflow, native filesystem scanning, broad cleanup-classification changes, and irreversible deletion of ignored worktree data. It also enables the preview capability by default and changes shared Git/PR behavior, creating a blast radius that warrants human review.
Not approved because:
- 3 blocking correctness issues found at or above your repo's Minimum Blocking Severity
Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).