@blackbelt-technology/pi-agent-dashboard 0.6.1 → 0.7.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 (105) hide show
  1. package/README.md +40 -38
  2. package/docs/architecture.md +148 -2
  3. package/package.json +6 -4
  4. package/packages/extension/package.json +4 -3
  5. package/packages/extension/src/AGENTS.md +1 -0
  6. package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +333 -0
  7. package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +145 -0
  8. package/packages/extension/src/__tests__/provider-register-native-models.test.ts +182 -0
  9. package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +54 -1
  10. package/packages/extension/src/__tests__/single-derivation-guard.test.ts +39 -0
  11. package/packages/extension/src/bridge-context.ts +21 -0
  12. package/packages/extension/src/bridge.ts +41 -6
  13. package/packages/extension/src/openspec-cli-shim.ts +173 -0
  14. package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +7 -0
  15. package/packages/extension/src/provider-register.ts +180 -17
  16. package/packages/extension/src/provider-register.ts.AGENTS.md +1 -1
  17. package/packages/extension/src/session-sync.ts +9 -4
  18. package/packages/server/package.json +8 -8
  19. package/packages/server/src/__tests__/decorate-goals-spend.test.ts +79 -0
  20. package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +44 -0
  21. package/packages/server/src/__tests__/goal-routes.test.ts +62 -7
  22. package/packages/server/src/__tests__/goal-supervisor.test.ts +4 -4
  23. package/packages/server/src/__tests__/headless-pid-registry.test.ts +7 -3
  24. package/packages/server/src/__tests__/memory-event-store.test.ts +369 -13
  25. package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +67 -0
  26. package/packages/server/src/__tests__/pi-changelog-routes.test.ts +9 -2
  27. package/packages/server/src/__tests__/recovery-offer.test.ts +42 -7
  28. package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +188 -0
  29. package/packages/server/src/__tests__/session-tags-persistence.test.ts +29 -0
  30. package/packages/server/src/browser-handlers/AGENTS.md +1 -1
  31. package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +98 -1
  32. package/packages/server/src/browser-handlers/handler-context.ts +24 -13
  33. package/packages/server/src/browser-handlers/session-action-handler.ts +12 -1
  34. package/packages/server/src/browser-handlers/session-meta-handler.ts +29 -0
  35. package/packages/server/src/embed-lifecycle/AGENTS.md +17 -0
  36. package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +129 -0
  37. package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +84 -0
  38. package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +73 -0
  39. package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +173 -0
  40. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +26 -0
  41. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +32 -0
  42. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +106 -0
  43. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +39 -0
  44. package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +77 -0
  45. package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +175 -0
  46. package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +77 -0
  47. package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +38 -0
  48. package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +140 -0
  49. package/packages/server/src/embed-lifecycle/caps.ts +88 -0
  50. package/packages/server/src/embed-lifecycle/cwd-allowlist.ts +50 -0
  51. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +90 -0
  52. package/packages/server/src/embed-lifecycle/identity-key.ts +73 -0
  53. package/packages/server/src/embed-lifecycle/idle-reaper.ts +161 -0
  54. package/packages/server/src/embed-lifecycle/lifecycle-event-capture.ts +30 -0
  55. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +70 -0
  56. package/packages/server/src/embed-lifecycle/liveness-probe.ts +123 -0
  57. package/packages/server/src/embed-lifecycle/quiescence.ts +159 -0
  58. package/packages/server/src/embed-lifecycle/session-lifecycle-policy.ts +31 -0
  59. package/packages/server/src/embed-lifecycle/visitor-session-registry.ts +178 -0
  60. package/packages/server/src/event-wiring.ts +20 -0
  61. package/packages/server/src/event-wiring.ts.AGENTS.md +1 -0
  62. package/packages/server/src/goal/AGENTS.md +1 -0
  63. package/packages/server/src/goal/decorate-goals-spend.ts +47 -0
  64. package/packages/server/src/goal/goal-supervisor.ts +5 -3
  65. package/packages/server/src/model-proxy/AGENTS.md +2 -2
  66. package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +155 -0
  67. package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +92 -0
  68. package/packages/server/src/model-proxy/internal-registry.ts +49 -23
  69. package/packages/server/src/model-proxy/registry-singleton.ts +15 -9
  70. package/packages/server/src/pairing/browser-gateway.ts +40 -11
  71. package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +1 -1
  72. package/packages/server/src/persistence/memory-event-store.ts +369 -23
  73. package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +1 -1
  74. package/packages/server/src/routes/AGENTS.md +2 -2
  75. package/packages/server/src/routes/goal-routes.ts +14 -9
  76. package/packages/server/src/routes/models-introspection-routes.ts +10 -0
  77. package/packages/server/src/routes/system-routes.ts +16 -1
  78. package/packages/server/src/server.ts +216 -65
  79. package/packages/server/src/server.ts.AGENTS.md +1 -1
  80. package/packages/server/src/session/memory-session-manager.ts +4 -0
  81. package/packages/server/src/session/session-scanner.ts +9 -0
  82. package/packages/server/src/session/session-to-meta.ts +6 -0
  83. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -4
  84. package/packages/shared/package.json +1 -1
  85. package/packages/shared/src/AGENTS.md +5 -3
  86. package/packages/shared/src/__tests__/models-json-reader.test.ts +100 -0
  87. package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +125 -0
  88. package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +112 -0
  89. package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +177 -0
  90. package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +6 -3
  91. package/packages/shared/src/browser-protocol.ts +22 -0
  92. package/packages/shared/src/config.ts +70 -0
  93. package/packages/shared/src/dashboard-plugin/AGENTS.md +1 -1
  94. package/packages/shared/src/dashboard-plugin/slot-props.ts +9 -0
  95. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +19 -0
  96. package/packages/shared/src/models-json-reader.ts +98 -0
  97. package/packages/shared/src/platform/AGENTS.md +1 -1
  98. package/packages/shared/src/platform/paths.ts +12 -0
  99. package/packages/shared/src/session-meta.ts +9 -0
  100. package/packages/shared/src/types.ts +52 -1
  101. package/docs/AGENTS.md +0 -47
  102. package/packages/extension/AGENTS.md +0 -7
  103. package/packages/server/AGENTS.md +0 -7
  104. package/packages/shared/AGENTS.md +0 -7
  105. package/scripts/AGENTS.md +0 -38
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Canonical identity key for the idempotent acquire path (D10).
3
+ *
4
+ * `identityKey = visitor-or-channel-or-trigger identity + canonical cwd +
5
+ * agent/profile identity`, where the canonical cwd is realpath-resolved and
6
+ * case-normalized so symlinks, worktrees, and case-insensitive filesystems
7
+ * (macOS/Windows default) collapse one physical dir to a single key — otherwise
8
+ * one visitor/cwd maps to many keys and spawns many sessions (E11).
9
+ *
10
+ * Case normalization is platform-gated: lower-casing is applied ONLY on
11
+ * case-insensitive filesystems, so `/Foo` and `/foo` (genuinely distinct on
12
+ * case-sensitive Linux) are NOT wrongly collapsed there.
13
+ *
14
+ * See OpenSpec change: add-embed-session-lifecycle.
15
+ */
16
+ import { realpathSync } from "node:fs";
17
+ import { caseInsensitiveFilesystem } from "@blackbelt-technology/pi-dashboard-shared/platform/paths.js";
18
+
19
+ const NUL = "\u0000"; // unambiguous separator — cannot appear in a path/identity
20
+
21
+ export interface IdentityKeyParts {
22
+ /** visitorId | channelId | trigger — the machine-front identity. */
23
+ visitorId: string;
24
+ /** Requested working directory (raw; canonicalized here). */
25
+ cwd: string;
26
+ /** Agent/profile identity; empty string when unspecified. */
27
+ agentIdentity?: string;
28
+ }
29
+
30
+ export interface CanonicalizeOptions {
31
+ /** Test seam for `realpathSync`. */
32
+ realpath?: (p: string) => string;
33
+ /** Force case-insensitivity (defaults to darwin/win32 detection). */
34
+ caseInsensitive?: boolean;
35
+ }
36
+
37
+ const platformIsCaseInsensitive = caseInsensitiveFilesystem();
38
+
39
+ /**
40
+ * Realpath-resolve + case-normalize a cwd. A realpath failure (missing dir)
41
+ * falls back to the input path so an out-of-allowlist reject still has a stable
42
+ * key to log. Never throws.
43
+ */
44
+ export function canonicalizeCwd(cwd: string, opts: CanonicalizeOptions = {}): string {
45
+ const realpath = opts.realpath ?? realpathSync;
46
+ const caseInsensitive = opts.caseInsensitive ?? platformIsCaseInsensitive;
47
+ let resolved: string;
48
+ try {
49
+ resolved = realpath(cwd);
50
+ } catch {
51
+ resolved = cwd;
52
+ }
53
+ return caseInsensitive ? resolved.toLowerCase() : resolved;
54
+ }
55
+
56
+ /** Extract the visitor/channel/trigger identity (first segment) from a key. */
57
+ export function visitorIdOf(key: string): string {
58
+ return key.split(NUL)[0] ?? "";
59
+ }
60
+
61
+ /** Join already-canonical parts into the composite key (no canonicalization). */
62
+ export function composeIdentityKey(
63
+ visitorId: string,
64
+ canonicalCwd: string,
65
+ agentIdentity = "",
66
+ ): string {
67
+ return [visitorId, canonicalCwd, agentIdentity].join(NUL);
68
+ }
69
+
70
+ /** Build the composite identity key from its parts (cwd canonicalized). */
71
+ export function buildIdentityKey(parts: IdentityKeyParts, opts: CanonicalizeOptions = {}): string {
72
+ return composeIdentityKey(parts.visitorId, canonicalizeCwd(parts.cwd, opts), parts.agentIdentity);
73
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Idle reaper loop (three gears) for machine-fronted `ephemeral` sessions.
3
+ *
4
+ * A thin orchestrator around the pure `decideReap` core: per sweep it assembles
5
+ * a `LifecycleSignals` snapshot for each ephemeral session from injected live
6
+ * deps (liveness probe, subscriber/terminal/ask/queue sources), asks
7
+ * `decideReap` for a verdict, and applies it:
8
+ * - gear 1 `idle` → `killBySessionId` (graceful ladder, lossless)
9
+ * - gear 2 `stop-after-turn` → `sendStopAfterTurn` (finish turn, clean exit)
10
+ * - gear 3 `phantom` → `killBySessionId` (SAME graceful ladder, NOT a
11
+ * bare SIGKILL — bounds the session-file
12
+ * mid-write window, keeps resume intact) (E16)
13
+ *
14
+ * All policy lives in `decideReap`; this file only maps live state → signals and
15
+ * verdict → action, so it stays trivially injectable for tests (no server
16
+ * instance, fake deps). Dormant when `config().enabled` is false (E22).
17
+ *
18
+ * See OpenSpec change: add-embed-session-lifecycle.
19
+ */
20
+ import type { EmbedLifecycleConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
21
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
22
+ import type { LivenessProbe } from "./liveness-probe.js";
23
+ import {
24
+ decideReap,
25
+ type LifecycleSignals,
26
+ type LifecycleThresholds,
27
+ type ReapReason,
28
+ } from "./quiescence.js";
29
+ import { isEphemeral } from "./session-lifecycle-policy.js";
30
+
31
+ /** CPU% at or below which a pi tree counts as "~0 CPU" for phantom detection. */
32
+ export const CPU_IDLE_THRESHOLD = 1;
33
+
34
+ export interface ReaperDeps {
35
+ /** Live config read each sweep (so an operator toggle takes effect). */
36
+ config: () => EmbedLifecycleConfig;
37
+ /** All known sessions (durable ones are filtered out here). */
38
+ listSessions: () => readonly DashboardSession[];
39
+ /** Bounded pid-tree + CPU probe. */
40
+ probe: LivenessProbe;
41
+ /** A browser is currently subscribed to the session. */
42
+ hasSubscriber: (sessionId: string) => boolean;
43
+ /** A live terminal PTY shares the cwd. */
44
+ hasTerminalInCwd: (cwd: string) => boolean;
45
+ /** An unanswered `ask_user` is tracked for the session. */
46
+ hasPendingAsk: (sessionId: string) => boolean;
47
+ /** Queued follow-up / steering counts (pi in-memory queue mirror). */
48
+ queueCounts: (sessionId: string) => { followUp: number; steering: number };
49
+ /** Graceful SIGTERM→grace→SIGKILL runtime kill (gear 1 + gear 3). */
50
+ killBySessionId: (sessionId: string) => Promise<boolean>;
51
+ /** Latch `stop_after_turn` so the session ends cleanly at `turn_end` (gear 2). */
52
+ sendStopAfterTurn: (sessionId: string) => void;
53
+ /** Fires on every applied reap for the diagnostics counters. */
54
+ onReap?: (sessionId: string, reason: ReapReason) => void;
55
+ /** Injectable clock. */
56
+ now?: () => number;
57
+ }
58
+
59
+ export interface IdleReaper {
60
+ /** Run one sweep across all ephemeral sessions. */
61
+ sweepOnce: () => Promise<void>;
62
+ /** Start the periodic sweep on the config cadence. */
63
+ start: () => void;
64
+ /** Stop the periodic sweep. */
65
+ stop: () => void;
66
+ }
67
+
68
+ function toThresholds(cfg: EmbedLifecycleConfig): LifecycleThresholds {
69
+ return {
70
+ idleTimeoutMs: cfg.idleTimeoutSeconds * 1000,
71
+ graceWindowMs: cfg.graceWindowSeconds * 1000,
72
+ hardCeilingMs: cfg.hardCeilingSeconds * 1000,
73
+ };
74
+ }
75
+
76
+ export function createIdleReaper(deps: ReaperDeps): IdleReaper {
77
+ const now = deps.now ?? Date.now;
78
+ // Guards against re-selecting a session already mid-reap across overlapping
79
+ // sweeps (and, later, coordinating with the caps reclaim path).
80
+ const reaping = new Set<string>();
81
+ let timer: ReturnType<typeof setInterval> | undefined;
82
+
83
+ async function assembleSignals(s: DashboardSession): Promise<LifecycleSignals> {
84
+ const probeSnap =
85
+ typeof s.pid === "number"
86
+ ? await deps.probe(s.pid)
87
+ : { ok: false, childCount: 0, cpuPercent: 0 };
88
+ const q = deps.queueCounts(s.id);
89
+ return {
90
+ lifecyclePolicy: s.lifecyclePolicy,
91
+ lastSettledAt: s.lastSettledAt,
92
+ lastRunStartedAt: s.lastRunStartedAt,
93
+ currentTool: s.currentTool,
94
+ hasPendingAsk: deps.hasPendingAsk(s.id),
95
+ followUpCount: q.followUp,
96
+ steeringCount: q.steering,
97
+ // Unknown probe ⇒ assume a live child (never idle-reap on unknown) and
98
+ // NOT cpu-idle (never phantom-reap on unknown) — both the SAFE direction.
99
+ hasLiveChild: probeSnap.ok ? probeSnap.childCount > 0 : true,
100
+ hasTerminalInCwd: deps.hasTerminalInCwd(s.cwd),
101
+ hasSubscriber: deps.hasSubscriber(s.id),
102
+ activatedAt: s.startedAt,
103
+ lastActivityAt: s.lastActivityAt,
104
+ cpuIdle: probeSnap.ok ? probeSnap.cpuPercent <= CPU_IDLE_THRESHOLD : false,
105
+ };
106
+ }
107
+
108
+ async function reapOne(s: DashboardSession, t: LifecycleThresholds): Promise<void> {
109
+ if (reaping.has(s.id)) return;
110
+ const verdict = decideReap(await assembleSignals(s), t, now());
111
+ if (verdict.action !== "reap") return;
112
+
113
+ reaping.add(s.id);
114
+ try {
115
+ if (verdict.reason === "stop-after-turn") {
116
+ deps.sendStopAfterTurn(s.id);
117
+ } else {
118
+ // idle + phantom both use the graceful, resumable kill ladder.
119
+ await deps.killBySessionId(s.id);
120
+ }
121
+ deps.onReap?.(s.id, verdict.reason);
122
+ } finally {
123
+ reaping.delete(s.id);
124
+ }
125
+ }
126
+
127
+ async function sweepOnce(): Promise<void> {
128
+ const cfg = deps.config();
129
+ if (!cfg.enabled) return; // dormant when the feature is off (E22)
130
+ const t = toThresholds(cfg);
131
+ for (const s of deps.listSessions()) {
132
+ if (s.status === "ended") continue; // already gone
133
+ if (!isEphemeral(s)) continue; // durable sessions are never governed (E1)
134
+ // Isolate per-session failures: a throwing probe / kill must not reject
135
+ // the whole sweep (which runs unattended via setInterval → unhandled
136
+ // rejection) nor skip the remaining sessions.
137
+ try {
138
+ await reapOne(s, t);
139
+ } catch (err) {
140
+ console.warn(`[embed-lifecycle] reap sweep failed for ${s.id}:`, err);
141
+ }
142
+ }
143
+ }
144
+
145
+ return {
146
+ sweepOnce,
147
+ start() {
148
+ if (timer) return;
149
+ const intervalMs = Math.max(1, deps.config().sweepIntervalSeconds) * 1000;
150
+ timer = setInterval(() => {
151
+ void sweepOnce();
152
+ }, intervalMs);
153
+ // Do not keep the process alive solely for the reaper.
154
+ timer.unref?.();
155
+ },
156
+ stop() {
157
+ if (timer) clearInterval(timer);
158
+ timer = undefined;
159
+ },
160
+ };
161
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Pure capture of the lifecycle run-boundary timestamps from a forwarded event.
3
+ *
4
+ * The quiescence gate reads `lastSettledAt` / `lastRunStartedAt` (D3) rather
5
+ * than an inferred `status`. `agent_settled` is bridge-normalized — native on
6
+ * pi ≥ 0.80.4, synthesized after `agent_end` on the floor — so this capture is
7
+ * version-agnostic by construction: it keys on the event NAME only, with no
8
+ * `piVersion` branch (E23).
9
+ *
10
+ * See OpenSpec change: add-embed-session-lifecycle.
11
+ */
12
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
13
+
14
+ export type LifecycleTimestampUpdate = Partial<
15
+ Pick<DashboardSession, "lastRunStartedAt" | "lastSettledAt">
16
+ >;
17
+
18
+ /**
19
+ * Map a forwarded event type to a lifecycle-timestamp update, or `null` when
20
+ * the event is not a run boundary. `agent_start` marks a run in flight;
21
+ * `agent_settled` marks it at rest.
22
+ */
23
+ export function captureLifecycleTimestamp(
24
+ eventType: string,
25
+ now: number,
26
+ ): LifecycleTimestampUpdate | null {
27
+ if (eventType === "agent_start") return { lastRunStartedAt: now };
28
+ if (eventType === "agent_settled") return { lastSettledAt: now };
29
+ return null;
30
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Lifecycle observability counters (D-observability).
3
+ *
4
+ * A tiny in-memory counter store fed by the acquire/reap/cap decision hooks:
5
+ * reuse hit/miss, reaped-by-reason, capacity rejections. Live active/idle counts
6
+ * are computed at snapshot time from injected session accessors (not
7
+ * accumulated), so they always reflect current reality. Exposed via
8
+ * `/api/health` (and/or a JWT-gated diagnostics endpoint) so an operator can
9
+ * answer "why did my embed spawn a second pi" / "why was my session reaped".
10
+ *
11
+ * See OpenSpec change: add-embed-session-lifecycle.
12
+ */
13
+ import type { ReapReason } from "./quiescence.js";
14
+
15
+ export interface LifecycleMetricsSnapshot {
16
+ /** Live count of active ephemeral sessions. */
17
+ activeEphemeral: number;
18
+ /** Live count of quiescent (idle) ephemeral sessions. */
19
+ idleEphemeral: number;
20
+ /** Cumulative reaps by reason. */
21
+ reaped: Record<ReapReason, number>;
22
+ /** Cumulative capacity rejections. */
23
+ capacityRejections: number;
24
+ /** Acquire reuse hits (returned a live session). */
25
+ reuseHits: number;
26
+ /** Acquire reuse misses (spawned or resumed). */
27
+ reuseMisses: number;
28
+ }
29
+
30
+ export interface LifecycleMetricsDeps {
31
+ /** Live active-ephemeral count (computed at snapshot). */
32
+ countActiveEphemeral?: () => number;
33
+ /** Live idle/quiescent-ephemeral count (computed at snapshot). */
34
+ countIdleEphemeral?: () => number;
35
+ }
36
+
37
+ export interface LifecycleMetrics {
38
+ recordReap: (reason: ReapReason) => void;
39
+ recordCapacityReject: () => void;
40
+ recordReuse: (hit: boolean) => void;
41
+ snapshot: () => LifecycleMetricsSnapshot;
42
+ }
43
+
44
+ export function createLifecycleMetrics(deps: LifecycleMetricsDeps = {}): LifecycleMetrics {
45
+ const reaped: Record<ReapReason, number> = { idle: 0, "stop-after-turn": 0, phantom: 0 };
46
+ let capacityRejections = 0;
47
+ let reuseHits = 0;
48
+ let reuseMisses = 0;
49
+
50
+ return {
51
+ recordReap: (reason) => {
52
+ reaped[reason] += 1;
53
+ },
54
+ recordCapacityReject: () => {
55
+ capacityRejections += 1;
56
+ },
57
+ recordReuse: (hit) => {
58
+ if (hit) reuseHits += 1;
59
+ else reuseMisses += 1;
60
+ },
61
+ snapshot: () => ({
62
+ activeEphemeral: deps.countActiveEphemeral?.() ?? 0,
63
+ idleEphemeral: deps.countIdleEphemeral?.() ?? 0,
64
+ reaped: { ...reaped },
65
+ capacityRejections,
66
+ reuseHits,
67
+ reuseMisses,
68
+ }),
69
+ };
70
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Bounded pid-child-tree + CPU liveness probe.
3
+ *
4
+ * `process-classifier` classifies a bridge-provided `process_list` but carries
5
+ * no CPU field and does not walk the pid tree (D4 correction). This probe adds
6
+ * exactly that: given a session's root `pi` pid it returns whether the tree has
7
+ * a live child and the aggregate CPU% — serving BOTH the quiescence gate's
8
+ * "no live child" condition (gear 1) AND phantom detection's "~0 CPU" condition
9
+ * (gear 3).
10
+ *
11
+ * The tree-walk + CPU-sum is a pure function (`summarizeProcessTree`) over
12
+ * parsed `ps` rows, unit-testable without spawning anything. The default
13
+ * implementation shells out to `ps` (posix) with a hard timeout; on any failure
14
+ * it returns `{ ok: false }` so the reaper can map an unknown result to the
15
+ * SAFE direction (never force-reap on unknown CPU; never idle-reap on unknown
16
+ * children).
17
+ *
18
+ * See OpenSpec change: add-embed-session-lifecycle.
19
+ */
20
+ import { execFileAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
21
+
22
+ export interface LivenessSnapshot {
23
+ /** False when the probe could not be taken (ps failed / unsupported). */
24
+ ok: boolean;
25
+ /** Count of descendant processes of the root pid (excluding the root). */
26
+ childCount: number;
27
+ /** Aggregate CPU% across the root pid's tree (0 when wedged/idle). */
28
+ cpuPercent: number;
29
+ }
30
+
31
+ /** Probe a session's pi process tree by its root pid. */
32
+ export type LivenessProbe = (rootPid: number) => Promise<LivenessSnapshot>;
33
+
34
+ /** One parsed `ps` row: a process, its parent, and its instantaneous CPU%. */
35
+ export interface PsRow {
36
+ pid: number;
37
+ ppid: number;
38
+ cpu: number;
39
+ }
40
+
41
+ /**
42
+ * Pure tree summariser: BFS the descendants of `rootPid` over the parsed rows,
43
+ * counting children and summing CPU% across the root and every descendant.
44
+ */
45
+ export function summarizeProcessTree(rows: readonly PsRow[], rootPid: number): LivenessSnapshot {
46
+ const byParent = new Map<number, PsRow[]>();
47
+ const byPid = new Map<number, PsRow>();
48
+ for (const r of rows) {
49
+ byPid.set(r.pid, r);
50
+ const siblings = byParent.get(r.ppid) ?? [];
51
+ siblings.push(r);
52
+ byParent.set(r.ppid, siblings);
53
+ }
54
+
55
+ const root = byPid.get(rootPid);
56
+ if (!root) return { ok: true, childCount: 0, cpuPercent: 0 };
57
+
58
+ let cpuPercent = root.cpu;
59
+ let childCount = 0;
60
+ const queue = [rootPid];
61
+ const seen = new Set<number>([rootPid]);
62
+ while (queue.length > 0) {
63
+ const pid = queue.shift() as number;
64
+ for (const child of byParent.get(pid) ?? []) {
65
+ if (seen.has(child.pid)) continue; // guard against pid-cycle edge cases
66
+ seen.add(child.pid);
67
+ childCount += 1;
68
+ cpuPercent += child.cpu;
69
+ queue.push(child.pid);
70
+ }
71
+ }
72
+ return { ok: true, childCount, cpuPercent };
73
+ }
74
+
75
+ /** Parse `ps -o pid=,ppid=,pcpu=` whitespace-columned output into rows. */
76
+ export function parsePsOutput(output: string): PsRow[] {
77
+ const rows: PsRow[] = [];
78
+ for (const line of output.split("\n")) {
79
+ const parts = line.trim().split(/\s+/);
80
+ if (parts.length < 3) continue;
81
+ const pid = Number.parseInt(parts[0], 10);
82
+ const ppid = Number.parseInt(parts[1], 10);
83
+ const cpu = Number.parseFloat(parts[2]);
84
+ if (Number.isFinite(pid) && Number.isFinite(ppid)) {
85
+ rows.push({ pid, ppid, cpu: Number.isFinite(cpu) ? cpu : 0 });
86
+ }
87
+ }
88
+ return rows;
89
+ }
90
+
91
+ export interface LivenessProbeOptions {
92
+ /** Hard timeout for the `ps` call. */
93
+ timeoutMs?: number;
94
+ /** Injectable `ps` runner (tests / non-posix). Returns raw stdout. */
95
+ runPs?: () => Promise<string>;
96
+ }
97
+
98
+ /**
99
+ * Default posix liveness probe. Shells out to `ps` once, parses, and summarises
100
+ * the root pid's tree. Never throws — returns `{ ok: false }` on any failure so
101
+ * the caller maps an unknown result to the safe direction.
102
+ */
103
+ export function createLivenessProbe(options: LivenessProbeOptions = {}): LivenessProbe {
104
+ const timeoutMs = options.timeoutMs ?? 2000;
105
+ const runPs =
106
+ options.runPs ??
107
+ (async () => {
108
+ const { stdout } = await execFileAsync("ps", ["-eo", "pid=,ppid=,pcpu="], {
109
+ timeout: timeoutMs,
110
+ encoding: "utf-8",
111
+ });
112
+ return typeof stdout === "string" ? stdout : stdout.toString("utf-8");
113
+ });
114
+
115
+ return async (rootPid: number): Promise<LivenessSnapshot> => {
116
+ try {
117
+ const rows = parsePsOutput(await runPs());
118
+ return summarizeProcessTree(rows, rootPid);
119
+ } catch {
120
+ return { ok: false, childCount: 0, cpuPercent: 0 };
121
+ }
122
+ };
123
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Pure quiescence / reap-decision core for the embed-session-lifecycle reaper.
3
+ *
4
+ * `decideReap` is a side-effect-free function of a signal snapshot + thresholds
5
+ * + `now`. It encodes the three-gear policy (D2, D4) and every veto so the
6
+ * reaper (Section 4) is a thin loop that assembles signals, calls this, and
7
+ * acts on the verdict. Being pure, it is trivially unit-testable (the X4
8
+ * one-signal-veto matrix, the E12 BVA boundary, the E15 phantom decision-table,
9
+ * the F1/F2 stop-after-turn guard) with no server instance.
10
+ *
11
+ * Design invariants:
12
+ * - "At rest" is derived from the captured `agent_settled` timestamps, NOT an
13
+ * inferred `status` (D3): a run is at rest only when a terminal settle is the
14
+ * latest run signal.
15
+ * - Idle reaping (gear 1) requires FULL quiescence — every busy signal clear —
16
+ * because a runtime kill is lossless ONLY for a session with nothing in
17
+ * flight (D2).
18
+ * - A subscribed browser and the post-spawn/resume grace window veto ALL gears
19
+ * (X4 watcher, D12 grace).
20
+ * - Phantom (gear 3) additionally requires no pending ask + empty queues (X5)
21
+ * so a session merely blocked on human input is never force-reaped.
22
+ *
23
+ * See OpenSpec change: add-embed-session-lifecycle.
24
+ */
25
+ import { isEphemeral } from "./session-lifecycle-policy.js";
26
+
27
+ /** The reason a session was reaped, surfaced in diagnostics (E20/E21). */
28
+ export type ReapReason = "idle" | "stop-after-turn" | "phantom";
29
+
30
+ /** The injectable per-session snapshot the reaper assembles from live deps. */
31
+ export interface LifecycleSignals {
32
+ /** Absent ⇒ durable; only ephemeral sessions are governed. */
33
+ lifecyclePolicy?: "ephemeral" | "durable";
34
+ /** Epoch ms of the latest captured `agent_settled` (terminal at-rest mark). */
35
+ lastSettledAt?: number;
36
+ /** Epoch ms of the latest `agent_start`; newer than `lastSettledAt` ⇒ mid-run. */
37
+ lastRunStartedAt?: number;
38
+ /** Non-null while a tool is executing. */
39
+ currentTool?: string | null;
40
+ /** An unanswered `ask_user` is tracked for the session. */
41
+ hasPendingAsk: boolean;
42
+ /** Queued follow-up prompts (mirror of pi's in-memory queue). */
43
+ followUpCount: number;
44
+ /** Queued steering messages. */
45
+ steeringCount: number;
46
+ /** The session's pi process tree has a live child (from the liveness probe). */
47
+ hasLiveChild: boolean;
48
+ /** A live terminal PTY shares the session's cwd. */
49
+ hasTerminalInCwd: boolean;
50
+ /** A browser is currently subscribed to the session. */
51
+ hasSubscriber: boolean;
52
+ /** Epoch ms when the session was spawned or last resumed (grace anchor). */
53
+ activatedAt: number;
54
+ /** Epoch ms of the most recent activity event. */
55
+ lastActivityAt?: number;
56
+ /** Near-zero CPU across the pi tree (phantom liveness signal). */
57
+ cpuIdle: boolean;
58
+ }
59
+
60
+ export interface LifecycleThresholds {
61
+ /** Idle reap fires when `now - lastActivityAt` exceeds this. */
62
+ idleTimeoutMs: number;
63
+ /** Freshly spawned/resumed sessions are exempt for this long. */
64
+ graceWindowMs: number;
65
+ /** Phantom force-reap fires when a run streams longer than this without settling. */
66
+ hardCeilingMs: number;
67
+ }
68
+
69
+ export type ReapVerdict =
70
+ | { action: "reap"; reason: ReapReason }
71
+ | { action: "skip"; reason: string };
72
+
73
+ const skip = (reason: string): ReapVerdict => ({ action: "skip", reason });
74
+ const reap = (reason: ReapReason): ReapVerdict => ({ action: "reap", reason });
75
+
76
+ /**
77
+ * A run is "at rest" when a terminal `agent_settled` is the latest run signal.
78
+ * A session that has never started a run is at rest by definition (nothing in
79
+ * flight); a run that started without a later settle is mid-run.
80
+ */
81
+ export function isAtRest(s: Pick<LifecycleSignals, "lastSettledAt" | "lastRunStartedAt">): boolean {
82
+ if (s.lastRunStartedAt === undefined) return true;
83
+ if (s.lastSettledAt === undefined) return false;
84
+ return s.lastSettledAt >= s.lastRunStartedAt;
85
+ }
86
+
87
+ /** Post-spawn/resume grace window — exempts a session before it settles (D12). */
88
+ export function isWithinGraceWindow(
89
+ s: Pick<LifecycleSignals, "activatedAt">,
90
+ t: Pick<LifecycleThresholds, "graceWindowMs">,
91
+ now: number,
92
+ ): boolean {
93
+ return now - s.activatedAt < t.graceWindowMs;
94
+ }
95
+
96
+ /** Age since the last activity event; `Infinity` when never observed. */
97
+ function idleAge(s: LifecycleSignals, now: number): number {
98
+ return s.lastActivityAt === undefined ? Number.POSITIVE_INFINITY : now - s.lastActivityAt;
99
+ }
100
+
101
+ /** True when the queues are empty AND no ask is pending (gear-2/3 precondition). */
102
+ function queuesDrainedAndUnblocked(s: LifecycleSignals): boolean {
103
+ return !s.hasPendingAsk && s.followUpCount === 0 && s.steeringCount === 0;
104
+ }
105
+
106
+ /** Gear 1: idle reap of an at-rest session — requires FULL quiescence. */
107
+ function idleGearVerdict(s: LifecycleSignals, t: LifecycleThresholds, now: number): ReapVerdict {
108
+ if (s.currentTool != null) return skip("current-tool");
109
+ if (s.hasPendingAsk) return skip("pending-ask");
110
+ if (s.followUpCount > 0) return skip("followup-queued");
111
+ if (s.steeringCount > 0) return skip("steering-queued");
112
+ if (s.hasTerminalInCwd) return skip("terminal-in-cwd");
113
+ if (s.hasLiveChild) return skip("live-child");
114
+ if (idleAge(s, now) <= t.idleTimeoutMs) return skip("not-idle-yet");
115
+ return reap("idle");
116
+ }
117
+
118
+ /** Gears 2 & 3: a streaming / mid-run session (the at-rest gate failed). */
119
+ function streamingGearVerdict(
120
+ s: LifecycleSignals,
121
+ t: LifecycleThresholds,
122
+ now: number,
123
+ ): ReapVerdict {
124
+ // A live child means genuine work — never touch it.
125
+ if (s.hasLiveChild) return skip("live-child");
126
+
127
+ const streamAge = now - (s.lastRunStartedAt ?? s.activatedAt);
128
+
129
+ // Gear 3: phantom force-reap — wedged past the hard ceiling. Pending-ask +
130
+ // empty-queue guards are mandatory (X5): a session blocked on human input or
131
+ // holding queued work is NEVER force-reaped.
132
+ if (streamAge > t.hardCeilingMs && s.cpuIdle && queuesDrainedAndUnblocked(s)) {
133
+ return reap("phantom");
134
+ }
135
+
136
+ // Gear 2: graceful stop-after-turn — idle-trending, drains queues first (F2).
137
+ if (idleAge(s, now) > t.idleTimeoutMs && queuesDrainedAndUnblocked(s)) {
138
+ return reap("stop-after-turn");
139
+ }
140
+
141
+ return skip("streaming-active");
142
+ }
143
+
144
+ /**
145
+ * Decide whether — and how — to reap a session. Pure; the caller applies the
146
+ * verdict (gear 1 → `killBySessionId`, gear 2 → `stop_after_turn`, gear 3 →
147
+ * graceful phantom kill). Order: universal vetoes first, then the at-rest idle
148
+ * gear, then the streaming phantom/stop gears.
149
+ */
150
+ export function decideReap(
151
+ s: LifecycleSignals,
152
+ t: LifecycleThresholds,
153
+ now: number,
154
+ ): ReapVerdict {
155
+ if (!isEphemeral(s)) return skip("not-ephemeral"); // durable never governed
156
+ if (s.hasSubscriber) return skip("active-watcher"); // universal veto
157
+ if (isWithinGraceWindow(s, t, now)) return skip("grace-window"); // universal veto
158
+ return isAtRest(s) ? idleGearVerdict(s, t, now) : streamingGearVerdict(s, t, now);
159
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Provenance accessor for the embed-session-lifecycle layer.
3
+ *
4
+ * The `lifecyclePolicy` marker is optional on the wire and on disk; an ABSENT
5
+ * value means `"durable"` (D1: legacy bridges + pre-change `.meta.json` load
6
+ * unchanged and are never reaped). Every downstream gate — the idle reaper, the
7
+ * quiescence predicate, the active-session caps — MUST read the policy through
8
+ * these accessors rather than comparing `session.lifecyclePolicy` raw, so the
9
+ * absent-⇒-durable default is enforced in exactly one place.
10
+ *
11
+ * See OpenSpec change: add-embed-session-lifecycle.
12
+ */
13
+ import type { LifecyclePolicy } from "@blackbelt-technology/pi-dashboard-shared/types.js";
14
+
15
+ /** Minimal shape the accessors read — any object carrying the marker. */
16
+ export interface HasLifecyclePolicy {
17
+ lifecyclePolicy?: LifecyclePolicy;
18
+ }
19
+
20
+ /** Resolve the effective policy, defaulting an absent marker to `"durable"`. */
21
+ export function effectiveLifecyclePolicy(session: HasLifecyclePolicy): LifecyclePolicy {
22
+ return session.lifecyclePolicy === "ephemeral" ? "ephemeral" : "durable";
23
+ }
24
+
25
+ /**
26
+ * True only for sessions the lifecycle layer may govern (reap / cap). A session
27
+ * with no marker is durable and therefore never ephemeral.
28
+ */
29
+ export function isEphemeral(session: HasLifecyclePolicy): boolean {
30
+ return effectiveLifecyclePolicy(session) === "ephemeral";
31
+ }