@blackbelt-technology/pi-dashboard-extension 0.8.0 → 0.9.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.
Files changed (78) hide show
  1. package/.pi/skills/browser/SKILL.md +69 -28
  2. package/.pi/skills/browser/UPSTREAM.md +6 -3
  3. package/.pi/skills/browser/references/challenge.md +183 -0
  4. package/.pi/skills/browser/references/dashboard-relay.md +150 -0
  5. package/.pi/skills/browser/references/own-browser.md +7 -1
  6. package/.pi/skills/doctor/SKILL.md +1 -0
  7. package/.pi/skills/doctor/_lib/checks.ts +133 -0
  8. package/.pi/skills/doctor/_lib/derive-tokens.ts +4 -0
  9. package/.pi/skills/doctor/modules/apple-tools.md +2 -1
  10. package/.pi/skills/doctor/modules/mcp-builtin.knowledge.hash +1 -0
  11. package/.pi/skills/doctor/modules/mcp-builtin.md +61 -0
  12. package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -1
  13. package/.pi/skills/doctor/modules/plugins-bridges.md +14 -1
  14. package/.pi/skills/pi-dashboard/SKILL.md +10 -3
  15. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +4 -4
  16. package/.pi/skills/project-init/SKILL.md +40 -27
  17. package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +0 -23
  18. package/package.json +19 -16
  19. package/src/ask-user-tool.ts +4 -0
  20. package/src/bridge-activation.ts +26 -0
  21. package/src/bridge-context.ts +21 -19
  22. package/src/bridge-default-model-gate.ts +38 -0
  23. package/src/bridge-polling.ts +148 -0
  24. package/src/bridge.ts +954 -248
  25. package/src/canvas-tool.ts +5 -0
  26. package/src/command-handler.ts +77 -31
  27. package/src/connection.ts +481 -16
  28. package/src/custom-entry-forward.ts +92 -0
  29. package/src/endpoint-resolution.ts +32 -0
  30. package/src/event-forwarder.ts +42 -0
  31. package/src/extension-identity.ts +59 -0
  32. package/src/git-dir-watcher.ts +79 -0
  33. package/src/git-poll.ts +45 -12
  34. package/src/git-probe-scheduler.ts +119 -0
  35. package/src/git-tracker.ts +284 -0
  36. package/src/instance-verification.ts +31 -0
  37. package/src/mcp-token-delivery.ts +147 -0
  38. package/src/message-update-coalescer.ts +340 -0
  39. package/src/model-tracker.ts +118 -35
  40. package/src/notify-proxy.ts +3 -0
  41. package/src/path-gate/decide.ts +149 -0
  42. package/src/path-gate/grant-cache.ts +71 -0
  43. package/src/path-gate/grant-link.ts +108 -0
  44. package/src/path-gate/handler.ts +307 -0
  45. package/src/path-gate/index.ts +155 -0
  46. package/src/path-gate/resolve.ts +126 -0
  47. package/src/path-gate/roots.ts +137 -0
  48. package/src/path-gate/suppression.ts +27 -0
  49. package/src/pending-prompt-emitter.ts +59 -0
  50. package/src/pi-env.d.ts +2 -10
  51. package/src/plugin-request-client.ts +114 -0
  52. package/src/poll-cost.ts +40 -0
  53. package/src/pr-status.ts +338 -0
  54. package/src/process-metrics.ts +77 -1
  55. package/src/process-scan-scheduler.ts +137 -0
  56. package/src/process-scanner.ts +226 -247
  57. package/src/project-init/dox-kb-config.ts +3 -0
  58. package/src/project-init/scaffold.ts +1 -4
  59. package/src/project-init/seed-doctrine.ts +23 -60
  60. package/src/prompt-bus.ts +13 -0
  61. package/src/provider-register.ts +6 -0
  62. package/src/retry-tracker.ts +0 -7
  63. package/src/role-manager.ts +22 -95
  64. package/src/role-model-tools.ts +6 -0
  65. package/src/server-auto-start.ts +192 -23
  66. package/src/server-launcher.ts +70 -34
  67. package/src/session-move.ts +4 -4
  68. package/src/session-sync.ts +51 -15
  69. package/src/slash-dispatch.ts +66 -81
  70. package/src/subagent-fanout-admission.ts +234 -0
  71. package/src/subagent-saturation.ts +196 -0
  72. package/src/terminal-reload.ts +298 -0
  73. package/src/tui-prompt-adapter.ts +13 -1
  74. package/src/usage-drain.ts +167 -0
  75. package/src/vcs-info.ts +261 -63
  76. package/.pi/skills/project-init/dox-doctrine.md +0 -146
  77. package/src/agent-settled.ts +0 -90
  78. package/src/transcript-request-guard.ts +0 -76
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Pure mapping for pi `entry_appended` events → the dashboard `custom_entry`
3
+ * protocol event (change: render-inline-reasoning-and-custom-entries, D2).
4
+ *
5
+ * `pi.appendEntry(customType, data)` persists a `CustomEntry` and fires
6
+ * `entry_appended`; before this module the bridge did not subscribe, so
7
+ * generic custom entries rendered as nothing at all. The mapping forwards
8
+ * ONLY `customType` / `data` / `entryId` — the entry's other fields are
9
+ * transport trivia the renderer never needs.
10
+ *
11
+ * `customType: "flow-event"` returns null: pi-flows appends those entries
12
+ * live itself, so forwarding them would double-render alongside the
13
+ * dedicated flow card. Non-`custom` entry types are likewise not ours to
14
+ * forward.
15
+ */
16
+
17
+ export interface CustomEntryForwardData {
18
+ customType: string;
19
+ data: unknown;
20
+ entryId: string;
21
+ /**
22
+ * Server-stamped custom event group id (design D1,
23
+ * add-custom-event-group-filters). The extension never sets it: resolution
24
+ * + stamping happen in the dashboard server before browser ingest.
25
+ */
26
+ groupId?: string;
27
+ }
28
+
29
+ /**
30
+ * Map one pi entry to the custom_entry payload, or null when the entry must
31
+ * NOT be forwarded (non-custom type, missing/empty customType, flow-event).
32
+ */
33
+ export function toCustomEntryForward(entry: unknown): CustomEntryForwardData | null {
34
+ if (!entry || typeof entry !== "object") return null;
35
+ const e = entry as Record<string, unknown>;
36
+ if (e.type !== "custom") return null;
37
+ if (typeof e.customType !== "string" || e.customType === "") return null;
38
+ if (e.customType === "flow-event") return null;
39
+ return {
40
+ customType: e.customType,
41
+ data: e.data,
42
+ entryId: typeof e.id === "string" ? e.id : String(e.id ?? ""),
43
+ };
44
+ }
45
+
46
+ export interface CustomMessageForwardData {
47
+ message: {
48
+ role: "custom";
49
+ customType: string;
50
+ content: unknown;
51
+ display: boolean | undefined;
52
+ details: unknown;
53
+ /** Server-stamped (design D1); never set by the extension. */
54
+ groupId?: string;
55
+ };
56
+ entryId: string | undefined;
57
+ }
58
+
59
+ /**
60
+ * Map one persisted custom MESSAGE (pi.sendMessage) to the `message_end`
61
+ * payload the client reducer's role=custom arm expects, or null when it must
62
+ * NOT be forwarded.
63
+ *
64
+ * EXACT `display === false` exclusion (D5): pi normalizes content but NOT
65
+ * display, so an untyped extension omitting the flag yields undefined — which
66
+ * RENDERS (absent flag = meant to be seen). Mirrors the state-replay arm so
67
+ * live and replay forward identically.
68
+ */
69
+ export function toCustomMessageForward(m: {
70
+ customType: unknown;
71
+ content: unknown;
72
+ display?: unknown;
73
+ details?: unknown;
74
+ entryId?: unknown;
75
+ }): CustomMessageForwardData | null {
76
+ if (!m || typeof m.customType !== "string" || m.customType === "") return null;
77
+ if (m.display === false) return null;
78
+ // flow-event parity with the entry path: pi-flows does not send custom
79
+ // MESSAGES today, but a spoofing customType must not lease the generic
80
+ // card either. See change: render-inline-reasoning-and-custom-entries.
81
+ if (m.customType === "flow-event") return null;
82
+ return {
83
+ message: {
84
+ role: "custom",
85
+ customType: m.customType,
86
+ content: m.content,
87
+ display: m.display as boolean | undefined,
88
+ details: m.details,
89
+ },
90
+ entryId: typeof m.entryId === "string" ? m.entryId : undefined,
91
+ };
92
+ }
@@ -71,6 +71,38 @@ function present(s: string | undefined): string | undefined {
71
71
  return t ? t : undefined;
72
72
  }
