# #34834 hasWorkTree amendment: measurements

Revisions (local commits; each label in the rows below is `name@sha`):

- `main`: origin/main 0813f4978e.
- `pr`: #34834 head 095acf2d1a, its diff applied onto main.
- `hybrid`: `pr` plus the attached patch.
- `only-37324`: #37324 head d152b1a187, its diff applied onto main.
- `pr+37324-pr-line`: `pr` plus #37324, the `isGitRepository` conflict resolved with #34834's line.
- `pr+37324-their-line`: the same, resolved with #37324's `detectOrFail(...) !== null` line.
- `pr+37324+hasWorkTree`: `pr` plus #37324 plus the `hasWorkTree` field, with
  `isGitRepository` returning `detectOrFail(...)?.repository.hasWorkTree === true`.

The test runs on `TestClock`, so neither the 5-minute positive TTL nor #37324's 30 s negative TTL expires.

## Spawn counts

`probes` counts `GitVcsDriver.detectRepository` and `GitVcsDriver.isInsideWorkTree` spawns; `all` counts
every git process. `status` is the run's capture status and whether `captureBaseline` failed.

```jsonl
{"label":"main@0813f4978e","repoRun1":{"probes":2,"all":28},"repoRun2":{"probes":0,"all":16},"bareRun1":{"probes":6,"all":6},"plainRun1":{"probes":6,"all":6},"plainRun2":{"probes":6,"all":6},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"missing","baselineFailed":false},"plain":{"status":"missing","baselineFailed":false}}}
{"label":"pr@58eb89407a","repoRun1":{"probes":4,"all":30},"repoRun2":{"probes":2,"all":18},"bareRun1":{"probes":3,"all":3},"plainRun1":{"probes":3,"all":3},"plainRun2":{"probes":3,"all":3},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"missing","baselineFailed":false},"plain":{"status":"missing","baselineFailed":false}}}
{"label":"hybrid@d7ccbd7fed","repoRun1":{"probes":2,"all":28},"repoRun2":{"probes":0,"all":16},"bareRun1":{"probes":1,"all":1},"plainRun1":{"probes":3,"all":3},"plainRun2":{"probes":3,"all":3},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"missing","baselineFailed":false},"plain":{"status":"missing","baselineFailed":false}}}
{"label":"only-37324@5f126d5724","repoRun1":{"probes":2,"all":28},"repoRun2":{"probes":0,"all":16},"bareRun1":{"probes":3,"all":3},"plainRun1":{"probes":1,"all":1},"plainRun2":{"probes":0,"all":0},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"missing","baselineFailed":false},"plain":{"status":"missing","baselineFailed":false}}}
{"label":"pr+37324-pr-line@a232aa1255","repoRun1":{"probes":4,"all":30},"repoRun2":{"probes":2,"all":18},"bareRun1":{"probes":3,"all":3},"plainRun1":{"probes":3,"all":3},"plainRun2":{"probes":3,"all":3},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"missing","baselineFailed":false},"plain":{"status":"missing","baselineFailed":false}}}
{"label":"pr+37324-their-line@d0cfaaee74","repoRun1":{"probes":2,"all":28},"repoRun2":{"probes":0,"all":16},"bareRun1":{"probes":2,"all":22},"plainRun1":{"probes":1,"all":1},"plainRun2":{"probes":0,"all":0},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"error","baselineFailed":true},"plain":{"status":"missing","baselineFailed":false}}}
{"label":"pr+37324+hasWorkTree@7eb7e81e3b","repoRun1":{"probes":2,"all":28},"repoRun2":{"probes":0,"all":16},"bareRun1":{"probes":1,"all":1},"plainRun1":{"probes":1,"all":1},"plainRun2":{"probes":0,"all":0},"status":{"repo":{"status":"ready","baselineFailed":false},"bare":{"status":"missing","baselineFailed":false},"plain":{"status":"missing","baselineFailed":false}}}
```

## Spawn benchmark (n = 200, 3 runs)

Produced by `bench/run-bench.sh`, which records `uptime` load averages before and after the three runs. The
machine was running other work, so the event-loop-delay fields are noisy and are not used in the comment.
`cachedFsChecksMs` is a stand-in for a cached detect hit: three parallel `fs.access` calls, not the registry's
own sequential Effect checks.

