@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,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';