73
73
 
74
+ /**
75
+ * Loopback hosts, lexically: the reserved localhost names plus the loopback
76
+ * literal addresses. Hostname-as-hint classification (design D3): a `*.local`
77
+ * mDNS name is REMOTE even though some such names resolve to loopback — the
78
+ * poisoned advertisement was exactly a `*.local` name, and treating it as
79
+ * remote is the strict side of the rule: it can only decline a migration,
80
+ * never adopt a wrong endpoint, and the health gate still guards any
81
+ * legitimate move. DNS resolution is deliberately NOT performed here — the
82
+ * ambiguous "`.local` that resolves loopback" shape is removed at the source
83
+ * by the advertisement gate, and reachability is verified independently.
84
+ */
85
+ function isLoopbackHost(host: string): boolean {
86
+ const h = host.trim().toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
87
+ if (h === "localhost" || h.endsWith(".localhost")) return true;
88
+ if (h === "::1") return true;
89
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true;
90
+ return false;
91
+ }
92
+
93
+ /**
94
+ * {@link isLoopbackHost} for a URL (any scheme). A URL that cannot be parsed
95
+ * classifies REMOTE: the strict side never displaces an established loopback
96
+ * connection on a guess.
97
+ */
98
+ export function isLoopbackEndpoint(url: string): boolean {
99
+ try {
100
+ return isLoopbackHost(new URL(url).hostname);
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
74
106
  /** `ws+unix://<path>:/` — the `ws` package's unix-socket URL form. */
75
107
  function socketUrl(socketPath: string): string {
76
108
  return `ws+unix://${socketPath}:/`;
@@ -38,3 +38,45 @@ export function mapEventToProtocol(
38
38
  },
39
39
  };
40
40
  }
41
+
42
+ /**
43
+ * Bridge forwarding policy for `session_compact`: return a shallow COPY of the
44
+ * event with `compactionEntry` omitted. Every other top-level field is
45
+ * preserved.
46
+ *
47
+ * The field carries pi >= 0.86's prompt-sections + tool-declaration
48
+ * `systemMessage` checkpoint and the compaction `summary`; no dashboard
49
+ * consumer reads either (the client renders the divider from the event's
50
+ * presence and the badge from `reason`/`willRetry`/`estimatedPostCompactionTokens`;
51
+ * the server only clears the `compacting` latch).
52
+ *
53
+ * Copy, never mutate: pi's `ExtensionRunner.emit` hands the SAME event object
54
+ * to every subscribed handler, so `delete event.compactionEntry` would strip the
55
+ * field from unrelated extensions too. Applied at the bridge's `session_compact`
56
+ * forwarding site — NOT inside {@link mapEventToProtocol}, which stays generic
57
+ * over every forwarded event type.
58
+ *
59
+ * See OpenSpec change: filter-system-role-message-forwarding (D6/D7).
60
+ */
61
+ export function redactCompactionEntry(
62
+ event: Record<string, unknown>,
63
+ ): Record<string, unknown> {
64
+ const forwarded: Record<string, unknown> = { ...event };
65
+ delete forwarded.compactionEntry;
66
+ return forwarded;
67
+ }
68
+
69
+ /**
70
+ * Bridge forwarding policy for pi 0.87+ `agent_before_settle`: a shallow COPY
71
+ * without `context` (the boundary preview carries full message arrays, like
72
+ * the never-forwarded `context` event). No dashboard consumer reads it; the
73
+ * event itself has no status effect. Copy, never mutate (shared event object).
74
+ * See change: update-pi-core-1-0-adopt-apis (D5).
75
+ */
76
+ export function redactBeforeSettleContext(
77
+ event: Record<string, unknown>,
78
+ ): Record<string, unknown> {
79
+ const forwarded: Record<string, unknown> = { ...event };
80
+ delete forwarded.context;
81
+ return forwarded;
82
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The bridge's own extension package identity (D8): realpath of the nearest
3
+ * package dir above this module + its version. Cached for the process.
4
+ * Sent on every `session_register`; the server compares it with the active
5
+ * runtime's extension and reloads a stale bridge once.
6
+ *
7
+ * See change: electron-runtime-overlay-updates.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import type { BridgeExtensionIdentity } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
13
+
14
+ function readVersion(file: string): string | undefined {
15
+ try {
16
+ const v = (JSON.parse(fs.readFileSync(file, "utf8")) as { version?: unknown }).version;
17
+ return typeof v === "string" ? v : undefined;
18
+ } catch {
19
+ return undefined; // unreadable manifest — identity is the dir alone
20
+ }
21
+ }
22
+
23
+ function realpathOr(dir: string): string {
24
+ try {
25
+ return fs.realpathSync(dir);
26
+ } catch {
27
+ return dir;
28
+ }
29
+ }
30
+
31
+ /** Walk up from `startDir` to the first dir with a package.json. */
32
+ export function resolveExtensionIdentity(startDir: string): BridgeExtensionIdentity | undefined {
33
+ let dir = startDir;
34
+ for (let i = 0; i < 8; i++) {
35
+ const file = path.join(dir, "package.json");
36
+ if (fs.existsSync(file)) {
37
+ const version = readVersion(file);
38
+ const real = realpathOr(dir);
39
+ return version ? { dir: real, version } : { dir: real };
40
+ }
41
+ const parent = path.dirname(dir);
42
+ if (parent === dir) return undefined;
43
+ dir = parent;
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ let cached: BridgeExtensionIdentity | undefined | null = null;
49
+
50
+ export function bridgeExtensionIdentity(): BridgeExtensionIdentity | undefined {
51
+ if (cached === null) {
52
+ try {
53
+ cached = resolveExtensionIdentity(path.dirname(fileURLToPath(import.meta.url)));
54
+ } catch {
55
+ cached = undefined;
56
+ }
57
+ }
58
+ return cached;
59
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Non-recursive `fs.watch` on a session's git dir(s) (change:
3
+ * optimize-polling-hot-paths, D6). Routes by filename:
4
+ * HEAD / packed-refs / *_HEAD → fast lane (branch-affecting)
5
+ * index / null filename → slow lane (dirtiness; null = unknown event)
6
+ * `persistent: false` so a watcher never keeps pi alive. Modeled on
7
+ * `packages/server/src/git-worktree/folder-head-watcher.ts`.
8
+ *
9
+ * An attach failure (ENOENT/EMFILE/EACCES/EPERM…) returns `false` and leaves
10
+ * the 30 s tick's slow-lane probe as the fallback.
11
+ */
12
+ import { type FSWatcher, watch as fsWatch } from "node:fs";
13
+ import type { ProbeLane } from "./git-probe-scheduler.js";
14
+
15
+ export type WatchFn = (
16
+ dir: string,
17
+ opts: { persistent: boolean },
18
+ listener: (event: string, filename: string | Buffer | null) => void,
19
+ ) => Pick<FSWatcher, "close" | "on">;
20
+
21
+ export interface GitDirWatcherDeps {
22
+ /** Called for every routed event. */
23
+ onEvent: (lane: ProbeLane) => void;
24
+ watch?: WatchFn;
25
+ }
26
+
27
+ export interface GitDirWatcher {
28
+ /** Attach to `gitDir` (+ `commonDir` when different). Returns whether ≥ 1 watch attached. */
29
+ attach(gitDir: string, commonDir?: string): boolean;
30
+ detach(): void;
31
+ }
32
+
33
+ /** Filename → lane; `undefined` = irrelevant (lock files, objects, …). */
34
+ export function laneForGitDirFile(filename: string | null): ProbeLane | undefined {
35
+ if (filename === null) return "slow";
36
+ if (filename === "HEAD" || filename === "packed-refs" || filename.endsWith("_HEAD")) {
37
+ return "fast";
38
+ }
39
+ if (filename === "index") return "slow";
40
+ return undefined;
41
+ }
42
+
43
+ export function createGitDirWatcher(deps: GitDirWatcherDeps): GitDirWatcher {
44
+ const watch: WatchFn = deps.watch ?? ((dir, opts, listener) => fsWatch(dir, opts, listener));
45
+ let watchers: Array<Pick<FSWatcher, "close" | "on">> = [];
46
+
47
+ return {
48
+ attach(gitDir, commonDir) {
49
+ this.detach();
50
+ const dirs = commonDir && commonDir !== gitDir ? [gitDir, commonDir] : [gitDir];
51
+ for (const dir of dirs) {
52
+ try {
53
+ const w = watch(dir, { persistent: false }, (_event, filename) => {
54
+ const name = filename === null ? null : filename.toString();
55
+ const lane = laneForGitDirFile(name);
56
+ if (lane) deps.onEvent(lane);
57
+ });
58
+ w.on("error", () => {
59
+ /* a dead watcher must never throw; the tick probe still covers it */
60
+ });
61
+ watchers.push(w);
62
+ } catch {
63
+ /* not attached */
64
+ }
65
+ }
66
+ return watchers.length > 0;
67
+ },
68
+ detach() {
69
+ for (const w of watchers) {
70
+ try {
71
+ w.close();
72
+ } catch {
73
+ /* already closed */
74
+ }
75
+ }
76
+ watchers = [];
77
+ },
78
+ };
79
+ }
package/src/git-poll.ts CHANGED
@@ -1,38 +1,71 @@
1
1
  /**
2
- * Pure git + name/model poll-tick body, extracted from bridge.ts so the
3
- * session-start timer and the session-change timer share ONE implementation
4
- * and can never drift. Previously the two `setInterval` loops were duplicated;
5
- * the session-change copy dropped name/model polling, so session renames and
6
- * model changes stopped propagating after any new/fork/resume.
2
+ * Pure poll-tick body, extracted from bridge.ts so the session-start timer and
3
+ * the session-change timer share ONE implementation and can never drift.
4
+ * Previously the two `setInterval` loops were duplicated; the session-change
5
+ * copy dropped name/model polling, so session renames and model changes
6
+ * stopped propagating after any new/fork/resume.
7
7
  * See change: fix-stale-ctx-cwd-crash.
8
8
  *
9
9
  * Contract:
10
10
  * - Inactive tick (isActive() === false): no-op.
11
- * - cwd present: run git + cwd-missing checks (these need a directory).
11
+ * - cwd present: run the git tick (cheap checks + a probe REQUEST — git itself
12
+ * runs async in the probe scheduler) and the cwd-missing check.
12
13
  * - cwd absent (e.g. cachedCwd unset after a stale-ctx session swap): skip
13
14
  * git/cwd checks, but STILL run name + model checks every active tick.
15
+ * - pi version is re-read on ticks 1, 11, 21, …; a failed read retries on the
16
+ * next tick. See change: optimize-polling-hot-paths (D7).
17
+ * - A rejecting git tick is logged once and never blocks the rest of the tick
18
+ * or the next tick.
14
19
  */
15
20
  export interface GitPollDeps {
16
21
  isActive: () => boolean;
17
22
  /** Cached ctx.cwd. ctx.cwd is a throwing getter post session-swap, so the
18
23
  * caller caches it and exposes the snapshot here. */
19
24
  cachedCwd: () => string | undefined;
20
- sendGitInfoIfChanged: (cwd: string) => void;
25
+ /** Git part of the tick: facts stamp, HEAD-file branch, one probe request. */
26
+ tickGit: (cwd: string) => void | Promise<void>;
21
27
  sendCwdMissingIfChanged: (cwd: string) => void;
22
28
  sendSessionNameIfChanged: () => void;
23
29
  sendModelUpdateIfChanged: () => void;
24
- /** Re-read pi version; push pi_version_update only on change. */
25
- sendPiVersionIfChanged: () => void;
30
+ /** Re-read pi version; push pi_version_update only on change. Returns whether the read succeeded. */
31
+ sendPiVersionIfChanged: () => boolean | void;
32
+ /** Per-incarnation cadence state (see {@link createGitPollState}). */
33
+ state: GitPollState;
34
+ log?: (line: string) => void;
26
35
  }
27
36
 
28
- export function runGitPollTick(deps: GitPollDeps): void {
37
+ export interface GitPollState {
38
+ tick: number;
39
+ versionRetry: boolean;
40
+ gitErrorLogged: boolean;
41
+ }
42
+
43
+ export function createGitPollState(): GitPollState {
44
+ return { tick: 0, versionRetry: false, gitErrorLogged: false };
45
+ }
46
+
47
+ /** Read the version on ticks 1, 11, 21, … (and retry after a failed read). */
48
+ const VERSION_EVERY_N_TICKS = 10;
49
+
50
+ export async function runGitPollTick(deps: GitPollDeps): Promise<void> {
29
51
  if (!deps.isActive()) return;
52
+ const state = deps.state;
53
+ state.tick += 1;
30
54
  const cwd = deps.cachedCwd();
31
55
  if (cwd) {
32
- deps.sendGitInfoIfChanged(cwd);
56
+ try {
57
+ await deps.tickGit(cwd);
58
+ } catch (err) {
59
+ if (!state.gitErrorLogged) {
60
+ state.gitErrorLogged = true;
61
+ (deps.log ?? ((l: string) => console.error(l)))(`[dashboard] git poll tick failed: ${String(err)}`);
62
+ }
63
+ }
33
64
  deps.sendCwdMissingIfChanged(cwd);
34
65
  }
35
66
  deps.sendSessionNameIfChanged();
36
67
  deps.sendModelUpdateIfChanged();
37
- deps.sendPiVersionIfChanged();
68
+ if (state.versionRetry || (state.tick - 1) % VERSION_EVERY_N_TICKS === 0) {
69
+ state.versionRetry = deps.sendPiVersionIfChanged() === false;
70
+ }
38
71
  }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Two-lane, debounced scheduler for the async `git status` probe (change:
3
+ * optimize-polling-hot-paths, D6). Pure: clock and timers are injected.
4
+ *
5
+ * - `request(lane, reason)` records a wish for a probe; it never spawns.
6
+ * - 750 ms trailing debounce, capped (MAX_WAIT) so a steady event stream
7
+ * cannot starve the probe.
8
+ * - fast lane (branch-affecting events): probe starts ≥ 2 s apart;
9
+ * slow lane (dirtiness: tick, mutating tool, index events): ≥ 10 s apart.
10
+ * A request inside its window is deferred to the window's end, never dropped.
11
+ * A pending fast request upgrades a pending slow one; a fast probe also
12
+ * satisfies the slow lane's spacing.
13
+ * - One probe in flight; requests meanwhile set a dirty bit → exactly one
14
+ * follow-up. A probe resolving `"discard"` (HEAD moved / stale result)
15
+ * requests one more fast probe.
16
+ * - `dispose()` clears the timer; a late settle neither re-arms nor re-requests.
17
+ */
18
+
19
+ export type ProbeLane = "fast" | "slow";
20
+ export type ProbeReason = "tick" | "tool" | "watch" | "refresh";
21
+ export type ProbeOutcome = "ok" | "discard" | void;
22
+
23
+ type Timer = ReturnType<typeof setTimeout>;
24
+
25
+ export interface GitProbeSchedulerDeps {
26
+ /** Run one probe; never rejects. `"discard"` → run one more fast probe. */
27
+ probe: (info: { lane: ProbeLane; reason: ProbeReason }) => Promise<ProbeOutcome>;
28
+ now?: () => number;
29
+ setTimer?: (fn: () => void, ms: number) => Timer;
30
+ clearTimer?: (t: Timer) => void;
31
+ }
32
+
33
+ export interface GitProbeScheduler {
34
+ request(lane: ProbeLane, reason: ProbeReason): void;
35
+ dispose(): void;
36
+ }
37
+
38
+ const PROBE_DEBOUNCE_MS = 750;
39
+ const PROBE_MAX_WAIT_MS = 2_000;
40
+ const FAST_LANE_SPACING_MS = 2_000;
41
+ const SLOW_LANE_SPACING_MS = 10_000;
42
+
43
+ interface Pending {
44
+ lane: ProbeLane;
45
+ reason: ProbeReason;
46
+ firstAt: number;
47
+ lastAt: number;
48
+ }
49
+
50
+ export function createGitProbeScheduler(deps: GitProbeSchedulerDeps): GitProbeScheduler {
51
+ const now = deps.now ?? Date.now;
52
+ const setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
53
+ const clearTimer = deps.clearTimer ?? ((t) => clearTimeout(t));
54
+
55
+ let disposed = false;
56
+ let inFlight = false;
57
+ let pending: Pending | undefined;
58
+ let timer: Timer | undefined;
59
+ const lastStart = { fast: Number.NEGATIVE_INFINITY, slow: Number.NEGATIVE_INFINITY };
60
+
61
+ function schedule(): void {
62
+ if (disposed || inFlight || !pending) return;
63
+ const spacing = pending.lane === "fast" ? FAST_LANE_SPACING_MS : SLOW_LANE_SPACING_MS;
64
+ const debounced = Math.min(pending.lastAt + PROBE_DEBOUNCE_MS, pending.firstAt + PROBE_MAX_WAIT_MS);
65
+ const due = Math.max(debounced, lastStart[pending.lane] + spacing);
66
+ if (timer) clearTimer(timer);
67
+ timer = setTimer(() => {
68
+ timer = undefined;
69
+ start().catch(() => {
70
+ /* start() never rejects: the probe contract is non-throwing */
71
+ });
72
+ }, Math.max(0, due - now()));
73
+ }
74
+
75
+ async function start(): Promise<void> {
76
+ if (disposed || inFlight || !pending) return;
77
+ const { lane, reason } = pending;
78
+ pending = undefined;
79
+ inFlight = true;
80
+ const t = now();
81
+ lastStart[lane] = t;
82
+ if (lane === "fast") lastStart.slow = t; // a fast probe refreshes status too
83
+ let outcome: ProbeOutcome;
84
+ try {
85
+ outcome = await deps.probe({ lane, reason });
86
+ } catch {
87
+ outcome = undefined; // probe never rejects; defensive
88
+ }
89
+ inFlight = false;
90
+ if (disposed) return;
91
+ if (outcome === "discard") request("fast", "watch");
92
+ else schedule();
93
+ }
94
+
95
+ function request(lane: ProbeLane, reason: ProbeReason): void {
96
+ if (disposed) return;
97
+ const t = now();
98
+ if (!pending) {
99
+ pending = { lane, reason, firstAt: t, lastAt: t };
100
+ } else {
101
+ pending.lastAt = t;
102
+ if (lane === "fast" && pending.lane === "slow") {
103
+ pending.lane = "fast";
104
+ pending.reason = reason;
105
+ }
106
+ }
107
+ schedule();
108
+ }
109
+
110
+ return {
111
+ request,
112
+ dispose() {
113
+ disposed = true;
114
+ if (timer) clearTimer(timer);
115
+ timer = undefined;
116
+ pending = undefined;
117
+ },
118
+ };
119
+ }