```text
Apple M4 Max
v26.13.1
git version 2.54.0 (Apple Git-157)
before: 12.44 12.10 13.50
after: 11.80 11.97 13.43
```

Run 1:

```json
{
  "node": "v26.13.1",
  "cwd": "<temp repo with one empty commit>",
  "n": 200,
  "spawnTotalMs": {
    "n": 200,
    "p50": 12.115,
    "p95": 13.759,
    "p99": 36.507,
    "max": 39.21,
    "mean": 12.593
  },
  "spawnSyncBlockingMs": {
    "n": 200,
    "p50": 0.861,
    "p95": 1.019,
    "p99": 6.711,
    "max": 16.235,
    "mean": 0.994
  },
  "cachedFsChecksMs": {
    "n": 200,
    "p50": 0.018,
    "p95": 0.03,
    "p99": 0.09,
    "max": 0.13,
    "mean": 0.02
  },
  "eventLoopDelayDuringSpawnsMs": {
    "p50": 1.268,
    "p99": 2.097,
    "max": 16.359,
    "mean": 1.217
  },
  "eventLoopDelayIdleMs": {
    "p50": 1.268,
    "p99": 1.29,
    "max": 1.355,
    "mean": 1.239
  }
}
```

Run 2:

```json
{
  "node": "v26.13.1",
  "cwd": "<temp repo with one empty commit>",
  "n": 200,
  "spawnTotalMs": {
    "n": 200,
    "p50": 12.305,
    "p95": 13.64,
    "p99": 14.369,
    "max": 14.415,
    "mean": 12.319
  },
  "spawnSyncBlockingMs": {
    "n": 200,
    "p50": 0.864,
    "p95": 1.039,
    "p99": 1.38,
    "max": 1.41,
    "mean": 0.882
  },
  "cachedFsChecksMs": {
    "n": 200,
    "p50": 0.02,
    "p95": 0.041,
    "p99": 0.123,
    "max": 0.179,
    "mean": 0.024
  },
  "eventLoopDelayDuringSpawnsMs": {
    "p50": 1.268,
    "p99": 2.042,
    "max": 2.261,
    "mean": 1.206
  },
  "eventLoopDelayIdleMs": {
    "p50": 1.268,
    "p99": 2.353,
    "max": 6.341,
    "mean": 1.268
  }
}
```

Run 3:

```json
{
  "node": "v26.13.1",
  "cwd": "<temp repo with one empty commit>",
  "n": 200,
  "spawnTotalMs": {
    "n": 200,
    "p50": 12.399,
    "p95": 14.375,
    "p99": 15.876,
    "max": 21.789,
    "mean": 12.635
  },
  "spawnSyncBlockingMs": {
    "n": 200,
    "p50": 0.904,
    "p95": 1.134,
    "p99": 1.321,
    "max": 1.558,
    "mean": 0.925
  },
  "cachedFsChecksMs": {
    "n": 200,
    "p50": 0.018,
    "p95": 0.03,
    "p99": 0.088,
    "max": 0.129,
    "mean": 0.02
  },
  "eventLoopDelayDuringSpawnsMs": {
    "p50": 1.267,
    "p99": 1.616,
    "max": 2.206,
    "mean": 1.192
  },
  "eventLoopDelayIdleMs": {
    "p50": 1.268,
    "p99": 2.077,
    "max": 7.397,
    "mean": 1.257
  }
}
```

## Test logs

`does not checkpoint a bare repository's root, which has no work tree` at `pr+37324-their-line`:

```text
     × does not checkpoint a bare repository's root, which has no work tree 98ms
AssertionError: expected true to be false // Object.is equality
- Expected
+ Received
- false
+ true
      Tests  1 failed | 14 skipped (15)
```

The amendment's `answers a repository's later checks from the cached detection` test, run against `pr`:

```text
   × answers a repository's later checks from the cached detection 80ms
AssertionError: expected [ …(3) ] to deeply equal [ 'GitVcsDriver.detectRepository' ]
- Expected
+ Received
-   "GitVcsDriver.detectRepository",
+   "GitVcsDriver.isInsideWorkTree",
+   "GitVcsDriver.isInsideWorkTree",
+   "GitVcsDriver.isInsideWorkTree",
      Tests  1 failed | 15 skipped (16)
