@hearsay-tools/squawk 0.18.0-dev.8435 → 0.18.0-dev.8436

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.
@@ -113,42 +113,10 @@ export declare function createUiStateRoutes(): import("hono/hono-base").HonoBase
113
113
  "/ui-state": {
114
114
  $put: {
115
115
  output: {
116
- [x: string]: import("hono/utils/types").JSONValue;
117
- sidebarLimits?: {
118
- overall?: number | null | undefined;
119
- needsYou?: number | null | undefined;
120
- finished?: number | null | undefined;
121
- working?: number | null | undefined;
122
- } | undefined;
123
- lastTask?: {
124
- source: "skill" | "workflow";
125
- ref: string;
126
- } | null | undefined;
127
- recentSources?: {
128
- source: "skill" | "workflow";
129
- ref: string;
130
- }[] | undefined;
131
- lastWorktree?: boolean | undefined;
132
- lastAutonomous?: boolean | undefined;
133
- skillUsage?: {
134
- [x: string]: number;
135
- } | undefined;
136
- runsView?: "list" | "table" | undefined;
137
- githubView?: "issues" | "prs" | undefined;
138
- appearance?: {
139
- accent?: "cezarion" | "lime" | "violet" | undefined;
140
- density?: "comfortable" | "compact" | "ultra" | undefined;
141
- width?: "narrow" | "wide" | undefined;
142
- } | undefined;
143
- promptTemplates?: {
144
- id: string;
145
- label: string;
146
- text: string;
147
- skills?: string[] | undefined;
148
- }[] | undefined;
116
+ error: string;
149
117
  };
150
118
  outputFormat: "json";
151
- status: import("hono/utils/http-status").ContentfulStatusCode;
119
+ status: 500;
152
120
  input: {
153
121
  json: {
154
122
  [x: string]: unknown;
@@ -186,10 +154,42 @@ export declare function createUiStateRoutes(): import("hono/hono-base").HonoBase
186
154
  };
187
155
  } | {
188
156
  output: {
189
- error: string;
157
+ [x: string]: import("hono/utils/types").JSONValue;
158
+ sidebarLimits?: {
159
+ overall?: number | null | undefined;
160
+ needsYou?: number | null | undefined;
161
+ finished?: number | null | undefined;
162
+ working?: number | null | undefined;
163
+ } | undefined;
164
+ lastTask?: {
165
+ source: "skill" | "workflow";
166
+ ref: string;
167
+ } | null | undefined;
168
+ recentSources?: {
169
+ source: "skill" | "workflow";
170
+ ref: string;
171
+ }[] | undefined;
172
+ lastWorktree?: boolean | undefined;
173
+ lastAutonomous?: boolean | undefined;
174
+ skillUsage?: {
175
+ [x: string]: number;
176
+ } | undefined;
177
+ runsView?: "list" | "table" | undefined;
178
+ githubView?: "issues" | "prs" | undefined;
179
+ appearance?: {
180
+ accent?: "cezarion" | "lime" | "violet" | undefined;
181
+ density?: "comfortable" | "compact" | "ultra" | undefined;
182
+ width?: "narrow" | "wide" | undefined;
183
+ } | undefined;
184
+ promptTemplates?: {
185
+ id: string;
186
+ label: string;
187
+ text: string;
188
+ skills?: string[] | undefined;
189
+ }[] | undefined;
190
190
  };
191
191
  outputFormat: "json";
192
- status: 500;
192
+ status: import("hono/utils/http-status").ContentfulStatusCode;
193
193
  input: {
194
194
  json: {
195
195
  [x: string]: unknown;
@@ -275,10 +275,11 @@ export declare function createWorkflowsRoutes(): import("hono/hono-base").HonoBa
275
275
  "/workflows": {
276
276
  $post: {
277
277
  output: {
278
- error: string;
278
+ path: string;
279
+ name: string;
279
280
  };
280
281
  outputFormat: "json";
281
- status: 400;
282
+ status: 201;
282
283
  input: {
283
284
  json: {
284
285
  name: string;
@@ -311,10 +312,9 @@ export declare function createWorkflowsRoutes(): import("hono/hono-base").HonoBa
311
312
  } | {
312
313
  output: {
313
314
  error: string;
314
- exists: true;
315
315
  };
316
316
  outputFormat: "json";
317
- status: 409;
317
+ status: 400;
318
318
  input: {
319
319
  json: {
320
320
  name: string;
@@ -347,9 +347,10 @@ export declare function createWorkflowsRoutes(): import("hono/hono-base").HonoBa
347
347
  } | {
348
348
  output: {
349
349
  error: string;
350
+ exists: true;
350
351
  };
351
352
  outputFormat: "json";
352
- status: 500;
353
+ status: 409;
353
354
  input: {
354
355
  json: {
355
356
  name: string;
@@ -381,11 +382,10 @@ export declare function createWorkflowsRoutes(): import("hono/hono-base").HonoBa
381
382
  };
382
383
  } | {
383
384
  output: {
384
- path: string;
385
- name: string;
385
+ error: string;
386
386
  };
387
387
  outputFormat: "json";
388
- status: 201;
388
+ status: 500;
389
389
  input: {
390
390
  json: {
391
391
  name: string;
@@ -421,10 +421,11 @@ export declare function createWorkflowsRoutes(): import("hono/hono-base").HonoBa
421
421
  "/workflows/:name": {
422
422
  $delete: {
423
423
  output: {
424
- error: string;
424
+ ok: true;
425
+ path: string;
425
426
  };
426
427
  outputFormat: "json";
427
- status: 400 | 404 | 409 | 500;
428
+ status: import("hono/utils/http-status").ContentfulStatusCode;
428
429
  input: {
429
430
  param: {
430
431
  name: string;
@@ -432,11 +433,10 @@ export declare function createWorkflowsRoutes(): import("hono/hono-base").HonoBa
432
433
  };
433
434
  } | {
434
435
  output: {
435
- ok: true;
436
- path: string;
436
+ error: string;
437
437
  };
438
438
  outputFormat: "json";
439
- status: import("hono/utils/http-status").ContentfulStatusCode;
439
+ status: 400 | 404 | 409 | 500;
440
440
  input: {
441
441
  param: {
442
442
  name: string;
@@ -504,18 +504,6 @@ export interface PlanRouteDeps {
504
504
  export declare function createPlanRoutes(deps: PlanRouteDeps): import("hono/hono-base").HonoBase<ProjectApiEnv, {
505
505
  "/plan": {
506
506
  $post: {
507
- output: {
508
- error: string;
509
- };
510
- outputFormat: "json";
511
- status: 400 | 404 | 409;
512
- input: {
513
- json: {
514
- task: string;
515
- agentProfile?: string | undefined;
516
- };
517
- };
518
- } | {
519
507
  output: {
520
508
  name?: string;
521
509
  steps: {
@@ -552,6 +540,18 @@ export declare function createPlanRoutes(deps: PlanRouteDeps): import("hono/hono
552
540
  agentProfile?: string | undefined;
553
541
  };
554
542
  };
543
+ } | {
544
+ output: {
545
+ error: string;
546
+ };
547
+ outputFormat: "json";
548
+ status: 400 | 404 | 409;
549
+ input: {
550
+ json: {
551
+ task: string;
552
+ agentProfile?: string | undefined;
553
+ };
554
+ };
555
555
  };
556
556
  };
557
557
  }, "/", "/plan">;
@@ -599,34 +599,10 @@ export declare function createConfigRoutes(deps: ConfigRouteDeps): import("hono/
599
599
  "/config": {
600
600
  $put: {
601
601
  output: {
602
- archiveOnMerge: boolean | null;
603
- effectiveArchiveOnMerge: boolean;
604
- archiveOnMergeSource: "default" | "environment" | "global" | "project";
605
- baseBranch: string | null;
606
- defaultRunner: string;
607
- systemPrompt: string | null;
608
- defaultModels: {
609
- [x: string]: string | undefined;
610
- };
611
- modelsLocked: boolean;
612
- maxParallel: number;
613
- memoryLimitMb: number | null;
614
- worktreeRetention: number;
615
- liveTitleUpdates: boolean | null;
616
- reviewGate: boolean | null;
617
- worktreeSetup: {
618
- commands: string[];
619
- timeoutSeconds: number;
620
- } | null;
621
- worktreeSetupIssue: string | null;
622
- worktreeTeardown: {
623
- commands: string[];
624
- timeoutSeconds: number;
625
- } | null;
626
- worktreeTeardownIssue: string | null;
602
+ error: string;
627
603
  };
628
604
  outputFormat: "json";
629
- status: import("hono/utils/http-status").ContentfulStatusCode;
605
+ status: 409;
630
606
  input: {
631
607
  json: {
632
608
  archiveOnMerge?: boolean | null | undefined;
@@ -654,7 +630,7 @@ export declare function createConfigRoutes(deps: ConfigRouteDeps): import("hono/
654
630
  error: string;
655
631
  };
656
632
  outputFormat: "json";
657
- status: 409;
633
+ status: 500;
658
634
  input: {
659
635
  json: {
660
636
  archiveOnMerge?: boolean | null | undefined;
@@ -679,10 +655,34 @@ export declare function createConfigRoutes(deps: ConfigRouteDeps): import("hono/
679
655
  };
680
656
  } | {
681
657
  output: {
682
- error: string;
658
+ archiveOnMerge: boolean | null;
659
+ effectiveArchiveOnMerge: boolean;
660
+ archiveOnMergeSource: "default" | "environment" | "global" | "project";
661
+ baseBranch: string | null;
662
+ defaultRunner: string;
663
+ systemPrompt: string | null;
664
+ defaultModels: {
665
+ [x: string]: string | undefined;
666
+ };
667
+ modelsLocked: boolean;
668
+ maxParallel: number;
669
+ memoryLimitMb: number | null;
670
+ worktreeRetention: number;
671
+ liveTitleUpdates: boolean | null;
672
+ reviewGate: boolean | null;
673
+ worktreeSetup: {
674
+ commands: string[];
675
+ timeoutSeconds: number;
676
+ } | null;
677
+ worktreeSetupIssue: string | null;
678
+ worktreeTeardown: {
679
+ commands: string[];
680
+ timeoutSeconds: number;
681
+ } | null;
682
+ worktreeTeardownIssue: string | null;
683
683
  };
684
684
  outputFormat: "json";
685
- status: 500;
685
+ status: import("hono/utils/http-status").ContentfulStatusCode;
686
686
  input: {
687
687
  json: {
688
688
  archiveOnMerge?: boolean | null | undefined;
@@ -796,14 +796,10 @@ export declare function createAgentConfigRoutes(capabilities: ServerCapabilities
796
796
  "/agent-config/:id": {
797
797
  $put: {
798
798
  output: {
799
- id: string;
800
- path: string;
801
- exists: boolean;
802
- content: string;
803
- version: string | null;
799
+ error: string;
804
800
  };
805
801
  outputFormat: "json";
806
- status: import("hono/utils/http-status").ContentfulStatusCode;
802
+ status: 404;
807
803
  input: {
808
804
  json: {
809
805
  content: string;
@@ -816,10 +812,14 @@ export declare function createAgentConfigRoutes(capabilities: ServerCapabilities
816
812
  };
817
813
  } | {
818
814
  output: {
819
- error: string;
815
+ id: string;
816
+ path: string;
817
+ exists: boolean;
818
+ content: string;
819
+ version: string | null;
820
820
  };
821
821
  outputFormat: "json";
822
- status: 404;
822
+ status: import("hono/utils/http-status").ContentfulStatusCode;
823
823
  input: {
824
824
  json: {
825
825
  content: string;
@@ -941,9 +941,12 @@ export declare function createAgentWebhooksRoutes(deps: AgentWebhooksRouteDeps):
941
941
  export declare function createSseRoutes(): import("hono/hono-base").HonoBase<ProjectApiEnv, {
942
942
  "/runs/:id/events": {
943
943
  $get: {
944
- output: {};
945
- outputFormat: string;
946
- status: import("hono/utils/http-status").StatusCode;
944
+ output: {
945
+ error: string;
946
+ code?: "invalid_input" | undefined;
947
+ };
948
+ outputFormat: "json";
949
+ status: 400;
947
950
  input: {
948
951
  param: {
949
952
  id: string;
@@ -955,12 +958,9 @@ export declare function createSseRoutes(): import("hono/hono-base").HonoBase<Pro
955
958
  };
956
959
  };
957
960
  } | {
958
- output: {
959
- error: string;
960
- code?: "invalid_input" | undefined;
961
- };
962
- outputFormat: "json";
963
- status: 400;
961
+ output: {};
962
+ outputFormat: string;
963
+ status: import("hono/utils/http-status").StatusCode;
964
964
  input: {
965
965
  param: {
966
966
  id: string;
@@ -18,7 +18,7 @@ export declare function createProviderSignInRoutes(options: {
18
18
  error: string;
19
19
  };
20
20
  outputFormat: "json";
21
- status: 409;
21
+ status: 400;
22
22
  input: {
23
23
  json: {
24
24
  provider: string;
@@ -30,7 +30,7 @@ export declare function createProviderSignInRoutes(options: {
30
30
  error: string;
31
31
  };
32
32
  outputFormat: "json";
33
- status: 400;
33
+ status: 409;
34
34
  input: {
35
35
  json: {
36
36
  provider: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hearsay-tools/squawk",
3
- "version": "0.18.0-dev.8435",
3
+ "version": "0.18.0-dev.8436",
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",
@@ -68,8 +68,8 @@
68
68
  "devDependencies": {
69
69
  "@babel/parser": "^8.0.8",
70
70
  "@babel/types": "^8.0.8",
71
- "@open-mercato/cezar-api-client": "0.18.0-dev.8435",
72
- "@open-mercato/cezar-contract": "0.18.0-dev.8435",
71
+ "@open-mercato/cezar-api-client": "0.18.0-dev.8436",
72
+ "@open-mercato/cezar-contract": "0.18.0-dev.8436",
73
73
  "@types/node": "^24.19.1",
74
74
  "@types/ws": "^8.18.1",
75
75
  "esbuild": "^0.28.1",
@@ -86,5 +86,5 @@
86
86
  "publishConfig": {
87
87
  "access": "public"
88
88
  },
89
- "gitHead": "e2d6b253904f2eaf326813aa702f404f3969491f"
89
+ "gitHead": "ee0f51ed0361ce071db491fe3277a477491e0b89"
90
90
  }
@@ -8,7 +8,8 @@ import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
8
8
  import { tmpdir } from 'node:os';
9
9
  import { join } from 'node:path';
10
10
  import { setTimeout as delay } from 'node:timers/promises';
11
- import { timingSnapshot, timingDelta, blockingBudget, prepareOpenTiming } from './transcript-facts-timing.mjs';
11
+ import { PerformanceObserver } from 'node:perf_hooks';
12
+ import { timingSnapshot, timingDelta, blockingBudget, prepareOpenTiming, hookCalls, callsWithin, startThreadWatch, summarizeWaits } from './transcript-facts-timing.mjs';
12
13
  import { seedColdHistories, verifyFacts } from './transcript-facts-fixture.mjs';
13
14
 
14
15
  const root = mkdtempSync(join(process.platform === 'win32' ? tmpdir() : '/tmp', 'cez-facts-health-'));
@@ -23,6 +24,9 @@ let dataDir;
23
24
  let store;
24
25
  let bootStore;
25
26
  let server;
27
+ let unhookCalls;
28
+ let gcObserver;
29
+ let threadWatch;
26
30
  const watchdog = setTimeout(() => { console.error('health measurement exceeded 30s'); process.exitCode = 1; server?.closeAllConnections(); server?.close(); store?.close(); bootStore?.close(); }, 30_000);
27
31
  try {
28
32
  const { RunStore } = await import(new URL('runs/store.js', runtime.url));
@@ -79,18 +83,32 @@ try {
79
83
  assert.equal((await prime.json()).version, 'task4-measurement');
80
84
  const primingLatencyMs = performance.now() - primingStart;
81
85
  assert.equal(readdirSync(join(dataDir, 'runs')).filter(name => name.endsWith('.facts.json')).length, 0);
86
+ // Diagnostics only: name the main-thread calls and GC pauses inside each sample.
87
+ const { TranscriptFactsIndex } = await import(new URL('runs/transcript-facts.js', runtime.url));
88
+ const { TranscriptFactsQueue } = await import(new URL('runs/transcript-facts-queue.js', runtime.url));
89
+ const { RunQueriesTopic } = await import(new URL('runs/run-queries.js', runtime.url));
90
+ const calls = [];
91
+ unhookCalls = hookCalls([[RunQueriesTopic.prototype, 'listConversationRootIds'], [RunQueriesTopic.prototype, 'listFamilyRunIds'],
92
+ [RunQueriesTopic.prototype, 'listRunIds'], [TranscriptFactsIndex.prototype, 'warm'], [TranscriptFactsIndex.prototype, 'peek'],
93
+ [TranscriptFactsIndex.prototype, 'accept'], [TranscriptFactsIndex.prototype, 'persist'],
94
+ [TranscriptFactsQueue.prototype, 'start'], [TranscriptFactsQueue.prototype, 'createWorker']], calls);
95
+ const gcPauses = [];
96
+ gcObserver = new PerformanceObserver(list => { for (const entry of list.getEntries()) gcPauses.push(entry); });
97
+ gcObserver.observe({ entryTypes: ['gc'] });
98
+ threadWatch = await startThreadWatch();
82
99
  const start = performance.now();
83
100
  let end;
84
101
  let warming;
85
102
  const samples = [];
86
103
  const pauseMs = 5;
87
104
  // Each sample after the first also covers the pause before its request, so blocking
88
- // between requests is measured too; blockingBudget subtracts the planned pause.
105
+ // between requests is measured too; the pause is loop idle time, which blockingBudget excludes.
89
106
  let pauseStart;
90
107
  for (;;) {
91
108
  const measurementStart = pauseStart ?? timingSnapshot();
92
109
  const plannedMs = pauseStart ? pauseMs : 0;
93
110
  const requestStart = performance.now();
111
+ if (!store) threadWatch?.watch(true);
94
112
  const pendingResponse = fetch(endpoint, { signal: AbortSignal.timeout(2_000) });
95
113
  // The first request includes synchronous project-open work too.
96
114
  if (!store) {
@@ -103,13 +121,26 @@ try {
103
121
  const requestEnd = performance.now();
104
122
  // Include EVERY request begun while cold warm-up was active, even one ending after it.
105
123
  const measurement = timingDelta(measurementStart, timingSnapshot());
124
+ threadWatch?.watch(false);
106
125
  samples.push({ fromMs: measurementStart.at - start, startMs: requestStart - start, endMs: requestEnd - start,
107
- latencyMs: requestEnd - requestStart, plannedMs, ...measurement, ...blockingBudget(measurement, plannedMs) });
126
+ latencyMs: requestEnd - requestStart, plannedMs, ...measurement, ...blockingBudget(measurement) });
108
127
  if (end !== undefined) break;
109
128
  pauseStart = timingSnapshot();
110
129
  await delay(pauseMs);
111
130
  }
112
131
  await warming;
132
+ unhookCalls();
133
+ const firstSampleWaits = (await threadWatch?.stop()) ?? [];
134
+ threadWatch = undefined;
135
+ for (const entry of gcObserver.takeRecords()) gcPauses.push(entry);
136
+ gcObserver.disconnect();
137
+ for (const sample of samples) {
138
+ const from = start + sample.fromMs;
139
+ const to = from + sample.elapsedMs;
140
+ const gc = gcPauses.filter(entry => entry.startTime >= from && entry.startTime < to);
141
+ Object.assign(sample, { calls: callsWithin(calls, from, to),
142
+ gc: { count: gc.length, durationMs: gc.reduce((sum, entry) => sum + entry.duration, 0) } });
143
+ }
113
144
  assert.ok(samples.length > 0, 'health requests must overlap cold warming');
114
145
  assert.ok(samples.every(sample => sample.fromMs < end - start && sample.endMs > 0));
115
146
  // Keep first-open and repeated-open costs separate. Reopening must not rescan clean history.
@@ -124,12 +155,18 @@ try {
124
155
  ...verifyFacts(dataDir, fixtures, store), durationMs: end - start,
125
156
  maxBlockingMs: Math.max(...samples.map(sample => sample.blockingMs)),
126
157
  maxMainThreadCpuMs: Math.max(...samples.map(sample => sample.mainThreadCpuMs)),
158
+ maxLoopIdleMs: Math.max(...samples.map(sample => sample.loopIdleMs)),
159
+ firstSampleWaits: summarizeWaits(firstSampleWaits), firstSampleWaitTrace: firstSampleWaits.slice(0, 300),
127
160
  sampleCount: samples.length, maxLatencyMs: Math.max(...samples.map(sample => sample.latencyMs)), samples };
128
161
  console.log(JSON.stringify(result));
129
- // Exclude run-queue delay, but retain synchronous blocking and request latency.
162
+ // Exclude run-queue delay and loop idle time: a response that waits on the thread pool, a worker
163
+ // or the kernel is latency (kept in maxLatencyMs), not main-thread blocking. Synchronous work counts.
130
164
  assert.ok(result.maxBlockingMs < 50, `max health blocking ${result.maxBlockingMs.toFixed(3)}ms must be <50ms`);
131
165
  } finally {
132
166
  clearTimeout(watchdog);
167
+ unhookCalls?.();
168
+ gcObserver?.disconnect();
169
+ await threadWatch?.stop();
133
170
  let cleanupTimer;
134
171
  try {
135
172
  if (server) await Promise.race([server.shutdownForRestart(), new Promise((_, reject) => {
@@ -2,7 +2,7 @@
2
2
  * node --expose-gc --import tsx packages/cezar/scripts/measure-transcript-facts-lag.mjs
3
3
  * Built runtime: pass an absolute dist directory. Baseline source: pass its src directory and ts.
4
4
  * A separate process removes test-runner loop work, NOT unrelated host CPU scheduling.
5
- * Gate loop CPU and blocking time; exclude host run-queue delay.
5
+ * Gate loop CPU and blocking time; exclude loop idle time and host run-queue delay.
6
6
  */
7
7
  import assert from 'node:assert/strict';
8
8
  import { mkdtempSync, rmSync } from 'node:fs';
@@ -30,7 +30,7 @@ try {
30
30
  timer = setInterval(() => {
31
31
  const current = timingSnapshot();
32
32
  const sample = timingDelta(previous, current);
33
- ticks.push({ at: current.at, lagMs: Math.max(0, sample.elapsedMs - periodMs), ...sample, ...blockingBudget(sample, periodMs) });
33
+ ticks.push({ at: current.at, lagMs: Math.max(0, sample.elapsedMs - periodMs), ...sample, ...blockingBudget(sample) });
34
34
  previous = current;
35
35
  }, periodMs);
36
36
  // Establish a real interval before starting; retain the first tick after completion too.
@@ -69,7 +69,7 @@ try {
69
69
  assert.ok(result.trailingTicks > 0, 'must retain a trailing tick after warming');
70
70
  assert.ok(overlapping.length > 0, 'must sample during cold warm-up');
71
71
  assert.ok(result.durationMs > 0);
72
- // Exclude planned timer sleep and run-queue delay, but retain synchronous blocking.
72
+ // Exclude loop idle time (the planned timer sleep) and run-queue delay, but retain synchronous blocking.
73
73
  assert.ok(result.maxBlockingMs < 20, `max interval blocking ${result.maxBlockingMs.toFixed(3)}ms must be <20ms`);
74
74
  } finally {
75
75
  clearInterval(timer);
@@ -1,5 +1,7 @@
1
1
  /** Main-thread measurements only: worker CPU does not count as loop blocking. */
2
2
  import { readFileSync } from 'node:fs';
3
+ import { once } from 'node:events';
4
+ import { Worker } from 'node:worker_threads';
3
5
 
4
6
  export function readQueueWaitMs({ read = readFileSync, platform = process.platform } = {}) {
5
7
  // Linux schedstat field 2 is cumulative run-queue wait in nanoseconds.
@@ -11,34 +13,156 @@ export function readQueueWaitMs({ read = readFileSync, platform = process.platfo
11
13
  catch { return null; /* Optional diagnostic on restricted procfs mounts. */ }
12
14
  }
13
15
 
16
+ /** Linux per-thread major page faults and voluntary context switches: optional diagnostics
17
+ * that tell a disk page-in from a lock or I/O wait. Null where procfs cannot answer. */
18
+ export function readThreadStats({ read = readFileSync, platform = process.platform } = {}) {
19
+ if (platform !== 'linux') return null;
20
+ try {
21
+ const stat = read('/proc/thread-self/stat', 'utf8');
22
+ // Field 12 (majflt); the command name in field 2 may contain spaces, so count after ')'.
23
+ const majorFaults = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[9]);
24
+ const switches = /^voluntary_ctxt_switches:\s*(\d+)$/m.exec(read('/proc/thread-self/status', 'utf8'));
25
+ return Number.isFinite(majorFaults) && switches ? { majorFaults, voluntarySwitches: Number(switches[1]) } : null;
26
+ }
27
+ catch { return null; /* Optional diagnostic on restricted procfs mounts. */ }
28
+ }
29
+
30
+ /** libuv idle time: the loop waited in its poll phase for I/O, a timer or another thread. */
31
+ export function readLoopIdleMs() {
32
+ return performance.eventLoopUtilization().idle;
33
+ }
34
+
14
35
  export function timingSnapshot({ now = () => performance.now(), readQueue = readQueueWaitMs,
15
- readCpu = () => process.threadCpuUsage() } = {}) {
36
+ readCpu = () => process.threadCpuUsage(), readLoopIdle = readLoopIdleMs, readThread = readThreadStats } = {}) {
37
+ const thread = readThread();
16
38
  const cpu = readCpu();
39
+ const loopIdleMs = readLoopIdle();
17
40
  const queueBeforeMs = readQueue();
18
41
  const at = now();
19
42
  const queueAfterMs = readQueue();
20
- return { at, cpuMs: (cpu.user + cpu.system) / 1000, queueBeforeMs, queueAfterMs };
43
+ return { at, cpuMs: (cpu.user + cpu.system) / 1000, loopIdleMs, queueBeforeMs, queueAfterMs, thread };
21
44
  }
22
45
 
23
46
  export function timingDelta(start, end) {
24
47
  const elapsedMs = end.at - start.at;
25
48
  const mainThreadCpuMs = end.cpuMs - start.cpuMs;
49
+ // Snapshots run JavaScript, never inside the poll phase, so the idle delta lies in the interval.
50
+ const loopIdleMs = Math.max(0, Math.min(elapsedMs, end.loopIdleMs - start.loopIdleMs));
26
51
  // Previous AFTER -> next BEFORE is contained in the wall-clock interval.
27
52
  // Subtract only this inner queue-wait delta. A pause between a scheduler
28
53
  // read and the clock must never credit wait from outside the interval.
29
54
  const queueWaitMs = start.queueAfterMs === null || end.queueBeforeMs === null ? null
30
55
  : Math.max(0, Math.min(elapsedMs, end.queueBeforeMs - start.queueAfterMs));
31
- // Residual includes timer/IO sleep and measurement overhead, not just IO.
32
- return { elapsedMs, mainThreadCpuMs, queueWaitMs,
33
- blockedMs: queueWaitMs === null ? null : Math.max(0, elapsedMs - mainThreadCpuMs - queueWaitMs) };
56
+ // Residual: off-CPU time outside the poll phase (synchronous disk I/O, locks, Atomics.wait)
57
+ // plus measurement overhead. See blockingBudget for why the larger wait is subtracted once.
58
+ return { elapsedMs, mainThreadCpuMs, loopIdleMs, queueWaitMs,
59
+ blockedMs: queueWaitMs === null ? null : Math.max(0, elapsedMs - mainThreadCpuMs - Math.max(loopIdleMs, queueWaitMs)),
60
+ ...(start.thread && end.thread ? { majorFaults: end.thread.majorFaults - start.thread.majorFaults,
61
+ voluntarySwitches: end.thread.voluntarySwitches - start.thread.voluntarySwitches } : {}) };
34
62
  }
35
63
 
36
- /** Timer samples exclude their planned sleep; requests have no planned sleep. */
37
- export function blockingBudget(sample, periodMs = 0) {
64
+ /** Main-thread blocking is loop-active time without run-queue wait. Loop idle time is excluded:
65
+ * a planned timer sleep, and a request waiting on the thread pool, a worker or the kernel, are
66
+ * latency but do not block the loop. CPU, synchronous disk I/O and Atomics.wait still count.
67
+ * libuv counts a run-queue wait after a poll wake-up as idle time too, and the two cannot be
68
+ * told apart, so only the larger of idle and run-queue wait is subtracted. Subtracting both
69
+ * could hide a synchronous stall; this choice can only over-count, never above elapsed minus
70
+ * run-queue wait. It never drops below main-thread CPU. */
71
+ export function blockingBudget(sample) {
38
72
  const mode = sample.queueWaitMs === null ? 'cpu-only' : 'scheduler-adjusted';
39
73
  const blockingMs = sample.queueWaitMs === null ? sample.mainThreadCpuMs
40
- : Math.max(0, sample.elapsedMs - periodMs - sample.queueWaitMs);
41
- return { mode, blockingMs: Math.max(0, periodMs > 0 ? Math.max(sample.mainThreadCpuMs, blockingMs) : blockingMs) };
74
+ : Math.max(sample.mainThreadCpuMs, sample.elapsedMs - Math.max(sample.loopIdleMs, sample.queueWaitMs));
75
+ return { mode, blockingMs: Math.max(0, blockingMs) };
76
+ }
77
+
78
+ /** Light per-call timing (clock and thread CPU only), so many hooked calls add little loop time.
79
+ * Each call records its start; nested hooked calls are recorded too, under their own phase. */
80
+ export function hookCalls(hooks, calls) {
81
+ const restore = hooks.map(([target, name]) => {
82
+ const original = target[name];
83
+ target[name] = function (...args) {
84
+ const at = performance.now();
85
+ const cpu = process.threadCpuUsage();
86
+ try { return original.apply(this, args); }
87
+ finally {
88
+ const used = process.threadCpuUsage(cpu);
89
+ calls.push({ phase: name, at, elapsedMs: performance.now() - at, mainThreadCpuMs: (used.user + used.system) / 1000 });
90
+ }
91
+ };
92
+ return () => { target[name] = original; };
93
+ });
94
+ return () => { for (const undo of restore) undo(); };
95
+ }
96
+
97
+ /** Per-phase totals of the calls that started in [from, to). */
98
+ export function callsWithin(calls, from, to) {
99
+ const phases = {};
100
+ for (const call of calls) {
101
+ if (call.at < from || call.at >= to) continue;
102
+ const total = phases[call.phase] ??= { count: 0, elapsedMs: 0, mainThreadCpuMs: 0, maxElapsedMs: 0 };
103
+ total.count++;
104
+ total.elapsedMs += call.elapsedMs;
105
+ total.mainThreadCpuMs += call.mainThreadCpuMs;
106
+ total.maxElapsedMs = Math.max(total.maxElapsedMs, call.elapsedMs);
107
+ }
108
+ return phases;
109
+ }
110
+
111
+ // Polls the main thread's kernel state from another thread; records it whenever it is not running.
112
+ const WATCH_SOURCE = `
113
+ const { workerData, parentPort } = require('node:worker_threads');
114
+ const { readFileSync } = require('node:fs');
115
+ const flag = new Int32Array(workerData.flag);
116
+ const base = '/proc/' + workerData.pid + '/task/' + workerData.pid + '/';
117
+ const read = name => { try { return readFileSync(base + name, 'utf8').trim(); } catch { return null; } };
118
+ const seen = [];
119
+ parentPort.postMessage('ready');
120
+ for (let mode; (mode = Atomics.load(flag, 0)) !== 2;) {
121
+ if (mode === 0) { Atomics.wait(flag, 0, 0); continue; }
122
+ const stat = read('stat');
123
+ const state = stat === null ? '?' : stat.charAt(stat.lastIndexOf(')') + 2);
124
+ if (state !== 'R') {
125
+ seen.push({ at: performance.timeOrigin + performance.now(), state, wchan: read('wchan'),
126
+ syscall: read('syscall')?.split(' ')[0] ?? null });
127
+ Atomics.add(flag, 1, 1);
128
+ Atomics.notify(flag, 1);
129
+ }
130
+ Atomics.wait(flag, 0, 1, 1);
131
+ }
132
+ parentPort.postMessage(seen);
133
+ `;
134
+
135
+ /** Diagnostics only (Linux): name what the main thread waits in, such as a futex, a sleep, a
136
+ * child process or a page fault, about once a millisecond while watching is on. */
137
+ export async function startThreadWatch() {
138
+ if (process.platform !== 'linux') return null;
139
+ // [0]: 0 paused, 1 watching, 2 stop. [1]: samples recorded so far.
140
+ const flag = new Int32Array(new SharedArrayBuffer(8));
141
+ const worker = new Worker(WATCH_SOURCE, { eval: true, workerData: { flag: flag.buffer, pid: process.pid } });
142
+ await once(worker, 'message');
143
+ const set = mode => { Atomics.store(flag, 0, mode); Atomics.notify(flag, 0); };
144
+ return {
145
+ watch: on => set(on ? 1 : 0),
146
+ /** Block the main thread until the watcher records one more sample: 'ok' or 'timed-out'. */
147
+ awaitRecord: timeoutMs => Atomics.wait(flag, 1, Atomics.load(flag, 1), timeoutMs) === 'timed-out' ? 'timed-out' : 'ok',
148
+ async stop() {
149
+ const reply = once(worker, 'message');
150
+ set(2);
151
+ const [seen] = await reply;
152
+ await worker.terminate();
153
+ return seen.map(entry => ({ ...entry, at: entry.at - performance.timeOrigin }));
154
+ },
155
+ };
156
+ }
157
+
158
+ /** Counts of watched waits by state, syscall number and kernel wait channel. */
159
+ export function summarizeWaits(seen) {
160
+ const counts = {};
161
+ for (const entry of seen) {
162
+ const key = `${entry.state} syscall=${entry.syscall} ${entry.wchan}`;
163
+ counts[key] = (counts[key] ?? 0) + 1;
164
+ }
165
+ return counts;
42
166
  }
43
167
 
44
168
  /** Instrument only the synchronous open call. Imports and hook setup are outside its budget.