@myclaw163/clawclaw-cli 0.9.2 → 0.10.1

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 (197) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +23 -35
  7. package/docs/custom-modules/api-reference.md +95 -273
  8. package/docs/custom-modules/behavior.md +94 -78
  9. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +42 -603
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +16 -17
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +47 -46
  19. package/docs/runtime/components-and-boundaries.md +70 -28
  20. package/docs/runtime/events-and-state.md +41 -18
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +10 -7
  26. package/docs/user-guide/api-reference.md +81 -164
  27. package/docs/user-guide/behavior.md +84 -68
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +42 -586
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +8 -13
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +49 -49
  37. package/skills/clawclaw/references/BEHAVIORS.md +42 -73
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +60 -101
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +26 -10
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +3 -2
  53. package/src/commands/perception.ts +5 -0
  54. package/src/commands/strategy.ts +2 -0
  55. package/src/lib/capability-load-diagnostics.ts +3 -3
  56. package/src/lib/perception-config.ts +18 -6
  57. package/src/lib/runtime-cadence-config.ts +16 -0
  58. package/src/lib/workspace-runtime-lock.ts +3 -46
  59. package/src/pipeline/canonical-event-presentation.ts +23 -124
  60. package/src/pipeline/event-format.ts +12 -21
  61. package/src/pipeline/event-hints.ts +6 -6
  62. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  63. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  64. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  65. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  66. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  67. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  68. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  69. package/src/runtime/clawclaw/owner.ts +18 -4
  70. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  71. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  72. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  73. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  74. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  75. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  76. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  77. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  78. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  79. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  82. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  83. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  84. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  85. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  86. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
  87. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  88. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  89. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  90. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  91. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  92. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  93. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  94. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  95. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  96. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  97. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  98. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  99. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  100. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  101. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
  102. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  103. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  104. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
  105. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  106. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  107. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  108. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  109. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  110. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  111. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  112. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  113. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  114. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  115. package/src/runtime/clawclaw/runtime.ts +8 -0
  116. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  117. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  118. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  119. package/src/runtime/framework/action-diagnostics.ts +3 -83
  120. package/src/runtime/framework/capability-registry.ts +2 -395
  121. package/src/runtime/framework/contracts.ts +2 -144
  122. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  123. package/src/runtime/framework/control/domain-set.ts +2 -81
  124. package/src/runtime/framework/control/index.ts +1 -3
  125. package/src/runtime/framework/control/types.ts +2 -191
  126. package/src/runtime/framework/control-coordinator.ts +2 -11
  127. package/src/runtime/framework/events/event-catalog.ts +2 -74
  128. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  129. package/src/runtime/framework/events/event-ingress.ts +2 -99
  130. package/src/runtime/framework/events/event-repository.ts +2 -82
  131. package/src/runtime/framework/events/index.ts +2 -7
  132. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  133. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  134. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  135. package/src/runtime/framework/events/test-helpers.ts +1 -1
  136. package/src/runtime/framework/events/types.ts +2 -312
  137. package/src/runtime/framework/index.ts +3 -7
  138. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  139. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  140. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  141. package/src/runtime/framework/mailbox/identity.ts +2 -38
  142. package/src/runtime/framework/mailbox/index.ts +1 -7
  143. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  144. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  145. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  146. package/src/runtime/framework/mailbox/types.ts +2 -145
  147. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  148. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  149. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  150. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  151. package/src/runtime/framework/participation-manager.ts +2 -253
  152. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  153. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  154. package/src/runtime/framework/plugins/contracts.ts +2 -396
  155. package/src/runtime/framework/plugins/index.ts +1 -4
  156. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  157. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  158. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  159. package/src/runtime/framework/runtime.ts +5 -1843
  160. package/src/runtime/framework/serial-task-queue.ts +2 -14
  161. package/src/runtime/framework/state/contracts.ts +2 -49
  162. package/src/runtime/framework/state/current-state-store.ts +2 -184
  163. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  164. package/src/runtime/framework/state/freshness.ts +2 -72
  165. package/src/runtime/framework/state/history/contracts.ts +2 -158
  166. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  167. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  168. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  169. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  170. package/src/runtime/framework/state/index.ts +1 -13
  171. package/src/runtime/framework/state/state-ingress.ts +2 -95
  172. package/src/runtime/framework/state/state-provider.ts +2 -62
  173. package/src/runtime/framework/state/types.ts +2 -155
  174. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  175. package/src/runtime/mailbox-host-relay.ts +1 -326
  176. package/src/runtime/observability/detail-capture.ts +4 -108
  177. package/src/runtime/observability/process-timing.ts +2 -59
  178. package/src/runtime/observability/recorder.ts +2 -238
  179. package/src/runtime/observability/redaction.ts +2 -181
  180. package/src/runtime/observability/reporter.ts +2 -154
  181. package/src/runtime/observability/sinks.ts +2 -135
  182. package/src/runtime/observability/types.ts +2 -92
  183. package/src/runtime/owner-control.ts +45 -320
  184. package/src/runtime/parent-process-watch.ts +1 -51
  185. package/src/runtime/process-identity.ts +1 -72
  186. package/src/sdk/behavior-plugin/index.ts +9 -3
  187. package/src/sdk/index.ts +40 -2
  188. package/src/sdk/module-input/index.ts +5 -0
  189. package/src/sdk/perception-plugin/index.ts +3 -1
  190. package/src/sdk/perception-plugin/module.ts +12 -2
  191. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  192. package/src/sdk/perception-plugin/reminder.ts +2 -1
  193. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  194. package/src/sdk/strategy-memory.ts +1 -12
  195. package/src/sdk/strategy-plugin/index.ts +36 -0
  196. package/src/sdk/trigger-plugin/index.ts +1 -0
  197. package/docs/custom-modules/trigger.md +0 -295