```

## Scripts

`count.sh` (run with `WT=<t3code checkout> count.sh label=rev ...`):

```bash
#!/usr/bin/env bash
# Runs the spawn-count test at each "label=rev" argument, in the worktree given by $WT.
# Usage: WT=<t3code worktree> count.sh main=<rev> pr=<rev> ...
set -u
OUT=$(cd "$(dirname "$0")" && pwd)
: "${WT:?set WT to a t3code worktree with dependencies installed}"
export SPAWN_COUNT_OUT="$OUT/spawn-counts.jsonl"
cd "$WT"
start=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
for arg in "$@"; do
  label=${arg%%=*}; rev=${arg#*=}
  git switch -q --detach "$rev" || exit 1
  cp "$OUT/src/CheckpointSpawnCount.test.ts" apps/server/src/checkpointing/CheckpointSpawnCount.test.ts
  export SPAWN_COUNT_LABEL="$label@$(git rev-parse --short HEAD)"
  log="$OUT/count-$label.log"
  (cd apps/server && vp test run src/checkpointing/CheckpointSpawnCount.test.ts) >"$log" 2>&1
  echo "$SPAWN_COUNT_LABEL: $(tail -1 "$SPAWN_COUNT_OUT") | $(grep -E '^ +Tests ' "$log" | tr -s ' ')"
  rm apps/server/src/checkpointing/CheckpointSpawnCount.test.ts
done
git switch -q "$start"
```

`CheckpointSpawnCount.test.ts`, copied into `apps/server/src/checkpointing/` for each run:

```ts
// Counts the git spawns one run's checkpoint calls make: repository probes and all git processes.
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFs from "node:fs";
import * as NodePath from "node:path";

import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
  CheckpointScopeId,
  NodeId,
  ProviderThreadId,
  RunId,
  ThreadId,
  type OrchestrationV2CheckpointScope,
} from "@t3tools/contracts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";

import * as CheckpointService from "../orchestration-v2/CheckpointService.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import * as CheckpointStore from "./CheckpointStore.ts";

const PROBES = new Set(["GitVcsDriver.detectRepository", "GitVcsDriver.isInsideWorkTree"]);

const makeLayer = (spawns: Array<string>) => {
  const layerRealProcess = VcsProcess.layer.pipe(
    Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
  );
  const layerCountingProcess = Layer.effect(
    VcsProcess.VcsProcess,
    Effect.map(VcsProcess.VcsProcess, (real) =>
      VcsProcess.VcsProcess.of({
        run: (input) => {
          spawns.push(input.operation);
          return real.run(input);
        },
      }),
    ),
  ).pipe(Layer.provide(layerRealProcess));
  const layerRegistry = VcsDriverRegistry.layer.pipe(Layer.provide(layerCountingProcess));
  const layerStore = CheckpointStore.layer.pipe(
    Layer.provideMerge(layerRegistry),
    Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
  );
  return CheckpointService.layer.pipe(
    Layer.provideMerge(layerStore),
    Layer.provideMerge(Layer.mergeAll(IdAllocator.layer, NodeCrypto.layer)),
    Layer.provideMerge(layerCountingProcess),
    Layer.provideMerge(NodeServices.layer),
  );
};

const scopeAt = (cwd: string): OrchestrationV2CheckpointScope => ({
  id: CheckpointScopeId.make("checkpoint-scope:spawn-count"),
  threadId: ThreadId.make("thread:spawn-count"),
  runId: RunId.make("run:spawn-count:1"),
  nodeId: NodeId.make("node:spawn-count:1"),
  parentScopeId: null,
  providerThreadId: ProviderThreadId.make("provider-thread:spawn-count"),
  kind: "root_run",
  ordinalWithinParent: 0,
  advancesAppRunCount: true,
  cwd,
  createdAt: DateTime.makeUnsafe("2026-07-28T00:00:00.000Z"),
});

const git = (cwd: string, args: ReadonlyArray<string>) =>
  Effect.flatMap(VcsProcess.VcsProcess, (process) =>
    process.run({ operation: "test.git", command: "git", cwd, args, timeoutMs: 10_000 }),
  );

