screenhand 0.1.1 → 0.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 (177) hide show
  1. package/README.md +458 -93
  2. package/dist/.audit-log.jsonl +55 -0
  3. package/dist/.screenhand/memory/.lock +1 -0
  4. package/dist/.screenhand/memory/actions.jsonl +85 -0
  5. package/dist/.screenhand/memory/errors.jsonl +5 -0
  6. package/dist/.screenhand/memory/errors.jsonl.bak +4 -0
  7. package/dist/.screenhand/memory/state.json +35 -0
  8. package/dist/.screenhand/memory/state.json.bak +35 -0
  9. package/dist/.screenhand/memory/strategies.jsonl +12 -0
  10. package/dist/agent/cli.js +73 -0
  11. package/dist/agent/loop.js +258 -0
  12. package/dist/config.js +9 -0
  13. package/dist/index.js +56 -0
  14. package/dist/logging/timeline-logger.js +29 -0
  15. package/dist/mcp/mcp-stdio-server.js +448 -0
  16. package/dist/mcp/server.js +347 -0
  17. package/dist/mcp-desktop.js +2731 -0
  18. package/dist/mcp-entry.js +59 -0
  19. package/dist/memory/recall.js +160 -0
  20. package/dist/memory/research.js +98 -0
  21. package/dist/memory/seeds.js +89 -0
  22. package/dist/memory/session.js +161 -0
  23. package/dist/memory/store.js +391 -0
  24. package/dist/memory/types.js +4 -0
  25. package/dist/monitor/codex-monitor.js +377 -0
  26. package/dist/monitor/task-queue.js +84 -0
  27. package/dist/monitor/types.js +49 -0
  28. package/dist/native/bridge-client.js +174 -0
  29. package/dist/native/macos-bridge-client.js +5 -0
  30. package/dist/npm-publish-helper.js +117 -0
  31. package/dist/npm-token-cdp.js +113 -0
  32. package/dist/npm-token-create.js +135 -0
  33. package/dist/npm-token-finish.js +126 -0
  34. package/dist/playbook/engine.js +193 -0
  35. package/dist/playbook/index.js +4 -0
  36. package/dist/playbook/recorder.js +519 -0
  37. package/dist/playbook/runner.js +392 -0
  38. package/dist/playbook/store.js +166 -0
  39. package/dist/playbook/types.js +4 -0
  40. package/dist/runtime/accessibility-adapter.js +377 -0
  41. package/dist/runtime/app-adapter.js +48 -0
  42. package/dist/runtime/applescript-adapter.js +283 -0
  43. package/dist/runtime/ax-role-map.js +80 -0
  44. package/dist/runtime/browser-adapter.js +36 -0
  45. package/dist/runtime/cdp-chrome-adapter.js +505 -0
  46. package/dist/runtime/composite-adapter.js +205 -0
  47. package/dist/runtime/executor.js +250 -0
  48. package/dist/runtime/locator-cache.js +12 -0
  49. package/dist/runtime/planning-loop.js +47 -0
  50. package/dist/runtime/service.js +372 -0
  51. package/dist/runtime/session-manager.js +28 -0
  52. package/dist/runtime/state-observer.js +105 -0
  53. package/dist/runtime/vision-adapter.js +208 -0
  54. package/dist/scripts/codex-monitor-daemon.js +335 -0
  55. package/dist/scripts/supervisor-daemon.js +272 -0
  56. package/dist/scripts/worker-daemon.js +228 -0
  57. package/dist/src/agent/cli.js +82 -0
  58. package/dist/src/agent/loop.js +274 -0
  59. package/{src/config.ts → dist/src/config.js} +5 -10
  60. package/{src/index.ts → dist/src/index.js} +32 -52
  61. package/dist/src/jobs/manager.js +237 -0
  62. package/dist/src/jobs/runner.js +683 -0
  63. package/dist/src/jobs/store.js +102 -0
  64. package/dist/src/jobs/types.js +30 -0
  65. package/dist/src/jobs/worker.js +97 -0
  66. package/dist/src/logging/timeline-logger.js +45 -0
  67. package/dist/src/mcp/mcp-stdio-server.js +464 -0
  68. package/dist/src/mcp/server.js +363 -0
  69. package/dist/src/mcp-entry.js +60 -0
  70. package/dist/src/memory/recall.js +170 -0
  71. package/dist/src/memory/research.js +104 -0
  72. package/dist/src/memory/seeds.js +101 -0
  73. package/dist/src/memory/service.js +421 -0
  74. package/dist/src/memory/session.js +169 -0
  75. package/dist/src/memory/store.js +422 -0
  76. package/dist/src/memory/types.js +17 -0
  77. package/dist/src/monitor/codex-monitor.js +382 -0
  78. package/dist/src/monitor/task-queue.js +97 -0
  79. package/dist/src/monitor/types.js +62 -0
  80. package/dist/src/native/bridge-client.js +190 -0
  81. package/{src/native/macos-bridge-client.ts → dist/src/native/macos-bridge-client.js} +0 -1
  82. package/dist/src/playbook/engine.js +201 -0
  83. package/dist/src/playbook/index.js +20 -0
  84. package/dist/src/playbook/recorder.js +535 -0
  85. package/dist/src/playbook/runner.js +408 -0
  86. package/dist/src/playbook/store.js +183 -0
  87. package/dist/src/playbook/types.js +17 -0
  88. package/dist/src/runtime/accessibility-adapter.js +393 -0
  89. package/dist/src/runtime/app-adapter.js +64 -0
  90. package/dist/src/runtime/applescript-adapter.js +299 -0
  91. package/dist/src/runtime/ax-role-map.js +96 -0
  92. package/dist/src/runtime/browser-adapter.js +52 -0
  93. package/dist/src/runtime/cdp-chrome-adapter.js +521 -0
  94. package/dist/src/runtime/composite-adapter.js +221 -0
  95. package/dist/src/runtime/execution-contract.js +159 -0
  96. package/dist/src/runtime/executor.js +266 -0
  97. package/{src/runtime/locator-cache.ts → dist/src/runtime/locator-cache.js} +10 -15
  98. package/dist/src/runtime/planning-loop.js +63 -0
  99. package/dist/src/runtime/service.js +388 -0
  100. package/dist/src/runtime/session-manager.js +60 -0
  101. package/dist/src/runtime/state-observer.js +121 -0
  102. package/dist/src/runtime/vision-adapter.js +224 -0
  103. package/dist/src/supervisor/locks.js +186 -0
  104. package/dist/src/supervisor/supervisor.js +403 -0
  105. package/dist/src/supervisor/types.js +30 -0
  106. package/dist/src/test-mcp-protocol.js +154 -0
  107. package/dist/src/types.js +17 -0
  108. package/dist/src/util/atomic-write.js +118 -0
  109. package/dist/test-mcp-protocol.js +138 -0
  110. package/dist/types.js +1 -0
  111. package/package.json +18 -4
  112. package/.claude/commands/automate.md +0 -28
  113. package/.claude/commands/debug-ui.md +0 -19
  114. package/.claude/commands/screenshot.md +0 -15
  115. package/.github/FUNDING.yml +0 -1
  116. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -27
  117. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  118. package/.mcp.json +0 -8
  119. package/DESKTOP_MCP_GUIDE.md +0 -92
  120. package/SECURITY.md +0 -44
  121. package/docs/architecture.md +0 -47
  122. package/install-skills.sh +0 -19
  123. package/mcp-bridge.ts +0 -271
  124. package/mcp-desktop.ts +0 -1221
  125. package/native/macos-bridge/Package.swift +0 -21
  126. package/native/macos-bridge/Sources/AccessibilityBridge.swift +0 -261
  127. package/native/macos-bridge/Sources/AppManagement.swift +0 -129
  128. package/native/macos-bridge/Sources/CoreGraphicsBridge.swift +0 -242
  129. package/native/macos-bridge/Sources/ObserverBridge.swift +0 -120
  130. package/native/macos-bridge/Sources/VisionBridge.swift +0 -80
  131. package/native/macos-bridge/Sources/main.swift +0 -345
  132. package/native/windows-bridge/AppManagement.cs +0 -234
  133. package/native/windows-bridge/InputBridge.cs +0 -436
  134. package/native/windows-bridge/Program.cs +0 -265
  135. package/native/windows-bridge/ScreenCapture.cs +0 -329
  136. package/native/windows-bridge/UIAutomationBridge.cs +0 -571
  137. package/native/windows-bridge/WindowsBridge.csproj +0 -17
  138. package/playbooks/devpost.json +0 -186
  139. package/playbooks/instagram.json +0 -41
  140. package/playbooks/instagram_v2.json +0 -201
  141. package/playbooks/x_v1.json +0 -211
  142. package/scripts/devpost-live-loop.mjs +0 -421
  143. package/src/logging/timeline-logger.ts +0 -55
  144. package/src/mcp/server.ts +0 -449
  145. package/src/memory/recall.ts +0 -191
  146. package/src/memory/research.ts +0 -146
  147. package/src/memory/seeds.ts +0 -123
  148. package/src/memory/session.ts +0 -201
  149. package/src/memory/store.ts +0 -434
  150. package/src/memory/types.ts +0 -69
  151. package/src/native/bridge-client.ts +0 -239
  152. package/src/runtime/accessibility-adapter.ts +0 -487
  153. package/src/runtime/app-adapter.ts +0 -169
  154. package/src/runtime/applescript-adapter.ts +0 -376
  155. package/src/runtime/ax-role-map.ts +0 -102
  156. package/src/runtime/browser-adapter.ts +0 -129
  157. package/src/runtime/cdp-chrome-adapter.ts +0 -676
  158. package/src/runtime/composite-adapter.ts +0 -274
  159. package/src/runtime/executor.ts +0 -396
  160. package/src/runtime/planning-loop.ts +0 -81
  161. package/src/runtime/service.ts +0 -448
  162. package/src/runtime/session-manager.ts +0 -50
  163. package/src/runtime/state-observer.ts +0 -136
  164. package/src/runtime/vision-adapter.ts +0 -297
  165. package/src/types.ts +0 -297
  166. package/tests/bridge-client.test.ts +0 -176
  167. package/tests/browser-stealth.test.ts +0 -210
  168. package/tests/composite-adapter.test.ts +0 -64
  169. package/tests/mcp-server.test.ts +0 -151
  170. package/tests/memory-recall.test.ts +0 -339
  171. package/tests/memory-research.test.ts +0 -159
  172. package/tests/memory-seeds.test.ts +0 -120
  173. package/tests/memory-store.test.ts +0 -392
  174. package/tests/types.test.ts +0 -92
  175. package/tsconfig.check.json +0 -17
  176. package/tsconfig.json +0 -19
  177. package/vitest.config.ts +0 -8
