@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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 (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -1,158 +1,2 @@
1
- import type { RuntimeScope } from '../types.js';
2
-
3
- export type TrajectorySubjectKind = 'self' | 'player' | 'system';
4
-
5
- export type TrajectoryRecordKind =
6
- | 'position'
7
- | 'visibility_gained'
8
- | 'visibility_lost'
9
- | 'stream_gap_started'
10
- | 'stream_gap_ended'
11
- | 'persistence_gap_started'
12
- | 'persistence_gap_ended'
13
- | 'retention_trimmed';
14
-
15
- export interface TrajectoryRecord<TPosition = unknown> {
16
- recordId: string;
17
- recordSeq?: number;
18
- scope: RuntimeScope;
19
- connectionId?: string;
20
- subjectId: string;
21
- subjectKind: TrajectorySubjectKind;
22
- kind: TrajectoryRecordKind;
23
- sourceType: 'backend_state' | 'canonical_event' | 'local_lifecycle';
24
- sourceKey: string;
25
- sourceSeq?: number | string;
26
- backendTick?: number;
27
- observedAtMs?: number;
28
- receivedAtMs: number;
29
- spaceId?: string;
30
- areaId?: string;
31
- position?: TPosition;
32
- attributes?: Record<string, unknown>;
33
- }
34
-
35
- export interface HistoryScopeRecord {
36
- scope: RuntimeScope;
37
- status: 'OPEN' | 'SEALED';
38
- openedAtMs: number;
39
- sealedAtMs: number | null;
40
- historyComplete: boolean;
41
- historyRevision: number;
42
- }
43
-
44
- export interface HistoryQuery {
45
- scope: RuntimeScope;
46
- subjectIds?: string[];
47
- kinds?: TrajectoryRecordKind[];
48
- afterRecordSeq?: number;
49
- beforeRecordSeq?: number;
50
- order?: 'asc' | 'desc';
51
- limit?: number;
52
- }
53
-
54
- export interface HistoryQueryResult<TPosition = unknown> {
55
- scope: HistoryScopeRecord | null;
56
- records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }>;
57
- page: {
58
- order: 'asc' | 'desc';
59
- limit: number;
60
- hasMore: boolean;
61
- firstRecordSeq: number | null;
62
- lastRecordSeq: number | null;
63
- };
64
- }
65
-
66
- export interface AppendHistoryResult {
67
- inserted: number;
68
- duplicates: number;
69
- }
70
-
71
- export interface StateFrameRecord<TState = Record<string, unknown>> {
72
- frameSeq?: number;
73
- /** Runtime epoch that admitted this complete State. */
74
- epochSeq?: number;
75
- scope: RuntimeScope;
76
- sourceId?: string;
77
- connectionId: string;
78
- /** Stable accepted-frame identity within the scope. */
79
- sourceKey: string;
80
- sourceSeq?: number | string;
81
- backendTick?: number;
82
- observedAtMs?: number;
83
- receivedAtMs: number;
84
- state: TState;
85
- }
86
-
87
- export interface StoredStateFrame<TState = Record<string, unknown>>
88
- extends StateFrameRecord<TState> {
89
- frameSeq: number;
90
- }
91
-
92
- export interface StateFrameQuery {
93
- scope: RuntimeScope;
94
- /** Runtime epoch bounds. A plugin invocation may read only its epoch and earlier epochs. */
95
- fromEpochSeq?: number;
96
- toEpochSeq?: number;
97
- afterFrameSeq?: number;
98
- beforeFrameSeq?: number;
99
- fromBackendTick?: number;
100
- toBackendTick?: number;
101
- order?: 'asc' | 'desc';
102
- limit?: number;
103
- }
104
-
105
- export interface StateFrameQueryResult<TState = Record<string, unknown>> {
106
- frames: StoredStateFrame<TState>[];
107
- page: {
108
- order: 'asc' | 'desc';
109
- limit: number;
110
- hasMore: boolean;
111
- firstFrameSeq: number | null;
112
- lastFrameSeq: number | null;
113
- };
114
- }
115
-
116
- export interface AppendStateFrameResult<TState = Record<string, unknown>> {
117
- inserted: boolean;
118
- frame: StoredStateFrame<TState>;
119
- }
120
-
121
- export interface StateHistorySnapshot<TPosition = unknown, TState = Record<string, unknown>> {
122
- scopes: HistoryScopeRecord[];
123
- stateFrames: StoredStateFrame<TState>[];
124
- records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }>;
125
- nextFrameSeq: number;
126
- nextRecordSeq: number;
127
- }
128
-
129
- export interface StateFrameHistoryReader<TState = Record<string, unknown>> {
130
- /** Reads the canonical accepted State journal. Implementations may use a hot cache. */
131
- queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState>;
132
- latestStateFrame(scope: RuntimeScope): StoredStateFrame<TState> | null;
133
- }
134
-
135
- /**
136
- * Durable journal for complete accepted State frames. Game-specific projections
137
- * are derived from this journal and must be rebuildable from it.
138
- */
139
- export interface StateJournal<TState = Record<string, unknown>>
140
- extends StateFrameHistoryReader<TState> {
141
- openScope(scope: RuntimeScope, openedAtMs?: number, historyComplete?: boolean): HistoryScopeRecord;
142
- sealScope(scope: RuntimeScope, sealedAtMs?: number): void;
143
- markScopeIncomplete(scope: RuntimeScope): void;
144
- getScope(scope: RuntimeScope): HistoryScopeRecord | null;
145
- appendStateFrame(frame: StateFrameRecord<TState>): AppendStateFrameResult<TState>;
146
- close?(): void | Promise<void>;
147
- }
148
-
149
- /** Sparse records used by transport-gap diagnostics and adapters that explicitly project them. */
150
- export interface TrajectoryHistoryRepository<TPosition = unknown> {
151
- append(records: TrajectoryRecord<TPosition>[]): AppendHistoryResult;
152
- query(query: HistoryQuery): HistoryQueryResult<TPosition>;
153
- }
154
-
155
- export interface StateHistoryRepository<
156
- TPosition = unknown,
157
- TState = Record<string, unknown>,
158
- > extends StateJournal<TState>, TrajectoryHistoryRepository<TPosition> {}
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/history/contracts.js';
@@ -1,194 +1,2 @@
1
- import { randomUUID } from 'crypto';
2
- import { cloneCanonical, runtimeScopeKey, type RuntimeScope } from '../types.js';
3
- import type { StateHistoryRepository, TrajectoryRecord } from './contracts.js';
4
-
5
- export interface HistoryWriterHealth {
6
- status: 'healthy' | 'degraded';
7
- queueDepth: number;
8
- droppedRecordCount: number;
9
- degradedSinceMs: number | null;
10
- reason: string | null;
11
- }
12
-
13
- export interface HistoryWriterDegradedScopeHealth {
14
- scope: RuntimeScope;
15
- queueDepth: number;
16
- droppedRecordCount: number;
17
- degradedSinceMs: number;
18
- reason: string;
19
- }
20
-
21
- export interface HistoryWriterOptions {
22
- maxQueueSize?: number;
23
- batchSize?: number;
24
- idFactory?: () => string;
25
- now?: () => number;
26
- onHealthChanged?: (health: HistoryWriterHealth) => void;
27
- }
28
-
29
- interface DegradedScope {
30
- scope: RuntimeScope;
31
- gapId: string;
32
- startedAtMs: number;
33
- reason: string;
34
- dropped: number;
35
- }
36
-
37
- export class HistoryWriter<TPosition = unknown> {
38
- private readonly queue: TrajectoryRecord<TPosition>[] = [];
39
- private readonly degradedScopes = new Map<string, DegradedScope>();
40
- private readonly maxQueueSize: number;
41
- private readonly batchSize: number;
42
- private readonly idFactory: () => string;
43
- private readonly now: () => number;
44
- private scheduled = false;
45
- private flushing: Promise<void> | null = null;
46
- private droppedRecordCount = 0;
47
-
48
- constructor(
49
- private readonly repository: StateHistoryRepository<TPosition>,
50
- private readonly options: HistoryWriterOptions = {},
51
- ) {
52
- this.maxQueueSize = Math.max(1, options.maxQueueSize ?? 2_000);
53
- this.batchSize = Math.max(1, options.batchSize ?? 100);
54
- this.idFactory = options.idFactory ?? randomUUID;
55
- this.now = options.now ?? Date.now;
56
- }
57
-
58
- openScope(scope: RuntimeScope, openedAtMs = this.now(), historyComplete = true): void {
59
- this.repository.openScope(scope, openedAtMs, historyComplete);
60
- }
61
-
62
- enqueue(records: TrajectoryRecord<TPosition>[]): { accepted: number; dropped: number } {
63
- const available = Math.max(0, this.maxQueueSize - this.queue.length);
64
- const accepted = records.slice(0, available).map((record) => cloneCanonical(record));
65
- const dropped = records.slice(available);
66
- this.queue.push(...accepted);
67
- if (dropped.length > 0) {
68
- this.droppedRecordCount += dropped.length;
69
- for (const record of dropped) this.markDegraded(record.scope, 'queue_overflow', 1);
70
- }
71
- if (this.queue.length > 0 || this.degradedScopes.size > 0) this.scheduleFlush();
72
- this.emitHealth();
73
- return { accepted: accepted.length, dropped: dropped.length };
74
- }
75
-
76
- async flush(): Promise<void> {
77
- if (this.flushing) return this.flushing;
78
- this.flushing = this.flushInternal().finally(() => {
79
- this.flushing = null;
80
- this.emitHealth();
81
- });
82
- return this.flushing;
83
- }
84
-
85
- health(): HistoryWriterHealth {
86
- const degraded = Array.from(this.degradedScopes.values());
87
- return {
88
- status: degraded.length > 0 ? 'degraded' : 'healthy',
89
- queueDepth: this.queue.length,
90
- droppedRecordCount: this.droppedRecordCount,
91
- degradedSinceMs: degraded.length > 0
92
- ? Math.min(...degraded.map((entry) => entry.startedAtMs))
93
- : null,
94
- reason: degraded[0]?.reason ?? null,
95
- };
96
- }
97
-
98
- /**
99
- * Active gaps are reported separately so an online reader can merge health
100
- * only into the matching durable history scope. The queue remains private;
101
- * callers receive counts and never mutable trajectory payloads.
102
- */
103
- degradedScopeHealth(): HistoryWriterDegradedScopeHealth[] {
104
- const queuedByScope = new Map<string, number>();
105
- for (const record of this.queue) {
106
- const key = runtimeScopeKey(record.scope);
107
- queuedByScope.set(key, (queuedByScope.get(key) ?? 0) + 1);
108
- }
109
- return Array.from(this.degradedScopes.entries())
110
- .map(([key, entry]) => ({
111
- scope: cloneCanonical(entry.scope),
112
- queueDepth: queuedByScope.get(key) ?? 0,
113
- droppedRecordCount: entry.dropped,
114
- degradedSinceMs: entry.startedAtMs,
115
- reason: entry.reason,
116
- }))
117
- .sort((left, right) => left.degradedSinceMs - right.degradedSinceMs);
118
- }
119
-
120
- private async flushInternal(): Promise<void> {
121
- this.scheduled = false;
122
- while (this.queue.length > 0 || this.degradedScopes.size > 0) {
123
- const batch = this.queue.splice(0, this.batchSize);
124
- const recovering = Array.from(this.degradedScopes.values());
125
- const recoveryRecords = recovering.flatMap((entry) => this.persistenceGapRecords(entry));
126
- try {
127
- this.repository.append([...recoveryRecords, ...batch]);
128
- for (const entry of recovering) {
129
- this.repository.markScopeIncomplete(entry.scope);
130
- this.degradedScopes.delete(runtimeScopeKey(entry.scope));
131
- }
132
- } catch (error) {
133
- this.queue.unshift(...batch);
134
- const reason = error instanceof Error ? error.message : String(error);
135
- for (const record of batch) this.markDegraded(record.scope, reason, 0);
136
- break;
137
- }
138
- await Promise.resolve();
139
- }
140
- }
141
-
142
- private scheduleFlush(): void {
143
- if (this.scheduled || this.flushing) return;
144
- this.scheduled = true;
145
- setTimeout(() => { void this.flush(); }, 0);
146
- }
147
-
148
- private markDegraded(scope: RuntimeScope, reason: string, dropped: number): void {
149
- const key = runtimeScopeKey(scope);
150
- const existing = this.degradedScopes.get(key);
151
- if (existing) {
152
- existing.dropped += dropped;
153
- if (existing.reason === 'queue_overflow' && reason !== 'queue_overflow') existing.reason = reason;
154
- return;
155
- }
156
- this.degradedScopes.set(key, {
157
- scope: cloneCanonical(scope),
158
- gapId: this.idFactory(),
159
- startedAtMs: this.now(),
160
- reason,
161
- dropped,
162
- });
163
- }
164
-
165
- private persistenceGapRecords(entry: DegradedScope): TrajectoryRecord<TPosition>[] {
166
- const endedAtMs = this.now();
167
- const common = {
168
- scope: cloneCanonical(entry.scope),
169
- subjectId: '__stream__',
170
- subjectKind: 'system' as const,
171
- sourceType: 'local_lifecycle' as const,
172
- sourceKey: `persistence-gap:${entry.gapId}`,
173
- attributes: { reason: entry.reason, dropped_record_count: entry.dropped },
174
- };
175
- return [
176
- {
177
- ...common,
178
- recordId: `${entry.gapId}:started`,
179
- kind: 'persistence_gap_started',
180
- receivedAtMs: entry.startedAtMs,
181
- },
182
- {
183
- ...common,
184
- recordId: `${entry.gapId}:ended`,
185
- kind: 'persistence_gap_ended',
186
- receivedAtMs: endedAtMs,
187
- },
188
- ];
189
- }
190
-
191
- private emitHealth(): void {
192
- this.options.onHealthChanged?.(this.health());
193
- }
194
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/history/history-writer.js';
@@ -1,230 +1,2 @@
1
- import { cloneCanonical, runtimeScopeKey, sameRuntimeScope, type RuntimeScope } from '../types.js';
2
- import type {
3
- AppendHistoryResult,
4
- AppendStateFrameResult,
5
- HistoryQuery,
6
- HistoryQueryResult,
7
- HistoryScopeRecord,
8
- StateFrameQuery,
9
- StateFrameQueryResult,
10
- StateFrameRecord,
11
- StateHistoryRepository,
12
- StateHistorySnapshot,
13
- StoredStateFrame,
14
- TrajectoryRecord,
15
- } from './contracts.js';
16
-
17
- function dedupeKey(record: TrajectoryRecord): string {
18
- return [runtimeScopeKey(record.scope), record.sourceKey, record.subjectId, record.kind].join('\u001f');
19
- }
20
-
21
- export class MemoryStateHistoryRepository<
22
- TPosition = unknown,
23
- TState = Record<string, unknown>,
24
- > implements StateHistoryRepository<TPosition, TState> {
25
- private readonly scopes = new Map<string, HistoryScopeRecord>();
26
- private readonly stateFrames: StoredStateFrame<TState>[] = [];
27
- private readonly stateFramesByScope = new Map<string, StoredStateFrame<TState>[]>();
28
- private readonly stateFrameDedupe = new Map<string, StoredStateFrame<TState>>();
29
- private readonly records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }> = [];
30
- private readonly recordsByScope = new Map<string, Array<TrajectoryRecord<TPosition> & { recordSeq: number }>>();
31
- private readonly dedupe = new Set<string>();
32
-
33
- diagnosticCounts(): Readonly<Record<string, number>> {
34
- return {
35
- scopes: this.scopes.size,
36
- state_frames: this.stateFrames.length,
37
- trajectory_records: this.records.length,
38
- state_frame_dedupe_keys: this.stateFrameDedupe.size,
39
- trajectory_dedupe_keys: this.dedupe.size,
40
- };
41
- }
42
- private nextFrameSeq = 1;
43
- private nextRecordSeq = 1;
44
-
45
- constructor(snapshot?: StateHistorySnapshot<TPosition, TState>) {
46
- if (!snapshot) return;
47
- for (const scope of snapshot.scopes) this.scopes.set(runtimeScopeKey(scope.scope), cloneCanonical(scope));
48
- for (const frame of snapshot.stateFrames) {
49
- const stored = cloneCanonical(frame);
50
- this.stateFrames.push(stored);
51
- const scoped = this.stateFramesByScope.get(runtimeScopeKey(frame.scope)) ?? [];
52
- scoped.push(stored);
53
- this.stateFramesByScope.set(runtimeScopeKey(frame.scope), scoped);
54
- this.stateFrameDedupe.set(`${runtimeScopeKey(frame.scope)}\u001f${frame.sourceKey}`, stored);
55
- }
56
- for (const record of snapshot.records) {
57
- const stored = cloneCanonical(record);
58
- this.records.push(stored);
59
- const scoped = this.recordsByScope.get(runtimeScopeKey(record.scope)) ?? [];
60
- scoped.push(stored);
61
- this.recordsByScope.set(runtimeScopeKey(record.scope), scoped);
62
- this.dedupe.add(dedupeKey(stored));
63
- }
64
- this.nextFrameSeq = Math.max(snapshot.nextFrameSeq, 1);
65
- this.nextRecordSeq = Math.max(snapshot.nextRecordSeq, 1);
66
- }
67
-
68
- snapshot(): StateHistorySnapshot<TPosition, TState> {
69
- return cloneCanonical({
70
- scopes: [...this.scopes.values()],
71
- stateFrames: this.stateFrames,
72
- records: this.records,
73
- nextFrameSeq: this.nextFrameSeq,
74
- nextRecordSeq: this.nextRecordSeq,
75
- });
76
- }
77
-
78
- openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true): HistoryScopeRecord {
79
- for (const stored of this.scopes.values()) {
80
- if (
81
- stored.status === 'OPEN'
82
- && stored.scope.adapterId === scope.adapterId
83
- && stored.scope.accountId === scope.accountId
84
- && !sameRuntimeScope(stored.scope, scope)
85
- ) {
86
- stored.status = 'SEALED';
87
- stored.sealedAtMs = openedAtMs;
88
- }
89
- }
90
- const key = runtimeScopeKey(scope);
91
- const existing = this.scopes.get(key);
92
- const value: HistoryScopeRecord = existing
93
- ? { ...existing, status: 'OPEN', sealedAtMs: null }
94
- : {
95
- scope: cloneCanonical(scope),
96
- status: 'OPEN',
97
- openedAtMs,
98
- sealedAtMs: null,
99
- historyComplete,
100
- historyRevision: 1,
101
- };
102
- if (!historyComplete) value.historyComplete = false;
103
- this.scopes.set(key, value);
104
- return cloneCanonical(value);
105
- }
106
-
107
- sealScope(scope: RuntimeScope, sealedAtMs = Date.now()): void {
108
- const stored = this.scopes.get(runtimeScopeKey(scope));
109
- if (!stored) return;
110
- stored.status = 'SEALED';
111
- stored.sealedAtMs = sealedAtMs;
112
- }
113
-
114
- markScopeIncomplete(scope: RuntimeScope): void {
115
- const stored = this.scopes.get(runtimeScopeKey(scope));
116
- if (stored) stored.historyComplete = false;
117
- }
118
-
119
- getScope(scope: RuntimeScope): HistoryScopeRecord | null {
120
- const stored = this.scopes.get(runtimeScopeKey(scope));
121
- return stored ? cloneCanonical(stored) : null;
122
- }
123
-
124
- appendStateFrame(frame: StateFrameRecord<TState>): AppendStateFrameResult<TState> {
125
- const scopeKey = runtimeScopeKey(frame.scope);
126
- if (!this.scopes.has(scopeKey)) {
127
- throw new Error(`History scope is not open: ${scopeKey}`);
128
- }
129
- const dedupe = `${scopeKey}\u001f${frame.sourceKey}`;
130
- const existing = this.stateFrameDedupe.get(dedupe);
131
- if (existing) return { inserted: false, frame: cloneCanonical(existing) };
132
- const stored: StoredStateFrame<TState> = {
133
- ...cloneCanonical(frame),
134
- frameSeq: this.nextFrameSeq++,
135
- };
136
- this.stateFrames.push(stored);
137
- const scopedFrames = this.stateFramesByScope.get(scopeKey) ?? [];
138
- scopedFrames.push(stored);
139
- this.stateFramesByScope.set(scopeKey, scopedFrames);
140
- this.stateFrameDedupe.set(dedupe, stored);
141
- return { inserted: true, frame: cloneCanonical(stored) };
142
- }
143
-
144
- queryStateFrames(query: StateFrameQuery): StateFrameQueryResult<TState> {
145
- const order = query.order ?? 'asc';
146
- const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));
147
- let selected = (this.stateFramesByScope.get(runtimeScopeKey(query.scope)) ?? []).filter((frame) => (
148
- (query.fromEpochSeq === undefined
149
- || (frame.epochSeq !== undefined && frame.epochSeq >= query.fromEpochSeq))
150
- && (query.toEpochSeq === undefined
151
- || (frame.epochSeq !== undefined && frame.epochSeq <= query.toEpochSeq))
152
- && (query.afterFrameSeq === undefined || frame.frameSeq > query.afterFrameSeq)
153
- && (query.beforeFrameSeq === undefined || frame.frameSeq < query.beforeFrameSeq)
154
- && (query.fromBackendTick === undefined
155
- || (frame.backendTick !== undefined && frame.backendTick >= query.fromBackendTick))
156
- && (query.toBackendTick === undefined
157
- || (frame.backendTick !== undefined && frame.backendTick <= query.toBackendTick))
158
- ));
159
- selected = selected.sort((a, b) => order === 'asc'
160
- ? a.frameSeq - b.frameSeq
161
- : b.frameSeq - a.frameSeq);
162
- const hasMore = selected.length > limit;
163
- const frames = selected.slice(0, limit).map((frame) => cloneCanonical(frame));
164
- return {
165
- frames,
166
- page: {
167
- order,
168
- limit,
169
- hasMore,
170
- firstFrameSeq: frames[0]?.frameSeq ?? null,
171
- lastFrameSeq: frames.at(-1)?.frameSeq ?? null,
172
- },
173
- };
174
- }
175
-
176
- latestStateFrame(scope: RuntimeScope): StoredStateFrame<TState> | null {
177
- return this.queryStateFrames({ scope, order: 'desc', limit: 1 }).frames[0] ?? null;
178
- }
179
-
180
- append(records: TrajectoryRecord<TPosition>[]): AppendHistoryResult {
181
- let inserted = 0;
182
- let duplicates = 0;
183
- for (const record of records) {
184
- if (!this.scopes.has(runtimeScopeKey(record.scope))) {
185
- throw new Error(`History scope is not open: ${runtimeScopeKey(record.scope)}`);
186
- }
187
- const key = dedupeKey(record);
188
- if (this.dedupe.has(key)) {
189
- duplicates += 1;
190
- continue;
191
- }
192
- this.dedupe.add(key);
193
- const stored = { ...cloneCanonical(record), recordSeq: this.nextRecordSeq++ };
194
- this.records.push(stored);
195
- const scopeKey = runtimeScopeKey(record.scope);
196
- const scoped = this.recordsByScope.get(scopeKey) ?? [];
197
- scoped.push(stored);
198
- this.recordsByScope.set(scopeKey, scoped);
199
- inserted += 1;
200
- }
201
- return { inserted, duplicates };
202
- }
203
-
204
- query(query: HistoryQuery): HistoryQueryResult<TPosition> {
205
- const order = query.order ?? 'asc';
206
- const limit = Math.max(1, Math.min(query.limit ?? 100, 1000));
207
- const subjectSet = query.subjectIds ? new Set(query.subjectIds) : null;
208
- const kindSet = query.kinds ? new Set(query.kinds) : null;
209
- let selected = (this.recordsByScope.get(runtimeScopeKey(query.scope)) ?? []).filter((record) => (
210
- (!subjectSet || subjectSet.has(record.subjectId))
211
- && (!kindSet || kindSet.has(record.kind))
212
- && (query.afterRecordSeq === undefined || record.recordSeq > query.afterRecordSeq)
213
- && (query.beforeRecordSeq === undefined || record.recordSeq < query.beforeRecordSeq)
214
- ));
215
- selected = selected.sort((a, b) => order === 'asc' ? a.recordSeq - b.recordSeq : b.recordSeq - a.recordSeq);
216
- const hasMore = selected.length > limit;
217
- const pageRecords = selected.slice(0, limit).map((record) => cloneCanonical(record));
218
- return {
219
- scope: this.getScope(query.scope),
220
- records: pageRecords,
221
- page: {
222
- order,
223
- limit,
224
- hasMore,
225
- firstRecordSeq: pageRecords[0]?.recordSeq ?? null,
226
- lastRecordSeq: pageRecords.at(-1)?.recordSeq ?? null,
227
- },
228
- };
229
- }
230
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/state/history/memory-state-history-repository.js';