// The calls CheckpointCaptureService and RunExecutionService make for run N.
const runCheckpoints = (scope: OrchestrationV2CheckpointScope, ordinal: number, first: boolean) =>
  Effect.gen(function* () {
    const checkpoints = yield* CheckpointService.CheckpointServiceV2;
    const capturedAt = yield* DateTime.now;
    // Recorded rather than raised, so a variant that tries to checkpoint a bare root still reports.
    const baseline = yield* Effect.exit(
      checkpoints.captureBaseline({ scope, ordinalWithinScope: ordinal - 1 }),
    );
    // A first run materializes its baseline; later runs find it preserved.
    if (first)
      yield* checkpoints.materializeBaselineCheckpoint({
        scope,
        ordinalWithinScope: 0,
        nodeId: scope.nodeId,
        capturedAt,
      });
    const captured = yield* checkpoints.capture({
      scope,
      runId: scope.runId!,
      nodeId: scope.nodeId,
      ordinalWithinScope: ordinal,
      appRunOrdinal: ordinal,
      capturedAt,
    });
    return { status: captured.status, baselineFailed: Exit.isFailure(baseline) };
  });

const count = (spawns: Array<string>, from: number) => {
  const slice = spawns.slice(from);
  return { probes: slice.filter((op) => PROBES.has(op)).length, all: slice.length };
};

it.effect("counts git spawns per run for a normal repository and a bare repository's root", () => {
  const spawns: Array<string> = [];
  return Effect.gen(function* () {
    const fileSystem = yield* FileSystem.FileSystem;
    const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "spawn-count-repo-" });
    yield* git(repo, ["init", "--initial-branch=main"]);
    yield* git(repo, ["config", "user.email", "test@test.com"]);
    yield* git(repo, ["config", "user.name", "Test"]);
    yield* fileSystem.writeFileString(NodePath.join(repo, "README.md"), "# test\n");
    yield* git(repo, ["add", "."]);
    yield* git(repo, ["commit", "-m", "Initial"]);

    const bare = yield* fileSystem.makeTempDirectoryScoped({ prefix: "spawn-count-bare-" });
    yield* git(bare, ["clone", "--bare", repo, ".bare"]);
    yield* fileSystem.writeFileString(NodePath.join(bare, ".git"), "gitdir: ./.bare\n");

    const repoScope = scopeAt(repo);
    let mark = spawns.length;
    const run1 = yield* runCheckpoints(repoScope, 1, true);
    const repoRun1 = count(spawns, mark);
    mark = spawns.length;
    yield* runCheckpoints(repoScope, 2, false);
    const repoRun2 = count(spawns, mark);

    const bareScope = scopeAt(bare);
    mark = spawns.length;
    const bareRun1 = yield* runCheckpoints(bareScope, 1, true);
    const bareCounts = count(spawns, mark);

    // A folder with no repository, such as a Scratch thread's: its unready baseline is not
    // preserved, so every run materializes it again.
    const plain = yield* fileSystem.makeTempDirectoryScoped({ prefix: "spawn-count-plain-" });
    const plainScope = scopeAt(plain);
    mark = spawns.length;
    const plainRun1 = yield* runCheckpoints(plainScope, 1, true);
    const plainCounts1 = count(spawns, mark);
    mark = spawns.length;
    yield* runCheckpoints(plainScope, 2, true);
    const plainCounts2 = count(spawns, mark);

    const status = { repo: run1, bare: bareRun1, plain: plainRun1 };
    NodeFs.appendFileSync(
      process.env.SPAWN_COUNT_OUT!,
      JSON.stringify({ label: process.env.SPAWN_COUNT_LABEL, repoRun1, repoRun2, bareRun1: bareCounts, plainRun1: plainCounts1, plainRun2: plainCounts2, status }) + "\n",
    );
    assert.deepEqual(status.repo, { status: "ready", baselineFailed: false });
    // A bare root has no work tree: checkpoints are skipped, not failed.
    assert.deepEqual(status.bare, { status: "missing", baselineFailed: false });
    assert.deepEqual(status.plain, { status: "missing", baselineFailed: false });
  }).pipe(Effect.scoped, Effect.provide(makeLayer(spawns)));
});
```

`run-bench.sh`:

```bash
#!/usr/bin/env bash
# Times the work-tree probe spawn three times and records machine load before and after.
set -eu
OUT=$(cd "$(dirname "$0")/.." && pwd)
REPO="$OUT/bench/repo"
rm -rf "$REPO" && git init -q -b main "$REPO"
git -C "$REPO" -c user.email=t@t -c user.name=t commit -q --allow-empty -m init
{ echo "before: $(uptime | sed 's/.*load averages*: //')"; } > "$OUT/spawn-bench-load.txt"
for i in 1 2 3; do node "$OUT/bench/spawn-bench.mjs" "$REPO" 200 > "$OUT/spawn-bench-run$i.json"; done
{ echo "after: $(uptime | sed 's/.*load averages*: //')"; } >> "$OUT/spawn-bench-load.txt"
{ sysctl -n machdep.cpu.brand_string; node --version; git --version; } > "$OUT/spawn-bench-env.txt"
```

`spawn-bench.mjs` (run with `node spawn-bench.mjs <repo> 200`):

```js
// Cost of `git rev-parse --is-inside-work-tree` via child_process.spawn vs the cached detect's fs checks.
// Usage: node spawn-bench.mjs <repoDir> [n=200]
import { spawn } from "node:child_process";
import { access } from "node:fs/promises";
import { join } from "node:path";
import { monitorEventLoopDelay } from "node:perf_hooks";

