@blackbelt-technology/pi-agent-dashboard 0.6.0 → 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.
- package/README.md +40 -38
- package/docs/architecture.md +148 -2
- package/package.json +6 -4
- package/packages/extension/package.json +4 -3
- package/packages/extension/src/AGENTS.md +1 -0
- package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +333 -0
- package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +145 -0
- package/packages/extension/src/__tests__/provider-register-native-models.test.ts +182 -0
- package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +54 -1
- package/packages/extension/src/__tests__/single-derivation-guard.test.ts +39 -0
- package/packages/extension/src/bridge-context.ts +21 -0
- package/packages/extension/src/bridge.ts +41 -6
- package/packages/extension/src/openspec-cli-shim.ts +173 -0
- package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +7 -0
- package/packages/extension/src/provider-register.ts +180 -17
- package/packages/extension/src/provider-register.ts.AGENTS.md +1 -1
- package/packages/extension/src/session-sync.ts +9 -4
- package/packages/server/package.json +8 -8
- package/packages/server/src/__tests__/decorate-goals-spend.test.ts +79 -0
- package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +44 -0
- package/packages/server/src/__tests__/goal-routes.test.ts +62 -7
- package/packages/server/src/__tests__/goal-supervisor.test.ts +4 -4
- package/packages/server/src/__tests__/headless-pid-registry.test.ts +7 -3
- package/packages/server/src/__tests__/memory-event-store.test.ts +369 -13
- package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +67 -0
- package/packages/server/src/__tests__/pi-changelog-routes.test.ts +9 -2
- package/packages/server/src/__tests__/recovery-offer.test.ts +42 -7
- package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +188 -0
- package/packages/server/src/__tests__/session-tags-persistence.test.ts +29 -0
- package/packages/server/src/browser-handlers/AGENTS.md +1 -1
- package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +98 -1
- package/packages/server/src/browser-handlers/handler-context.ts +24 -13
- package/packages/server/src/browser-handlers/session-action-handler.ts +12 -1
- package/packages/server/src/browser-handlers/session-meta-handler.ts +29 -0
- package/packages/server/src/embed-lifecycle/AGENTS.md +17 -0
- package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +129 -0
- package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +84 -0
- package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +73 -0
- package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +173 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +26 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +32 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +106 -0
- package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +39 -0
- package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +77 -0
- package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +175 -0
- package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +77 -0
- package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +38 -0
- package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +140 -0
- package/packages/server/src/embed-lifecycle/caps.ts +88 -0
- package/packages/server/src/embed-lifecycle/cwd-allowlist.ts +50 -0
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +90 -0
- package/packages/server/src/embed-lifecycle/identity-key.ts +73 -0
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +161 -0
- package/packages/server/src/embed-lifecycle/lifecycle-event-capture.ts +30 -0
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +70 -0
- package/packages/server/src/embed-lifecycle/liveness-probe.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +159 -0
- package/packages/server/src/embed-lifecycle/session-lifecycle-policy.ts +31 -0
- package/packages/server/src/embed-lifecycle/visitor-session-registry.ts +178 -0
- package/packages/server/src/event-wiring.ts +20 -0
- package/packages/server/src/event-wiring.ts.AGENTS.md +1 -0
- package/packages/server/src/goal/AGENTS.md +1 -0
- package/packages/server/src/goal/decorate-goals-spend.ts +47 -0
- package/packages/server/src/goal/goal-supervisor.ts +5 -3
- package/packages/server/src/model-proxy/AGENTS.md +2 -2
- package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +155 -0
- package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +92 -0
- package/packages/server/src/model-proxy/internal-registry.ts +49 -23
- package/packages/server/src/model-proxy/registry-singleton.ts +15 -9
- package/packages/server/src/pairing/browser-gateway.ts +40 -11
- package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +1 -1
- package/packages/server/src/persistence/memory-event-store.ts +369 -23
- package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +1 -1
- package/packages/server/src/routes/AGENTS.md +2 -2
- package/packages/server/src/routes/goal-routes.ts +14 -9
- package/packages/server/src/routes/models-introspection-routes.ts +10 -0
- package/packages/server/src/routes/system-routes.ts +16 -1
- package/packages/server/src/server.ts +216 -65
- package/packages/server/src/server.ts.AGENTS.md +1 -1
- package/packages/server/src/session/memory-session-manager.ts +4 -0
- package/packages/server/src/session/session-scanner.ts +9 -0
- package/packages/server/src/session/session-to-meta.ts +6 -0
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -4
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/AGENTS.md +5 -3
- package/packages/shared/src/__tests__/models-json-reader.test.ts +100 -0
- package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +125 -0
- package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +112 -0
- package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +177 -0
- package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +6 -3
- package/packages/shared/src/browser-protocol.ts +22 -0
- package/packages/shared/src/config.ts +70 -0
- package/packages/shared/src/dashboard-plugin/AGENTS.md +1 -1
- package/packages/shared/src/dashboard-plugin/slot-props.ts +9 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +19 -0
- package/packages/shared/src/models-json-reader.ts +98 -0
- package/packages/shared/src/platform/AGENTS.md +1 -1
- package/packages/shared/src/platform/paths.ts +12 -0
- package/packages/shared/src/session-meta.ts +9 -0
- package/packages/shared/src/types.ts +52 -1
- package/docs/AGENTS.md +0 -47
- package/packages/extension/AGENTS.md +0 -7
- package/packages/server/AGENTS.md +0 -7
- package/packages/shared/AGENTS.md +0 -7
- package/scripts/AGENTS.md +0 -38
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACCEPTANCE test for the recovery-offer process-liveness gate.
|
|
3
|
+
* (Promoted from the red explore-mode spike once the gate landed.)
|
|
4
|
+
*
|
|
5
|
+
* The cold-start recovery offer must be gated by PROCESS LIVENESS, not by the
|
|
6
|
+
* on-disk `live:true` marker alone. A session is only worth a "Reopen" offer
|
|
7
|
+
* when the process-carrier that held its pi is genuinely gone. There are two
|
|
8
|
+
* liveness channels the current disk-only classifier ignores:
|
|
9
|
+
*
|
|
10
|
+
* Class 1 — KEEPER / headless sessions: pi liveness IS synchronously
|
|
11
|
+
* probeable at cold start via the `<sid>.rpc.sock.pid` scan +
|
|
12
|
+
* isProcessAlive (rpc-keeper-sidecar / headless-spawn specs). The server
|
|
13
|
+
* reclaims these at start() BEFORE the offer is broadcast. A candidate
|
|
14
|
+
* whose keeper+pi the scan finds alive was never lost.
|
|
15
|
+
*
|
|
16
|
+
* Class 2 — NON-KEEPER sessions (tmux / TUI / mDNS-discovery bridges): no
|
|
17
|
+
* socket to probe. Liveness is revealed only when the bridge re-discovers
|
|
18
|
+
* the server and REATTACHES — asynchronously, AFTER the offer fires. A
|
|
19
|
+
* reattaching bridge proves the session is alive.
|
|
20
|
+
*
|
|
21
|
+
* A plain server RESTART (/api/restart → process.exit(0) WITHOUT stop()) leaves
|
|
22
|
+
* every running session `live:true` + non-`ended` on disk — indistinguishable
|
|
23
|
+
* from a crash to the disk-only classifier. So it phantom-offers sessions whose
|
|
24
|
+
* keeper survived (Class 1) or whose bridge reattaches (Class 2). Reopening a
|
|
25
|
+
* still-alive session double-spawns pi for one sessionId → gateway map goes
|
|
26
|
+
* last-write-wins → "can't send messages".
|
|
27
|
+
*
|
|
28
|
+
* This test asserts the CORRECT end state:
|
|
29
|
+
* - keeper-alive candidate → NOT offered
|
|
30
|
+
* - bridge-reattach candidate → NOT offered
|
|
31
|
+
* - genuinely-dead candidate → STILL offered (the feature must still work)
|
|
32
|
+
*
|
|
33
|
+
* Class 1 (keeper) is subtracted synchronously at broadcast time; Class 2
|
|
34
|
+
* (bridge) is retracted when the reattach comes alive within the grace window.
|
|
35
|
+
* See change: fix-recovery-offer-bridge-liveness-gate.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
39
|
+
import os from "node:os";
|
|
40
|
+
import path from "node:path";
|
|
41
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
42
|
+
import { WebSocket } from "ws";
|
|
43
|
+
|
|
44
|
+
function seedCandidate(sessionsDir: string, id: string, meta: Record<string, unknown>): string {
|
|
45
|
+
const cwdDir = path.join(sessionsDir, id.slice(0, 4)); // distinct cwd per candidate
|
|
46
|
+
mkdirSync(cwdDir, { recursive: true });
|
|
47
|
+
const jsonl = path.join(cwdDir, `2026-06-30T10-00-00-000Z_${id}.jsonl`);
|
|
48
|
+
writeFileSync(jsonl, `${JSON.stringify({ type: "session", id, cwd: cwdDir })}\n`);
|
|
49
|
+
writeFileSync(jsonl.replace(/\.jsonl$/, ".meta.json"), JSON.stringify({
|
|
50
|
+
source: "cli", cwd: cwdDir, status: "streaming",
|
|
51
|
+
startedAt: Date.now(), cachedAt: Date.now() + 60_000,
|
|
52
|
+
live: true, ...meta,
|
|
53
|
+
}));
|
|
54
|
+
return jsonl;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// ~/.pi/dashboard/{config.json, sessions/, headless-pids.json} live under the
|
|
58
|
+
// ephemeral HOME set by `npm test` (setup-home tripwire). Snapshot/restore keeps
|
|
59
|
+
// the suite self-cleaning within that HOME.
|
|
60
|
+
const DASH_DIR = path.join(os.homedir(), ".pi", "dashboard");
|
|
61
|
+
const CONFIG_PATH = path.join(DASH_DIR, "config.json");
|
|
62
|
+
const KEEPER_SOCK_DIR = path.join(DASH_DIR, "sessions");
|
|
63
|
+
const PID_FILE = path.join(DASH_DIR, "headless-pids.json");
|
|
64
|
+
let configSnapshot: string | null = null;
|
|
65
|
+
|
|
66
|
+
function writeConfig(mode: "ask" | "auto"): void {
|
|
67
|
+
mkdirSync(DASH_DIR, { recursive: true });
|
|
68
|
+
configSnapshot = existsSync(CONFIG_PATH) ? readFileSync(CONFIG_PATH, "utf-8") : null;
|
|
69
|
+
writeFileSync(CONFIG_PATH, JSON.stringify({ reopenSessionsAfterShutdown: mode }));
|
|
70
|
+
}
|
|
71
|
+
function writeAskConfig(): void { writeConfig("ask"); }
|
|
72
|
+
function restoreConfig(): void {
|
|
73
|
+
if (configSnapshot !== null) writeFileSync(CONFIG_PATH, configSnapshot);
|
|
74
|
+
else if (existsSync(CONFIG_PATH)) rmSync(CONFIG_PATH);
|
|
75
|
+
configSnapshot = null;
|
|
76
|
+
rmSync(KEEPER_SOCK_DIR, { recursive: true, force: true });
|
|
77
|
+
if (existsSync(PID_FILE)) rmSync(PID_FILE);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
describe("recovery offer is gated by process liveness (keeper + bridge)", () => {
|
|
81
|
+
let sessionsDir: string;
|
|
82
|
+
let server: any;
|
|
83
|
+
|
|
84
|
+
beforeEach(() => { sessionsDir = mkdtempSync(path.join(os.tmpdir(), "pi-spike-")); });
|
|
85
|
+
afterEach(async () => {
|
|
86
|
+
restoreConfig();
|
|
87
|
+
try { await server?.stop(); } catch {}
|
|
88
|
+
vi.unstubAllEnvs();
|
|
89
|
+
vi.resetModules();
|
|
90
|
+
rmSync(sessionsDir, { recursive: true, force: true });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("offers ONLY the genuinely-dead session; excludes keeper-alive and reattached", async () => {
|
|
94
|
+
writeAskConfig();
|
|
95
|
+
vi.stubEnv("PI_CODING_AGENT_SESSION_DIR", sessionsDir);
|
|
96
|
+
vi.resetModules();
|
|
97
|
+
const { createServer } = await import("../server.js");
|
|
98
|
+
|
|
99
|
+
// Three restart-crash-shaped candidates (live:true + non-ended on disk).
|
|
100
|
+
const KEEPER = "keee1111-2222-3333-4444-555555555555"; // Class 1: keeper survived
|
|
101
|
+
const BRIDGE = "brid1111-2222-3333-4444-555555555555"; // Class 2: bridge reattaches
|
|
102
|
+
const DEAD = "dead1111-2222-3333-4444-555555555555"; // control: truly gone
|
|
103
|
+
seedCandidate(sessionsDir, KEEPER, {});
|
|
104
|
+
const bridgeJsonl = seedCandidate(sessionsDir, BRIDGE, {});
|
|
105
|
+
seedCandidate(sessionsDir, DEAD, {});
|
|
106
|
+
|
|
107
|
+
// Class 1 fixture: an alive keeper PID sidecar for KEEPER. The keeper scan
|
|
108
|
+
// (cleanupKeeperOrphans → discoverExistingKeepers) reads `<sid>.rpc.sock.pid`,
|
|
109
|
+
// checks isProcessAlive, and (isPiAlive defaults true) reports it live.
|
|
110
|
+
// process.pid is this test runner — guaranteed alive, never killed because
|
|
111
|
+
// the pi-alive gate short-circuits true.
|
|
112
|
+
mkdirSync(KEEPER_SOCK_DIR, { recursive: true });
|
|
113
|
+
writeFileSync(path.join(KEEPER_SOCK_DIR, `${KEEPER}.rpc.sock.pid`), String(process.pid));
|
|
114
|
+
|
|
115
|
+
// Cold start (ask mode). Disk-only classifier flags ALL THREE as candidates;
|
|
116
|
+
// keeper reclaim runs in start() before the offer broadcast, and the bridge
|
|
117
|
+
// reattach retracts BRIDGE before the browser connects.
|
|
118
|
+
server = await createServer({
|
|
119
|
+
port: 0, piPort: 0, host: "127.0.0.1", dev: true,
|
|
120
|
+
autoShutdown: false, shutdownIdleSeconds: 999, tunnel: false,
|
|
121
|
+
});
|
|
122
|
+
await server.start();
|
|
123
|
+
const piPort = server.piPort();
|
|
124
|
+
const httpPort = server.httpPort();
|
|
125
|
+
|
|
126
|
+
// Class 2: BRIDGE's pi survived the restart — its bridge reattaches now.
|
|
127
|
+
const cwdB = path.join(sessionsDir, BRIDGE.slice(0, 4));
|
|
128
|
+
const bridge = new WebSocket(`ws://127.0.0.1:${piPort}`);
|
|
129
|
+
await new Promise<void>((resolve) => {
|
|
130
|
+
bridge.on("open", () => {
|
|
131
|
+
bridge.send(JSON.stringify({ type: "session_register", sessionId: BRIDGE, cwd: cwdB, source: "cli", sessionFile: bridgeJsonl }));
|
|
132
|
+
bridge.send(JSON.stringify({ type: "replay_complete", sessionId: BRIDGE }));
|
|
133
|
+
bridge.send(JSON.stringify({ type: "event_forward", sessionId: BRIDGE, event: { eventType: "message_start", timestamp: Date.now(), data: {} } }));
|
|
134
|
+
setTimeout(resolve, 300);
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
// A browser connecting now should be offered to reopen ONLY the dead one.
|
|
139
|
+
const browser = new WebSocket(`ws://127.0.0.1:${httpPort}/ws`);
|
|
140
|
+
const msgs: Record<string, unknown>[] = [];
|
|
141
|
+
await new Promise<void>((resolve) => {
|
|
142
|
+
browser.on("open", () => {
|
|
143
|
+
browser.on("message", (raw) => { try { msgs.push(JSON.parse(raw.toString())); } catch {} });
|
|
144
|
+
setTimeout(resolve, 300);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
bridge.close();
|
|
148
|
+
browser.close();
|
|
149
|
+
|
|
150
|
+
const offeredIds = msgs
|
|
151
|
+
.filter((m) => m.type === "recovery_offer")
|
|
152
|
+
.flatMap((o) => (o.candidates as any[]).map((c) => c.sessionId));
|
|
153
|
+
|
|
154
|
+
// The feature must still work for a genuine loss.
|
|
155
|
+
expect(offeredIds).toContain(DEAD);
|
|
156
|
+
// Gated out: keeper reclaim proves KEEPER alive; BRIDGE's reattach retracts it.
|
|
157
|
+
expect(offeredIds).not.toContain(KEEPER);
|
|
158
|
+
expect(offeredIds).not.toContain(BRIDGE);
|
|
159
|
+
}, 15_000);
|
|
160
|
+
|
|
161
|
+
// Auto-mode Class 1: a keeper-alive candidate SHALL NOT be auto-resumed. The
|
|
162
|
+
// gate runs synchronously in start() (before the deferred resume), so the
|
|
163
|
+
// proof is the consumed on-disk marker — a second `continue` spawn for an
|
|
164
|
+
// already-alive sessionId is what breaks message routing.
|
|
165
|
+
// See change: fix-recovery-offer-bridge-liveness-gate.
|
|
166
|
+
it("auto mode: keeper-alive candidate is excluded (marker consumed, not resumed)", async () => {
|
|
167
|
+
writeConfig("auto");
|
|
168
|
+
vi.stubEnv("PI_CODING_AGENT_SESSION_DIR", sessionsDir);
|
|
169
|
+
vi.resetModules();
|
|
170
|
+
const { createServer } = await import("../server.js");
|
|
171
|
+
|
|
172
|
+
const KEEPER = "keee2222-3333-4444-5555-666666666666";
|
|
173
|
+
seedCandidate(sessionsDir, KEEPER, {});
|
|
174
|
+
mkdirSync(KEEPER_SOCK_DIR, { recursive: true });
|
|
175
|
+
writeFileSync(path.join(KEEPER_SOCK_DIR, `${KEEPER}.rpc.sock.pid`), String(process.pid));
|
|
176
|
+
|
|
177
|
+
server = await createServer({
|
|
178
|
+
port: 0, piPort: 0, host: "127.0.0.1", dev: true,
|
|
179
|
+
autoShutdown: false, shutdownIdleSeconds: 999, tunnel: false,
|
|
180
|
+
});
|
|
181
|
+
await server.start();
|
|
182
|
+
|
|
183
|
+
// Keeper reclaim consumed the marker synchronously at start() — a later
|
|
184
|
+
// cold boot will not re-classify it, and the deferred auto-resume skips it.
|
|
185
|
+
const metaFile = path.join(sessionsDir, KEEPER.slice(0, 4), `2026-06-30T10-00-00-000Z_${KEEPER}.meta.json`);
|
|
186
|
+
expect(JSON.parse(readFileSync(metaFile, "utf-8")).live).toBe(false);
|
|
187
|
+
}, 15_000);
|
|
188
|
+
});
|
|
@@ -82,4 +82,33 @@ describe("session tags persistence", () => {
|
|
|
82
82
|
const restored = result.sessions.find((s) => s.id === "tag-id");
|
|
83
83
|
expect(restored?.tags).toEqual(["docs"]);
|
|
84
84
|
});
|
|
85
|
+
|
|
86
|
+
it("preserves tags across a bridge reattach (register with registerReason=reattach)", () => {
|
|
87
|
+
mgr.update("tag-id", { tags: ["feature"] });
|
|
88
|
+
metaPersistence.flushAll();
|
|
89
|
+
expect(readSessionMeta(sessionFile)?.tags).toEqual(["feature"]);
|
|
90
|
+
|
|
91
|
+
// Simulate reboot-resume: the pi session's bridge reattaches and re-registers.
|
|
92
|
+
mgr.register({
|
|
93
|
+
id: "tag-id",
|
|
94
|
+
cwd: "/test/cwd",
|
|
95
|
+
source: "tui",
|
|
96
|
+
startedAt: 1000,
|
|
97
|
+
sessionFile,
|
|
98
|
+
registerReason: "reattach",
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// In-memory survival: the reattach carry-over must keep user-owned tags.
|
|
102
|
+
expect(mgr.get("tag-id")?.tags).toEqual(["feature"]);
|
|
103
|
+
|
|
104
|
+
// Disk survival: the reattach onChange full-overwrite save must not wipe them.
|
|
105
|
+
metaPersistence.flushAll();
|
|
106
|
+
expect(readSessionMeta(sessionFile)?.tags).toEqual(["feature"]);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("leaves tags undefined on a genuine first register (no prior record)", () => {
|
|
110
|
+
const fresh = createMemorySessionManager();
|
|
111
|
+
const s = fresh.register({ id: "fresh-id", cwd: "/test/cwd", source: "tui", startedAt: 2000 });
|
|
112
|
+
expect(s.tags).toBeUndefined();
|
|
113
|
+
});
|
|
85
114
|
});
|
|
@@ -8,6 +8,6 @@ Files in this directory. One row per source file.
|
|
|
8
8
|
| `handler-context.ts` | Defines `BrowserHandlerContext` interface — shared handler dependency bag passed to every browser-message handler. Carries `ws`, `sessionManager`, `eventStore`, `piGateway`, `headlessPidRegistry`, `pendingResumeRegistry`, optional `preferencesStore`, `sessionOrderManager`, `directoryService`, `terminalManager`, `metaPersistence`, pending registries (fork/attach/worktree-base/resume-intent/client-correlations), send/broadcast/replay callbacks. See change: open-view-command-in-editor-pane (removed `viewMessageStore` — `/view` opens the editor pane, no inline row store). |
|
|
9
9
|
| `session-action-handler.ts` | Browser→server session action handlers: `handleSendPrompt` (auto-resume ended sessions), `handleResumeSession` (continue/fork, placement intent, empty-session fork degrade), `handleSpawnSession` (preflight + watchdog arm + spawn-failure logging; enqueues optional `initialPrompt` into `pendingInitialPromptRegistry` — see change: project-init-skill-and-profiles), `handleShutdown`, `handleAbort`, `handleStopAfterTurn`, `handleForceKill`, follow-up queue forwarders (`handleClearFollowupEntries` … `handlePromoteFollowupEntry`), `handleFlowControl`, `handleKillProcess`, `handleSubagentResyncRequest` (forwards `subagent_resync_request` to owning bridge — change: fix-subagent-live-detail-reliability D2), `handleHeadlessReload` (kill+respawn reload for headless `/reload`). Exports `FORK_DEGRADED_TO_NEW_MESSAGE`, `FORK_DEGRADED_TO_NEW_CODE`. |
|
|
10
10
|
| `session-action-helpers.ts` | Pure helpers for `session-action-handler.ts`, extracted for unit tests. Exports `shouldInterceptReload` — returns true when `send_prompt` text is exactly `/reload`, no images, and session PID tracked in `headlessPidRegistry.getPid(sessionId)`. |
|
|
11
|
-
| `session-meta-handler.ts` | Browser→server session metadata handlers: `handleRenameSession`, `handleHideSession`, `handleUnhideSession` (moveToFront ordering), `handleAttachProposal`/`applyAttachProposal` (idempotent attach + auto-rename), `handleAcceptReplaceProposal`/`handleDismissReplaceProposal`, `handleDetachProposal`, `handleSetSessionDisplayPrefs`, `handleSetSessionProcessDrawer`, `handleSetSessionTags` (normalize + `update({tags})` + broadcast; persistence via `onChange`, NOT `mergeSessionMeta` — mirrors `handleHideSession`; see change: add-session-tags), `handleFetchContent`, `handleListSessions`. Exports `pushAttachProposalChanged` (pushes `attach_proposal_changed` to bridge). |
|
|
11
|
+
| `session-meta-handler.ts` | Browser→server session metadata handlers: `handleRenameSession`, `handleHideSession`, `handleUnhideSession` (moveToFront ordering), `handleAttachProposal`/`applyAttachProposal` (idempotent attach + auto-rename), `handleAcceptReplaceProposal`/`handleDismissReplaceProposal`, `handleDetachProposal`, `handleSetSessionDisplayPrefs`, `handleSetSessionProcessDrawer`, `handleSetSessionTags` (normalize + `update({tags})` + broadcast; persistence via `onChange`, NOT `mergeSessionMeta` — mirrors `handleHideSession`; see change: add-session-tags), `handleRemoveTagGlobally` (normalize inbound `tag` → empty ⇒ no-op; iterate `sessionManager.listAll()`, strip from carriers via the same normalize→`update`→`broadcast(session_updated)` path, one broadcast per changed session; global/not folder-scoped; see change: sidebar-tag-collapse-and-delete), `handleFetchContent`, `handleListSessions`. Exports `pushAttachProposalChanged` (pushes `attach_proposal_changed` to bridge). |
|
|
12
12
|
| `subscription-handler.ts` | Browser→server subscription handlers: `handleSubscribe` (replay stored events in batches with backpressure, stale-lastSeq reset + full replay, on-disk load via `directoryService`, asset/UI-state replay) and exports `replayUiState`, `replaySessionAssets`, `sendEventBatches`. Replays `ui_modules_list`, `ui_data_list`, `ext_ui_decorator`, `plugin_intents`, view-messages snapshot. Cold-load branch emits a hydration heartbeat (`setInterval` `HYDRATE_HEARTBEAT_MS=10000`) re-sending the empty `event_replay{events:[],isLast:false}` marker to live subscribers while `loadSessionEvents` parses; `stopHeartbeat()` clears it in every exit path (success/cancelled/error/catch), guarded by `ws.readyState===OPEN`. Keeps the client's hydration ceiling alive on very large parses. See change: fix-history-loading-false-empty-flash. |
|
|
13
13
|
| `terminal-handler.ts` | Browser→server terminal handlers: `handleCreateTerminal` (spawn PTY + reorder), `handleOpenInlineTerminal`/`handleCloseInlineTerminal` (event-sourced inline terminal card via `inline_terminal_open`/`inline_terminal_close` events), `handleKillTerminal`, `handleRenameTerminal`. |
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { beforeEach, describe, expect, it } from "vitest";
|
|
6
6
|
import { createMemorySessionManager, type SessionManager } from "../../session/memory-session-manager.js";
|
|
7
7
|
import type { BrowserHandlerContext } from "../handler-context.js";
|
|
8
|
-
import { handleAttachProposal, handleDetachProposal, handleSetSessionProcessDrawer, handleSetSessionTags, pushAttachProposalChanged } from "../session-meta-handler.js";
|
|
8
|
+
import { handleAttachProposal, handleDetachProposal, handleRemoveTagGlobally, handleSetSessionProcessDrawer, handleSetSessionTags, pushAttachProposalChanged } from "../session-meta-handler.js";
|
|
9
9
|
|
|
10
10
|
interface PiSent {
|
|
11
11
|
sessionId: string;
|
|
@@ -238,6 +238,103 @@ describe("handleSetSessionTags", () => {
|
|
|
238
238
|
});
|
|
239
239
|
});
|
|
240
240
|
|
|
241
|
+
describe("handleRemoveTagGlobally", () => {
|
|
242
|
+
let mgr: SessionManager;
|
|
243
|
+
beforeEach(() => {
|
|
244
|
+
mgr = createMemorySessionManager();
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
// E3: 5 sessions, 3 carry `explore`, 2 do not.
|
|
248
|
+
it("E3 — strips the tag from every carrier, one broadcast each, non-carriers untouched", () => {
|
|
249
|
+
registerSession(mgr, "s1", { tags: ["explore", "backend"] });
|
|
250
|
+
registerSession(mgr, "s2", { tags: ["explore"] });
|
|
251
|
+
registerSession(mgr, "s3", { tags: ["frontend"] });
|
|
252
|
+
registerSession(mgr, "s4", { tags: ["explore", "api"] });
|
|
253
|
+
registerSession(mgr, "s5", { tags: [] });
|
|
254
|
+
const { ctx, broadcasts } = makeCtx(mgr);
|
|
255
|
+
|
|
256
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: "explore" } as any, ctx);
|
|
257
|
+
|
|
258
|
+
expect(mgr.get("s1")!.tags).toEqual(["backend"]);
|
|
259
|
+
expect(mgr.get("s2")!.tags).toEqual([]);
|
|
260
|
+
expect(mgr.get("s4")!.tags).toEqual(["api"]);
|
|
261
|
+
// Non-carriers untouched.
|
|
262
|
+
expect(mgr.get("s3")!.tags).toEqual(["frontend"]);
|
|
263
|
+
expect(mgr.get("s5")!.tags).toEqual([]);
|
|
264
|
+
// Exactly one session_updated per carrier (3), none for non-carriers.
|
|
265
|
+
expect(broadcasts).toHaveLength(3);
|
|
266
|
+
expect(broadcasts.every((b) => b.type === "session_updated")).toBe(true);
|
|
267
|
+
expect(broadcasts.map((b) => b.sessionId).sort()).toEqual(["s1", "s2", "s4"]);
|
|
268
|
+
for (const b of broadcasts) {
|
|
269
|
+
expect((b.updates.tags as string[]).includes("explore")).toBe(false);
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// E4: no session carries `ghost`.
|
|
274
|
+
it("E4 — removing a tag no session carries is a no-op", () => {
|
|
275
|
+
registerSession(mgr, "s1", { tags: ["explore"] });
|
|
276
|
+
registerSession(mgr, "s2", { tags: ["frontend"] });
|
|
277
|
+
const { ctx, broadcasts } = makeCtx(mgr);
|
|
278
|
+
|
|
279
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: "ghost" } as any, ctx);
|
|
280
|
+
|
|
281
|
+
expect(mgr.get("s1")!.tags).toEqual(["explore"]);
|
|
282
|
+
expect(mgr.get("s2")!.tags).toEqual(["frontend"]);
|
|
283
|
+
expect(broadcasts).toEqual([]);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// E5: whitespace-only tag normalizes to empty.
|
|
287
|
+
it("E5 — blank tag normalizes empty ⇒ no-op", () => {
|
|
288
|
+
registerSession(mgr, "s1", { tags: ["explore"] });
|
|
289
|
+
const { ctx, broadcasts } = makeCtx(mgr);
|
|
290
|
+
|
|
291
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: " " } as any, ctx);
|
|
292
|
+
|
|
293
|
+
expect(mgr.get("s1")!.tags).toEqual(["explore"]);
|
|
294
|
+
expect(broadcasts).toEqual([]);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
// E6: inbound ` Explore ` normalizes to `explore` before matching.
|
|
298
|
+
it("E6 — normalizes the inbound tag before matching", () => {
|
|
299
|
+
registerSession(mgr, "s1", { tags: ["explore", "backend"] });
|
|
300
|
+
registerSession(mgr, "s2", { tags: ["explore"] });
|
|
301
|
+
const { ctx, broadcasts } = makeCtx(mgr);
|
|
302
|
+
|
|
303
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: " Explore " } as any, ctx);
|
|
304
|
+
|
|
305
|
+
expect(mgr.get("s1")!.tags).toEqual(["backend"]);
|
|
306
|
+
expect(mgr.get("s2")!.tags).toEqual([]);
|
|
307
|
+
expect(broadcasts).toHaveLength(2);
|
|
308
|
+
expect(broadcasts.map((b) => b.sessionId).sort()).toEqual(["s1", "s2"]);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// Untrusted payload: a non-string `tag` is a no-op (never reaches normalize).
|
|
312
|
+
it("non-string tag is a no-op (guards malformed WS payload)", () => {
|
|
313
|
+
registerSession(mgr, "s1", { tags: ["explore"] });
|
|
314
|
+
const { ctx, broadcasts } = makeCtx(mgr);
|
|
315
|
+
|
|
316
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: null } as any, ctx);
|
|
317
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: 42 } as any, ctx);
|
|
318
|
+
|
|
319
|
+
expect(mgr.get("s1")!.tags).toEqual(["explore"]);
|
|
320
|
+
expect(broadcasts).toEqual([]);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// X3: fresh listAll (reconnect snapshot) reflects the stripped tags.
|
|
324
|
+
it("X3 — a fresh listAll after the strip reflects the tag absent (reconnect replay)", () => {
|
|
325
|
+
registerSession(mgr, "s1", { tags: ["explore", "backend"] });
|
|
326
|
+
registerSession(mgr, "s2", { tags: ["explore"] });
|
|
327
|
+
const { ctx } = makeCtx(mgr);
|
|
328
|
+
|
|
329
|
+
handleRemoveTagGlobally({ type: "remove_tag_globally", tag: "explore" } as any, ctx);
|
|
330
|
+
|
|
331
|
+
// Simulate a reconnect snapshot: replay listAll and confirm no session
|
|
332
|
+
// still carries `explore`.
|
|
333
|
+
const replayed = mgr.listAll();
|
|
334
|
+
expect(replayed.every((s) => !(s.tags ?? []).includes("explore"))).toBe(true);
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
|
|
241
338
|
describe("handleDetachProposal — decision matrix", () => {
|
|
242
339
|
let mgr: SessionManager;
|
|
243
340
|
beforeEach(() => {
|
|
@@ -2,24 +2,25 @@
|
|
|
2
2
|
* Shared context for browser message handlers.
|
|
3
3
|
* Each handler receives only what it needs via this context.
|
|
4
4
|
*/
|
|
5
|
-
|
|
5
|
+
|
|
6
6
|
import type { ServerToBrowserMessage } from "@blackbelt-technology/pi-dashboard-shared/browser-protocol.js";
|
|
7
|
-
import type {
|
|
8
|
-
import type { EventStore } from "../persistence/memory-event-store.js";
|
|
9
|
-
import type { PiGateway } from "../pi/pi-gateway.js";
|
|
10
|
-
import type { PendingForkRegistry } from "../pending/pending-fork-registry.js";
|
|
11
|
-
import type { SessionOrderManager } from "../session/session-order-manager.js";
|
|
12
|
-
import type { PreferencesStore } from "../persistence/preferences-store.js";
|
|
7
|
+
import type { WebSocket } from "ws";
|
|
13
8
|
import type { DirectoryService } from "../directory-service.js";
|
|
14
|
-
import type { TerminalManager } from "../terminal/terminal-manager.js";
|
|
15
|
-
import type { HeadlessPidRegistry } from "../spawn-process/headless-pid-registry.js";
|
|
16
|
-
import type { MetaPersistence } from "../persistence/meta-persistence.js";
|
|
17
|
-
import type { PendingResumeRegistry } from "../pending/pending-resume-registry.js";
|
|
18
9
|
import type { PendingAttachRegistry } from "../pending/pending-attach-registry.js";
|
|
10
|
+
import type { PendingClientCorrelations } from "../pending/pending-client-correlations.js";
|
|
11
|
+
import type { PendingForkRegistry } from "../pending/pending-fork-registry.js";
|
|
19
12
|
import type { PendingInitialPromptRegistry } from "../pending/pending-initial-prompt-registry.js";
|
|
20
|
-
import type { PendingWorktreeBaseRegistry } from "../pending/pending-worktree-base-registry.js";
|
|
21
13
|
import type { PendingResumeIntentRegistry } from "../pending/pending-resume-intent-registry.js";
|
|
22
|
-
import type {
|
|
14
|
+
import type { PendingResumeRegistry } from "../pending/pending-resume-registry.js";
|
|
15
|
+
import type { PendingWorktreeBaseRegistry } from "../pending/pending-worktree-base-registry.js";
|
|
16
|
+
import type { EventStore } from "../persistence/memory-event-store.js";
|
|
17
|
+
import type { MetaPersistence } from "../persistence/meta-persistence.js";
|
|
18
|
+
import type { PreferencesStore } from "../persistence/preferences-store.js";
|
|
19
|
+
import type { PiGateway } from "../pi/pi-gateway.js";
|
|
20
|
+
import type { SessionManager } from "../session/memory-session-manager.js";
|
|
21
|
+
import type { SessionOrderManager } from "../session/session-order-manager.js";
|
|
22
|
+
import type { HeadlessPidRegistry } from "../spawn-process/headless-pid-registry.js";
|
|
23
|
+
import type { TerminalManager } from "../terminal/terminal-manager.js";
|
|
23
24
|
|
|
24
25
|
export interface BrowserHandlerContext {
|
|
25
26
|
ws: WebSocket;
|
|
@@ -76,6 +77,16 @@ export interface BrowserHandlerContext {
|
|
|
76
77
|
* See change: spawn-correlation-token.
|
|
77
78
|
*/
|
|
78
79
|
pendingClientCorrelations?: PendingClientCorrelations;
|
|
80
|
+
/**
|
|
81
|
+
* True while `sessionId` is an unresolved cold-start recovery candidate whose
|
|
82
|
+
* process liveness is still being determined (the Class-2 bridge-reattach
|
|
83
|
+
* grace window). A `continue` resume MUST be refused in this window: a
|
|
84
|
+
* surviving bridge may be about to reattach, and spawning now would
|
|
85
|
+
* double-register the session and break message routing. Finalized (dead)
|
|
86
|
+
* candidates leave the pending set when the window closes.
|
|
87
|
+
* See change: fix-recovery-offer-bridge-liveness-gate.
|
|
88
|
+
*/
|
|
89
|
+
isRecoveryLivenessPending?(sessionId: string): boolean;
|
|
79
90
|
/** Send message to a specific WebSocket */
|
|
80
91
|
sendTo(ws: WebSocket, msg: ServerToBrowserMessage): void;
|
|
81
92
|
/** Broadcast to all connected browsers */
|
|
@@ -12,9 +12,9 @@ import {
|
|
|
12
12
|
import {
|
|
13
13
|
findPidByMarker,
|
|
14
14
|
} from "@blackbelt-technology/pi-dashboard-shared/platform/process-identify.js";
|
|
15
|
+
import { createBranchedSessionFile } from "../session/session-file-reader.js";
|
|
15
16
|
import { keeperOptsFromSpawnResult } from "../spawn-process/headless-pid-registry.js";
|
|
16
17
|
import { spawnPiSession } from "../spawn-process/process-manager.js";
|
|
17
|
-
import { createBranchedSessionFile } from "../session/session-file-reader.js";
|
|
18
18
|
import { appendSpawnFailure } from "../spawn-process/spawn-failure-log.js";
|
|
19
19
|
import { preflightSpawn } from "../spawn-process/spawn-preflight.js";
|
|
20
20
|
import { getSpawnRegisterWatchdog } from "../spawn-process/spawn-register-watchdog.js";
|
|
@@ -288,6 +288,17 @@ export async function handleResumeSession(
|
|
|
288
288
|
sendTo(ws, { type: "resume_result", sessionId: msg.sessionId, success: false, message: "Session is already active", code: "resume.already_active", requestId: msg.requestId });
|
|
289
289
|
return;
|
|
290
290
|
}
|
|
291
|
+
// Defense-in-depth against the Class-2 double-spawn race: while a cold-start
|
|
292
|
+
// recovery candidate's liveness is still unresolved (grace window open), a
|
|
293
|
+
// surviving bridge may be about to reattach. Reopening now would spawn a
|
|
294
|
+
// second pi for a sessionId whose process is alive, and the gateway
|
|
295
|
+
// session→connection map is last-write-wins → message routing breaks. Refuse
|
|
296
|
+
// until liveness is finalized (the UI shows a "verifying" state meanwhile).
|
|
297
|
+
// See change: fix-recovery-offer-bridge-liveness-gate.
|
|
298
|
+
if (msg.mode === "continue" && ctx.isRecoveryLivenessPending?.(msg.sessionId)) {
|
|
299
|
+
sendTo(ws, { type: "resume_result", sessionId: msg.sessionId, success: false, message: "Verifying whether this session is still running…", code: "resume.already_resuming", requestId: msg.requestId });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
291
302
|
if (session.resuming) {
|
|
292
303
|
sendTo(ws, { type: "resume_result", sessionId: msg.sessionId, success: false, message: "Session is already being resumed", code: "resume.already_resuming", requestId: msg.requestId });
|
|
293
304
|
return;
|
|
@@ -71,6 +71,35 @@ export function handleSetSessionTags(
|
|
|
71
71
|
ctx.broadcast({ type: "session_updated", sessionId: msg.sessionId, updates });
|
|
72
72
|
}
|
|
73
73
|
|
|
74
|
+
/**
|
|
75
|
+
* Browser → server: strip a single user tag from EVERY session that carries it
|
|
76
|
+
* (global, not folder-scoped — over `sessionManager.listAll()`). Normalizes the
|
|
77
|
+
* inbound tag first; a blank/whitespace-only tag (`normalizeTags` → `[]`) is an
|
|
78
|
+
* early no-op. For each carrying session it reuses the same
|
|
79
|
+
* `normalizeTags` → `sessionManager.update({ tags })` → `broadcast(session_updated)`
|
|
80
|
+
* path as `handleSetSessionTags` (one broadcast per changed session; no
|
|
81
|
+
* `mergeSessionMeta`). Best-effort fan-out, not a transaction.
|
|
82
|
+
* See change: sidebar-tag-collapse-and-delete.
|
|
83
|
+
*/
|
|
84
|
+
export function handleRemoveTagGlobally(
|
|
85
|
+
msg: Extract<BrowserToServerMessage, { type: "remove_tag_globally" }>,
|
|
86
|
+
ctx: BrowserHandlerContext,
|
|
87
|
+
): void {
|
|
88
|
+
const { sessionManager, broadcast } = ctx;
|
|
89
|
+
// Untrusted WS payload: guard non-string `tag` before normalize (`normalizeTags`
|
|
90
|
+
// calls `.trim()` — a malformed `null`/number would throw). See CodeRabbit #8.
|
|
91
|
+
if (typeof msg.tag !== "string") return;
|
|
92
|
+
const target = normalizeTags([msg.tag])[0];
|
|
93
|
+
if (!target) return;
|
|
94
|
+
for (const session of sessionManager.listAll()) {
|
|
95
|
+
const tags = session.tags ?? [];
|
|
96
|
+
if (!tags.includes(target)) continue;
|
|
97
|
+
const updates = { tags: normalizeTags(tags.filter((t) => t !== target)) };
|
|
98
|
+
sessionManager.update(session.id, updates);
|
|
99
|
+
broadcast({ type: "session_updated", sessionId: session.id, updates });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
74
103
|
export function handleUnhideSession(
|
|
75
104
|
msg: Extract<BrowserToServerMessage, { type: "unhide_session" }>,
|
|
76
105
|
ctx: BrowserHandlerContext,
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# DOX — packages/server/src/embed-lifecycle
|
|
2
|
+
|
|
3
|
+
Files in this directory. One row per source file. Server-side lifecycle control plane for machine-fronted (`ephemeral`) sessions: idempotent acquire, idle reaper, active-session caps, observability — all off by default (`config.embedLifecycle.enabled`). See change: add-embed-session-lifecycle.
|
|
4
|
+
|
|
5
|
+
| File | Purpose |
|
|
6
|
+
|------|---------|
|
|
7
|
+
| `caps.ts` | Active-session caps admission gate. `createCapsAdmission(deps)` → `{ admit(key) }`; counts only ephemeral, reclaims oldest quiescent, else throws `CapacityError` (exported). Global cap = hard bound; shared `reclaimGuard` avoids double-select. |
|
|
8
|
+
| `cwd-allowlist.ts` | `isCwdAllowed(cwd, allowedRoots, {realpath?})` — realpath + `within` containment; empty allowlist denies (D11). |
|
|
9
|
+
| `embed-lifecycle-controller.ts` | Server-integration facade. `createEmbedLifecycleController(deps)` → `{ metrics, reaper, start, stop, snapshot }`; wires the live reaper + metrics to sessionManager/browserGateway/terminalManager/pidRegistry/piGateway. Dormant when disabled. |
|
|
10
|
+
| `idle-reaper.ts` | Three-gear reaper loop. `createIdleReaper(deps)` → `{ sweepOnce, start, stop }`; assembles signals, calls `decideReap`, applies (idle/phantom → `killBySessionId`, stop-after-turn → latch). `CPU_IDLE_THRESHOLD`. |
|
|
11
|
+
| `identity-key.ts` | Canonical identity key. `canonicalizeCwd` (realpath + case-normalize via `caseInsensitiveFilesystem`), `buildIdentityKey`, `composeIdentityKey`, `visitorIdOf`. NUL-joined `visitor + cwd + agent` (D10). |
|
|
12
|
+
| `lifecycle-event-capture.ts` | `captureLifecycleTimestamp(eventType, now)` → `{lastRunStartedAt}` / `{lastSettledAt}` / null. Version-agnostic settle capture (keys on event name, no piVersion branch). Wired in `event-wiring.ts`. |
|
|
13
|
+
| `lifecycle-metrics.ts` | Observability counters. `createLifecycleMetrics(deps)` → `{ recordReap, recordCapacityReject, recordReuse, snapshot }`. Live active/idle from injected accessors; cumulative reap/reuse/reject. Exposed via `/api/health` `embedLifecycle`. |
|
|
14
|
+
| `liveness-probe.ts` | Bounded pid-tree + CPU probe. `createLivenessProbe({timeoutMs?,runPs?})` → `(rootPid)⇒LivenessSnapshot`; pure `summarizeProcessTree` + `parsePsOutput`. `{ok:false}` on ps failure ⇒ safe direction. |
|
|
15
|
+
| `quiescence.ts` | Pure reap-decision core. `decideReap(signals, thresholds, now)` → `{action,reason}`; `isAtRest`, `isWithinGraceWindow`. Encodes 3 gears + every veto (X4 matrix, X5 phantom guard). `LifecycleSignals`, `LifecycleThresholds`, `ReapReason`. |
|
|
16
|
+
| `session-lifecycle-policy.ts` | Provenance accessor. `isEphemeral(session)`, `effectiveLifecyclePolicy(session)` — absent `lifecyclePolicy` ⇒ `"durable"` (D1). Every downstream gate reads through here. |
|
|
17
|
+
| `visitor-session-registry.ts` | Idempotent acquire. `createVisitorSessionRegistry(deps)` → `{ acquire, resolveByCwd, mappedSessionId }`; coalescing `key→Promise`, reuse→resume→spawn ladder, bounded register timeout (X2), key re-point across resume renumber (E10). |
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Active-session caps (test-plan #E17, #E18, #E19, #X3): count only ephemeral,
|
|
3
|
+
* reclaim oldest quiescent at the cap, global cap bounds a visitorId spoofer,
|
|
4
|
+
* and a structured capacity error when every candidate is busy.
|
|
5
|
+
* See change: add-embed-session-lifecycle.
|
|
6
|
+
*/
|
|
7
|
+
import { DEFAULT_EMBED_LIFECYCLE } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
8
|
+
import { describe, expect, it, vi } from "vitest";
|
|
9
|
+
import { CapacityError, type CapSessionInfo, createCapsAdmission } from "../caps.js";
|
|
10
|
+
import { composeIdentityKey } from "../identity-key.js";
|
|
11
|
+
|
|
12
|
+
const cfg = (over = {}) => () => ({
|
|
13
|
+
...DEFAULT_EMBED_LIFECYCLE,
|
|
14
|
+
enabled: true,
|
|
15
|
+
maxActiveEmbedSessionsPerVisitor: 2,
|
|
16
|
+
maxActiveEmbedSessionsGlobal: 3,
|
|
17
|
+
...over,
|
|
18
|
+
});
|
|
19
|
+
const keyFor = (v: string) => composeIdentityKey(v, "/w", "a");
|
|
20
|
+
|
|
21
|
+
function info(over: Partial<CapSessionInfo> & { sessionId: string }): CapSessionInfo {
|
|
22
|
+
return { visitorId: "v1", quiescent: false, lastActivityAt: 0, ...over };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe("caps admission", () => {
|
|
26
|
+
// E17 — at the per-visitor cap with a quiescent candidate: reclaim the OLDEST
|
|
27
|
+
// quiescent, then admit.
|
|
28
|
+
it("reclaims the oldest quiescent session at the per-visitor cap", async () => {
|
|
29
|
+
const reclaim = vi.fn(async () => {});
|
|
30
|
+
const active: CapSessionInfo[] = [
|
|
31
|
+
info({ sessionId: "old", quiescent: true, lastActivityAt: 100 }),
|
|
32
|
+
info({ sessionId: "new", quiescent: true, lastActivityAt: 900 }),
|
|
33
|
+
];
|
|
34
|
+
const { admit } = createCapsAdmission({
|
|
35
|
+
config: cfg(),
|
|
36
|
+
listEphemeralActive: () => active,
|
|
37
|
+
reclaim,
|
|
38
|
+
});
|
|
39
|
+
await admit(keyFor("v1")); // perVisitor 2 >= cap 2 → reclaim
|
|
40
|
+
expect(reclaim).toHaveBeenCalledWith("old"); // oldest quiescent
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// X3 — at the cap with every candidate busy: structured error, nothing killed.
|
|
44
|
+
it("throws CapacityError and terminates nothing when all candidates are busy", async () => {
|
|
45
|
+
const reclaim = vi.fn(async () => {});
|
|
46
|
+
const active = [
|
|
47
|
+
info({ sessionId: "a", quiescent: false }),
|
|
48
|
+
info({ sessionId: "b", quiescent: false }),
|
|
49
|
+
];
|
|
50
|
+
const onCapacityReject = vi.fn();
|
|
51
|
+
const { admit } = createCapsAdmission({
|
|
52
|
+
config: cfg(),
|
|
53
|
+
listEphemeralActive: () => active,
|
|
54
|
+
reclaim,
|
|
55
|
+
onCapacityReject,
|
|
56
|
+
});
|
|
57
|
+
await expect(admit(keyFor("v1"))).rejects.toBeInstanceOf(CapacityError);
|
|
58
|
+
expect(reclaim).not.toHaveBeenCalled();
|
|
59
|
+
expect(onCapacityReject).toHaveBeenCalledTimes(1);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
// E18 — a durable session at the cap boundary is never counted (durable
|
|
63
|
+
// sessions are simply absent from listEphemeralActive).
|
|
64
|
+
it("counts only ephemeral sessions (durable are not listed)", async () => {
|
|
65
|
+
const reclaim = vi.fn(async () => {});
|
|
66
|
+
// Only ONE ephemeral active, under the per-visitor cap of 2 → admit, no reclaim.
|
|
67
|
+
const active = [info({ sessionId: "e1", quiescent: true, lastActivityAt: 1 })];
|
|
68
|
+
const { admit } = createCapsAdmission({
|
|
69
|
+
config: cfg(),
|
|
70
|
+
listEphemeralActive: () => active,
|
|
71
|
+
reclaim,
|
|
72
|
+
});
|
|
73
|
+
await admit(keyFor("v1"));
|
|
74
|
+
expect(reclaim).not.toHaveBeenCalled();
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// E19 — the GLOBAL cap bounds a spoofer minting distinct visitorIds: even
|
|
78
|
+
// though each visitor is under the per-visitor cap, the global cap forces a
|
|
79
|
+
// reclaim (adversarial breach reclaims across ALL visitors).
|
|
80
|
+
it("uses the global cap as the hard bound across spoofed visitorIds", async () => {
|
|
81
|
+
const reclaim = vi.fn(async () => {});
|
|
82
|
+
// 3 active from 3 distinct visitors = global cap (3); each visitor only 1
|
|
83
|
+
// (under per-visitor 2). A 4th distinct-visitor acquire must reclaim.
|
|
84
|
+
const active = [
|
|
85
|
+
info({ sessionId: "s1", visitorId: "v1", quiescent: true, lastActivityAt: 300 }),
|
|
86
|
+
info({ sessionId: "s2", visitorId: "v2", quiescent: true, lastActivityAt: 100 }),
|
|
87
|
+
info({ sessionId: "s3", visitorId: "v3", quiescent: false }),
|
|
88
|
+
];
|
|
89
|
+
const { admit } = createCapsAdmission({
|
|
90
|
+
config: cfg(),
|
|
91
|
+
listEphemeralActive: () => active,
|
|
92
|
+
reclaim,
|
|
93
|
+
});
|
|
94
|
+
await admit(keyFor("v4")); // over global → reclaim oldest quiescent across all
|
|
95
|
+
expect(reclaim).toHaveBeenCalledWith("s2"); // oldest quiescent globally
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
// X3 (global) — over the global cap with only busy candidates → CapacityError.
|
|
99
|
+
it("throws when over the global cap and no candidate is quiescent", async () => {
|
|
100
|
+
const active = [
|
|
101
|
+
info({ sessionId: "s1", visitorId: "v1", quiescent: false }),
|
|
102
|
+
info({ sessionId: "s2", visitorId: "v2", quiescent: false }),
|
|
103
|
+
info({ sessionId: "s3", visitorId: "v3", quiescent: false }),
|
|
104
|
+
];
|
|
105
|
+
const { admit } = createCapsAdmission({
|
|
106
|
+
config: cfg(),
|
|
107
|
+
listEphemeralActive: () => active,
|
|
108
|
+
reclaim: vi.fn(async () => {}),
|
|
109
|
+
});
|
|
110
|
+
await expect(admit(keyFor("v4"))).rejects.toBeInstanceOf(CapacityError);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("does not double-select a victim already in the shared reclaim guard", async () => {
|
|
114
|
+
const reclaim = vi.fn(async () => {});
|
|
115
|
+
const guard = new Set<string>(["old"]);
|
|
116
|
+
const active = [
|
|
117
|
+
info({ sessionId: "old", quiescent: true, lastActivityAt: 100 }),
|
|
118
|
+
info({ sessionId: "new", quiescent: true, lastActivityAt: 900 }),
|
|
119
|
+
];
|
|
120
|
+
const { admit } = createCapsAdmission({
|
|
121
|
+
config: cfg({ maxActiveEmbedSessionsPerVisitor: 1 }),
|
|
122
|
+
listEphemeralActive: () => active,
|
|
123
|
+
reclaim,
|
|
124
|
+
reclaimGuard: guard,
|
|
125
|
+
});
|
|
126
|
+
await admit(keyFor("v1")); // "old" is guarded → reclaim "new"
|
|
127
|
+
expect(reclaim).toHaveBeenCalledWith("new");
|
|
128
|
+
});
|
|
129
|
+
});
|