recallnest 1.4.1 → 2.2.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 (166) hide show
  1. package/.dockerignore +11 -0
  2. package/CLAUDE.md +7 -3
  3. package/Dockerfile +20 -0
  4. package/README.md +202 -130
  5. package/README_CN.md +263 -190
  6. package/ROADMAP.md +128 -81
  7. package/SKILL.md +250 -0
  8. package/assets/dashboard.png +0 -0
  9. package/assets/knowledge-graph.png +0 -0
  10. package/assets/screenshots/ui-full.png +0 -0
  11. package/assets/screenshots/ui-overview.png +0 -0
  12. package/assets/screenshots/ui-search.png +0 -0
  13. package/assets/ui/app.js +227 -3
  14. package/assets/ui/index.html +81 -11
  15. package/assets/ui/styles.css +178 -2
  16. package/bin/recallnest.mjs +62 -0
  17. package/bun.lock +337 -0
  18. package/daily-recall.sh +23 -0
  19. package/daily-reflections/2026-04-02.md +35 -0
  20. package/daily-reflections/2026-04-03.md +37 -0
  21. package/daily-reflections/2026-04-04.md +37 -0
  22. package/daily-reflections/2026-04-05.md +35 -0
  23. package/daily-reflections/2026-04-06.md +36 -0
  24. package/daily-reflections/2026-04-07.md +35 -0
  25. package/daily-reflections/2026-04-08.md +35 -0
  26. package/daily-reflections/2026-04-12.md +35 -0
  27. package/data/alias-map.example.json +22 -0
  28. package/docs/plans/2026-04-01-recall-boost.md +100 -0
  29. package/docs/superpowers/plans/2026-04-11-constructive-retrieval-emotion.md +1195 -0
  30. package/docs/superpowers/specs/2026-04-11-constructive-retrieval-emotion-design.md +398 -0
  31. package/glama.json +6 -0
  32. package/integrations/setup-all.sh +31 -0
  33. package/package.json +10 -3
  34. package/plan-philosophy-upgrades.md +363 -0
  35. package/plan-product-upgrades.md +155 -0
  36. package/plan.md +140 -0
  37. package/research-memory-evolution.md +440 -0
  38. package/research-rl-agent-memory.md +330 -0
  39. package/scripts/backfill-anchors.ts +130 -0
  40. package/scripts/diagnose-vector-search.ts +132 -0
  41. package/scripts/migrate-language.ts +75 -0
  42. package/scripts/verify-emotion-decay.ts +148 -0
  43. package/src/__tests__/activity-counter.test.ts +96 -0
  44. package/src/__tests__/admission-control.test.ts +206 -0
  45. package/src/__tests__/anchor-generator.test.ts +67 -0
  46. package/src/__tests__/babel-integration.test.ts +139 -0
  47. package/src/__tests__/capture-engine.test.ts +5 -3
  48. package/src/__tests__/cascade-forget.test.ts +1 -1
  49. package/src/__tests__/cc8-cc1-essential-context.test.ts +298 -0
  50. package/src/__tests__/circuit-breaker.test.ts +99 -0
  51. package/src/__tests__/cluster-consolidation.test.ts +712 -0
  52. package/src/__tests__/confidence-metadata.test.ts +125 -0
  53. package/src/__tests__/confidence-tracker.test.ts +53 -0
  54. package/src/__tests__/consolidation-engine.test.ts +1 -1
  55. package/src/__tests__/constructive-retrieval.test.ts +509 -0
  56. package/src/__tests__/context-collapse-renderer.test.ts +214 -0
  57. package/src/__tests__/context-reconstructor.test.ts +65 -0
  58. package/src/__tests__/conversation-importer.test.ts +692 -0
  59. package/src/__tests__/data-checkup.test.ts +225 -0
  60. package/src/__tests__/decay-exemption.test.ts +84 -0
  61. package/src/__tests__/dedup-guard.test.ts +39 -0
  62. package/src/__tests__/distill-lock.test.ts +176 -0
  63. package/src/__tests__/dream-pipeline.test.ts +232 -0
  64. package/src/__tests__/emotion-decay.test.ts +46 -0
  65. package/src/__tests__/emotion-detector.test.ts +56 -0
  66. package/src/__tests__/emotion-phase1-integration.test.ts +153 -0
  67. package/src/__tests__/emotion-retrieval.test.ts +56 -0
  68. package/src/__tests__/ethics-layer.test.ts +476 -0
  69. package/src/__tests__/feature-flags-integration.test.ts +54 -0
  70. package/src/__tests__/frequency-tracker.test.ts +113 -0
  71. package/src/__tests__/graph-export.test.ts +489 -0
  72. package/src/__tests__/interference-detector.test.ts +203 -0
  73. package/src/__tests__/mcp-efficiency.test.ts +288 -0
  74. package/src/__tests__/memory-evolution-b2-b3-e1.test.ts +243 -0
  75. package/src/__tests__/memory-evolution.test.ts +271 -0
  76. package/src/__tests__/memory-lint.test.ts +271 -0
  77. package/src/__tests__/narrative-architecture.test.ts +456 -0
  78. package/src/__tests__/pending-review.test.ts +77 -0
  79. package/src/__tests__/post-retrieval-filter.test.ts +178 -0
  80. package/src/__tests__/prediction-engine.test.ts +349 -0
  81. package/src/__tests__/predictive-prospective-memory.test.ts +416 -0
  82. package/src/__tests__/preference-slots.test.ts +99 -0
  83. package/src/__tests__/query-expander-alias.test.ts +89 -0
  84. package/src/__tests__/recall-governor.test.ts +227 -0
  85. package/src/__tests__/resume-context.test.ts +156 -1
  86. package/src/__tests__/salience-scoring.test.ts +106 -0
  87. package/src/__tests__/session-distiller.test.ts +611 -0
  88. package/src/__tests__/skill-engine.test.ts +546 -0
  89. package/src/__tests__/skill-promotion.test.ts +349 -0
  90. package/src/__tests__/supersede-chain.test.ts +154 -0
  91. package/src/__tests__/temporal-validity.test.ts +160 -0
  92. package/src/__tests__/topic-tag.test.ts +113 -0
  93. package/src/__tests__/trusted-memory.test.ts +828 -0
  94. package/src/__tests__/write-verifier.test.ts +122 -0
  95. package/src/access-tracker.ts +3 -2
  96. package/src/activity-counter.ts +109 -0
  97. package/src/adaptive-retrieval.ts +6 -5
  98. package/src/admission-control.ts +163 -0
  99. package/src/anchor-generator.ts +80 -0
  100. package/src/api-server.ts +10 -0
  101. package/src/audit-log.ts +122 -0
  102. package/src/auto-gc.ts +98 -29
  103. package/src/auto-recall.ts +33 -4
  104. package/src/capture-engine.ts +372 -23
  105. package/src/cascade-forget.ts +3 -2
  106. package/src/cli.ts +107 -5
  107. package/src/compat.ts +22 -0
  108. package/src/confidence-tracker.ts +210 -47
  109. package/src/conflict-store.ts +12 -3
  110. package/src/consolidation-engine.ts +296 -8
  111. package/src/context-collapse-renderer.ts +222 -0
  112. package/src/context-composer-stable-selection.ts +5 -1
  113. package/src/context-composer.ts +239 -4
  114. package/src/context-reconstructor.ts +404 -0
  115. package/src/conversation-importer.ts +441 -0
  116. package/src/data-checkup.ts +232 -0
  117. package/src/decay-engine.ts +84 -0
  118. package/src/distill-lock.ts +122 -0
  119. package/src/doctor.ts +8 -10
  120. package/src/dream-pipeline.ts +227 -0
  121. package/src/emotion-detector.ts +90 -0
  122. package/src/eval.ts +3 -2
  123. package/src/forget-engine.ts +269 -0
  124. package/src/frequency-tracker.ts +175 -0
  125. package/src/graph-export.ts +644 -0
  126. package/src/ingest.ts +36 -6
  127. package/src/interference-detector.ts +187 -0
  128. package/src/kg-extractor.ts +15 -24
  129. package/src/kg-store.ts +2 -1
  130. package/src/language-hook.ts +67 -0
  131. package/src/llm-client.ts +289 -6
  132. package/src/mcp-server.ts +707 -80
  133. package/src/memory-assets.ts +22 -5
  134. package/src/memory-evolution.ts +365 -0
  135. package/src/memory-lint.ts +429 -0
  136. package/src/memory-output.ts +69 -0
  137. package/src/memory-schema.ts +74 -2
  138. package/src/narrative-schema.ts +79 -0
  139. package/src/narrative-tagger.ts +164 -0
  140. package/src/pii-detector.ts +98 -0
  141. package/src/post-retrieval-filter.ts +76 -0
  142. package/src/prediction-engine.ts +253 -0
  143. package/src/preference-slots.ts +65 -2
  144. package/src/prospective-memory.ts +215 -0
  145. package/src/query-expander.ts +67 -0
  146. package/src/recall-governor.ts +183 -0
  147. package/src/retention-policy.ts +90 -0
  148. package/src/retriever.ts +828 -55
  149. package/src/rif.ts +34 -8
  150. package/src/runtime-config.ts +23 -8
  151. package/src/scope-inventory.ts +4 -3
  152. package/src/scope-policy.ts +4 -0
  153. package/src/session-distiller.ts +307 -0
  154. package/src/session-output.ts +40 -0
  155. package/src/session-schema.ts +37 -0
  156. package/src/session-store.ts +7 -2
  157. package/src/skill-engine.ts +208 -0
  158. package/src/skill-promotion.ts +293 -0
  159. package/src/skill-schema.ts +39 -0
  160. package/src/store.ts +96 -10
  161. package/src/topic-tag.ts +66 -0
  162. package/src/tracker.ts +3 -1
  163. package/src/ui-server.ts +80 -8
  164. package/src/workflow-observation-scope-review.ts +2 -1
  165. package/src/workflow-observation-store.ts +2 -1
  166. package/src/write-verifier.ts +126 -0