const cwd = process.argv[2];
const n = Number(process.argv[3] ?? 200);
const ms = (ns) => Number(ns) / 1e6;
const stats = (xs) => {
  const s = [...xs].sort((a, b) => a - b);
  const q = (p) => s[Math.min(s.length - 1, Math.floor(p * s.length))];
  return { n: s.length, p50: q(0.5), p95: q(0.95), p99: q(0.99), max: s.at(-1), mean: s.reduce((a, b) => a + b, 0) / s.length };
};
const fmt = (o) => Object.fromEntries(Object.entries(o).map(([k, v]) => [k, k === "n" ? v : Number(v.toFixed(3))]));

function revParse() {
  return new Promise((resolve, reject) => {
    const t0 = process.hrtime.bigint();
    const child = spawn("git", ["-C", cwd, "rev-parse", "--is-inside-work-tree"], {
      cwd: process.cwd(),
      env: { ...process.env, LC_ALL: "C" },
      stdio: ["ignore", "pipe", "pipe"],
    });
    const t1 = process.hrtime.bigint(); // spawn() returned: this part blocks the event loop
    let out = "";
    child.stdout.on("data", (d) => (out += d));
    child.on("error", reject);
    child.on("close", (code) => {
      const t2 = process.hrtime.bigint();
      if (code !== 0 || out.trim() !== "true") return reject(new Error(`unexpected: ${code} ${out}`));
      resolve({ syncMs: ms(t1 - t0), totalMs: ms(t2 - t0) });
    });
  });
}

async function cachedChecks() {
  // VcsDriverRegistry.detect on a hit at the repo root: exists(<cwd>/.git), exists(cwd), exists(metadataPath).
  const t0 = process.hrtime.bigint();
  await Promise.all([access(join(cwd, ".git")), access(cwd), access(join(cwd, ".git"))]);
  return ms(process.hrtime.bigint() - t0);
}

for (let i = 0; i < 10; i++) await revParse(); // warm up

const idle = monitorEventLoopDelay({ resolution: 1 });
idle.enable();
await new Promise((r) => setTimeout(r, 2000));
idle.disable();

const eld = monitorEventLoopDelay({ resolution: 1 });
eld.enable();
const sync = [], total = [];
for (let i = 0; i < n; i++) {
  const r = await revParse();
  sync.push(r.syncMs);
  total.push(r.totalMs);
}
eld.disable();

const cached = [];
for (let i = 0; i < n; i++) cached.push(await cachedChecks());

const eldStats = (h) => ({ p50: h.percentile(50) / 1e6, p99: h.percentile(99) / 1e6, max: h.max / 1e6, mean: h.mean / 1e6 });
console.log(JSON.stringify({
  node: process.version, cwd, n,
  spawnTotalMs: fmt(stats(total)),
  spawnSyncBlockingMs: fmt(stats(sync)),
  cachedFsChecksMs: fmt(stats(cached)),
  eventLoopDelayDuringSpawnsMs: fmt(eldStats(eld)),
  eventLoopDelayIdleMs: fmt(eldStats(idle)),
}, null, 2));
```
