@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,84 @@
1
+ /**
2
+ * Controller integration (test-plan #E21, #E22, #E1): the wired reaper reclaims
3
+ * an idle ephemeral session end-to-end through the controller, the diagnostics
4
+ * snapshot reports active/idle + reaped-by-reason (the /api/health surface), and
5
+ * the whole thing is dormant when disabled.
6
+ * See change: add-embed-session-lifecycle.
7
+ */
8
+ import { DEFAULT_EMBED_LIFECYCLE } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import { describe, expect, it, vi } from "vitest";
11
+ import {
12
+ createEmbedLifecycleController,
13
+ type EmbedLifecycleControllerDeps,
14
+ } from "../embed-lifecycle-controller.js";
15
+
16
+ const NOW = Date.now();
17
+
18
+ function ephemeral(over: Partial<DashboardSession> = {}): DashboardSession {
19
+ return {
20
+ id: "e1",
21
+ cwd: "/work",
22
+ source: "embed",
23
+ lifecyclePolicy: "ephemeral",
24
+ status: "idle",
25
+ startedAt: NOW - 10_000_000,
26
+ pid: 100,
27
+ lastRunStartedAt: NOW - 9_000_000,
28
+ lastSettledAt: NOW - 8_000_000,
29
+ currentTool: null,
30
+ lastActivityAt: NOW - 8_000_000,
31
+ ...over,
32
+ } as DashboardSession;
33
+ }
34
+
35
+ function makeController(
36
+ sessions: DashboardSession[],
37
+ enabled: boolean,
38
+ kills: string[],
39
+ ): ReturnType<typeof createEmbedLifecycleController> {
40
+ const deps: EmbedLifecycleControllerDeps = {
41
+ config: () => ({ ...DEFAULT_EMBED_LIFECYCLE, enabled, idleTimeoutSeconds: 1 }),
42
+ listSessions: () => sessions,
43
+ getSubscriberCount: () => 0,
44
+ listTerminalCwds: () => [],
45
+ hasPendingUiRequest: () => false,
46
+ killBySessionId: async (id) => {
47
+ kills.push(id);
48
+ return true;
49
+ },
50
+ sendStopAfterTurn: vi.fn(),
51
+ probe: async () => ({ ok: true, childCount: 0, cpuPercent: 0 }),
52
+ };
53
+ return createEmbedLifecycleController(deps);
54
+ }
55
+
56
+ describe("embed lifecycle controller", () => {
57
+ // E1 / E12 / E21 — enabled: sweep reaps the idle ephemeral session and the
58
+ // snapshot records it under reaped.idle.
59
+ it("reaps an idle ephemeral session and records it in the snapshot", async () => {
60
+ const kills: string[] = [];
61
+ const ctrl = makeController([ephemeral()], true, kills);
62
+ expect(ctrl.snapshot().activeEphemeral).toBe(1);
63
+ expect(ctrl.snapshot().idleEphemeral).toBe(1);
64
+
65
+ await ctrl.reaper.sweepOnce();
66
+ expect(kills).toEqual(["e1"]);
67
+ expect(ctrl.snapshot().reaped.idle).toBe(1);
68
+ });
69
+
70
+ // E22 — disabled: dormant, nothing reaped, but the snapshot still resolves.
71
+ it("is dormant when disabled and still exposes a snapshot", async () => {
72
+ const kills: string[] = [];
73
+ const ctrl = makeController([ephemeral()], false, kills);
74
+ await ctrl.reaper.sweepOnce();
75
+ expect(kills).toEqual([]);
76
+ expect(ctrl.snapshot().reaped).toEqual({ idle: 0, "stop-after-turn": 0, phantom: 0 });
77
+ });
78
+
79
+ // A durable session is never counted as ephemeral in the diagnostics.
80
+ it("excludes durable sessions from the active-ephemeral count", () => {
81
+ const ctrl = makeController([ephemeral({ lifecyclePolicy: "durable" })], true, []);
82
+ expect(ctrl.snapshot().activeEphemeral).toBe(0);
83
+ });
84
+ });
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Canonical identity key + cwd allowlist (test-plan #E11, #X1).
3
+ * See change: add-embed-session-lifecycle.
4
+ */
5
+ import { describe, expect, it } from "vitest";
6
+ import { isCwdAllowed } from "../cwd-allowlist.js";
7
+ import { buildIdentityKey, canonicalizeCwd } from "../identity-key.js";
8
+
9
+ describe("canonicalizeCwd", () => {
10
+ // E11 — symlink/worktree paths collapse via realpath.
11
+ it("collapses a symlinked path via realpath", () => {
12
+ const realpath = (p: string) => (p === "/link/work" ? "/real/work" : p);
13
+ expect(canonicalizeCwd("/link/work", { realpath, caseInsensitive: false })).toBe("/real/work");
14
+ });
15
+
16
+ // E11 — case-variants collapse on a case-insensitive filesystem.
17
+ it("collapses case-variants when case-insensitive", () => {
18
+ const realpath = (p: string) => p;
19
+ const a = canonicalizeCwd("/Work/Repo", { realpath, caseInsensitive: true });
20
+ const b = canonicalizeCwd("/work/repo", { realpath, caseInsensitive: true });
21
+ expect(a).toBe(b);
22
+ });
23
+
24
+ it("preserves case on a case-sensitive filesystem", () => {
25
+ const realpath = (p: string) => p;
26
+ expect(canonicalizeCwd("/Work", { realpath, caseInsensitive: false })).toBe("/Work");
27
+ expect(canonicalizeCwd("/work", { realpath, caseInsensitive: false })).toBe("/work");
28
+ });
29
+
30
+ it("falls back to the raw path when realpath throws", () => {
31
+ const realpath = () => {
32
+ throw new Error("ENOENT");
33
+ };
34
+ expect(canonicalizeCwd("/missing", { realpath, caseInsensitive: false })).toBe("/missing");
35
+ });
36
+ });
37
+
38
+ describe("buildIdentityKey", () => {
39
+ // E11 — same physical dir via two path strings ⇒ one key.
40
+ it("produces one key for two path strings of the same physical dir", () => {
41
+ const realpath = (p: string) => (p.startsWith("/link") ? p.replace("/link", "/real") : p);
42
+ const k1 = buildIdentityKey(
43
+ { visitorId: "v1", cwd: "/link/w", agentIdentity: "a" },
44
+ { realpath, caseInsensitive: false },
45
+ );
46
+ const k2 = buildIdentityKey(
47
+ { visitorId: "v1", cwd: "/real/w", agentIdentity: "a" },
48
+ { realpath, caseInsensitive: false },
49
+ );
50
+ expect(k1).toBe(k2);
51
+ });
52
+
53
+ it("distinguishes different visitors on the same cwd", () => {
54
+ const realpath = (p: string) => p;
55
+ const k1 = buildIdentityKey({ visitorId: "v1", cwd: "/w" }, { realpath });
56
+ const k2 = buildIdentityKey({ visitorId: "v2", cwd: "/w" }, { realpath });
57
+ expect(k1).not.toBe(k2);
58
+ });
59
+ });
60
+
61
+ describe("isCwdAllowed", () => {
62
+ const realpath = (p: string) => p;
63
+ // X1 — an out-of-allowlist cwd is rejected.
64
+ it("rejects a cwd outside every allowed root", () => {
65
+ expect(isCwdAllowed("/etc", ["/srv/embeds"], { realpath })).toBe(false);
66
+ });
67
+ it("accepts a cwd inside an allowed root", () => {
68
+ expect(isCwdAllowed("/srv/embeds/proj", ["/srv/embeds"], { realpath })).toBe(true);
69
+ });
70
+ it("denies everything when the allowlist is empty (unconfigured)", () => {
71
+ expect(isCwdAllowed("/srv/embeds/proj", [], { realpath })).toBe(false);
72
+ });
73
+ });
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Idle reaper sweep (test-plan #E1, #E12, #E15, #E16, #F1, #F2, #F3, #E13, #E22):
3
+ * proves gear selection → action wiring with fully injected deps — durable
4
+ * untouched, disabled dormant, idle/phantom via the graceful kill ladder,
5
+ * stop-after-turn via the latch, queued/busy left alone.
6
+ * See change: add-embed-session-lifecycle.
7
+ */
8
+ import { DEFAULT_EMBED_LIFECYCLE } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import { describe, expect, it } from "vitest";
11
+ import { createIdleReaper, type ReaperDeps } from "../idle-reaper.js";
12
+ import type { LivenessSnapshot } from "../liveness-probe.js";
13
+ import type { ReapReason } from "../quiescence.js";
14
+
15
+ const NOW = 10_000_000;
16
+ const CFG = {
17
+ ...DEFAULT_EMBED_LIFECYCLE,
18
+ enabled: true,
19
+ idleTimeoutSeconds: 60,
20
+ graceWindowSeconds: 10,
21
+ hardCeilingSeconds: 600,
22
+ };
23
+
24
+ function session(overrides: Partial<DashboardSession> = {}): DashboardSession {
25
+ return {
26
+ id: "s1",
27
+ cwd: "/work",
28
+ source: "embed",
29
+ lifecyclePolicy: "ephemeral",
30
+ status: "idle",
31
+ startedAt: NOW - 500_000,
32
+ pid: 100,
33
+ lastRunStartedAt: NOW - 400_000,
34
+ lastSettledAt: NOW - 300_000, // settled after start ⇒ at rest
35
+ currentTool: null,
36
+ lastActivityAt: NOW - 120_000, // idle 120s > 60s timeout
37
+ ...overrides,
38
+ } as DashboardSession;
39
+ }
40
+
41
+ interface Harness {
42
+ deps: ReaperDeps;
43
+ kills: string[];
44
+ stops: string[];
45
+ reaped: Array<[string, ReapReason]>;
46
+ }
47
+
48
+ function harness(
49
+ sessions: DashboardSession[],
50
+ opts: { probe?: LivenessSnapshot; enabled?: boolean } = {},
51
+ ): Harness {
52
+ const kills: string[] = [];
53
+ const stops: string[] = [];
54
+ const reaped: Array<[string, ReapReason]> = [];
55
+ const probeSnap: LivenessSnapshot = opts.probe ?? { ok: true, childCount: 0, cpuPercent: 0 };
56
+ const deps: ReaperDeps = {
57
+ config: () => ({ ...CFG, enabled: opts.enabled ?? true }),
58
+ listSessions: () => sessions,
59
+ probe: async () => probeSnap,
60
+ hasSubscriber: () => false,
61
+ hasTerminalInCwd: () => false,
62
+ hasPendingAsk: () => false,
63
+ queueCounts: () => ({ followUp: 0, steering: 0 }),
64
+ killBySessionId: async (id) => {
65
+ kills.push(id);
66
+ return true;
67
+ },
68
+ sendStopAfterTurn: (id) => stops.push(id),
69
+ onReap: (id, reason) => reaped.push([id, reason]),
70
+ now: () => NOW,
71
+ };
72
+ return { deps, kills, stops, reaped };
73
+ }
74
+
75
+ describe("idle reaper sweep", () => {
76
+ let h: Harness;
77
+
78
+ // E12 / E1 — an eligible idle ephemeral session is reaped via the graceful
79
+ // kill ladder, recording reason "idle".
80
+ it("reaps an eligible idle ephemeral session via killBySessionId", async () => {
81
+ h = harness([session()]);
82
+ await createIdleReaper(h.deps).sweepOnce();
83
+ expect(h.kills).toEqual(["s1"]);
84
+ expect(h.stops).toEqual([]);
85
+ expect(h.reaped).toEqual([["s1", "idle"]]);
86
+ });
87
+
88
+ // E1 — a durable session is never reaped.
89
+ it("never reaps a durable session", async () => {
90
+ h = harness([session({ lifecyclePolicy: "durable" })]);
91
+ await createIdleReaper(h.deps).sweepOnce();
92
+ expect(h.kills).toEqual([]);
93
+ expect(h.reaped).toEqual([]);
94
+ });
95
+
96
+ it("skips an already-ended session", async () => {
97
+ h = harness([session({ status: "ended" })]);
98
+ await createIdleReaper(h.deps).sweepOnce();
99
+ expect(h.kills).toEqual([]);
100
+ });
101
+
102
+ // E22 — dormant when the feature is disabled.
103
+ it("does nothing when the feature is disabled", async () => {
104
+ h = harness([session()], { enabled: false });
105
+ await createIdleReaper(h.deps).sweepOnce();
106
+ expect(h.kills).toEqual([]);
107
+ expect(h.stops).toEqual([]);
108
+ });
109
+
110
+ // E15 / E16 — a wedged streaming session is force-reaped as "phantom" via the
111
+ // SAME graceful kill ladder (not a bare SIGKILL), keeping it resumable.
112
+ it("force-reaps a phantom session via the graceful ladder", async () => {
113
+ const phantom = session({
114
+ status: "streaming",
115
+ lastRunStartedAt: NOW - (CFG.hardCeilingSeconds * 1000 + 1),
116
+ lastSettledAt: NOW - (CFG.hardCeilingSeconds * 1000 + 100_000), // older ⇒ mid-run
117
+ });
118
+ h = harness([phantom], { probe: { ok: true, childCount: 0, cpuPercent: 0 } });
119
+ await createIdleReaper(h.deps).sweepOnce();
120
+ expect(h.kills).toEqual(["s1"]); // graceful ladder, same path as idle
121
+ expect(h.reaped).toEqual([["s1", "phantom"]]);
122
+ });
123
+
124
+ // F1 — an idle-trending streaming session gets stop-after-turn, NOT a kill.
125
+ it("sends stop-after-turn for an idle-trending streaming session", async () => {
126
+ const idleStream = session({
127
+ status: "streaming",
128
+ lastRunStartedAt: NOW - 100_000, // past idle, below hard ceiling
129
+ lastSettledAt: NOW - 200_000,
130
+ });
131
+ h = harness([idleStream]);
132
+ await createIdleReaper(h.deps).sweepOnce();
133
+ expect(h.stops).toEqual(["s1"]);
134
+ expect(h.kills).toEqual([]);
135
+ expect(h.reaped).toEqual([["s1", "stop-after-turn"]]);
136
+ });
137
+
138
+ // F2 — a streaming session with queued work is left to drain.
139
+ it("does not stop a streaming session with queued follow-up", async () => {
140
+ const idleStream = session({
141
+ status: "streaming",
142
+ lastRunStartedAt: NOW - 100_000,
143
+ lastSettledAt: NOW - 200_000,
144
+ });
145
+ const { deps, stops, kills } = harness([idleStream]);
146
+ deps.queueCounts = () => ({ followUp: 1, steering: 0 });
147
+ await createIdleReaper(deps).sweepOnce();
148
+ expect(stops).toEqual([]);
149
+ expect(kills).toEqual([]);
150
+ });
151
+
152
+ // X4 / F3 — a live child (probe reports a descendant) vetoes reaping; an
153
+ // active subscriber also vetoes (disconnect ≠ reclaim is the inverse).
154
+ it("does not reap when the liveness probe reports a live child", async () => {
155
+ h = harness([session()], { probe: { ok: true, childCount: 1, cpuPercent: 0 } });
156
+ await createIdleReaper(h.deps).sweepOnce();
157
+ expect(h.kills).toEqual([]);
158
+ });
159
+
160
+ it("does not reap a subscribed session", async () => {
161
+ const { deps, kills } = harness([session()]);
162
+ deps.hasSubscriber = () => true;
163
+ await createIdleReaper(deps).sweepOnce();
164
+ expect(kills).toEqual([]);
165
+ });
166
+
167
+ // Unknown probe (ps failed) is the SAFE direction: no idle reap.
168
+ it("does not idle-reap when the probe result is unknown", async () => {
169
+ h = harness([session()], { probe: { ok: false, childCount: 0, cpuPercent: 0 } });
170
+ await createIdleReaper(h.deps).sweepOnce();
171
+ expect(h.kills).toEqual([]);
172
+ });
173
+ });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Config off-by-default contract (test-plan #E22, task 7.1): the lifecycle
3
+ * feature is disabled by default and every threshold is inert until an operator
4
+ * opts in, so an upgrade never reaps/caps/reuses.
5
+ * See change: add-embed-session-lifecycle.
6
+ */
7
+ import {
8
+ DEFAULT_EMBED_LIFECYCLE,
9
+ loadConfig,
10
+ } from "@blackbelt-technology/pi-dashboard-shared/config.js";
11
+ import { describe, expect, it } from "vitest";
12
+
13
+ describe("embed lifecycle config", () => {
14
+ it("is disabled by default", () => {
15
+ expect(DEFAULT_EMBED_LIFECYCLE.enabled).toBe(false);
16
+ });
17
+
18
+ it("loadConfig leaves the feature dormant when no config.json exists", () => {
19
+ // Tests run under a fresh mktemp HOME with no config.json → pure defaults.
20
+ const cfg = loadConfig();
21
+ expect(cfg.embedLifecycle.enabled).toBe(false);
22
+ // Thresholds are present (so the reaper CAN be enabled) but inert while off.
23
+ expect(cfg.embedLifecycle.idleTimeoutSeconds).toBeGreaterThan(0);
24
+ expect(cfg.embedLifecycle.maxActiveEmbedSessionsGlobal).toBeGreaterThan(0);
25
+ });
26
+ });
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Lifecycle run-boundary capture (test-plan #E23): the server derives "at rest"
3
+ * from the bridge-normalized `agent_settled` event NAME with no `piVersion`
4
+ * branch, so a native settle and a floor-synthesized settle are captured
5
+ * identically.
6
+ * See change: add-embed-session-lifecycle.
7
+ */
8
+ import { describe, expect, it } from "vitest";
9
+ import { captureLifecycleTimestamp } from "../lifecycle-event-capture.js";
10
+
11
+ describe("captureLifecycleTimestamp", () => {
12
+ it("captures agent_start as lastRunStartedAt", () => {
13
+ expect(captureLifecycleTimestamp("agent_start", 1234)).toEqual({ lastRunStartedAt: 1234 });
14
+ });
15
+
16
+ it("captures agent_settled as lastSettledAt", () => {
17
+ expect(captureLifecycleTimestamp("agent_settled", 5678)).toEqual({ lastSettledAt: 5678 });
18
+ });
19
+
20
+ // E23 — native vs synthesized settle are the same normalized event, so the
21
+ // capture is version-agnostic (no branch can distinguish them).
22
+ it("captures native and synthesized agent_settled identically", () => {
23
+ const native = captureLifecycleTimestamp("agent_settled", 9000);
24
+ const synthesized = captureLifecycleTimestamp("agent_settled", 9000);
25
+ expect(native).toEqual(synthesized);
26
+ });
27
+
28
+ it("ignores non-run-boundary events", () => {
29
+ expect(captureLifecycleTimestamp("tool_execution_start", 1)).toBeNull();
30
+ expect(captureLifecycleTimestamp("turn_end", 1)).toBeNull();
31
+ });
32
+ });
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Persistence contract for the `lifecyclePolicy` marker (test-plan #E3, #E4):
3
+ * the debounced full-overwrite save (`sessionToMeta`) MUST enumerate
4
+ * `lifecyclePolicy`, and `scanAllSessions` MUST restore it on cold start — else
5
+ * a server restart reclassifies an `ephemeral` session as `durable`
6
+ * (absent ⇒ durable) and it escapes reaping forever, re-creating the reported
7
+ * cross-restart accumulation.
8
+ *
9
+ * Mirrors session-name-provenance-persistence.test.ts.
10
+ * See change: add-embed-session-lifecycle.
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { readSessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
16
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
17
+ import { createMetaPersistence, type MetaPersistence } from "../../persistence/meta-persistence.js";
18
+ import { createMemorySessionManager, type SessionManager } from "../../session/memory-session-manager.js";
19
+ import { scanAllSessions } from "../../session/session-scanner.js";
20
+ import { sessionToMeta } from "../../session/session-to-meta.js";
21
+ import { isEphemeral } from "../session-lifecycle-policy.js";
22
+
23
+ describe("lifecyclePolicy marker persistence", () => {
24
+ let tmpDir: string;
25
+ let mgr: SessionManager;
26
+ let metaPersistence: MetaPersistence;
27
+ let sessionFile: string;
28
+
29
+ beforeEach(() => {
30
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "lifecycle-persist-"));
31
+ const dir = path.join(tmpDir, "--test-cwd--");
32
+ fs.mkdirSync(dir, { recursive: true });
33
+ sessionFile = path.join(dir, "2026-07-21T10-00-00-000Z_embed-id.jsonl");
34
+ fs.writeFileSync(
35
+ sessionFile,
36
+ `${JSON.stringify({ type: "session", id: "embed-id", cwd: "/test/cwd", timestamp: "2026-07-21T10:00:00.000Z" })}\n`,
37
+ );
38
+
39
+ mgr = createMemorySessionManager();
40
+ metaPersistence = createMetaPersistence();
41
+ mgr.onChange = (id) => {
42
+ const s = mgr.get(id);
43
+ if (!s?.sessionFile) return;
44
+ metaPersistence.save(s.sessionFile, sessionToMeta(s));
45
+ };
46
+
47
+ mgr.register({ id: "embed-id", cwd: "/test/cwd", source: "embed", startedAt: 1000 });
48
+ mgr.update("embed-id", { sessionFile, status: "ended" });
49
+ });
50
+
51
+ afterEach(() => {
52
+ metaPersistence.dispose();
53
+ fs.rmSync(tmpDir, { recursive: true, force: true });
54
+ });
55
+
56
+ // E4 — the full-overwrite save enumerates lifecyclePolicy (no wipe on a
57
+ // subsequent unrelated save).
58
+ it("does NOT wipe lifecyclePolicy on a later unrelated meta save", () => {
59
+ mgr.update("embed-id", { lifecyclePolicy: "ephemeral" });
60
+ mgr.update("embed-id", { processDrawerCollapsed: true });
61
+ metaPersistence.flushAll();
62
+
63
+ const onDisk = readSessionMeta(sessionFile);
64
+ expect(onDisk?.lifecyclePolicy).toBe("ephemeral");
65
+ });
66
+
67
+ // E3 — ephemeral marker survives a restart: persisted to .meta.json and
68
+ // restored (not reclassified to durable) by the cold-start scan.
69
+ it("round-trips an ephemeral marker and restores it on cold-start scan", () => {
70
+ mgr.update("embed-id", { lifecyclePolicy: "ephemeral" });
71
+ metaPersistence.flushAll();
72
+
73
+ expect(readSessionMeta(sessionFile)?.lifecyclePolicy).toBe("ephemeral");
74
+
75
+ const result = scanAllSessions(tmpDir);
76
+ const restored = result.sessions.find((s) => s.id === "embed-id");
77
+ expect(restored?.lifecyclePolicy).toBe("ephemeral");
78
+ // The restored session remains reap-eligible (ephemeral, not durable).
79
+ expect(isEphemeral(restored ?? {})).toBe(true);
80
+ });
81
+
82
+ // E14 — cold-start settle seed: a rehydrated session with no captured
83
+ // lastSettledAt is seeded from the session-file mtime so the quiescence gate
84
+ // is immediately evaluable (not stalled waiting for a fresh run to settle).
85
+ it("seeds lastSettledAt from the session-file mtime on cold-start scan", () => {
86
+ mgr.update("embed-id", { lifecyclePolicy: "ephemeral" });
87
+ metaPersistence.flushAll();
88
+
89
+ const result = scanAllSessions(tmpDir);
90
+ const restored = result.sessions.find((s) => s.id === "embed-id");
91
+ expect(restored?.lastSettledAt).toBeTypeOf("number");
92
+ // Seeded from the same mtime source as lastActivityAt.
93
+ expect(restored?.lastSettledAt).toBe(restored?.lastActivityAt);
94
+ });
95
+
96
+ // E3 (negative) — a durable / unmarked session restores durable and is never
97
+ // reap-eligible after restart.
98
+ it("restores an unmarked session as durable after a cold-start scan", () => {
99
+ mgr.update("embed-id", { lifecyclePolicy: undefined });
100
+ metaPersistence.flushAll();
101
+
102
+ const result = scanAllSessions(tmpDir);
103
+ const restored = result.sessions.find((s) => s.id === "embed-id");
104
+ expect(isEphemeral(restored ?? {})).toBe(false);
105
+ });
106
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Lifecycle counters (test-plan #E20, #E21): each decision path increments the
3
+ * matching counter, and the snapshot reports live active/idle + reaped-by-reason
4
+ * for the diagnostics surface.
5
+ * See change: add-embed-session-lifecycle.
6
+ */
7
+ import { describe, expect, it } from "vitest";
8
+ import { createLifecycleMetrics } from "../lifecycle-metrics.js";
9
+
10
+ describe("lifecycle metrics", () => {
11
+ // E20 — each path fires its counter.
12
+ it("increments reuse hit/miss, reaped-by-reason, and capacity rejections", () => {
13
+ const m = createLifecycleMetrics();
14
+ m.recordReuse(true);
15
+ m.recordReuse(false);
16
+ m.recordReuse(false);
17
+ m.recordReap("idle");
18
+ m.recordReap("phantom");
19
+ m.recordReap("phantom");
20
+ m.recordCapacityReject();
21
+
22
+ const s = m.snapshot();
23
+ expect(s.reuseHits).toBe(1);
24
+ expect(s.reuseMisses).toBe(2);
25
+ expect(s.reaped).toEqual({ idle: 1, "stop-after-turn": 0, phantom: 2 });
26
+ expect(s.capacityRejections).toBe(1);
27
+ });
28
+
29
+ // E21 — snapshot reports live active/idle from the injected accessors.
30
+ it("reports live active/idle counts from injected accessors", () => {
31
+ const m = createLifecycleMetrics({
32
+ countActiveEphemeral: () => 4,
33
+ countIdleEphemeral: () => 1,
34
+ });
35
+ const s = m.snapshot();
36
+ expect(s.activeEphemeral).toBe(4);
37
+ expect(s.idleEphemeral).toBe(1);
38
+ });
39
+ });
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Liveness probe (test-plan #E12 gear-1 child check, #E15 phantom CPU signal):
3
+ * the pure tree-walk sums CPU across a session's pi tree and counts live
4
+ * children, and the injectable `ps` runner lets the reaper drive both gates
5
+ * deterministically.
6
+ * See change: add-embed-session-lifecycle.
7
+ */
8
+ import { describe, expect, it } from "vitest";
9
+ import {
10
+ createLivenessProbe,
11
+ type PsRow,
12
+ parsePsOutput,
13
+ summarizeProcessTree,
14
+ } from "../liveness-probe.js";
15
+
16
+ // pi(100) → keeper(200) → child(300); an unrelated tree at 900.
17
+ const TREE: PsRow[] = [
18
+ { pid: 1, ppid: 0, cpu: 0 },
19
+ { pid: 100, ppid: 1, cpu: 0.1 },
20
+ { pid: 200, ppid: 100, cpu: 0.2 },
21
+ { pid: 300, ppid: 200, cpu: 12.5 },
22
+ { pid: 900, ppid: 1, cpu: 40 },
23
+ ];
24
+
25
+ describe("summarizeProcessTree", () => {
26
+ it("counts descendants and sums CPU across the root's tree", () => {
27
+ const snap = summarizeProcessTree(TREE, 100);
28
+ expect(snap.ok).toBe(true);
29
+ expect(snap.childCount).toBe(2); // 200 + 300
30
+ expect(snap.cpuPercent).toBeCloseTo(0.1 + 0.2 + 12.5);
31
+ });
32
+
33
+ it("reports a wedged (~0 CPU) leaf-less root as no children, ~0 CPU", () => {
34
+ const snap = summarizeProcessTree([{ pid: 100, ppid: 1, cpu: 0 }], 100);
35
+ expect(snap.childCount).toBe(0);
36
+ expect(snap.cpuPercent).toBe(0);
37
+ });
38
+
39
+ it("excludes unrelated trees", () => {
40
+ const snap = summarizeProcessTree(TREE, 900);
41
+ expect(snap.childCount).toBe(0);
42
+ expect(snap.cpuPercent).toBe(40);
43
+ });
44
+
45
+ it("returns an empty snapshot when the root pid is gone", () => {
46
+ expect(summarizeProcessTree(TREE, 42)).toEqual({ ok: true, childCount: 0, cpuPercent: 0 });
47
+ });
48
+ });
49
+
50
+ describe("parsePsOutput", () => {
51
+ it("parses whitespace-columned ps rows and tolerates junk lines", () => {
52
+ const rows = parsePsOutput(" 100 1 0.1\n 200 100 12.5\n\ngarbage\n");
53
+ expect(rows).toEqual([
54
+ { pid: 100, ppid: 1, cpu: 0.1 },
55
+ { pid: 200, ppid: 100, cpu: 12.5 },
56
+ ]);
57
+ });
58
+ });
59
+
60
+ describe("createLivenessProbe", () => {
61
+ it("summarizes via the injected ps runner", async () => {
62
+ const probe = createLivenessProbe({
63
+ runPs: async () => "100 1 0.1\n200 100 5\n",
64
+ });
65
+ const snap = await probe(100);
66
+ expect(snap).toEqual({ ok: true, childCount: 1, cpuPercent: 5.1 });
67
+ });
68
+
69
+ it("returns ok:false when ps throws (safe unknown)", async () => {
70
+ const probe = createLivenessProbe({
71
+ runPs: async () => {
72
+ throw new Error("ps failed");
73
+ },
74
+ });
75
+ expect(await probe(100)).toEqual({ ok: false, childCount: 0, cpuPercent: 0 });
76
+ });
77
+ });