|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 2 | +import * as fs from "fs"; |
| 3 | +import * as os from "os"; |
| 4 | +import * as path from "path"; |
| 5 | +import { AgenticBlackboard, type AgentIntent, type SystemLog } from "../src/core/blackboard.js"; |
| 6 | +import { RuntimeLogger } from "../src/core/logger.js"; |
| 7 | + |
| 8 | +describe("AgenticBlackboard", () => { |
| 9 | + let tmpDir: string; |
| 10 | + let globalDir: string; |
| 11 | + |
| 12 | + beforeEach(async () => { |
| 13 | + await AgenticBlackboard.flushPendingWrites(); |
| 14 | + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "blackboard-test-")); |
| 15 | + fs.mkdirSync(path.join(tmpDir, ".refiner")); |
| 16 | + globalDir = path.join(tmpDir, "global"); |
| 17 | + process.env.PROMPT_REFINER_GLOBAL_DIR = globalDir; |
| 18 | + }); |
| 19 | + |
| 20 | + afterEach(async () => { |
| 21 | + await AgenticBlackboard.flushPendingWrites(); |
| 22 | + delete process.env.PROMPT_REFINER_GLOBAL_DIR; |
| 23 | + vi.restoreAllMocks(); |
| 24 | + if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true }); |
| 25 | + }); |
| 26 | + |
| 27 | + it("stores nested-project activity at the nearest project root", async () => { |
| 28 | + const project = path.join(tmpDir, "project"); |
| 29 | + const nested = path.join(project, "src", "feature"); |
| 30 | + fs.mkdirSync(path.join(project, ".refiner"), { recursive: true }); |
| 31 | + fs.mkdirSync(nested, { recursive: true }); |
| 32 | + |
| 33 | + AgenticBlackboard.postLog("nested activity", nested); |
| 34 | + await AgenticBlackboard.flushPendingWrites(); |
| 35 | + |
| 36 | + const storagePath = path.join(project, ".refiner", "blackboard.json"); |
| 37 | + expect(fs.existsSync(storagePath)).toBe(true); |
| 38 | + expect(fs.existsSync(path.join(nested, ".refiner"))).toBe(false); |
| 39 | + expect(AgenticBlackboard.getLogs(nested)[0]?.message).toBe("nested activity"); |
| 40 | + }); |
| 41 | + |
| 42 | + it("initializes missing collections, bounds histories, and de-duplicates projects", async () => { |
| 43 | + const refinerDir = path.join(tmpDir, ".refiner"); |
| 44 | + const storagePath = path.join(refinerDir, "blackboard.json"); |
| 45 | + const globalPath = path.join(globalDir, "global_history.json"); |
| 46 | + const projectPath = path.resolve(tmpDir); |
| 47 | + const projectLogs = Array.from({ length: 200 }, (_, index): SystemLog => ({ |
| 48 | + timestamp: new Date(0).toISOString(), |
| 49 | + message: `project-${index}`, |
| 50 | + })); |
| 51 | + const globalLogs = Array.from({ length: 500 }, (_, index): SystemLog => ({ |
| 52 | + timestamp: new Date(0).toISOString(), |
| 53 | + message: `global-${index}`, |
| 54 | + })); |
| 55 | + fs.mkdirSync(refinerDir, { recursive: true }); |
| 56 | + fs.mkdirSync(globalDir); |
| 57 | + fs.writeFileSync(storagePath, JSON.stringify({ activeIntents: [], logs: projectLogs })); |
| 58 | + fs.writeFileSync(globalPath, JSON.stringify({ logs: globalLogs, projects: [projectPath] })); |
| 59 | + |
| 60 | + AgenticBlackboard.postLog("bounded", tmpDir); |
| 61 | + await AgenticBlackboard.flushPendingWrites(); |
| 62 | + |
| 63 | + expect(AgenticBlackboard.getLogs(tmpDir)).toHaveLength(200); |
| 64 | + expect(AgenticBlackboard.getGlobalData()).toMatchObject({ |
| 65 | + logs: expect.arrayContaining([expect.objectContaining({ message: "bounded" })]), |
| 66 | + projects: [projectPath], |
| 67 | + }); |
| 68 | + expect(AgenticBlackboard.getGlobalData().logs).toHaveLength(500); |
| 69 | + |
| 70 | + fs.writeFileSync(storagePath, "{}"); |
| 71 | + fs.writeFileSync(globalPath, "{}"); |
| 72 | + AgenticBlackboard.postLog("initialize arrays", tmpDir); |
| 73 | + await AgenticBlackboard.flushPendingWrites(); |
| 74 | + |
| 75 | + expect(AgenticBlackboard.getLogs(tmpDir)[0]?.message).toBe("initialize arrays"); |
| 76 | + expect(AgenticBlackboard.getGlobalData().projects).toEqual([projectPath]); |
| 77 | + }); |
| 78 | + |
| 79 | + it("notifies healthy listeners, isolates failing listeners, and supports unsubscribe", async () => { |
| 80 | + const healthy = vi.fn(); |
| 81 | + const failing = vi.fn(() => { |
| 82 | + throw new Error("listener failed"); |
| 83 | + }); |
| 84 | + const error = vi.spyOn(RuntimeLogger, "error").mockImplementation(() => undefined); |
| 85 | + const unsubscribeHealthy = AgenticBlackboard.onUpdate(healthy); |
| 86 | + const unsubscribeFailing = AgenticBlackboard.onUpdate(failing); |
| 87 | + |
| 88 | + AgenticBlackboard.postLog("first", tmpDir); |
| 89 | + await AgenticBlackboard.flushPendingWrites(); |
| 90 | + |
| 91 | + expect(healthy).toHaveBeenCalledOnce(); |
| 92 | + expect(failing).toHaveBeenCalledOnce(); |
| 93 | + expect(error).toHaveBeenCalledWith("Listener notification failed", expect.any(Error)); |
| 94 | + |
| 95 | + unsubscribeHealthy(); |
| 96 | + unsubscribeFailing(); |
| 97 | + AgenticBlackboard.postLog("second", tmpDir); |
| 98 | + await AgenticBlackboard.flushPendingWrites(); |
| 99 | + |
| 100 | + expect(healthy).toHaveBeenCalledOnce(); |
| 101 | + expect(failing).toHaveBeenCalledOnce(); |
| 102 | + }); |
| 103 | + |
| 104 | + it("replaces duplicate intents, removes expired intents, and preserves other active agents", async () => { |
| 105 | + const refinerDir = path.join(tmpDir, ".refiner"); |
| 106 | + const storagePath = path.join(refinerDir, "blackboard.json"); |
| 107 | + const active = (agentName: string, expiresAt: string): AgentIntent => ({ |
| 108 | + agentName, |
| 109 | + toolType: "CLI", |
| 110 | + intent: "existing", |
| 111 | + timestamp: new Date(0).toISOString(), |
| 112 | + expiresAt, |
| 113 | + }); |
| 114 | + fs.mkdirSync(refinerDir, { recursive: true }); |
| 115 | + fs.writeFileSync(storagePath, JSON.stringify({ |
| 116 | + logs: [], |
| 117 | + activeIntents: [ |
| 118 | + active("expired", new Date(0).toISOString()), |
| 119 | + active("replacement", new Date(Date.now() + 60_000).toISOString()), |
| 120 | + active("other", new Date(Date.now() + 60_000).toISOString()), |
| 121 | + ], |
| 122 | + })); |
| 123 | + |
| 124 | + const created = AgenticBlackboard.postIntent("replacement", "lint", "x".repeat(80), tmpDir); |
| 125 | + await AgenticBlackboard.flushPendingWrites(); |
| 126 | + |
| 127 | + expect(created.projectPath).toBe(path.resolve(tmpDir)); |
| 128 | + expect(new Date(created.expiresAt).getTime()).toBeGreaterThan(Date.now()); |
| 129 | + expect(AgenticBlackboard.getActiveIntents(tmpDir).map(intent => intent.agentName)).toEqual([ |
| 130 | + "other", |
| 131 | + "replacement", |
| 132 | + ]); |
| 133 | + expect(AgenticBlackboard.getLogs(tmpDir)[0]?.message).toContain(`${"x".repeat(50)}...`); |
| 134 | + |
| 135 | + fs.writeFileSync(storagePath, "{}"); |
| 136 | + AgenticBlackboard.postIntent("fresh", "lint", "new", tmpDir); |
| 137 | + await AgenticBlackboard.flushPendingWrites(); |
| 138 | + expect(AgenticBlackboard.getActiveIntents(tmpDir).map(intent => intent.agentName)).toEqual(["fresh"]); |
| 139 | + }); |
| 140 | + |
| 141 | + it("returns safe fallbacks for missing, malformed, and incomplete project data", () => { |
| 142 | + const error = vi.spyOn(RuntimeLogger, "error").mockImplementation(() => undefined); |
| 143 | + |
| 144 | + expect(AgenticBlackboard.getLogs(tmpDir)).toEqual([]); |
| 145 | + expect(AgenticBlackboard.getActiveIntents(tmpDir)).toEqual([]); |
| 146 | + expect(AgenticBlackboard.getLastRefinement(tmpDir)).toBeNull(); |
| 147 | + |
| 148 | + const refinerDir = path.join(tmpDir, ".refiner"); |
| 149 | + fs.mkdirSync(refinerDir, { recursive: true }); |
| 150 | + fs.writeFileSync(path.join(refinerDir, "blackboard.json"), "{"); |
| 151 | + |
| 152 | + expect(AgenticBlackboard.getLogs(tmpDir)).toEqual([]); |
| 153 | + expect(error).toHaveBeenCalledWith(expect.stringContaining("Failed to read JSON file"), expect.any(Error)); |
| 154 | + |
| 155 | + fs.writeFileSync(path.join(refinerDir, "blackboard.json"), "{}"); |
| 156 | + expect(AgenticBlackboard.getLogs(tmpDir)).toEqual([]); |
| 157 | + expect(AgenticBlackboard.getActiveIntents(tmpDir)).toEqual([]); |
| 158 | + expect(AgenticBlackboard.getLastRefinement(tmpDir)).toBeNull(); |
| 159 | + }); |
| 160 | + |
| 161 | + it("persists and returns the latest refinement with default gain", async () => { |
| 162 | + await AgenticBlackboard.setLastRefinement("before", "after", tmpDir); |
| 163 | + await AgenticBlackboard.flushPendingWrites(); |
| 164 | + |
| 165 | + expect(AgenticBlackboard.getLastRefinement(tmpDir)).toMatchObject({ |
| 166 | + original: "before", |
| 167 | + refined: "after", |
| 168 | + gain: 0, |
| 169 | + }); |
| 170 | + expect(AgenticBlackboard.getLogs(tmpDir)[0]?.message).toBe("Refinement Complete (Gain: 0%)"); |
| 171 | + }); |
| 172 | + |
| 173 | + it("logs and recovers from project-root and storage failures", async () => { |
| 174 | + const error = vi.spyOn(RuntimeLogger, "error").mockImplementation(() => undefined); |
| 175 | + const warn = vi.spyOn(RuntimeLogger, "warn").mockImplementation(() => undefined); |
| 176 | + const blockedProject = path.join(tmpDir, "blocked-project"); |
| 177 | + fs.mkdirSync(blockedProject); |
| 178 | + fs.writeFileSync(path.join(blockedProject, ".refiner"), "not a directory"); |
| 179 | + fs.writeFileSync(globalDir, "not a directory"); |
| 180 | + |
| 181 | + AgenticBlackboard.postLog("cannot persist", blockedProject); |
| 182 | + await AgenticBlackboard.setLastRefinement("before", "after", blockedProject, 5); |
| 183 | + await AgenticBlackboard.flushPendingWrites(); |
| 184 | + |
| 185 | + expect(AgenticBlackboard.getGlobalData()).toEqual({ logs: [], projects: [] }); |
| 186 | + expect(error).toHaveBeenCalledWith("Failed to ensure project blackboard storage", expect.any(Error)); |
| 187 | + expect(error).toHaveBeenCalledWith("Failed to ensure global blackboard storage", expect.any(Error)); |
| 188 | + expect(error).toHaveBeenCalledWith(expect.stringContaining("Atomic update failed"), expect.any(Error)); |
| 189 | + |
| 190 | + expect(Array.isArray(AgenticBlackboard.getLogs(null as unknown as string))).toBe(true); |
| 191 | + expect(warn).toHaveBeenCalledWith(expect.stringContaining("Failed to resolve project root"), expect.any(Error)); |
| 192 | + }); |
| 193 | + |
| 194 | + it("uses the home-directory global store when no override is configured", () => { |
| 195 | + delete process.env.PROMPT_REFINER_GLOBAL_DIR; |
| 196 | + |
| 197 | + const data = AgenticBlackboard.getGlobalData(); |
| 198 | + |
| 199 | + expect(data).toHaveProperty("logs"); |
| 200 | + expect(data).toHaveProperty("projects"); |
| 201 | + }); |
| 202 | +}); |
0 commit comments