@@ -97,7 +97,7 @@ describe("persistMemory", () => {
97
97
  expect(result.canonicalKey).toBe("preferences:user-prefers-dark-mode");
98
98
  expect(result.disposition).toBe("stored");
99
99
  expect(storedEntries[0].scope).toBe(TEST_SCOPE);
100
- expect(JSON.parse(storedEntries[0].metadata)).toEqual({
100
+ expect(JSON.parse(storedEntries[0].metadata)).toMatchObject({
101
101
  source: "manual",
102
102
  tags: ["ui"],
103
103
  capture: "store_memory_schema_v1",
@@ -369,7 +369,7 @@ describe("persistWorkflowPattern", () => {
369
369
  expect(result.text).toContain("1. Call resume_context before coding");
370
370
  expect(result.text).toContain("Tools: resume_context, checkpoint_session");
371
371
  expect(storedEntries[0].category).toBe("patterns");
372
- expect(JSON.parse(storedEntries[0].metadata)).toEqual({
372
+ expect(JSON.parse(storedEntries[0].metadata)).toMatchObject({
373
373
  source: "agent",
374
374
  tags: ["continuity", "workflow", "pattern"],
375
375
  capture: "workflow_pattern_schema_v1",
@@ -381,6 +381,7 @@ describe("persistWorkflowPattern", () => {
381
381
  note: "Structured memory writes are the durable source inside RecallNest.",
382
382
  },
383
383
  canonicalKey: "patterns:cross-window-continuity-handoff",
384
+ anchor: "Cross-window continuity handoff",
384
385
  workflowPattern: {
385
386
  title: "Cross-window continuity handoff",
386
387
  trigger: "When opening a fresh terminal window for the same project",
@@ -422,7 +423,7 @@ describe("persistCaseMemory", () => {
422
423
  expect(result.text).toContain("Problem: resume_context returned noisy transcript fragments");
423
424
  expect(result.text).toContain("1. Filter low-signal transcript fragments from stable recall.");
424
425
  expect(storedEntries[0].category).toBe("cases");
425
- expect(JSON.parse(storedEntries[0].metadata)).toEqual({
426
+ expect(JSON.parse(storedEntries[0].metadata)).toMatchObject({
426
427
  source: "agent",
427
428
  tags: ["continuity", "case", "solution"],
428
429
  capture: "case_memory_schema_v1",
@@ -434,6 +435,7 @@ describe("persistCaseMemory", () => {
434
435
  note: "Structured memory writes are the durable source inside RecallNest.",
435
436
  },
436
437
  canonicalKey: "cases:recallnest-sparse-startup-context-cleanup",
438
+ anchor: "RecallNest sparse startup context cleanup",
437
439
  caseMemory: {
438
440
  title: "RecallNest sparse startup context cleanup",
439
441
  problem: "resume_context returned noisy transcript fragments instead of a clean project handoff.",
@@ -110,7 +110,7 @@ describe("cascade-forget", () => {
110
110
  it("skips already-archived entries", async () => {
111
111
  const archived = makeEntry("arch-1", "archived", {
112
112
  importance: 0.6,
113
- metadata: JSON.stringify({ state: "archived" }),
113
+ metadata: JSON.stringify({ evolution: { status: "archived" } }),
114
114
  });
115
115
  const searchResults: MemorySearchResult[] = [
116
116
  { entry: archived, score: 0.9 },
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Tests for CC-8 (Post-Compact Reconstruction) and CC-1 (Injection Hint).
3
+ *
4
+ * CC-8: essentialContext field in ResumeContextResponse — pinned memories,
5
+ * active patterns, and open loops assembled independently of search relevance.
6
+ * CC-1: injectionHint field — placement suggestion for recalled context.
7
+ */
8
+ import { describe, expect, test } from "bun:test";
9
+
10
+ import {
11
+ EssentialContextSchema,
12
+ ResumeContextResponseSchema,
13
+ } from "../session-schema.js";
14
+ import { formatResumeContext } from "../session-output.js";
15
+ import type { ResumeContextResponse } from "../session-schema.js";
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Helpers
19
+ // ---------------------------------------------------------------------------
20
+
21
+ function buildMinimalResponse(overrides: Partial<ResumeContextResponse> = {}): ResumeContextResponse {
22
+ return ResumeContextResponseSchema.parse({
23
+ summary: "Test resume summary",
24
+ stableContext: [],
25
+ relevantPatterns: [],
26
+ recentCases: [],
27
+ generatedAt: new Date().toISOString(),
28
+ ...overrides,
29
+ });
30
+ }
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // CC-8: EssentialContext Schema
34
+ // ---------------------------------------------------------------------------
35
+
36
+ describe("CC-8: EssentialContextSchema", () => {
37
+ test("accepts full essential context with all fields", () => {
38
+ const result = EssentialContextSchema.parse({
39
+ pinnedMemories: ["Pin A", "Pin B"],
40
+ activePatterns: ["Pattern X"],
41
+ openLoops: ["Loop 1", "Loop 2"],
42
+ });
43
+ expect(result.pinnedMemories).toEqual(["Pin A", "Pin B"]);
44
+ expect(result.activePatterns).toEqual(["Pattern X"]);
45
+ expect(result.openLoops).toEqual(["Loop 1", "Loop 2"]);
46
+ });
47
+
48
+ test("accepts empty object (all fields optional)", () => {
49
+ const result = EssentialContextSchema.parse({});
50
+ expect(result.pinnedMemories).toBeUndefined();
51
+ expect(result.activePatterns).toBeUndefined();
52
+ expect(result.openLoops).toBeUndefined();
53
+ });
54
+
55
+ test("enforces max 3 pinned memories", () => {
56
+ expect(() =>
57
+ EssentialContextSchema.parse({
58
+ pinnedMemories: ["a", "b", "c", "d"],
59
+ }),
60
+ ).toThrow();
61
+ });
62
+
63
+ test("enforces max 2 active patterns", () => {
64
+ expect(() =>
65
+ EssentialContextSchema.parse({
66
+ activePatterns: ["a", "b", "c"],
67
+ }),
68
+ ).toThrow();
69
+ });
70
+
71
+ test("enforces max 3 open loops", () => {
72
+ expect(() =>
73
+ EssentialContextSchema.parse({
74
+ openLoops: ["a", "b", "c", "d"],
75
+ }),
76
+ ).toThrow();
77
+ });
78
+ });
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // CC-8: essentialContext in ResumeContextResponse
82
+ // ---------------------------------------------------------------------------
83
+
84
+ describe("CC-8: essentialContext in ResumeContextResponse", () => {
85
+ test("response includes essentialContext when pins are present", () => {
86
+ const response = buildMinimalResponse({
87
+ essentialContext: {
88
+ pinnedMemories: ["Important pin"],
89
+ },
90
+ });
91
+ expect(response.essentialContext).toBeDefined();
92
+ expect(response.essentialContext!.pinnedMemories).toEqual(["Important pin"]);
93
+ });
94
+
95
+ test("essentialContext is undefined when no pins, patterns, or loops", () => {
96
+ const response = buildMinimalResponse({
97
+ essentialContext: undefined,
98
+ });
99
+ expect(response.essentialContext).toBeUndefined();
100
+ });
101
+
102
+ test("essentialContext with only openLoops is valid", () => {
103
+ const response = buildMinimalResponse({
104
+ essentialContext: {
105
+ openLoops: ["Pending PR review", "Deploy staging"],
106
+ },
107
+ });
108
+ expect(response.essentialContext).toBeDefined();
109
+ expect(response.essentialContext!.openLoops).toHaveLength(2);
110
+ expect(response.essentialContext!.pinnedMemories).toBeUndefined();
111
+ expect(response.essentialContext!.activePatterns).toBeUndefined();
112
+ });
113
+
114
+ test("essentialContext with only activePatterns is valid", () => {
115
+ const response = buildMinimalResponse({
116
+ essentialContext: {
117
+ activePatterns: ["Always run tests before commit"],
118
+ },
119
+ });
120
+ expect(response.essentialContext!.activePatterns).toEqual(["Always run tests before commit"]);
121
+ });
122
+
123
+ test("essentialContext coexists with other response fields", () => {
124
+ const response = buildMinimalResponse({
125
+ stableContext: ["User identity: developer"],
126
+ relevantPatterns: ["pattern 1"],
127
+ recentCases: ["case 1"],
128
+ essentialContext: {
129
+ pinnedMemories: ["Pinned note"],
130
+ activePatterns: ["Workflow pattern"],
131
+ openLoops: ["Open loop item"],
132
+ },
133
+ });
134
+ expect(response.stableContext).toHaveLength(1);
135
+ expect(response.relevantPatterns).toHaveLength(1);
136
+ expect(response.recentCases).toHaveLength(1);
137
+ expect(response.essentialContext!.pinnedMemories).toHaveLength(1);
138
+ expect(response.essentialContext!.activePatterns).toHaveLength(1);
139
+ expect(response.essentialContext!.openLoops).toHaveLength(1);
140
+ });
141
+ });
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // CC-1: injectionHint in ResumeContextResponse
145
+ // ---------------------------------------------------------------------------
146
+
147
+ describe("CC-1: injectionHint", () => {
148
+ test("defaults to user_attachment when not specified", () => {
149
+ const response = buildMinimalResponse();
150
+ expect(response.injectionHint).toBe("user_attachment");
151
+ });
152
+
153
+ test("accepts system_prompt value", () => {
154
+ const response = buildMinimalResponse({
155
+ injectionHint: "system_prompt",
156
+ });
157
+ expect(response.injectionHint).toBe("system_prompt");
158
+ });
159
+
160
+ test("accepts user_attachment value", () => {
161
+ const response = buildMinimalResponse({
162
+ injectionHint: "user_attachment",
163
+ });
164
+ expect(response.injectionHint).toBe("user_attachment");
165
+ });
166
+
167
+ test("rejects invalid injection hint", () => {
168
+ expect(() =>
169
+ ResumeContextResponseSchema.parse({
170
+ summary: "test",
171
+ stableContext: [],
172
+ relevantPatterns: [],
173
+ recentCases: [],
174
+ injectionHint: "invalid_value",
175
+ generatedAt: new Date().toISOString(),
176
+ }),
177
+ ).toThrow();
178
+ });
179
+ });
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // CC-8 + CC-1: formatResumeContext rendering
183
+ // ---------------------------------------------------------------------------
184
+
185
+ describe("formatResumeContext renders CC-8 and CC-1", () => {
186
+ test("renders essentialContext with all three sub-fields", () => {
187
+ const response = buildMinimalResponse({
188
+ essentialContext: {
189
+ pinnedMemories: ["Pin summary A", "Pin summary B"],
190
+ activePatterns: ["Always checkpoint before closing"],
191
+ openLoops: ["PR #42 needs review", "Deploy to staging"],
192
+ },
193
+ });
194
+ const output = formatResumeContext(response);
195
+
196
+ expect(output).toContain("Essential context:");
197
+ expect(output).toContain("- Pinned: Pin summary A");
198
+ expect(output).toContain("- Pinned: Pin summary B");
199
+ expect(output).toContain("- Pattern: Always checkpoint before closing");
200
+ expect(output).toContain("- Open loop: PR #42 needs review");
201
+ expect(output).toContain("- Open loop: Deploy to staging");
202
+ });
203
+
204
+ test("renders essentialContext with only pinnedMemories", () => {
205
+ const response = buildMinimalResponse({
206
+ essentialContext: {
207
+ pinnedMemories: ["Single pin"],
208
+ },
209
+ });
210
+ const output = formatResumeContext(response);
211
+
212
+ expect(output).toContain("Essential context:");
213
+ expect(output).toContain("- Pinned: Single pin");
214
+ expect(output).not.toContain("- Pattern:");
215
+ expect(output).not.toContain("- Open loop:");
216
+ });
217
+
218
+ test("does not render essential context section when essentialContext is undefined", () => {
219
+ const response = buildMinimalResponse({
220
+ essentialContext: undefined,
221
+ });
222
+ const output = formatResumeContext(response);
223
+
224
+ expect(output).not.toContain("Essential context:");
225
+ expect(output).not.toContain("- Pinned:");
226
+ });
227
+
228
+ test("does not render essential context section when essentialContext is empty object", () => {
229
+ const response = buildMinimalResponse({
230
+ essentialContext: {},
231
+ });
232
+ const output = formatResumeContext(response);
233
+
234
+ expect(output).not.toContain("Essential context:");
235
+ });
236
+
237
+ test("essential context appears after collapsed context and before latest checkpoint", () => {
238
+ const response = buildMinimalResponse({
239
+ collapsedItems: [
240
+ { entryId: "e1", text: "Collapsed item", renderLevel: "L0" },
241
+ ],
242
+ essentialContext: {
243
+ pinnedMemories: ["Pin note"],
244
+ },
245
+ latestCheckpoint: {
246
+ sessionId: "sess-123",
247
+ summary: "Previous session summary",
248
+ updatedAt: new Date().toISOString(),
249
+ },
250
+ });
251
+ const output = formatResumeContext(response);
252
+
253
+ const collapsedIdx = output.indexOf("Collapsed context (mixed granularity):");
254
+ const essentialIdx = output.indexOf("Essential context:");
255
+ const checkpointIdx = output.indexOf("Latest checkpoint:");
256
+
257
+ expect(collapsedIdx).toBeGreaterThan(-1);
258
+ expect(essentialIdx).toBeGreaterThan(collapsedIdx);
259
+ expect(checkpointIdx).toBeGreaterThan(essentialIdx);
260
+ });
261
+
262
+ test("renders injectionHint", () => {
263
+ const response = buildMinimalResponse({
264
+ injectionHint: "user_attachment",
265
+ });
266
+ const output = formatResumeContext(response);
267
+
268
+ expect(output).toContain("Injection hint: user_attachment");
269
+ expect(output).toContain("prompt cache hit rate");
270
+ });
271
+
272
+ test("renders system_prompt injectionHint", () => {
273
+ const response = buildMinimalResponse({
274
+ injectionHint: "system_prompt",
275
+ });
276
+ const output = formatResumeContext(response);
277
+
278
+ expect(output).toContain("Injection hint: system_prompt");
279
+ });
280
+
281
+ test("injection hint appears after latest checkpoint section", () => {
282
+ const response = buildMinimalResponse({
283
+ latestCheckpoint: {
284
+ sessionId: "sess-456",
285
+ summary: "Checkpoint summary",
286
+ updatedAt: new Date().toISOString(),
287
+ },
288
+ injectionHint: "user_attachment",
289
+ });
290
+ const output = formatResumeContext(response);
291
+
292
+ const checkpointIdx = output.indexOf("Latest checkpoint:");
293
+ const hintIdx = output.indexOf("Injection hint:");
294
+
295
+ expect(checkpointIdx).toBeGreaterThan(-1);
296
+ expect(hintIdx).toBeGreaterThan(checkpointIdx);
297
+ });
298
+ });
@@ -0,0 +1,99 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { CircuitBreaker } from "../llm-client.js";
4
+
5
+ describe("CircuitBreaker", () => {
6
+ it("starts in closed state", () => {
7
+ const cb = new CircuitBreaker();
8
+ expect(cb.getState()).toBe("closed");
9
+ expect(cb.canAttempt()).toBe(true);
10
+ });
11
+
12
+ it("remains closed after failures below threshold", () => {
13
+ const cb = new CircuitBreaker({ failureThreshold: 3 });
14
+ cb.recordFailure();
15
+ cb.recordFailure();
16
+ expect(cb.getState()).toBe("closed");
17
+ expect(cb.canAttempt()).toBe(true);
18
+ });
19
+
20
+ it("opens after reaching failure threshold", () => {
21
+ const cb = new CircuitBreaker({ failureThreshold: 3 });
22
+ cb.recordFailure();
23
+ cb.recordFailure();
24
+ cb.recordFailure();
25
+ expect(cb.getState()).toBe("open");
26
+ expect(cb.canAttempt()).toBe(false);
27
+ });
28
+
29
+ it("resets failure count on success", () => {
30
+ const cb = new CircuitBreaker({ failureThreshold: 3 });
31
+ cb.recordFailure();
32
+ cb.recordFailure();
33
+ cb.recordSuccess();
34
+ expect(cb.getState()).toBe("closed");
35
+ expect(cb.getFailureCount()).toBe(0);
36
+ // Need 3 more to open
37
+ cb.recordFailure();
38
+ cb.recordFailure();
39
+ expect(cb.getState()).toBe("closed");
40
+ });
41
+
42
+ it("transitions to half-open after cooldown", () => {
43
+ const cb = new CircuitBreaker({ failureThreshold: 1, cooldownMs: 10 });
44
+ cb.recordFailure();
45
+ expect(cb.getState()).toBe("open");
46
+ expect(cb.canAttempt()).toBe(false);
47
+
48
+ // Simulate cooldown elapsed by waiting
49
+ const start = Date.now();
50
+ while (Date.now() - start < 15) { /* busy wait */ }
51
+
52
+ expect(cb.canAttempt()).toBe(true);
53
+ expect(cb.getState()).toBe("half-open");
54
+ });
55
+
56
+ it("closes on successful probe in half-open state", () => {
57
+ const cb = new CircuitBreaker({ failureThreshold: 1, cooldownMs: 10 });
58
+ cb.recordFailure();
59
+ expect(cb.getState()).toBe("open");
60
+
61
+ const start = Date.now();
62
+ while (Date.now() - start < 15) { /* busy wait */ }
63
+
64
+ cb.canAttempt(); // triggers half-open
65
+ cb.recordSuccess();
66
+ expect(cb.getState()).toBe("closed");
67
+ expect(cb.getFailureCount()).toBe(0);
68
+ });
69
+
70
+ it("re-opens on failed probe in half-open state", () => {
71
+ const cb = new CircuitBreaker({ failureThreshold: 1, cooldownMs: 10 });
72
+ cb.recordFailure();
73
+
74
+ const start = Date.now();
75
+ while (Date.now() - start < 15) { /* busy wait */ }
76
+
77
+ cb.canAttempt(); // triggers half-open
78
+ cb.recordFailure(); // probe fails
79
+ expect(cb.getState()).toBe("open");
80
+ });
81
+
82
+ it("blocks attempts while open and within cooldown", () => {
83
+ const cb = new CircuitBreaker({ failureThreshold: 1, cooldownMs: 60_000 });
84
+ cb.recordFailure();
85
+ expect(cb.canAttempt()).toBe(false);
86
+ expect(cb.canAttempt()).toBe(false);
87
+ expect(cb.canAttempt()).toBe(false);
88
+ });
89
+
90
+ it("uses custom config values", () => {
91
+ const cb = new CircuitBreaker({ failureThreshold: 5, cooldownMs: 100 });
92
+ // 4 failures — still closed
93
+ for (let i = 0; i < 4; i++) cb.recordFailure();
94
+ expect(cb.getState()).toBe("closed");
95
+ // 5th opens it
96
+ cb.recordFailure();
97
+ expect(cb.getState()).toBe("open");
98
+ });
99
+ });