@@ -1,489 +1,4 @@
1
- import { randomUUID } from 'crypto';
2
- import { statSync } from 'fs';
3
- import { getHeapStatistics } from 'v8';
4
- import { canReuseParticipationSegment } from '../participation-manager.js';
5
- import { createRequire } from 'module';
6
- import { pathToFileURL } from 'url';
7
- import { Worker } from 'worker_threads';
8
- import type { MailboxRepository } from '../mailbox/mailbox-repository.js';
9
- import type {
10
- AckMailboxClaimRequest,
11
- ClaimMailboxItemsRequest,
12
- EnqueueMailboxItem,
13
- MailboxPeekFilter,
14
- NackMailboxClaimRequest,
15
- SuppressMailboxItemsFilter,
16
- } from '../mailbox/types.js';
17
- import { MemoryEventRepository } from '../events/memory-event-repository.js';
18
- import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
19
- import { canResumeRuntimeScope, type RuntimeResumeSelection } from '../events/runtime-resume.js';
20
- import type { EventRepository } from '../events/event-repository.js';
21
- import type {
22
- AcquireLeaseRequest,
23
- CommittedEventListFilter,
24
- CommitEventRequest,
25
- ConsumerLease,
26
- DetailStateTransition,
27
- EventAccountScope,
28
- EventListFilter,
29
- EventSegmentRecord,
30
- LatestEventScopeOptions,
31
- MonitorDeliveryAttempt,
32
- MonitorStateTransition,
33
- PlaySessionRecord,
34
- } from '../events/types.js';
35
- import type {
36
- RuntimeEpochPluginProgress,
37
- RuntimeEpochPluginRecord,
38
- RuntimeEpochStateRecord,
39
- RuntimeInputBatch,
40
- RuntimePersistenceStore,
41
- } from '../plugins/contracts.js';
42
- import { MemoryRuntimeInputJournal, SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
43
- import type { RuntimeScope } from '../state/types.js';
44
- import type {
45
- HistoryQuery,
46
- StateFrameQuery,
47
- StateFrameRecord,
48
- StateHistoryRepository,
49
- TrajectoryRecord,
50
- } from '../state/history/contracts.js';
51
- import { MemoryStateHistoryRepository } from '../state/history/memory-state-history-repository.js';
52
- import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
53
-
54
- type StoreName = 'events' | 'history' | 'input';
55
- interface PersistenceOperation { store: StoreName; method: string; args: unknown[] }
56
- const localRequire = createRequire(import.meta.url);
57
-
58
- export interface MemoryFirstPersistenceOptions {
59
- eventLedgerPath: string;
60
- stateHistoryPath: string;
61
- inputJournalPath: string;
62
- maxPendingOperations?: number;
63
- batchSize?: number;
64
- flushIntervalMs?: number;
65
- recovery?: RuntimeResumeSelection & { account: EventAccountScope };
66
- onDiagnostic?: (name: string, attributes: Readonly<Record<string, unknown>>) => void;
67
- onDegraded?: (error: Error, health: AsyncPersistenceHealth) => void;
68
- }
69
-
70
- interface ResolvedMemoryFirstPersistenceOptions {
71
- eventLedgerPath: string;
72
- stateHistoryPath: string;
73
- inputJournalPath: string;
74
- maxPendingOperations: number;
75
- batchSize: number;
76
- flushIntervalMs: number;
77
- onDegraded?: MemoryFirstPersistenceOptions['onDegraded'];
78
- onDiagnostic?: MemoryFirstPersistenceOptions['onDiagnostic'];
79
- }
80
-
81
- export interface AsyncPersistenceHealth {
82
- mode: 'memory-first-sqlite-mirror';
83
- pendingOperations: number;
84
- droppedOperations: number;
85
- degraded: boolean;
86
- error?: string;
87
- workerMemory?: Readonly<Record<string, number>>;
88
- }
89
-
90
- function memorySample(): Readonly<Record<string, number>> {
91
- const memory = process.memoryUsage();
92
- return {
93
- sampled_at_ms: Date.now(), rss_bytes: memory.rss,
94
- heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
95
- external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
96
- heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
97
- };
98
- }
99
-
100
- function databaseBytes(path: string): number {
101
- try { return statSync(path).size; } catch { return 0; }
102
- }
103
-
104
- class AsyncSqliteMirror {
105
- private readonly worker: Worker;
106
- private readonly local: PersistenceOperation[] = [];
107
- private readonly waiters = new Map<number, { resolve(): void; reject(error: Error): void }>();
108
- private timer?: NodeJS.Timeout;
109
- private nextMessageId = 1;
110
- private sentOperations = 0;
111
- private acknowledgedOperations = 0;
112
- private readonly batchSizes = new Map<number, number>();
113
- private droppedOperations = 0;
114
- private degradedError?: Error;
115
- private closing?: Promise<void>;
116
- private references = 3;
117
- private workerMemory?: Readonly<Record<string, number>>;
118
-
119
- constructor(private readonly options: ResolvedMemoryFirstPersistenceOptions) {
120
- const workerUrl = new URL('./async-sqlite-persistence-worker.ts', import.meta.url).href;
121
- // Resolve from this package, not from the process cwd. Installed CCL is
122
- // commonly launched from an Agent workspace that does not contain tsx.
123
- const tsxApiUrl = pathToFileURL(localRequire.resolve('tsx/esm/api')).href;
124
- const bootstrap = `void (async () => {
125
- const { register } = await import(${JSON.stringify(tsxApiUrl)});
126
- register();
127
- await import(${JSON.stringify(workerUrl)});
128
- })();`;
129
- this.worker = new Worker(bootstrap, {
130
- eval: true,
131
- workerData: {
132
- eventLedgerPath: options.eventLedgerPath,
133
- stateHistoryPath: options.stateHistoryPath,
134
- inputJournalPath: options.inputJournalPath,
135
- diagnostics: !!options.onDiagnostic,
136
- },
137
- });
138
- this.worker.on('message', (message: { type: string; id: number; error?: string; memory?: Readonly<Record<string, number>> }) => {
139
- if (message.type === 'diagnostics') {
140
- this.workerMemory = message.memory;
141
- try { this.options.onDiagnostic?.('runtime.persistence.worker_memory', { worker_memory: message.memory }); } catch { /* observational */ }
142
- return;
143
- }
144
- if (message.type === 'ack') {
145
- this.acknowledgedOperations += this.batchSizes.get(message.id) ?? 0;
146
- this.batchSizes.delete(message.id);
147
- }
148
- const waiter = this.waiters.get(message.id);
149
- if (message.type === 'error') {
150
- const error = new Error(message.error ?? 'Async SQLite persistence failed.');
151
- this.degrade(error);
152
- waiter?.reject(error);
153
- } else {
154
- waiter?.resolve();
155
- }
156
- this.waiters.delete(message.id);
157
- });
158
- this.worker.on('error', (error) => this.degrade(error));
159
- this.worker.on('exit', (code) => {
160
- if (code !== 0 && !this.closing) this.degrade(new Error(`Async SQLite worker exited with code ${code}.`));
161
- });
162
- }
163
-
164
- enqueue(operation: PersistenceOperation): void {
165
- if (this.degradedError || this.closing) {
166
- this.droppedOperations += 1;
167
- return;
168
- }
169
- if (this.pendingCount() >= this.options.maxPendingOperations) {
170
- this.degrade(new Error(`Async SQLite queue exceeded ${this.options.maxPendingOperations} operations.`));
171
- this.droppedOperations += 1;
172
- this.local.length = 0;
173
- return;
174
- }
175
- this.local.push(structuredClone(operation));
176
- if (this.local.length >= this.options.batchSize) this.dispatch();
177
- else this.timer ??= setTimeout(() => this.dispatch(), this.options.flushIntervalMs);
178
- }
179
-
180
- health(): AsyncPersistenceHealth {
181
- return {
182
- mode: 'memory-first-sqlite-mirror',
183
- pendingOperations: this.pendingCount(),
184
- droppedOperations: this.droppedOperations,
185
- degraded: !!this.degradedError,
186
- ...(this.degradedError ? { error: this.degradedError.message } : {}),
187
- ...(this.workerMemory ? { workerMemory: this.workerMemory } : {}),
188
- };
189
- }
190
-
191
- async release(): Promise<void> {
192
- this.references -= 1;
193
- if (this.references > 0) return;
194
- await this.close();
195
- }
196
-
197
- private pendingCount(): number {
198
- return this.local.length + Math.max(0, this.sentOperations - this.acknowledgedOperations);
199
- }
200
-
201
- private dispatch(): void {
202
- if (this.timer) clearTimeout(this.timer);
203
- this.timer = undefined;
204
- if (this.local.length === 0 || this.degradedError) return;
205
- const operations = this.local.splice(0, this.options.batchSize);
206
- const id = this.nextMessageId++;
207
- this.sentOperations += operations.length;
208
- this.batchSizes.set(id, operations.length);
209
- this.worker.postMessage({ type: 'batch', id, operations });
210
- if (this.local.length > 0) this.timer = setTimeout(() => this.dispatch(), 0);
211
- }
212
-
213
- private async flush(): Promise<void> {
214
- if (this.degradedError) return;
215
- while (this.local.length > 0) this.dispatch();
216
- const id = this.nextMessageId++;
217
- await new Promise<void>((resolve, reject) => {
218
- this.waiters.set(id, { resolve, reject });
219
- this.worker.postMessage({ type: 'barrier', id });
220
- });
221
- }
222
-
223
- private close(): Promise<void> {
224
- if (this.closing) return this.closing;
225
- this.closing = (async () => {
226
- if (this.timer) clearTimeout(this.timer);
227
- this.timer = undefined;
228
- try {
229
- await this.flush();
230
- if (!this.degradedError) {
231
- const id = this.nextMessageId++;
232
- await new Promise<void>((resolve, reject) => {
233
- this.waiters.set(id, { resolve, reject });
234
- this.worker.postMessage({ type: 'close', id });
235
- });
236
- }
237
- } finally {
238
- await this.worker.terminate();
239
- }
240
- })();
241
- return this.closing;
242
- }
243
-
244
- private degrade(error: Error): void {
245
- if (this.degradedError) return;
246
- this.degradedError = error;
247
- for (const waiter of this.waiters.values()) waiter.reject(error);
248
- this.waiters.clear();
249
- this.options.onDegraded?.(error, this.health());
250
- }
251
- }
252
-
253
- abstract class MirroredStore {
254
- readonly persistenceKind = 'memory-first-sqlite' as const;
255
- constructor(protected readonly mirror: AsyncSqliteMirror) {}
256
- persistenceHealth(): AsyncPersistenceHealth { return this.mirror.health(); }
257
- close(): Promise<void> { return this.mirror.release(); }
258
- protected persist(store: StoreName, method: string, ...args: unknown[]): void {
259
- this.mirror.enqueue({ store, method, args });
260
- }
261
- }
262
-
263
- class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
264
- constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository,
265
- private readonly closeArchive: () => void) { super(mirror); }
266
- override async close(): Promise<void> {
267
- try { await super.close(); } finally { this.closeArchive(); }
268
- }
269
- diagnosticCounts() { return this.memory.diagnosticCounts(); }
270
- saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
271
- saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
272
- currentScope(account?: EventAccountScope) { return this.memory.currentScope(account); }
273
- latestScope(account: EventAccountScope, options?: LatestEventScopeOptions) { return this.memory.latestScope(account, options); }
274
- commitEvent(value: CommitEventRequest) { const result = this.memory.commitEvent(value); this.persist('events', 'commitEvent', value); return result; }
275
- resolveEventDelivery(value: import('../events/types.js').EventDeliveryDecision) {
276
- this.memory.resolveEventDelivery(value); this.persist('events', 'resolveEventDelivery', value);
277
- }
278
- eventById(eventId: string) { return this.memory.eventById(eventId); }
279
- latestEventByType(sessionId: string, type: string, segmentId?: string) { return this.memory.latestEventByType(sessionId, type, segmentId); }
280
- highWaterCommitSeq(sessionId: string, segmentId?: string) { return this.memory.highWaterCommitSeq(sessionId, segmentId); }
281
- listCommittedEvents(filter: CommittedEventListFilter) { return this.memory.listCommittedEvents(filter); }
282
- ensureDeliveries(sessionId: string, consumerId: string, channels?: readonly ConsumerLease['channel'][]): void {
283
- this.memory.ensureDeliveries(sessionId, consumerId, channels);
284
- this.persist('events', 'ensureDeliveries', sessionId, consumerId, channels);
285
- }
286
- delivery(eventId: string, consumerId: string) { return this.memory.delivery(eventId, consumerId); }
287
- listEvents(filter: EventListFilter, consumerId: string, channels?: readonly ConsumerLease['channel'][]) {
288
- this.ensureDeliveries(filter.sessionId, consumerId, channels);
289
- return this.memory.listEvents(filter, consumerId, channels);
290
- }
291
- backlogSummary(sessionId: string, consumerId: string) {
292
- this.ensureDeliveries(sessionId, consumerId, ['details']);
293
- return this.memory.backlogSummary(sessionId, consumerId);
294
- }
295
- transitionDetails(value: DetailStateTransition) {
296
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
297
- const result = this.memory.transitionDetails(stable); this.persist('events', 'transitionDetails', stable); return result;
298
- }
299
- transitionMonitor(value: MonitorStateTransition) {
300
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
301
- const result = this.memory.transitionMonitor(stable); this.persist('events', 'transitionMonitor', stable); return result;
302
- }
303
- recordMonitorAttempt(value: MonitorDeliveryAttempt) {
304
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
305
- const result = this.memory.recordMonitorAttempt(stable); this.persist('events', 'recordMonitorAttempt', stable); return result;
306
- }
307
- acquireLease(value: AcquireLeaseRequest) {
308
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
309
- const result = this.memory.acquireLease(stable); this.persist('events', 'acquireLease', stable); return result;
310
- }
311
- leaseIsValid(lease: ConsumerLease, nowMs?: number) { return this.memory.leaseIsValid(lease, nowMs); }
312
- releaseLease(lease: ConsumerLease) { const result = this.memory.releaseLease(lease); this.persist('events', 'releaseLease', lease); return result; }
313
- sourceCheckpoint(sourceId: string) { return this.memory.sourceCheckpoint(sourceId); }
314
- enqueueMailboxItem<T = unknown>(value: EnqueueMailboxItem<T>) {
315
- const nowMs = Date.now();
316
- const stable = { ...value, createdAt: value.createdAt ?? new Date(nowMs).toISOString(), availableAtMs: value.availableAtMs ?? 0 };
317
- const result = this.memory.enqueueMailboxItem(stable); this.persist('events', 'enqueueMailboxItem', stable); return result;
318
- }
319
- mailboxItem<T = unknown>(itemId: string) { return this.memory.mailboxItem<T>(itemId); }
320
- mailboxItemForEvent<T = unknown>(consumerId: string, eventId: string, mode: 'short') { return this.memory.mailboxItemForEvent<T>(consumerId, eventId, mode); }
321
- peekMailbox<T = unknown>(filter: MailboxPeekFilter) { return this.memory.peekMailbox<T>(filter); }
322
- claimMailbox<T = unknown>(value: ClaimMailboxItemsRequest) {
323
- const stable = { ...value, nowMs: value.nowMs ?? Date.now(), claimToken: value.claimToken ?? randomUUID() };
324
- const result = this.memory.claimMailbox<T>(stable); this.persist('events', 'claimMailbox', stable); return result;
325
- }
326
- ackMailboxClaim(value: AckMailboxClaimRequest) {
327
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
328
- const result = this.memory.ackMailboxClaim(stable); this.persist('events', 'ackMailboxClaim', stable); return result;
329
- }
330
- nackMailboxClaim(value: NackMailboxClaimRequest) {
331
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
332
- const result = this.memory.nackMailboxClaim(stable); this.persist('events', 'nackMailboxClaim', stable); return result;
333
- }
334
- suppressMailboxItems(value: SuppressMailboxItemsFilter) {
335
- const stable = { ...value, nowMs: value.nowMs ?? Date.now() };
336
- const result = this.memory.suppressMailboxItems(stable); this.persist('events', 'suppressMailboxItems', stable); return result;
337
- }
338
- }
339
-
340
- class MemoryFirstStateHistory<TPosition, TState extends Record<string, unknown>> extends MirroredStore
341
- implements StateHistoryRepository<TPosition, TState> {
342
- constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryStateHistoryRepository<TPosition, TState>) { super(mirror); }
343
- diagnosticCounts() { return this.memory.diagnosticCounts(); }
344
- openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true) {
345
- const result = this.memory.openScope(scope, openedAtMs, historyComplete);
346
- this.persist('history', 'openScope', scope, openedAtMs, historyComplete); return result;
347
- }
348
- sealScope(scope: RuntimeScope, sealedAtMs = Date.now()) { this.memory.sealScope(scope, sealedAtMs); this.persist('history', 'sealScope', scope, sealedAtMs); }
349
- markScopeIncomplete(scope: RuntimeScope) { this.memory.markScopeIncomplete(scope); this.persist('history', 'markScopeIncomplete', scope); }
350
- getScope(scope: RuntimeScope) { return this.memory.getScope(scope); }
351
- appendStateFrame(frame: StateFrameRecord<TState>) { const result = this.memory.appendStateFrame(frame); this.persist('history', 'appendStateFrame', frame); return result; }
352
- queryStateFrames(query: StateFrameQuery) { return this.memory.queryStateFrames(query); }
353
- latestStateFrame(scope: RuntimeScope) { return this.memory.latestStateFrame(scope); }
354
- append(records: TrajectoryRecord<TPosition>[]) { const result = this.memory.append(records); this.persist('history', 'append', records); return result; }
355
- query(query: HistoryQuery) { return this.memory.query(query); }
356
- }
357
-
358
- class MemoryFirstInputJournal<TState extends Record<string, unknown>, TEvent extends Record<string, unknown>>
359
- extends MirroredStore implements RuntimePersistenceStore<TState, TEvent> {
360
- constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryRuntimeInputJournal<TState, TEvent>) { super(mirror); }
361
- diagnosticCounts() { return this.memory.diagnosticCounts(); }
362
- accept(batch: RuntimeInputBatch<TState, TEvent>) { const result = this.memory.accept(batch); if (result.inserted) this.persist('input', 'accept', batch); return result; }
363
- epoch(epochSeq: number) { return this.memory.epoch(epochSeq); }
364
- list(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.list(scope, afterEpochSeq, limit); }
365
- listOpen(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.listOpen(scope, afterEpochSeq, limit); }
366
- inputEventsCommitted(epochSeq: number) { return this.memory.inputEventsCommitted(epochSeq); }
367
- markInputEventsCommitted(epochSeq: number, watermark: number, committedAt = new Date().toISOString()) { this.memory.markInputEventsCommitted(epochSeq, watermark); this.persist('input', 'markInputEventsCommitted', epochSeq, watermark, committedAt); }
368
- eventWatermarkThrough(scope: RuntimeScope, epochSeq: number) { return this.memory.eventWatermarkThrough(scope, epochSeq); }
369
- markEventWatermark(epochSeq: number, watermark: number) { this.memory.markEventWatermark(epochSeq, watermark); this.persist('input', 'markEventWatermark', epochSeq, watermark); }
370
- markClosed(epochSeq: number, closedAt = new Date().toISOString(), durationMs?: number) { this.memory.markClosed(epochSeq); this.persist('input', 'markClosed', epochSeq, closedAt, durationMs); }
371
- recordPlugin(record: RuntimeEpochPluginRecord) { this.memory.recordPlugin(record); this.persist('input', 'recordPlugin', record); }
372
- pluginRecords(epochSeq: number) { return this.memory.pluginRecords(epochSeq); }
373
- pluginProgress(pluginId: string, scope: RuntimeScope) { return this.memory.pluginProgress(pluginId, scope); }
374
- savePluginProgress(progress: RuntimeEpochPluginProgress, scope: RuntimeScope) { this.memory.savePluginProgress(progress, scope); this.persist('input', 'savePluginProgress', progress, scope); }
375
- saveStates(records: readonly RuntimeEpochStateRecord[]) { this.memory.saveStates(records); this.persist('input', 'saveStates', records); }
376
- states(epochSeq: number) { return this.memory.states(epochSeq); }
377
- }
378
-
379
- export interface MemoryFirstPersistence<TPosition = unknown, TState extends Record<string, unknown> = Record<string, unknown>, TEvent extends Record<string, unknown> = Record<string, unknown>> {
380
- eventRepository: EventRepository & MailboxRepository;
381
- stateHistoryRepository: StateHistoryRepository<TPosition, TState>;
382
- inputJournal: RuntimePersistenceStore<TState, TEvent>;
383
- health(): AsyncPersistenceHealth;
384
- }
385
-
386
- export function createMemoryFirstPersistence<
387
- TPosition = unknown,
388
- TState extends Record<string, unknown> = Record<string, unknown>,
389
- TEvent extends Record<string, unknown> = Record<string, unknown>,
390
- >(options: MemoryFirstPersistenceOptions): MemoryFirstPersistence<TPosition, TState, TEvent> {
391
- const startedAt = performance.now();
392
- const diagnostic = (stage: string, attributes: Record<string, unknown> = {}): void => {
393
- if (!options.onDiagnostic) return;
394
- try {
395
- options.onDiagnostic('runtime.persistence.hydration', {
396
- stage, elapsed_ms: performance.now() - startedAt,
397
- process_memory: memorySample(), ...attributes,
398
- });
399
- } catch { /* Diagnostics must not prevent startup. */ }
400
- };
401
- diagnostic('started', {
402
- event_db_bytes: databaseBytes(options.eventLedgerPath),
403
- event_wal_bytes: databaseBytes(`${options.eventLedgerPath}-wal`),
404
- history_db_bytes: databaseBytes(options.stateHistoryPath),
405
- history_wal_bytes: databaseBytes(`${options.stateHistoryPath}-wal`),
406
- input_db_bytes: databaseBytes(options.inputJournalPath),
407
- input_wal_bytes: databaseBytes(`${options.inputJournalPath}-wal`),
408
- });
409
- const eventSqlite = SqliteEventRepository.open(options.eventLedgerPath);
410
- if (!eventSqlite.ok) {
411
- diagnostic('failed', { error_name: eventSqlite.unavailable.code });
412
- throw new Error(`${eventSqlite.unavailable.code}: ${eventSqlite.unavailable.message}`);
413
- }
414
- let historySqlite: SqliteStateHistoryRepository<TPosition, TState> | undefined;
415
- let inputSqlite: SqliteRuntimeInputJournal<TState, TEvent> | undefined;
416
- let eventMemory: MemoryEventRepository;
417
- let historyMemory: MemoryStateHistoryRepository<TPosition, TState>;
418
- let inputMemory: MemoryRuntimeInputJournal<TState, TEvent>;
419
- let hydrated = false;
420
- try {
421
- historySqlite = new SqliteStateHistoryRepository<TPosition, TState>(options.stateHistoryPath);
422
- inputSqlite = new SqliteRuntimeInputJournal<TState, TEvent>(options.inputJournalPath);
423
- const current = eventSqlite.repository.currentScope(options.recovery?.account);
424
- const restore = options.recovery
425
- ? canResumeRuntimeScope(current, options.recovery)
426
- : current?.session.status === 'open';
427
- const sessionId = restore && current ? current.session.sessionId : null;
428
- const reuseSegment = !options.recovery || (current && current.segment.status === 'open'
429
- && canReuseParticipationSegment({ kind: current.segment.kind, identity: current.segment.scopeRef },
430
- options.recovery.initialSegment.kind, options.recovery.initialSegment.identity));
431
- const scope: RuntimeScope | null = restore && current && reuseSegment ? {
432
- adapterId: current.session.adapterId, accountId: current.session.accountId,
433
- sessionId: current.session.sessionId, segmentId: current.segment.segmentId,
434
- segmentSeq: current.segment.sequence,
435
- } : null;
436
- diagnostic('selected', {
437
- restore_session: !!sessionId, event_selection: sessionId ? 'current_session' : 'metadata_only',
438
- state_selection: scope ? 'current_segment' : 'none',
439
- });
440
- // Event consumers can still own pending deliveries in earlier segments of
441
- // the same session. State/plugin recovery, however, reads the active scope only.
442
- const events = eventSqlite.repository.snapshot(sessionId);
443
- if (!sessionId && current) {
444
- // Runtime must still seal the previous durable scope on a fresh start.
445
- events.sessions = [current.session];
446
- events.segments = [current.segment];
447
- }
448
- const archiveThrough = events.nextCommitSeq - 1;
449
- eventMemory = new MemoryEventRepository(events, (event) =>
450
- eventSqlite.repository.archivedEventIdentities(event, sessionId, archiveThrough));
451
- diagnostic('events_loaded', { loaded_records: eventMemory.diagnosticCounts() });
452
- historyMemory = new MemoryStateHistoryRepository(historySqlite.snapshot(scope));
453
- diagnostic('history_loaded', { loaded_records: historyMemory.diagnosticCounts() });
454
- inputMemory = new MemoryRuntimeInputJournal(inputSqlite.snapshot(scope));
455
- diagnostic('input_loaded', { loaded_records: inputMemory.diagnosticCounts() });
456
- hydrated = true;
457
- } catch (error) {
458
- diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
459
- throw error;
460
- } finally {
461
- if (!hydrated) eventSqlite.repository.close();
462
- historySqlite?.close();
463
- inputSqlite?.close();
464
- }
465
- const required: ResolvedMemoryFirstPersistenceOptions = {
466
- ...options,
467
- maxPendingOperations: options.maxPendingOperations ?? 20_000,
468
- batchSize: options.batchSize ?? 128,
469
- flushIntervalMs: options.flushIntervalMs ?? 8,
470
- };
471
- let mirror: AsyncSqliteMirror;
472
- try { mirror = new AsyncSqliteMirror(required); }
473
- catch (error) {
474
- eventSqlite.repository.close();
475
- diagnostic('failed', { error_name: error instanceof Error ? error.name : 'unknown' });
476
- throw error;
477
- }
478
- diagnostic('completed', {
479
- loaded_records: {
480
- events: eventMemory.diagnosticCounts(), history: historyMemory.diagnosticCounts(), input: inputMemory.diagnosticCounts(),
481
- },
482
- });
483
- return {
484
- eventRepository: new MemoryFirstEventRepository(mirror, eventMemory, () => eventSqlite.repository.close()),
485
- stateHistoryRepository: new MemoryFirstStateHistory(mirror, historyMemory),
486
- inputJournal: new MemoryFirstInputJournal(mirror, inputMemory),
487
- health: () => mirror.health(),
488
- };
489
- }
1
+ import { createMemoryFirstPersistence as createPersistence, type MemoryFirstPersistenceOptions } from '@myclaw163/game-agent-runtime/framework/persistence/memory-first-persistence.js';
2
+ import { CLAWCLAW_STORE_COMPATIBILITY } from '../../clawclaw/persistence-compatibility.js';
3
+ export * from '@myclaw163/game-agent-runtime/framework/persistence/memory-first-persistence.js';
4
+ export function createMemoryFirstPersistence<P=unknown,S extends Record<string,unknown>=Record<string,unknown>,E extends Record<string,unknown>=Record<string,unknown>>(options: MemoryFirstPersistenceOptions) { return createPersistence<P,S,E>({...options,eventStoreCompatibility:CLAWCLAW_STORE_COMPATIBILITY}); }