dsh-remote-vs 0.29.0 → 0.30.0

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.
@@ -41,6 +41,7 @@ import type { RemotePool } from '../pool.ts'
41
41
  import type { RemoteWorlds, WorldRoute } from '../p2/worlds.ts'
42
42
  import {
43
43
  excludeDirNames,
44
+ isUntrackedDirectoryPath,
44
45
  parseReads,
45
46
  parseStatusZ,
46
47
  parseUntrackedZ,
@@ -50,12 +51,26 @@ import {
50
51
  trackedStatusCommand,
51
52
  UNTRACKED_EXCLUDED_DIRECTORIES,
52
53
  untrackedCommand,
54
+ untrackedExpandCommand,
53
55
  type ChangeStatus,
54
56
  type ReadResult,
55
57
  type StatusEntry,
56
58
  } from './status.ts'
57
59
  import { diffText, filePatch, hunkPatch, type TextHunk } from './text-diff.ts'
58
60
 
61
+ /**
62
+ * How many collapsed directories one untracked scan will expand.
63
+ *
64
+ * The fast walk (`--directory`) answers in one command no matter how many
65
+ * untracked directories there are; expanding each one is another `git ls-files`
66
+ * on the SAME shared connection, so the count has to be bounded. Twenty is the
67
+ * budget that keeps a normal monorepo complete (a session creates a handful of
68
+ * directories) while a checkout full of un-ignored build output stops early and
69
+ * says so (`truncated`), instead of turning one background scan into hundreds of
70
+ * exec channels.
71
+ */
72
+ export const UNTRACKED_EXPAND_DIRS = 20
73
+
59
74
  /** The two facts a turn boundary needs from a Session, kept cordis-free. */
60
75
  export interface LedgerTarget {
61
76
  sessionId: string
@@ -362,6 +377,16 @@ interface Ledger {
362
377
  tracked: StatusEntry[]
363
378
  /** Latest untracked scan; undefined until the first one lands. */
364
379
  untracked: StatusEntry[] | undefined
380
+ /**
381
+ * The latest untracked list is INCOMPLETE on purpose.
382
+ *
383
+ * Set when the expansion of `--directory` entries hit its bounds — more
384
+ * directories than {@link UNTRACKED_EXPAND_DIRS}, the file cap, the scan's
385
+ * deadline, or a failed expansion. Folded into the published `truncated` flag
386
+ * so the panel says "the list is short" instead of presenting a bounded answer
387
+ * as the whole truth.
388
+ */
389
+ untrackedTruncated: boolean
365
390
  /** When the last untracked scan STARTED, for the cadence. */
366
391
  untrackedAt: number
367
392
  /** How long the last completed untracked scan took, for the cadence. */
@@ -964,6 +989,7 @@ export class SessionChanges {
964
989
  ledger.adoptedSubdir = false
965
990
  ledger.tracked = []
966
991
  ledger.untracked = undefined
992
+ ledger.untrackedTruncated = false
967
993
  ledger.untrackedAt = 0
968
994
  ledger.untrackedMs = undefined
969
995
  // The self-heal window describes THIS tree's scan cost; another root may be
@@ -1069,6 +1095,7 @@ export class SessionChanges {
1069
1095
  subdir: '',
1070
1096
  tracked: [],
1071
1097
  untracked: undefined,
1098
+ untrackedTruncated: false,
1072
1099
  untrackedAt: 0,
1073
1100
  untrackedMs: undefined,
1074
1101
  scanMs: undefined,
@@ -1172,7 +1199,11 @@ export class SessionChanges {
1172
1199
  const entries = [...merged.values()].sort((left, right) => left.path.localeCompare(right.path))
1173
1200
  const cap = this.deps.maxFiles ?? 500
1174
1201
  const listed = entries.slice(0, cap)
1175
- const truncated = entries.length > cap
1202
+ // The untracked list can be short for a reason of its own: its expansion phase
1203
+ // is bounded (`UNTRACKED_EXPAND_DIRS`/cap/deadline). Reporting that as
1204
+ // `truncated` keeps the panel honest — a bounded answer presented as complete
1205
+ // would read as "the session created nothing else".
1206
+ const truncated = entries.length > cap || ledger.untrackedTruncated
1176
1207
 
1177
1208
  if (!ledger.baselineTaken) {
1178
1209
  // First observation: everything dirty RIGHT NOW predates this ledger, so
@@ -1769,6 +1800,11 @@ export class SessionChanges {
1769
1800
  * runs twice at once, and only runs again after {@link untrackedCadence}. A
1770
1801
  * repository that cannot answer inside {@link untrackedBudget} is written off
1771
1802
  * for the session (`untrackedGivenUp`) rather than retried every turn.
1803
+ *
1804
+ * Two phases since the scan learned `--directory`: one fast walk that collapses
1805
+ * untracked directories (`build/` instead of 3000 paths) and then a BOUNDED
1806
+ * expansion of the collapsed entries, because the panel's contract is a list of
1807
+ * FILES. A walk that already answered with files expands nothing at all.
1772
1808
  */
1773
1809
  private async kickUntracked(ledger: Ledger): Promise<void> {
1774
1810
  if (ledger.disposed || ledger.untrackedGivenUp || ledger.untrackedJob !== undefined) return
@@ -1778,14 +1814,23 @@ export class SessionChanges {
1778
1814
  // merge the previous tree's names into the new one.
1779
1815
  const root = ledger.root
1780
1816
  ledger.untrackedAt = Date.now()
1817
+ // One deadline for BOTH phases: the bound that matters is how long this scan
1818
+ // holds an exec channel on the shared connection, not how long one command of
1819
+ // it takes.
1820
+ const deadline = ledger.untrackedAt + this.untrackedBudget()
1781
1821
  const job = (async () => {
1782
1822
  const started = Date.now()
1783
- const scan = await this.run(ledger.alias, untrackedCommand(root, this.excludedDirs()), this.untrackedBudget())
1784
- ledger.untrackedMs = Date.now() - started
1823
+ const excluded = this.excludedDirs()
1824
+ const scan = await this.run(ledger.alias, untrackedCommand(root, excluded), Math.max(1, deadline - Date.now()))
1785
1825
  if (ledger.disposed) return
1786
1826
  if (ledger.root !== root) return
1787
1827
  if (!scan.ok) {
1828
+ ledger.untrackedMs = Date.now() - started
1788
1829
  ledger.untrackedGivenUp = true
1830
+ // A walk that failed says nothing about HOW COMPLETE the previous one
1831
+ // was: leaving the old verdict behind would keep the panel claiming a
1832
+ // partial list it can no longer justify.
1833
+ ledger.untrackedTruncated = false
1789
1834
  // Keep WHY: the panel can show it, and its absence would make a dead
1790
1835
  // capability look like "this session created no files".
1791
1836
  ledger.untrackedFailure = scan.reason
@@ -1793,7 +1838,14 @@ export class SessionChanges {
1793
1838
  return
1794
1839
  }
1795
1840
  ledger.untrackedFailure = undefined
1796
- ledger.untracked = parseUntrackedZ(scan.stdout)
1841
+ const expanded = await this.expandUntracked(ledger, root, parseUntrackedZ(scan.stdout), excluded, deadline)
1842
+ if (ledger.disposed) return
1843
+ if (ledger.root !== root) return
1844
+ // The cadence backs off on what the scan COSTS, and both phases are that
1845
+ // cost — a fast walk followed by twenty expansions is not a 0.2s scan.
1846
+ ledger.untrackedMs = Date.now() - started
1847
+ ledger.untracked = expanded.entries
1848
+ ledger.untrackedTruncated = expanded.truncated
1797
1849
  await this.absorbPreExisting(ledger)
1798
1850
  // A completed scan is worth one more publish: it is the only source of
1799
1851
  // "a file appeared" rows — and of the per-turn delta that must include
@@ -1805,6 +1857,75 @@ export class SessionChanges {
1805
1857
  ledger.untrackedJob = job
1806
1858
  }
1807
1859
 
1860
+ /**
1861
+ * Turn the fast walk's collapsed directories back into files, within bounds.
1862
+ *
1863
+ * Bounded THREE ways, because every expansion is another `git ls-files` on the
1864
+ * same shared connection and the scan runs in the background where nobody is
1865
+ * watching:
1866
+ *
1867
+ * - at most {@link UNTRACKED_EXPAND_DIRS} directories, sorted first so the
1868
+ * choice is deterministic (a rescan of an unchanged tree expands the same
1869
+ * ones, and the gate can pin exactly which);
1870
+ * - the same file cap the panel lists (`maxFiles`, 500 by default), so one
1871
+ * huge directory cannot push the list past what is displayable;
1872
+ * - the fast walk's own deadline: when it runs out the phase stops.
1873
+ *
1874
+ * Hitting any of them — or an expansion that fails — marks the result
1875
+ * `truncated` instead of returning a short list silently. A failed expansion is
1876
+ * NOT `untrackedGivenUp`: the fast walk answered, so new-file detection still
1877
+ * works; only part of it is missing.
1878
+ *
1879
+ * @returns the file entries (walk files + expanded ones) and whether the list
1880
+ * is incomplete.
1881
+ */
1882
+ private async expandUntracked(
1883
+ ledger: Ledger,
1884
+ root: string,
1885
+ walked: readonly StatusEntry[],
1886
+ excludeDirs: readonly string[],
1887
+ deadline: number,
1888
+ ): Promise<{ entries: StatusEntry[]; truncated: boolean }> {
1889
+ const entries = walked.filter(entry => !isUntrackedDirectoryPath(entry.path))
1890
+ const dirs = walked
1891
+ .filter(entry => isUntrackedDirectoryPath(entry.path))
1892
+ .map(entry => entry.path.replace(/\/+$/, ''))
1893
+ .filter(path => path !== '')
1894
+ .sort()
1895
+ // Nothing collapsed (no untracked directory at all): the walk's answer IS the
1896
+ // answer, and this costs zero extra commands.
1897
+ if (dirs.length === 0) return { entries, truncated: false }
1898
+
1899
+ // ONE command for every directory (see `untrackedExpandCommand`): a directory
1900
+ // that only holds ignored or nothing at all then costs nothing, and cannot
1901
+ // push a real directory out of the budget below.
1902
+ const cap = this.deps.maxFiles ?? 500
1903
+ let truncated = dirs.length > UNTRACKED_EXPAND_DIRS
1904
+ const pending = dirs.slice(0, UNTRACKED_EXPAND_DIRS)
1905
+ const remaining = deadline - Date.now()
1906
+ if (remaining <= 0) {
1907
+ this.warn(`untracked expansion ran out of its budget before asking about ${pending.length} directories`)
1908
+ return { entries, truncated: true }
1909
+ }
1910
+ const result = await this.run(ledger.alias, untrackedExpandCommand(root, pending, excludeDirs), remaining)
1911
+ if (ledger.disposed || ledger.root !== root) return { entries, truncated: true }
1912
+ if (!result.ok) {
1913
+ this.warn(`expanding ${pending.length} untracked directories failed (${result.reason}); new files under them are not listed`)
1914
+ return { entries, truncated: true }
1915
+ }
1916
+ const seen = new Set(entries.map(entry => entry.path))
1917
+ for (const entry of parseUntrackedZ(result.stdout)) {
1918
+ if (seen.has(entry.path)) continue
1919
+ seen.add(entry.path)
1920
+ entries.push(entry)
1921
+ if (entries.length >= cap) {
1922
+ truncated = true
1923
+ break
1924
+ }
1925
+ }
1926
+ return { entries, truncated }
1927
+ }
1928
+
1808
1929
  /**
1809
1930
  * How long before the untracked scan may run again.
1810
1931
  *
@@ -1908,12 +2029,22 @@ export class SessionChanges {
1908
2029
  return parseReads(result.stdout)
1909
2030
  }
1910
2031
 
1911
- /** Run one command on the host, normalizing failure into a reason string. */
2032
+ /**
2033
+ * Run one command on the host, normalizing failure into a reason string.
2034
+ *
2035
+ * Every command this ledger issues is a git command (a repository read: `git
2036
+ * status`, the untracked walk, its expansion, the file-content reads — the
2037
+ * recorder never mutates). So they all spend the host's git-command budget
2038
+ * (`lane: 'git'`) instead of a shared exec slot: these scans run in the HOST
2039
+ * process while the user is working, and a 300-second `git status` must not be
2040
+ * the reason a monitor sample, the process panel or an agent tool answers
2041
+ * "host is busy".
2042
+ */
1912
2043
  private async run(alias: string, command: string, budget = this.execBudget()): Promise<
1913
2044
  { ok: true; stdout: string } | { ok: false; reason: string; code?: number | null }
1914
2045
  > {
1915
2046
  try {
1916
- const call = this.deps.pool.exec(alias, command, { timeoutMs: budget })
2047
+ const call = this.deps.pool.exec(alias, command, { timeoutMs: budget, lane: 'git' })
1917
2048
  const result = await this.withWatchdog(call, budget + Math.min(WATCHDOG_GRACE_MS, budget))
1918
2049
  if (result === WATCHDOG_FIRED) {
1919
2050
  // The host call never came back. Measured: `git ls-files --others` on a
@@ -1948,19 +2079,24 @@ export class SessionChanges {
1948
2079
  return this.budget(this.deps.timeouts().gitMs, 5_000, 60_000)
1949
2080
  }
1950
2081
 
1951
- /** The untracked scan gets its own, more generous budget. */
1952
2082
  /**
1953
- * The untracked scan gets its own, much more generous budget.
2083
+ * The untracked scan gets its own, more generous budget — one minute.
2084
+ *
2085
+ * The walk is proportional to the whole checkout, not to the session, so it
2086
+ * cannot use the ordinary git budget. It used to be three minutes; that ceiling
2087
+ * was set before the scan learned `--directory`, when a monorepo's answer really
2088
+ * could take that long. Now the fast walk collapses whole directories, so a
2089
+ * minute is already several times the useful wait, and every second past it is
2090
+ * spent holding an exec channel on the SHARED connection while the tree is
2091
+ * still being walked for nothing. Past a minute the honest answer is "this host
2092
+ * cannot enumerate new files quickly enough" — `untrackedFailure` says so and the
2093
+ * panel offers a retry, which is the same contract as before, just cut shorter.
1954
2094
  *
1955
- * Three minutes is a deliberate choice for a monorepo: the walk is proportional
1956
- * to the whole checkout, not to the session, and the reference AOSP tree has
1957
- * been measured past a minute cold. Waiting is acceptable here because the
1958
- * scan runs in the background and the tracked changes are already on screen;
1959
- * giving up early is not, because the files a session creates with a shell
1960
- * command are visible ONLY through this scan.
2095
+ * The floor (10s) is untouched: a small repository must never be cut off by a
2096
+ * tiny configured `gitMs`.
1961
2097
  */
1962
2098
  private untrackedBudget(): number {
1963
- return this.deps.untrackedBudgetMs ?? this.budget(this.deps.timeouts().gitMs, 10_000, 180_000)
2099
+ return this.deps.untrackedBudgetMs ?? this.budget(this.deps.timeouts().gitMs, 10_000, 60_000)
1964
2100
  }
1965
2101
 
1966
2102
  /**
@@ -229,13 +229,24 @@ export function excludeDirNames(dirs: readonly string[] | undefined): string[] {
229
229
  /**
230
230
  * New files git is not tracking yet (the ones a session usually creates).
231
231
  *
232
+ * `--directory` is the load-bearing flag. Without it git descends into every
233
+ * untracked directory and prints one path per FILE: measured on the reference
234
+ * monorepo that is 11.25s warm, and on a cold AOSP checkout past a minute. With
235
+ * it, an untracked directory is reported ONCE as `dir/` (trailing slash) and git
236
+ * stops descending — a build tree or an un-ignored dependency tree costs one
237
+ * record instead of thousands of `stat`s. The scan still has to walk the tracked
238
+ * part of the tree, but the expensive half is exactly the part that is skipped.
239
+ *
240
+ * The semantic cost is that the answer now names directories; the caller expands
241
+ * the ones it still wants files for with {@link untrackedExpandCommand}, within
242
+ * bounds of its own (see `UNTRACKED_EXPAND_DIRS` in `recorder.ts`). A file that
243
+ * git reports directly is already the final answer.
244
+ *
232
245
  * The exclusions are pushed down as pathspecs (`:(exclude)out`) rather than
233
246
  * filtered after the fact, so those paths never cross the wire and never enter
234
247
  * the 500-row cap. Measured on a tree with 3000 build outputs + 300 sources:
235
248
  * 3300 records / 61.5 KB unfiltered versus 300 records / 6.8 KB with two
236
- * exclusions — the walk itself costs the same either way (git still descends
237
- * those directories), so the win is wire bytes, parse time and the read budget,
238
- * not scan latency.
249
+ * exclusions.
239
250
  *
240
251
  * @param root - remote absolute POSIX directory (the session cwd).
241
252
  * @param excludeDirs - directory names to leave out (see {@link excludeDirNames}).
@@ -244,7 +255,51 @@ export function excludeDirNames(dirs: readonly string[] | undefined): string[] {
244
255
  export function untrackedCommand(root: string, excludeDirs: readonly string[] = []): string {
245
256
  const excludes = excludeDirNames(excludeDirs).map(name => shq(`:(exclude)${name}`))
246
257
  const pathspec = ['--', '.', ...excludes].join(' ')
247
- return [cdLine(root), `git ls-files --others --exclude-standard -z ${pathspec}`].join('\n')
258
+ return [cdLine(root), `git ls-files --others --exclude-standard -z --directory ${pathspec}`].join('\n')
259
+ }
260
+
261
+ /**
262
+ * Whether a `--directory` record names a collapsed DIRECTORY.
263
+ *
264
+ * git marks one with a trailing slash; a record without it is a file, which is
265
+ * already the final answer and must not be expanded again.
266
+ */
267
+ export function isUntrackedDirectoryPath(path: string): boolean {
268
+ return path.endsWith('/')
269
+ }
270
+
271
+ /**
272
+ * List the files inside EVERY directory a {@link untrackedCommand} walk
273
+ * collapsed, in ONE command.
274
+ *
275
+ * Same walk, same exclusions, minus `--directory`: the caller gets file paths
276
+ * again. One command for all of them on purpose — git also collapses directories
277
+ * that hold nothing but IGNORED files (`build/` full of gitignored output) and
278
+ * empty ones, so a per-directory loop would spend a whole round trip (and one of
279
+ * the expansion slots) proving that such a directory has no visible file inside.
280
+ * Batched, an empty directory costs nothing and cannot push a real one out of
281
+ * the slot budget.
282
+ *
283
+ * Every directory comes from git's own output, but each still crosses a shell, so
284
+ * each goes through {@link shq} — a directory named `it's a 目录` is one quoted
285
+ * argument, never a second command or a flag.
286
+ *
287
+ * The trailing slash the fast walk adds is dropped: the pathspec names the
288
+ * directory either way, and a bare path keeps this builder from ever emitting
289
+ * `-- ''` (which would mean "the whole repository").
290
+ *
291
+ * @param root - remote absolute POSIX directory (the session cwd).
292
+ * @param dirs - collapsed directories from {@link untrackedCommand}, with or
293
+ * without their trailing slashes.
294
+ * @param excludeDirs - the same exclusions the fast walk used (nested build
295
+ * output inside a collapsed directory must stay out too).
296
+ */
297
+ export function untrackedExpandCommand(root: string, dirs: readonly string[], excludeDirs: readonly string[] = []): string {
298
+ const targets = dirs.map(dir => dir.replace(/\/+$/, '')).filter(dir => dir !== '')
299
+ if (targets.length === 0) throw new Error('untracked expand needs at least one directory path')
300
+ const excludes = excludeDirNames(excludeDirs).map(name => shq(`:(exclude)${name}`))
301
+ const pathspec = [...targets.map(dir => shq(dir)), ...excludes].join(' ')
302
+ return [cdLine(root), `git ls-files --others --exclude-standard -z -- ${pathspec}`].join('\n')
248
303
  }
249
304
 
250
305
  /**