@hearsay-tools/squawk 0.18.0-dev.6865 → 0.18.0-dev.6870

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.
@@ -4794,6 +4794,19 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
4794
4794
  } & {
4795
4795
  "/repo/commit/:sha": {
4796
4796
  $get: {
4797
+ output: string;
4798
+ outputFormat: "text";
4799
+ status: import("hono/utils/http-status").ContentfulStatusCode;
4800
+ input: {
4801
+ query: {
4802
+ structured?: string | undefined;
4803
+ };
4804
+ } & {
4805
+ param: {
4806
+ sha: string;
4807
+ };
4808
+ };
4809
+ } | {
4797
4810
  output: {
4798
4811
  error: string;
4799
4812
  code?: "invalid_input" | undefined;
@@ -4857,19 +4870,6 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
4857
4870
  sha: string;
4858
4871
  };
4859
4872
  };
4860
- } | {
4861
- output: string;
4862
- outputFormat: "text";
4863
- status: import("hono/utils/http-status").ContentfulStatusCode;
4864
- input: {
4865
- query: {
4866
- structured?: string | undefined;
4867
- };
4868
- } & {
4869
- param: {
4870
- sha: string;
4871
- };
4872
- };
4873
4873
  };
4874
4874
  };
4875
4875
  } & {
@@ -18246,20 +18246,20 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
18246
18246
  } & {
18247
18247
  "/runs/:id/handoff": {
18248
18248
  $get: {
18249
- output: {
18250
- error: string;
18251
- };
18252
- outputFormat: "json";
18253
- status: 404;
18249
+ output: string;
18250
+ outputFormat: "text";
18251
+ status: 200;
18254
18252
  input: {
18255
18253
  param: {
18256
18254
  id: string;
18257
18255
  };
18258
18256
  };
18259
18257
  } | {
18260
- output: string;
18261
- outputFormat: "text";
18262
- status: 200;
18258
+ output: {
18259
+ error: string;
18260
+ };
18261
+ outputFormat: "json";
18262
+ status: 404;
18263
18263
  input: {
18264
18264
  param: {
18265
18265
  id: string;
@@ -18297,20 +18297,20 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
18297
18297
  } & {
18298
18298
  "/runs/:id/diff": {
18299
18299
  $get: {
18300
- output: {
18301
- error: string;
18302
- };
18303
- outputFormat: "json";
18304
- status: 404 | 409;
18300
+ output: string;
18301
+ outputFormat: "text";
18302
+ status: import("hono/utils/http-status").ContentfulStatusCode;
18305
18303
  input: {
18306
18304
  param: {
18307
18305
  id: string;
18308
18306
  };
18309
18307
  };
18310
18308
  } | {
18311
- output: string;
18312
- outputFormat: "text";
18313
- status: import("hono/utils/http-status").ContentfulStatusCode;
18309
+ output: {
18310
+ error: string;
18311
+ };
18312
+ outputFormat: "json";
18313
+ status: 404 | 409;
18314
18314
  input: {
18315
18315
  param: {
18316
18316
  id: string;
@@ -20603,6 +20603,19 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
20603
20603
  } & {
20604
20604
  "/repo/commit/:sha": {
20605
20605
  $get: {
20606
+ output: string;
20607
+ outputFormat: "text";
20608
+ status: import("hono/utils/http-status").ContentfulStatusCode;
20609
+ input: {
20610
+ query: {
20611
+ structured?: string | undefined;
20612
+ };
20613
+ } & {
20614
+ param: {
20615
+ sha: string;
20616
+ };
20617
+ };
20618
+ } | {
20606
20619
  output: {
20607
20620
  error: string;
20608
20621
  code?: "invalid_input" | undefined;
@@ -20666,19 +20679,6 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
20666
20679
  sha: string;
20667
20680
  };
20668
20681
  };
20669
- } | {
20670
- output: string;
20671
- outputFormat: "text";
20672
- status: import("hono/utils/http-status").ContentfulStatusCode;
20673
- input: {
20674
- query: {
20675
- structured?: string | undefined;
20676
- };
20677
- } & {
20678
- param: {
20679
- sha: string;
20680
- };
20681
- };
20682
20682
  };
20683
20683
  };
20684
20684
  } & {
@@ -34055,20 +34055,20 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
34055
34055
  } & {
34056
34056
  "/runs/:id/handoff": {
34057
34057
  $get: {
34058
- output: {
34059
- error: string;
34060
- };
34061
- outputFormat: "json";
34062
- status: 404;
34058
+ output: string;
34059
+ outputFormat: "text";
34060
+ status: 200;
34063
34061
  input: {
34064
34062
  param: {
34065
34063
  id: string;
34066
34064
  };
34067
34065
  };
34068
34066
  } | {
34069
- output: string;
34070
- outputFormat: "text";
34071
- status: 200;
34067
+ output: {
34068
+ error: string;
34069
+ };
34070
+ outputFormat: "json";
34071
+ status: 404;
34072
34072
  input: {
34073
34073
  param: {
34074
34074
  id: string;
@@ -34106,20 +34106,20 @@ export declare function createApp(deps: ServerDeps): import("hono/hono-base").Ho
34106
34106
  } & {
34107
34107
  "/runs/:id/diff": {
34108
34108
  $get: {
34109
- output: {
34110
- error: string;
34111
- };
34112
- outputFormat: "json";
34113
- status: 404 | 409;
34109
+ output: string;
34110
+ outputFormat: "text";
34111
+ status: import("hono/utils/http-status").ContentfulStatusCode;
34114
34112
  input: {
34115
34113
  param: {
34116
34114
  id: string;
34117
34115
  };
34118
34116
  };
34119
34117
  } | {
34120
- output: string;
34121
- outputFormat: "text";
34122
- status: import("hono/utils/http-status").ContentfulStatusCode;
34118
+ output: {
34119
+ error: string;
34120
+ };
34121
+ outputFormat: "json";
34122
+ status: 404 | 409;
34123
34123
  input: {
34124
34124
  param: {
34125
34125
  id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hearsay-tools/squawk",
3
- "version": "0.18.0-dev.6865",
3
+ "version": "0.18.0-dev.6870",
4
4
  "description": "Local cockpit for running and tracking AI agent tasks in your repo. Uses your logged-in `claude` CLI and `gh` — zero config, zero database.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -63,8 +63,8 @@
63
63
  "devDependencies": {
64
64
  "@babel/parser": "^8.0.8",
65
65
  "@babel/types": "^8.0.8",
66
- "@open-mercato/cezar-api-client": "0.18.0-dev.6865",
67
- "@open-mercato/cezar-contract": "0.18.0-dev.6865",
66
+ "@open-mercato/cezar-api-client": "0.18.0-dev.6870",
67
+ "@open-mercato/cezar-contract": "0.18.0-dev.6870",
68
68
  "@types/node": "^24.19.1",
69
69
  "@types/ws": "^8.18.1",
70
70
  "esbuild": "^0.28.1",
@@ -81,5 +81,5 @@
81
81
  "publishConfig": {
82
82
  "access": "public"
83
83
  },
84
- "gitHead": "ab70ef13d8e588db2866a20e10029ffc1601bf58"
84
+ "gitHead": "9742bb9c8f13d275ab9a3cc106dd259657ae320c"
85
85
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * What `serve` builds for one project, on a fresh temp Git repo, for the delegation benchmarks
3
+ * (`benchmark-stuck-destroys.ts`, `benchmark-worker-lifecycle.ts`). Production cadence: no timer is
4
+ * overridden. Import it after `prepareBenchmarkEnv()`, which points the home at a sandbox. To run a
5
+ * benchmark on an older ref, copy this file beside it.
6
+ */
7
+ import { execFileSync } from 'node:child_process';
8
+ import { mkdtempSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import type { RunnerFactory } from '../src/core/agent-runner.ts';
12
+ import { installWindowsIdentityStore } from '../src/delegation/windows-identity-store.ts';
13
+ import { benchmarkHome } from './benchmark-home.ts';
14
+
15
+ // Workspace receipts and markers use the host's identity store (ADR 0032).
16
+ installWindowsIdentityStore();
17
+
18
+ export const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
19
+
20
+ export async function benchmarkProject(prefix: string, opts: { createRunner: RunnerFactory; maxParallel: number }) {
21
+ const { RunStore } = await import('../src/runs/store.ts');
22
+ const { RunManager } = await import('../src/workflows/run.ts');
23
+ const home = benchmarkHome((await import('../src/home/resolve.ts')).resolveHome({ purpose: 'cli' }));
24
+ const { DelegationService } = await import('../src/delegation/service.ts');
25
+ const { acquireCiResources } = await import('../src/ci-wait/resources.ts');
26
+ const { workerCleanups } = await import('../src/delegation/worker-cleanup.ts');
27
+ const { WorkspaceSemaphore } = await import('../src/workspace/semaphore.ts');
28
+ const root = mkdtempSync(join(tmpdir(), prefix));
29
+ git(root, 'init', '-q', '-b', 'main');
30
+ git(root, 'config', 'gc.auto', '0');
31
+ git(root, 'config', 'maintenance.auto', 'false');
32
+ git(root, '-c', 'user.name=bench', '-c', 'user.email=bench@local', 'commit', '--allow-empty', '-qm', 'base');
33
+ const sha = git(root, 'rev-parse', 'HEAD');
34
+ const dataDir = join(root, '.ai/cezar');
35
+ const store = RunStore.open(dataDir, { keepLive: true });
36
+ const manager = new RunManager(store, root, { home, createRunner: opts.createRunner,
37
+ semaphore: new WorkspaceSemaphore({ home, initial: { maxParallel: opts.maxParallel } }), acquireCiResources });
38
+ const service = new DelegationService(workerCleanups());
39
+ const detach = service.registerProject({ id: 'bench', root, store, manager, home });
40
+ return { root, sha, dataDir, store, manager, service, detach };
41
+ }
@@ -1,4 +1,4 @@
1
- import { benchmarkHome, prepareBenchmarkEnv } from './benchmark-home.ts';
1
+ import { prepareBenchmarkEnv } from './benchmark-home.ts';
2
2
  import { setRunStatus } from '../src/runs/run-store.testkit.ts';
3
3
  /**
4
4
  * Stuck-destroy benchmark (hearsay-tools/cezarion#879): what permanently stuck worker destroys
@@ -14,20 +14,20 @@ import { setRunStatus } from '../src/runs/run-store.testkit.ts';
14
14
  * `DelegationService`, on a temp Git repo, with `CEZ_DRY_RUN=1` and production cadence (no
15
15
  * timer is overridden).
16
16
  * - Each worker is settled the way a finished worker is: a complete execution checkpoint, status
17
- * `review`, a real owned worktree and a local scratch dir. A `sleep` child holds each of the
18
- * two, so neither can ever be removed: the destroy stays incomplete and the scratch is retained.
17
+ * `review`, a real owned worktree and a local scratch dir. Its worktree is locked
18
+ * (`git worktree lock`), so Git never removes it and the destroy stays incomplete. A process
19
+ * working in the worktree no longer blocks a destroy (ADR 0032), so the lock is the blocker.
19
20
  * - Every worker is destroyed once through the human route, as Clean up does. Only then does the
20
21
  * window start, so the measurement is the retry and reprobe loops alone.
21
22
  * - CPU is this process (`process.cpuUsage`, every thread) plus the children it reaped during the
22
- * window (`/proc/self/stat` cutime/cstime: the git processes the loops spawn). The holders are
23
- * reaped only after the window. Event-loop delay is what an HTTP request would wait.
23
+ * window (`/proc/self/stat` cutime/cstime: the git processes the loops spawn). Event-loop delay is
24
+ * what an HTTP request would wait.
24
25
  * - Compare N workers against `--workers 0`; the difference is what the stuck workers add.
25
26
  */
26
- import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
27
+ import { execFileSync } from 'node:child_process';
27
28
  import { randomUUID } from 'node:crypto';
28
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
29
- import { cpus, tmpdir } from 'node:os';
30
- import { join } from 'node:path';
29
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
30
+ import { cpus } from 'node:os';
31
31
  import { monitorEventLoopDelay, performance } from 'node:perf_hooks';
32
32
  import { setTimeout as sleep } from 'node:timers/promises';
33
33
  import { parseArgs } from 'node:util';
@@ -52,14 +52,8 @@ const { values } = parseArgs({ options: {
52
52
  const workers = Number(values.workers), minutes = Number(values.minutes);
53
53
  if (!Number.isInteger(workers) || workers < 0 || !(minutes > 0)) throw new Error('--workers must be a whole number >= 0 and --minutes > 0');
54
54
 
55
- const { RunStore } = await import('../src/runs/store.ts');
56
- const { RunManager } = await import('../src/workflows/run.ts');
57
- const home = benchmarkHome((await import('../src/home/resolve.ts')).resolveHome({ purpose: 'cli' }));
58
- const { DelegationService } = await import('../src/delegation/service.ts');
59
- const { acquireCiResources } = await import('../src/ci-wait/resources.ts');
60
- const { workerCleanups } = await import('../src/delegation/worker-cleanup.ts');
55
+ const { benchmarkProject } = await import('./benchmark-project.ts');
61
56
  const { planOwnedWorkspace, ensureOwnedWorkspace } = await import('../src/delegation/workspace.ts');
62
- const { WorkspaceSemaphore } = await import('../src/workspace/semaphore.ts');
63
57
  const { agentTmpDir } = await import('../src/runs/agent-tmpdir.ts');
64
58
 
65
59
  /** Clock ticks of this process's reaped children (`cutime + cstime`), in ms; 0 off Linux. */
@@ -73,28 +67,16 @@ function childrenCpuMs(): number {
73
67
  return ticks * 1000 / hz;
74
68
  }
75
69
 
76
- const git = (cwd: string, ...args: string[]) => execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
77
- const root = mkdtempSync(join(tmpdir(), 'cez-bench-stuck-'));
78
- git(root, 'init', '-q', '-b', 'main');
79
- git(root, 'config', 'gc.auto', '0');
80
- git(root, 'config', 'maintenance.auto', 'false');
81
- git(root, '-c', 'user.name=bench', '-c', 'user.email=bench@local', 'commit', '--allow-empty', '-qm', 'base');
82
- const sha = git(root, 'rev-parse', 'HEAD');
83
- const dataDir = join(root, '.ai/cezar');
84
-
85
70
  // Teardown runs however the run ends, so a failed setup, destroy or measurement leaves no
86
- // `sleep` holder and no temporary repository behind.
87
- const holders: ChildProcess[] = [];
88
- let store: RunStoreInstance | undefined, manager: RunManagerInstance | undefined, detach: (() => void) | undefined;
71
+ // temporary repository behind.
72
+ let store: RunStoreInstance | undefined, manager: RunManagerInstance | undefined, detach: (() => void) | undefined, root: string | undefined;
89
73
  try {
90
- store = RunStore.open(dataDir, { keepLive: true });
91
- manager = new RunManager(store, root, { home, createRunner: noRunners, semaphore: new WorkspaceSemaphore({ home, initial: { maxParallel: 1 } }), acquireCiResources });
92
- const service = new DelegationService(workerCleanups());
93
- detach = service.registerProject({ id: 'bench', root, store, manager, home });
74
+ const project = await benchmarkProject('cez-bench-stuck-', { createRunner: noRunners, maxParallel: 1 });
75
+ ({ store, manager, detach, root } = project);
76
+ const { sha, dataDir, service } = project;
94
77
  const parent = store.createRun({ title: 'parent', task: 'parent', workflow: 'quick-task', steps: [] });
95
78
  setRunStatus(store, parent.id, 'waiting', { delegation: { role: 'root', permissions: ['spawn'], receipts: [] } });
96
79
 
97
- const hold = (cwd: string) => { holders.push(spawn('sleep', ['86400'], { cwd, stdio: 'ignore' })); };
98
80
  const ids: string[] = [];
99
81
  for (let i = 0; i < workers; i++) {
100
82
  const id = randomUUID();
@@ -107,14 +89,14 @@ try {
107
89
  if (!store.commitWorkerExecutionComplete(id, generation)) throw new Error(`worker ${id} did not complete`);
108
90
  const scratch = agentTmpDir(dataDir, id);
109
91
  mkdirSync(scratch, { recursive: true });
110
- hold(created.path); hold(scratch);
92
+ execFileSync('git', ['worktree', 'lock', '--reason', 'benchmark', created.path], { cwd: root });
111
93
  ids.push(id);
112
94
  }
113
95
  // What boot does after recovery: arm pending destroys and the scratch reprobes.
114
96
  service.armDestroyRetries('bench');
115
97
  for (const id of ids) {
116
98
  const result = await service.destroyForHuman('bench', id).catch((error: Error) => ({ state: 'error', error: error.message }));
117
- if (result.state === 'complete') throw new Error(`worker ${id} was not held: its destroy completed`);
99
+ if (result.state === 'complete') throw new Error(`worker ${id} was not locked: its destroy completed`);
118
100
  }
119
101
 
120
102
  const delay = monitorEventLoopDelay({ resolution: 10 });
@@ -140,11 +122,10 @@ try {
140
122
  if (values.out) writeFileSync(values.out, `${JSON.stringify(row, null, 2)}\n`);
141
123
 
142
124
  } finally {
143
- for (const child of holders) child.kill('SIGKILL');
144
125
  detach?.();
145
126
  manager?.dispose();
146
127
  store?.close();
147
- rmSync(root, { recursive: true, force: true });
128
+ if (root) rmSync(root, { recursive: true, force: true });
148
129
  if (ownHome) rmSync(ownHome, { recursive: true, force: true });
149
130
  }
150
131
  process.exit(0);
@@ -0,0 +1,154 @@
1
+ import { prepareBenchmarkEnv } from './benchmark-home.ts';
2
+ import { setRunStatus } from '../src/runs/run-store.testkit.ts';
3
+ /**
4
+ * Worker lifecycle benchmark (hearsay-tools/squawk#2180): spawn and destroy latency of real owned
5
+ * workers, run unchanged on the commit before worker process ownership and on one after it.
6
+ *
7
+ * node --import tsx packages/cezar/scripts/benchmark-worker-lifecycle.ts --workers 10 --out row.json
8
+ *
9
+ * End to end (the same calls on both refs): one process builds what `serve` builds for a project
10
+ * (`RunStore`, `RunManager`, `DelegationService`) on a temp Git repo, with the dry-run Claude mock.
11
+ * - spawn: `createOwnedRun` + `enqueueOwnedRun` to the session's first recorded process, and to the
12
+ * worker's first settled turn; this includes worktree creation and setup-free start.
13
+ * - destroy (clean): `destroyForHuman` on a settled worker.
14
+ * - destroy (outside holder): the same, while an unrelated `sleep` works in the worktree. Before the
15
+ * change that holder refuses the destroy (`incomplete`); after it, it is ignored.
16
+ * Every attempt is recorded with its state, incomplete ones included.
17
+ *
18
+ * Fixture (what this ref has, reported apart): before, the host-wide cwd scan destroy ran
19
+ * (`inspectGeneration`); after, a worker scope's stop of a detached descendant.
20
+ */
21
+ import { execFileSync, spawn, type ChildProcess } from 'node:child_process';
22
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
23
+ import { cpus, loadavg } from 'node:os';
24
+ import { join } from 'node:path';
25
+ import { performance } from 'node:perf_hooks';
26
+ import { setTimeout as sleep } from 'node:timers/promises';
27
+ import { parseArgs } from 'node:util';
28
+ import { randomUUID } from 'node:crypto';
29
+ import { ClaudeCliRunner } from '../src/core/claude-cli-runner.ts';
30
+ import { installWindowsIdentityStore } from '../src/delegation/windows-identity-store.ts';
31
+
32
+ installWindowsIdentityStore();
33
+ const ownHome = prepareBenchmarkEnv();
34
+ process.env.CEZ_DRY_RUN = '1'; process.env.CEZ_AUTONAME = '0'; process.env.CEZ_MOCK_NUDGE_REPLY = 'plain'; process.env.CEZ_MOCK_NOTES = '0';
35
+
36
+ const { values } = parseArgs({ options: { workers: { type: 'string', default: '10' }, out: { type: 'string' }, label: { type: 'string', default: '' } } });
37
+ const workers = Number(values.workers);
38
+ if (!Number.isInteger(workers) || workers < 1) throw new Error('--workers must be a whole number >= 1');
39
+
40
+ const { benchmarkProject, git } = await import('./benchmark-project.ts');
41
+ const { planOwnedWorkspace } = await import('../src/delegation/workspace.ts');
42
+
43
+ const median = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s.length ? Number(s[Math.floor(s.length / 2)]!.toFixed(1)) : null; };
44
+ const p90 = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s.length ? Number(s[Math.min(s.length - 1, Math.floor(s.length * 0.9))]!.toFixed(1)) : null; };
45
+ async function until(predicate: () => boolean, timeoutMs: number): Promise<boolean> {
46
+ const deadline = performance.now() + timeoutMs;
47
+ while (!predicate()) { if (performance.now() > deadline) return false; await sleep(5); }
48
+ return true;
49
+ }
50
+
51
+ const holders: ChildProcess[] = [];
52
+ const { root, sha, dataDir, store, manager, service, detach } = await benchmarkProject('cez-bench-lifecycle-', { createRunner: () => new ClaudeCliRunner(), maxParallel: 4 });
53
+ try {
54
+ const parent = store.createRun({ title: 'parent', task: 'parent', workflow: 'quick-task', steps: [] });
55
+ setRunStatus(store, parent.id, 'waiting', { delegation: { role: 'root', permissions: ['spawn'], receipts: [] } });
56
+ const processesFile = (id: string) => join(dataDir, 'runs', `${id}.processes.json`);
57
+ const started = (id: string) => existsSync(processesFile(id)) && (JSON.parse(readFileSync(processesFile(id), 'utf8')) as { processes: unknown[] }).processes.length > 0;
58
+ // A worker that ends its turn parks `waiting`; its execution stays open until destroy stops it.
59
+ const settled = (id: string) => ['waiting', 'review', 'done', 'failed'].includes(store.getRun(id)?.status ?? '');
60
+
61
+ const spawnToSession: number[] = [], spawnToSettled: number[] = [], spawned: string[] = [];
62
+ // Every attempt's outcome, so a timed-out or failed start is counted, never dropped.
63
+ const spawnOutcomes: Record<string, number> = {};
64
+ const outcome = (key: string) => { spawnOutcomes[key] = (spawnOutcomes[key] ?? 0) + 1; };
65
+ for (let i = 0; i < workers; i++) {
66
+ const id = randomUUID();
67
+ const t0 = performance.now();
68
+ const workspace = await planOwnedWorkspace(root, id, sha);
69
+ store.createOwnedRun({ title: `worker ${i}`, task: 'say hello', workflow: 'quick-task', runner: 'claude', steps: [{ id: 'task', kind: 'agent', name: 'Task' }] },
70
+ parent.id, randomUUID(), { role: 'worker', permissions: [], parentRunId: parent.id, workspace }, 'a'.repeat(64));
71
+ manager.enqueueOwnedRun(id);
72
+ if (await until(() => started(id), 60_000)) spawnToSession.push(performance.now() - t0);
73
+ else outcome('no-session-within-60s');
74
+ if (!await until(() => settled(id), 120_000)) { outcome(`not-settled-within-120s:${store.getRun(id)?.status}`); continue; }
75
+ const status = store.getRun(id)!.status;
76
+ outcome(status);
77
+ // Only a worker whose turn ended cleanly is a spawn sample; a failed one is counted above.
78
+ if (status === 'waiting' || status === 'review') { spawnToSettled.push(performance.now() - t0); spawned.push(id); }
79
+ }
80
+
81
+ const destroy = async (id: string) => {
82
+ const t0 = performance.now();
83
+ const result = await service.destroyForHuman('bench', id).catch((error: Error) => ({ state: 'error', error: error.message }));
84
+ return { ms: performance.now() - t0, state: (result as { state: string }).state };
85
+ };
86
+ const half = Math.ceil(spawned.length / 2);
87
+ const clean = [] as Array<{ ms: number; state: string }>, held = [] as Array<{ ms: number; state: string }>;
88
+ for (const id of spawned.slice(0, half)) clean.push(await destroy(id));
89
+ for (const id of spawned.slice(half)) {
90
+ const run = store.getRun(id);
91
+ const path = run?.delegation?.role === 'worker' ? run.delegation.workspace.path : root;
92
+ const holder = spawn('sleep', ['600'], { cwd: path, stdio: 'ignore' }); holders.push(holder);
93
+ held.push(await destroy(id));
94
+ holder.kill('SIGKILL');
95
+ }
96
+
97
+ // Fixture: the primitive each ref runs.
98
+ const fixture: Record<string, unknown> = {};
99
+ const liveness = await import('../src/delegation/process-liveness.ts') as Record<string, unknown>;
100
+ if (typeof liveness.inspectGeneration === 'function') {
101
+ const scan = liveness.inspectGeneration as (input: { paths: string[] }) => unknown;
102
+ const times: number[] = [];
103
+ for (let i = 0; i < 20; i++) { const t0 = performance.now(); scan({ paths: [root] }); times.push(performance.now() - t0); }
104
+ fixture.cwdScanMedianMs = median(times); fixture.cwdScanP90Ms = p90(times);
105
+ fixture.hostProcesses = execFileSync('sh', ['-c', 'ls /proc | grep -c "^[0-9]"'], { encoding: 'utf8' }).trim();
106
+ }
107
+ const scopesPath = '../src/worker-scope/worker-scopes.ts';
108
+ const scopes = await import(scopesPath).catch(() => undefined) as typeof import('../src/worker-scope/worker-scopes.ts') | undefined;
109
+ // A scope stop is measured only where the scope contains the setsid descendant; a `groups` host
110
+ // does not (ADR 0032), and its stop would time a different, weaker thing.
111
+ const host = scopes?.hostScope();
112
+ if (host && host.backend === 'groups') fixture.scopeStopSkipped = `groups backend (${host.reason}) does not contain a setsid descendant`;
113
+ if (scopes && host && host.backend !== 'groups') {
114
+ const stops: number[] = [];
115
+ let stopFailures = 0;
116
+ for (let i = 0; i < 10; i++) {
117
+ const id = randomUUID();
118
+ const scope = store.scopes.spawnScope(id);
119
+ const [file, args] = scope.command('/bin/sh', ['-c', 'setsid sleep 600 & echo $!']);
120
+ const leader = spawn(file, args, { detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
121
+ scope.started(leader.pid!);
122
+ const descendant = Number(String(await new Promise(resolve => leader.stdout!.once('data', resolve))).trim());
123
+ const t0 = performance.now();
124
+ try {
125
+ const stopped = await store.scopes.stop(id, 10_000);
126
+ if (stopped.stopped) stops.push(performance.now() - t0); else stopFailures++;
127
+ } catch { stopFailures++; } finally {
128
+ // Ended whatever the stop did: nothing this fixture started outlives it.
129
+ try { process.kill(descendant, 'SIGKILL'); } catch { /* the scope ended it */ }
130
+ }
131
+ }
132
+ fixture.scopeBackend = host.backend; fixture.scopeStopMedianMs = median(stops); fixture.scopeStopP90Ms = p90(stops); fixture.scopeStopFailures = stopFailures;
133
+ }
134
+
135
+ const states = (rows: Array<{ state: string }>) => rows.reduce<Record<string, number>>((acc, row) => ({ ...acc, [row.state]: (acc[row.state] ?? 0) + 1 }), {});
136
+ const row = {
137
+ label: values.label, commit: git(process.cwd(), 'rev-parse', '--short', 'HEAD'), workers, spawned: spawned.length, spawnOutcomes,
138
+ spawnToSessionMedianMs: median(spawnToSession), spawnToSessionP90Ms: p90(spawnToSession),
139
+ spawnToSettledMedianMs: median(spawnToSettled), spawnToSettledP90Ms: p90(spawnToSettled),
140
+ destroyCleanMedianMs: median(clean.map(r => r.ms)), destroyCleanStates: states(clean),
141
+ destroyHeldMedianMs: median(held.map(r => r.ms)), destroyHeldStates: states(held),
142
+ fixture, load1: Number(loadavg()[0]!.toFixed(1)), cores: cpus().length, node: process.version,
143
+ };
144
+ console.log(JSON.stringify(row, null, 2));
145
+ if (values.out) writeFileSync(values.out, `${JSON.stringify(row, null, 2)}\n`);
146
+ } finally {
147
+ for (const child of holders) child.kill('SIGKILL');
148
+ detach();
149
+ manager.dispose();
150
+ store.close();
151
+ rmSync(root, { recursive: true, force: true });
152
+ if (ownHome) rmSync(ownHome, { recursive: true, force: true });
153
+ }
154
+ process.exit(0);