@@ -0,0 +1,391 @@
1
+ /**
2
+ * Learning Memory — JSONL persistence layer (production-ready)
3
+ *
4
+ * - All data cached in-memory for zero-latency reads
5
+ * - Disk writes are non-blocking, buffered, flushed on exit
6
+ * - Per-line JSONL parsing — corrupted lines are skipped, not fatal
7
+ * - Cache size limits with LRU eviction
8
+ * - File locking for multi-instance safety
9
+ */
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { SEED_STRATEGIES } from "./seeds.js";
13
+ const MAX_ACTION_FILE_BYTES = 10 * 1024 * 1024; // 10 MB
14
+ const MAX_STRATEGIES = 500;
15
+ const MAX_ERRORS = 200;
16
+ export class MemoryStore {
17
+ dir;
18
+ // ── in-memory caches ──
19
+ strategiesCache = [];
20
+ errorsCache = [];
21
+ /** Fingerprint → Strategy index for O(1) exact lookup */
22
+ fingerprintIndex = new Map();
23
+ actionCount = 0;
24
+ actionSuccessCount = 0;
25
+ toolCounts = new Map();
26
+ initialized = false;
27
+ dirCreated = false;
28
+ /** True if ensureDir() had to create the memory directory (first boot) */
29
+ justCreatedDir = false;
30
+ // ── write buffer for flush-on-exit ──
31
+ pendingActionWrites = [];
32
+ flushTimer = null;
33
+ lockPath;
34
+ hasLock = false;
35
+ // Global flag — only register exit handlers once across all instances
36
+ static exitHandlerRegistered = false;
37
+ static activeInstance = null;
38
+ constructor(baseDir) {
39
+ this.dir = path.join(baseDir, ".screenhand", "memory");
40
+ this.lockPath = path.join(this.dir, ".lock");
41
+ }
42
+ /** Load caches from disk. Call once at startup. */
43
+ init() {
44
+ if (this.initialized)
45
+ return;
46
+ this.initialized = true;
47
+ this.ensureDir();
48
+ this.acquireLock();
49
+ this.registerExitHandler();
50
+ // Detect first boot: memory directory was just created (didn't exist before ensureDir)
51
+ const isFirstBoot = this.justCreatedDir;
52
+ this.strategiesCache = this.readLinesSafe("strategies.jsonl");
53
+ if (this.strategiesCache.length === 0 && isFirstBoot) {
54
+ for (const s of SEED_STRATEGIES)
55
+ this.strategiesCache.push(s);
56
+ this.writeLinesAsync("strategies.jsonl", this.strategiesCache);
57
+ }
58
+ this.enforceStrategyLimit();
59
+ this.rebuildFingerprintIndex();
60
+ this.errorsCache = this.readLinesSafe("errors.jsonl");
61
+ this.enforceErrorLimit();
62
+ // Build action stats without caching all entries
63
+ const actions = this.readLinesSafe("actions.jsonl");
64
+ this.actionCount = actions.length;
65
+ for (const a of actions) {
66
+ if (a.success)
67
+ this.actionSuccessCount++;
68
+ this.toolCounts.set(a.tool, (this.toolCounts.get(a.tool) ?? 0) + 1);
69
+ }
70
+ }
71
+ // ── file locking ──────────────────────────────
72
+ acquireLock() {
73
+ try {
74
+ // Check for stale lock (PID no longer running)
75
+ if (fs.existsSync(this.lockPath)) {
76
+ const lockContent = fs.readFileSync(this.lockPath, "utf-8").trim();
77
+ const lockPid = parseInt(lockContent, 10);
78
+ if (lockPid && !this.isProcessRunning(lockPid)) {
79
+ // Stale lock — remove it
80
+ fs.unlinkSync(this.lockPath);
81
+ }
82
+ }
83
+ // Write our PID
84
+ fs.writeFileSync(this.lockPath, String(process.pid), { flag: "wx" });
85
+ this.hasLock = true;
86
+ }
87
+ catch {
88
+ // Another instance holds the lock — we still work but skip writes
89
+ // to avoid corruption. Reads are from our own cache (stale but safe).
90
+ this.hasLock = false;
91
+ }
92
+ }
93
+ releaseLock() {
94
+ if (this.hasLock) {
95
+ try {
96
+ fs.unlinkSync(this.lockPath);
97
+ }
98
+ catch { /* ignore */ }
99
+ this.hasLock = false;
100
+ }
101
+ }
102
+ isProcessRunning(pid) {
103
+ try {
104
+ process.kill(pid, 0);
105
+ return true;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ // ── exit handling ─────────────────────────────
112
+ registerExitHandler() {
113
+ MemoryStore.activeInstance = this;
114
+ if (MemoryStore.exitHandlerRegistered)
115
+ return;
116
+ MemoryStore.exitHandlerRegistered = true;
117
+ const flush = () => MemoryStore.activeInstance?.flushSync();
118
+ process.on("beforeExit", flush);
119
+ process.on("exit", flush);
120
+ // SIGINT/SIGTERM — flush then re-raise
121
+ for (const sig of ["SIGINT", "SIGTERM"]) {
122
+ process.on(sig, () => {
123
+ flush();
124
+ process.exit(128 + (sig === "SIGINT" ? 2 : 15));
125
+ });
126
+ }
127
+ }
128
+ /** Synchronously flush all pending action writes to disk */
129
+ flushSync() {
130
+ if (this.pendingActionWrites.length === 0)
131
+ return;
132
+ if (!this.hasLock)
133
+ return;
134
+ try {
135
+ this.ensureDir();
136
+ const data = this.pendingActionWrites.join("");
137
+ fs.appendFileSync(this.filePath("actions.jsonl"), data);
138
+ this.pendingActionWrites = [];
139
+ }
140
+ catch {
141
+ // Non-critical on exit
142
+ }
143
+ this.releaseLock();
144
+ }
145
+ // ── helpers ────────────────────────────────────
146
+ ensureDir() {
147
+ if (!this.dirCreated) {
148
+ if (!fs.existsSync(this.dir)) {
149
+ fs.mkdirSync(this.dir, { recursive: true });
150
+ this.justCreatedDir = true;
151
+ }
152
+ this.dirCreated = true;
153
+ }
154
+ }
155
+ filePath(name) {
156
+ return path.join(this.dir, name);
157
+ }
158
+ /**
159
+ * Parse JSONL safely — skip corrupted lines instead of crashing.
160
+ * Returns all successfully parsed entries.
161
+ */
162
+ readLinesSafe(file) {
163
+ const fp = this.filePath(file);
164
+ if (!fs.existsSync(fp))
165
+ return [];
166
+ let text;
167
+ try {
168
+ text = fs.readFileSync(fp, "utf-8").trim();
169
+ }
170
+ catch {
171
+ return [];
172
+ }
173
+ if (!text)
174
+ return [];
175
+ const results = [];
176
+ for (const line of text.split("\n")) {
177
+ const trimmed = line.trim();
178
+ if (!trimmed)
179
+ continue;
180
+ try {
181
+ results.push(JSON.parse(trimmed));
182
+ }
183
+ catch {
184
+ // Skip corrupted line — don't crash
185
+ }
186
+ }
187
+ return results;
188
+ }
189
+ /** Non-blocking full rewrite — fire and forget (only if we hold lock) */
190
+ writeLinesAsync(file, items) {
191
+ if (!this.hasLock)
192
+ return;
193
+ this.ensureDir();
194
+ const data = items.map((i) => JSON.stringify(i)).join("\n") + (items.length ? "\n" : "");
195
+ fs.writeFile(this.filePath(file), data, () => { });
196
+ }
197
+ fileSize(file) {
198
+ const fp = this.filePath(file);
199
+ if (!fs.existsSync(fp))
200
+ return 0;
201
+ try {
202
+ return fs.statSync(fp).size;
203
+ }
204
+ catch {
205
+ return 0;
206
+ }
207
+ }
208
+ // ── actions (buffered async write) ─────────────
209
+ appendAction(entry) {
210
+ // Update in-memory stats
211
+ this.actionCount++;
212
+ if (entry.success)
213
+ this.actionSuccessCount++;
214
+ this.toolCounts.set(entry.tool, (this.toolCounts.get(entry.tool) ?? 0) + 1);
215
+ if (!this.hasLock)
216
+ return;
217
+ this.rotateActionsIfNeeded();
218
+ // Buffer the write
219
+ this.pendingActionWrites.push(JSON.stringify(entry) + "\n");
220
+ // Schedule batch flush (debounced 100ms)
221
+ if (!this.flushTimer) {
222
+ this.flushTimer = setTimeout(() => {
223
+ this.flushTimer = null;
224
+ if (this.pendingActionWrites.length === 0)
225
+ return;
226
+ this.ensureDir();
227
+ const data = this.pendingActionWrites.join("");
228
+ this.pendingActionWrites = [];
229
+ fs.appendFile(this.filePath("actions.jsonl"), data, () => { });
230
+ }, 100);
231
+ }
232
+ }
233
+ rotateActionsIfNeeded() {
234
+ if (this.fileSize("actions.jsonl") >= MAX_ACTION_FILE_BYTES) {
235
+ const src = this.filePath("actions.jsonl");
236
+ const dst = this.filePath("actions.1.jsonl");
237
+ try {
238
+ if (fs.existsSync(dst))
239
+ fs.unlinkSync(dst);
240
+ fs.renameSync(src, dst);
241
+ }
242
+ catch {
243
+ // Non-critical
244
+ }
245
+ }
246
+ }
247
+ /** Read actions from disk (only used by stats/clear, not in hot path) */
248
+ readActions() {
249
+ return this.readLinesSafe("actions.jsonl");
250
+ }
251
+ // ── strategies (cached + fingerprint indexed + LRU capped) ──
252
+ rebuildFingerprintIndex() {
253
+ this.fingerprintIndex.clear();
254
+ for (const s of this.strategiesCache) {
255
+ if (s.fingerprint) {
256
+ this.fingerprintIndex.set(s.fingerprint, s);
257
+ }
258
+ }
259
+ }
260
+ /** Evict least-recently-used strategies beyond MAX_STRATEGIES */
261
+ enforceStrategyLimit() {
262
+ if (this.strategiesCache.length <= MAX_STRATEGIES)
263
+ return;
264
+ // Sort by lastUsed ascending (oldest first), remove from the front
265
+ this.strategiesCache.sort((a, b) => new Date(a.lastUsed).getTime() - new Date(b.lastUsed).getTime());
266
+ this.strategiesCache = this.strategiesCache.slice(-MAX_STRATEGIES);
267
+ }
268
+ appendStrategy(strategy) {
269
+ // Ensure fingerprint exists
270
+ if (!strategy.fingerprint) {
271
+ strategy.fingerprint = MemoryStore.makeFingerprint(strategy.steps.map((s) => s.tool));
272
+ }
273
+ const idx = this.strategiesCache.findIndex((s) => s.task === strategy.task);
274
+ if (idx >= 0) {
275
+ const old = this.strategiesCache[idx];
276
+ this.strategiesCache[idx] = {
277
+ ...strategy,
278
+ successCount: old.successCount + 1,
279
+ failCount: old.failCount ?? 0,
280
+ lastUsed: strategy.lastUsed,
281
+ };
282
+ this.fingerprintIndex.set(strategy.fingerprint, this.strategiesCache[idx]);
283
+ }
284
+ else {
285
+ this.strategiesCache.push(strategy);
286
+ this.fingerprintIndex.set(strategy.fingerprint, strategy);
287
+ this.enforceStrategyLimit();
288
+ // Rebuild index after eviction
289
+ if (this.strategiesCache.length >= MAX_STRATEGIES) {
290
+ this.rebuildFingerprintIndex();
291
+ }
292
+ }
293
+ this.writeLinesAsync("strategies.jsonl", this.strategiesCache);
294
+ }
295
+ /** O(1) exact lookup by tool sequence fingerprint */
296
+ lookupByFingerprint(fingerprint) {
297
+ return this.fingerprintIndex.get(fingerprint);
298
+ }
299
+ /** Record that a recalled strategy succeeded or failed */
300
+ recordStrategyOutcome(fingerprint, success) {
301
+ const strategy = this.fingerprintIndex.get(fingerprint);
302
+ if (!strategy)
303
+ return;
304
+ if (success) {
305
+ strategy.successCount++;
306
+ strategy.lastUsed = new Date().toISOString();
307
+ }
308
+ else {
309
+ strategy.failCount = (strategy.failCount ?? 0) + 1;
310
+ }
311
+ this.writeLinesAsync("strategies.jsonl", this.strategiesCache);
312
+ }
313
+ /** Read from cache — ~0ms */
314
+ readStrategies() {
315
+ return this.strategiesCache;
316
+ }
317
+ /** Generate a fingerprint from a tool sequence */
318
+ static makeFingerprint(tools) {
319
+ return tools.join("→");
320
+ }
321
+ // ── errors (cached + LRU capped) ──────────────
322
+ /** Evict least-recently-seen errors beyond MAX_ERRORS */
323
+ enforceErrorLimit() {
324
+ if (this.errorsCache.length <= MAX_ERRORS)
325
+ return;
326
+ this.errorsCache.sort((a, b) => new Date(a.lastSeen).getTime() - new Date(b.lastSeen).getTime());
327
+ this.errorsCache = this.errorsCache.slice(-MAX_ERRORS);
328
+ }
329
+ appendError(pattern) {
330
+ const idx = this.errorsCache.findIndex((e) => e.tool === pattern.tool && e.error === pattern.error);
331
+ if (idx >= 0) {
332
+ this.errorsCache[idx] = {
333
+ ...this.errorsCache[idx],
334
+ occurrences: this.errorsCache[idx].occurrences + 1,
335
+ lastSeen: pattern.lastSeen,
336
+ resolution: pattern.resolution ?? this.errorsCache[idx].resolution,
337
+ };
338
+ }
339
+ else {
340
+ this.errorsCache.push(pattern);
341
+ this.enforceErrorLimit();
342
+ }
343
+ this.writeLinesAsync("errors.jsonl", this.errorsCache);
344
+ }
345
+ /** Read from cache — ~0ms */
346
+ readErrors() {
347
+ return this.errorsCache;
348
+ }
349
+ // ── stats (from in-memory counters) ────────────
350
+ getStats() {
351
+ const topTools = [...this.toolCounts.entries()]
352
+ .sort((a, b) => b[1] - a[1])
353
+ .slice(0, 10)
354
+ .map(([tool, count]) => ({ tool, count }));
355
+ const diskUsageBytes = this.fileSize("actions.jsonl") +
356
+ this.fileSize("strategies.jsonl") +
357
+ this.fileSize("errors.jsonl");
358
+ return {
359
+ totalActions: this.actionCount,
360
+ totalStrategies: this.strategiesCache.length,
361
+ totalErrors: this.errorsCache.length,
362
+ diskUsageBytes,
363
+ topTools,
364
+ successRate: this.actionCount > 0 ? this.actionSuccessCount / this.actionCount : 0,
365
+ };
366
+ }
367
+ // ── clear ──────────────────────────────────────
368
+ clear(what) {
369
+ const targets = what === "all"
370
+ ? ["actions", "strategies", "errors"]
371
+ : [what];
372
+ for (const category of targets) {
373
+ const fp = this.filePath(`${category}.jsonl`);
374
+ if (fs.existsSync(fp))
375
+ fs.writeFileSync(fp, "");
376
+ if (category === "actions") {
377
+ this.actionCount = 0;
378
+ this.actionSuccessCount = 0;
379
+ this.toolCounts.clear();
380
+ this.pendingActionWrites = [];
381
+ }
382
+ else if (category === "strategies") {
383
+ this.strategiesCache = [];
384
+ this.fingerprintIndex.clear();
385
+ }
386
+ else if (category === "errors") {
387
+ this.errorsCache = [];
388
+ }
389
+ }
390
+ }
391
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Learning Memory — Data types
3
+ */
4
+ export {};