@myclaw163/clawclaw-cli 0.8.4 → 0.8.5

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 (241) hide show
  1. package/README.md +3 -2
  2. package/docs/configuration.md +44 -26
  3. package/docs/custom-modules/README.md +7 -10
  4. package/docs/custom-modules/behavior.md +3 -1
  5. package/docs/custom-modules/perception.md +1 -1
  6. package/docs/custom-modules/trigger.md +1 -1
  7. package/docs/runtime/README.md +4 -4
  8. package/docs/runtime/official-perception-modules.md +2 -2
  9. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  10. package/package.json +9 -2
  11. package/scripts/build-official-hub-behaviors.mjs +136 -0
  12. package/scripts/build-official-hub-behaviors.test.mjs +178 -0
  13. package/scripts/enable_ccl_permissions.cjs +4 -2
  14. package/scripts/enable_ccl_permissions.test.mjs +8 -4
  15. package/scripts/postinstall.mjs +1 -4
  16. package/scripts/sync-bundled-skill.mjs +12 -159
  17. package/scripts/sync-bundled-skill.test.mjs +9 -74
  18. package/skills/clawclaw/SKILL.md +14 -9
  19. package/skills/clawclaw/references/BEHAVIORS.md +4 -4
  20. package/skills/clawclaw/references/COMMANDS.md +32 -16
  21. package/skills/clawclaw/references/HUB.md +25 -38
  22. package/src/commands/account.ts +58 -14
  23. package/src/commands/behavior.ts +116 -38
  24. package/src/commands/hub.ts +110 -153
  25. package/src/commands/load.ts +138 -33
  26. package/src/commands/perception.ts +55 -24
  27. package/src/commands/persona.ts +66 -20
  28. package/src/commands/skill.ts +12 -48
  29. package/src/commands/trigger.ts +68 -40
  30. package/src/hub-official-behaviors/kill-lone.ts +138 -0
  31. package/src/hub-official-behaviors/patrol.ts +30 -0
  32. package/src/hub-official-behaviors/shared.ts +125 -0
  33. package/src/hub-official-behaviors/task-only.ts +158 -0
  34. package/src/lib/account-guidance.ts +54 -9
  35. package/src/lib/agent-workspace-client.ts +135 -0
  36. package/src/lib/agent-workspace-runtime.ts +154 -0
  37. package/src/lib/agent-workspace-skills.ts +177 -0
  38. package/src/lib/agent-workspace-sync.ts +852 -0
  39. package/src/lib/gameplay-config.ts +29 -15
  40. package/src/lib/hub-client.ts +252 -34
  41. package/src/lib/hub-reminder.ts +22 -7
  42. package/src/lib/init-command.ts +0 -6
  43. package/src/lib/load-context.ts +12 -6
  44. package/src/lib/persona.ts +141 -69
  45. package/src/lib/server-status.ts +78 -0
  46. package/src/lib/skill-host.ts +160 -0
  47. package/src/lib/user-data.ts +197 -4
  48. package/src/runtime/clawclaw/owner.ts +63 -19
  49. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +8 -2
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +2 -2
  51. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +4 -1
  52. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +11 -5
  53. package/src/runtime/clawclaw/plugins/perception/replay.ts +0 -2
  54. package/personas//345/217/243/346/230/257/345/277/203/351/235/236.md +0 -50
  55. package/personas//345/277/240/345/277/203/350/200/201/344/273/206.md +0 -51
  56. package/personas//346/227/240/344/272/272/350/256/276.md +0 -1
  57. package/personas//350/264/253/345/230/264/346/215/237/345/217/213.md +0 -48
  58. package/personas//350/275/257/350/220/214/350/205/271/351/273/221.md +0 -51
  59. package/src/behaviors/official-finite/index.test.ts +0 -249
  60. package/src/channel/claude-channel-server.test.ts +0 -202
  61. package/src/commands/account.test.ts +0 -570
  62. package/src/commands/behavior.test.ts +0 -158
  63. package/src/commands/communication.test.ts +0 -282
  64. package/src/commands/competition.test.ts +0 -116
  65. package/src/commands/data.test.ts +0 -89
  66. package/src/commands/events-canonical-state.test.ts +0 -406
  67. package/src/commands/events.test.ts +0 -58
  68. package/src/commands/game/index.test.ts +0 -1251
  69. package/src/commands/game-map.test.ts +0 -69
  70. package/src/commands/hub.test.ts +0 -124
  71. package/src/commands/load.test.ts +0 -440
  72. package/src/commands/perception.test.ts +0 -75
  73. package/src/commands/setup/hermes.test.ts +0 -96
  74. package/src/commands/setup/openclaw.test.ts +0 -124
  75. package/src/commands/trigger.test.ts +0 -140
  76. package/src/commands/upgrade.test.ts +0 -82
  77. package/src/lib/account-guidance.test.ts +0 -36
  78. package/src/lib/auth.test.ts +0 -151
  79. package/src/lib/behavior-export.test.ts +0 -326
  80. package/src/lib/behavior-export.ts +0 -537
  81. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +0 -21
  82. package/src/lib/custom-tts.test.ts +0 -387
  83. package/src/lib/diagnostics-config.test.ts +0 -59
  84. package/src/lib/game-client-tts.test.ts +0 -151
  85. package/src/lib/game-client.test.ts +0 -250
  86. package/src/lib/gameplay-config.test.ts +0 -301
  87. package/src/lib/host-config-patcher.test.ts +0 -130
  88. package/src/lib/http-transport.test.ts +0 -124
  89. package/src/lib/hub-client.test.ts +0 -57
  90. package/src/lib/hub-install.test.ts +0 -135
  91. package/src/lib/hub-install.ts +0 -185
  92. package/src/lib/hub-unzip.test.ts +0 -69
  93. package/src/lib/init-command.test.ts +0 -103
  94. package/src/lib/load-context.test.ts +0 -62
  95. package/src/lib/match-state.test.ts +0 -134
  96. package/src/lib/official-resource-sync.test.ts +0 -199
  97. package/src/lib/official-resource-sync.ts +0 -221
  98. package/src/lib/perception-config.test.ts +0 -143
  99. package/src/lib/perception-export.test.ts +0 -145
  100. package/src/lib/perception-export.ts +0 -178
  101. package/src/lib/persona.test.ts +0 -84
  102. package/src/lib/room.test.ts +0 -88
  103. package/src/lib/server-registry.test.ts +0 -64
  104. package/src/lib/service-status.test.ts +0 -81
  105. package/src/lib/skill-version.test.ts +0 -48
  106. package/src/lib/trigger-config.test.ts +0 -102
  107. package/src/lib/trigger-export.test.ts +0 -80
  108. package/src/lib/trigger-export.ts +0 -210
  109. package/src/lib/user-data.test.ts +0 -121
  110. package/src/lib/workspace-argv.test.ts +0 -49
  111. package/src/pipeline/canonical-event-presentation.test.ts +0 -257
  112. package/src/pipeline/event-format.test.ts +0 -879
  113. package/src/pipeline/event-hints.test.ts +0 -337
  114. package/src/pipeline/game-sync-event-normalization.test.ts +0 -419
  115. package/src/pipeline/player-projection.test.ts +0 -247
  116. package/src/runtime/auto-upgrade.test.ts +0 -66
  117. package/src/runtime/canonical-event-emitter.test.ts +0 -70
  118. package/src/runtime/canonical-monitor.test.ts +0 -577
  119. package/src/runtime/clawclaw/agent-event-policy.test.ts +0 -60
  120. package/src/runtime/clawclaw/behavior-decision.test.ts +0 -43
  121. package/src/runtime/clawclaw/behavior-input-fields.test.ts +0 -175
  122. package/src/runtime/clawclaw/behavior-input.test.ts +0 -173
  123. package/src/runtime/clawclaw/behavior-observation-memory.test.ts +0 -59
  124. package/src/runtime/clawclaw/behavior-read-api.test.ts +0 -123
  125. package/src/runtime/clawclaw/notifications.test.ts +0 -47
  126. package/src/runtime/clawclaw/owner-lock.test.ts +0 -221
  127. package/src/runtime/clawclaw/owner.test.ts +0 -203
  128. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +0 -328
  129. package/src/runtime/clawclaw/plugins/assembly.test.ts +0 -200
  130. package/src/runtime/clawclaw/plugins/behavior/activation-manager.test.ts +0 -180
  131. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +0 -43
  132. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.test.ts +0 -156
  133. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.test.ts +0 -182
  134. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +0 -1094
  135. package/src/runtime/clawclaw/plugins/behavior/behavior-source.test.ts +0 -174
  136. package/src/runtime/clawclaw/plugins/behavior/control-driver.test.ts +0 -195
  137. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.test.ts +0 -283
  138. package/src/runtime/clawclaw/plugins/behavior-input-source.test.ts +0 -80
  139. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +0 -267
  140. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +0 -226
  141. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.test.ts +0 -239
  142. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.test.ts +0 -407
  143. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-push.integration.test.ts +0 -397
  144. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.test.ts +0 -270
  145. package/src/runtime/clawclaw/plugins/mailbox/mailbox-agent-event-batch.test.ts +0 -166
  146. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.test.ts +0 -194
  147. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.test.ts +0 -87
  148. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +0 -2012
  149. package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +0 -214
  150. package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +0 -347
  151. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.test.ts +0 -92
  152. package/src/runtime/clawclaw/plugins/perception/modules/corpse-visibility-module.ts +0 -248
  153. package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +0 -389
  154. package/src/runtime/clawclaw/plugins/perception/modules/index.ts +0 -8
  155. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +0 -342
  156. package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +0 -475
  157. package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +0 -30
  158. package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +0 -304
  159. package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +0 -179
  160. package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +0 -364
  161. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +0 -81
  162. package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +0 -200
  163. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +0 -216
  164. package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +0 -284
  165. package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +0 -120
  166. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +0 -105
  167. package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +0 -269
  168. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +0 -865
  169. package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +0 -1878
  170. package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +0 -278
  171. package/src/runtime/clawclaw/plugins/perception/replay.test.ts +0 -77
  172. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -853
  173. package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +0 -287
  174. package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +0 -321
  175. package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +0 -307
  176. package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +0 -2646
  177. package/src/runtime/clawclaw/plugins/source/task-change-tracker.test.ts +0 -212
  178. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.test.ts +0 -548
  179. package/src/runtime/clawclaw/plugins/trigger/trigger-source.test.ts +0 -169
  180. package/src/runtime/clawclaw/runtime-data-export.test.ts +0 -249
  181. package/src/runtime/clawclaw-event-catalog.test.ts +0 -128
  182. package/src/runtime/framework/action-diagnostics.test.ts +0 -81
  183. package/src/runtime/framework/capability-registry.test.ts +0 -423
  184. package/src/runtime/framework/control-coordinator.test.ts +0 -675
  185. package/src/runtime/framework/events/event-delivery-service.test.ts +0 -84
  186. package/src/runtime/framework/events/event-ingress.test.ts +0 -203
  187. package/src/runtime/framework/events/mailbox-event-repositories.test.ts +0 -710
  188. package/src/runtime/framework/events/sqlite-event-repository.test.ts +0 -802
  189. package/src/runtime/framework/mailbox/coalescer.test.ts +0 -55
  190. package/src/runtime/framework/mailbox/identity.test.ts +0 -38
  191. package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +0 -513
  192. package/src/runtime/framework/mailbox/notification-projector.test.ts +0 -77
  193. package/src/runtime/framework/modules/runtime-module-loader.test.ts +0 -435
  194. package/src/runtime/framework/participation-manager.test.ts +0 -108
  195. package/src/runtime/framework/plugins/runtime-input-journal.test.ts +0 -179
  196. package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +0 -2040
  197. package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +0 -144
  198. package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +0 -157
  199. package/src/runtime/framework/state/history/state-history.test.ts +0 -251
  200. package/src/runtime/framework/state/state-core.test.ts +0 -197
  201. package/src/runtime/game-sync-protocol.test.ts +0 -123
  202. package/src/runtime/host-monitor-rate-gate.test.ts +0 -73
  203. package/src/runtime/mailbox-host-relay.test.ts +0 -293
  204. package/src/runtime/observability/observability.test.ts +0 -583
  205. package/src/runtime/owner-control.test.ts +0 -153
  206. package/src/runtime/parent-process-watch.test.ts +0 -27
  207. package/src/runtime/pending-event-handoff.test.ts +0 -29
  208. package/src/runtime/raw-ws-log.test.ts +0 -102
  209. package/src/runtime/runtime-logger.test.ts +0 -58
  210. package/src/runtime/runtime-persistence.test.ts +0 -26
  211. package/src/runtime/runtime.test.ts +0 -1770
  212. package/src/runtime/ws-client.test.ts +0 -562
  213. package/src/sdk/action.test.ts +0 -8
  214. package/src/sdk/behavior-plugin/index.test.ts +0 -74
  215. package/src/sdk/index.test.ts +0 -45
  216. package/src/sdk/module-input/index.test.ts +0 -49
  217. package/src/sdk/perception-plugin/index.test.ts +0 -22
  218. package/src/sdk/resource-metadata.test.ts +0 -40
  219. package/src/sdk/trigger-plugin/index.test.ts +0 -41
  220. package/src/short-command/classifier.test.ts +0 -107
  221. package/src/short-command/presenter.test.ts +0 -119
  222. package/src/short-command/runner.test.ts +0 -78
  223. package/src/short-command/sensitive-data-filter.test.ts +0 -56
  224. package/src/short-command/transport-response.test.ts +0 -39
  225. package/src/strategies/custom-module.test.ts +0 -267
  226. package/src/strategies/game-utils.test.ts +0 -305
  227. package/src/strategies/goals/avoid-players-top.test.ts +0 -95
  228. package/src/strategies/goals/crab-sabotage-top.test.ts +0 -131
  229. package/src/strategies/goals/kill-lone-top.test.ts +0 -96
  230. package/src/strategies/goals/kill-target-top.test.ts +0 -65
  231. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -84
  232. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -112
  233. package/src/strategies/goals/paradise-fish-top.test.ts +0 -203
  234. package/src/strategies/goals/task-only-top.test.ts +0 -88
  235. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -138
  236. package/src/strategies/meeting-gate.test.ts +0 -59
  237. package/src/strategies/official-long-behavior.test.ts +0 -89
  238. package/src/strategies/pathfind/astar-path.test.ts +0 -198
  239. package/src/strategies/pathfind/escape-planner.test.ts +0 -223
  240. package/src/strategies/player-targets.test.ts +0 -10
  241. package/src/strategies/task-only.test.ts +0 -138
@@ -1,1094 +0,0 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import {
3
- ClawclawBehavior,
4
- type BehaviorDecision,
5
- type BehaviorInput,
6
- type ClawclawBehaviorClass,
7
- type ClawclawBehaviorManifest,
8
- } from '../../../../sdk/behavior-plugin/index.js';
9
- import type { CanonicalEvent } from '../../../framework/events/types.js';
10
- import type {
11
- RuntimeEpochPluginContext,
12
- RuntimeEpochPluginInput,
13
- RuntimeEpochPluginResult,
14
- } from '../../../framework/plugins/contracts.js';
15
- import type { StoredStateFrame } from '../../../framework/state/history/contracts.js';
16
- import { MemoryStateHistoryRepository } from '../../../framework/state/history/memory-state-history-repository.js';
17
- import { BehaviorActivationManager } from './activation-manager.js';
18
- import {
19
- CLAWCLAW_BEHAVIOR_STATE_TOPIC,
20
- ClawclawBehaviorPlugin,
21
- } from './behavior-plugin.js';
22
- import type { ClawclawBehaviorControlDriver } from './control-driver.js';
23
- import { prepareClawclawBehavior } from './behavior-normalization.js';
24
-
25
- const scope = {
26
- adapterId: 'clawclaw', accountId: 'account', sessionId: 'session', segmentId: 'game',
27
- };
28
-
29
- function manifest(
30
- id: string,
31
- options: Partial<ClawclawBehaviorManifest> = {},
32
- ): ClawclawBehaviorManifest {
33
- return {
34
- apiVersion: 3,
35
- id,
36
- name: id,
37
- description: `${id} fixture`,
38
- inputs: [],
39
- execution: 'serial',
40
- ...options,
41
- };
42
- }
43
-
44
- function catalog(classes: readonly ClawclawBehaviorClass[]) {
45
- const byId = new Map(classes.map((BehaviorClass) => [
46
- BehaviorClass.manifest!.id,
47
- BehaviorClass,
48
- ]));
49
- return {
50
- has: (id: string) => byId.has(id),
51
- prepare: async (id: string, input: unknown) => {
52
- const BehaviorClass = byId.get(id);
53
- if (!BehaviorClass) throw new Error(`Unknown behavior module '${id}'.`);
54
- return prepareClawclawBehavior(BehaviorClass, BehaviorClass.manifest!, input);
55
- },
56
- };
57
- }
58
-
59
- function driver(
60
- authorization: (activationId: string) => boolean = () => true,
61
- ): ClawclawBehaviorControlDriver {
62
- return {
63
- acquire: activation => ({
64
- caller: {
65
- kind: 'behavior',
66
- activationId: activation.activationId,
67
- layer: activation.layer,
68
- activationGeneration: activation.instanceGeneration,
69
- },
70
- scope,
71
- controllerId: `behavior:${activation.activationId}:${activation.instanceGeneration}`,
72
- isAuthorized: () => authorization(activation.activationId),
73
- release: vi.fn(),
74
- }),
75
- };
76
- }
77
-
78
- function event(commitSeq: number): CanonicalEvent {
79
- return {
80
- commitSeq,
81
- epochSeq: commitSeq,
82
- eventId: `event-${commitSeq}`,
83
- sessionId: scope.sessionId,
84
- segmentId: scope.segmentId,
85
- type: `event_${commitSeq}`,
86
- producer: 'backend_push',
87
- deliveryClass: 'monitor_and_events',
88
- occurredAt: new Date(commitSeq * 100).toISOString(),
89
- receivedAt: new Date(commitSeq * 100).toISOString(),
90
- payload: { commitSeq },
91
- sourceId: 'test',
92
- replayed: false,
93
- };
94
- }
95
-
96
- function input(
97
- epochSeq: number,
98
- options: Readonly<{
99
- tick?: number;
100
- nowMs?: number;
101
- phase?: string;
102
- role?: string;
103
- alive?: boolean;
104
- pendingEvents?: readonly CanonicalEvent[];
105
- }> = {},
106
- ): RuntimeEpochPluginInput<Record<string, any>> {
107
- const tick = options.tick ?? epochSeq;
108
- const gameState = {
109
- game_id: 'game',
110
- phase: options.phase ?? 'wandering',
111
- tick,
112
- you: {
113
- player: { name: 'self', seat: 1 },
114
- role: options.role ?? 'shrimp_generic',
115
- faction: 'lobster',
116
- x: 0,
117
- y: 0,
118
- room: 'navigation',
119
- is_alive: options.alive ?? true,
120
- activity: { kind: 'idle' },
121
- tasks: [],
122
- },
123
- players: [],
124
- visible_players: [],
125
- visible_corpses: [],
126
- };
127
- const state = {
128
- schema: 'clawclaw.runtime-state.v1',
129
- action_safety_generation: 7,
130
- stage: gameState.phase === 'meeting' ? 'meeting' : 'game',
131
- transport: 'game_ws',
132
- connection: 'connected',
133
- cause: 'game_snapshot',
134
- game_snapshot: { status: 'fresh', state: gameState },
135
- };
136
- const receivedAtMs = options.nowMs ?? epochSeq * 100;
137
- const frame: StoredStateFrame<Record<string, any>> = {
138
- frameSeq: epochSeq,
139
- epochSeq,
140
- scope,
141
- sourceId: 'test',
142
- connectionId: 'ws',
143
- sourceKey: `state:${epochSeq}`,
144
- backendTick: tick,
145
- receivedAtMs,
146
- state,
147
- };
148
- return {
149
- epoch: {
150
- epochSeq,
151
- scope,
152
- sourceId: 'test',
153
- connectionId: 'ws',
154
- sourceKey: `state:${epochSeq}`,
155
- domainTick: tick,
156
- state,
157
- events: [],
158
- completeness: 'complete',
159
- receivedAt: new Date(receivedAtMs).toISOString(),
160
- },
161
- frame,
162
- currentState: {
163
- state: gameState,
164
- stateStatus: {
165
- status: 'fresh', semantics: 'latest_received', source: 'owner_memory', scope,
166
- connectionId: 'ws', connectionState: 'connected', receivedAtMs,
167
- ageMs: 0, backendTick: tick, reason: null,
168
- },
169
- },
170
- previousState: null,
171
- epochEvents: [],
172
- pendingEvents: options.pendingEvents ?? [],
173
- upstreamStates: {},
174
- };
175
- }
176
-
177
- function context(
178
- actions: Array<Record<string, any>> = [],
179
- ): RuntimeEpochPluginContext<Record<string, any>> {
180
- const history = new MemoryStateHistoryRepository<unknown, Record<string, any>>();
181
- history.openScope(scope);
182
- return {
183
- scope,
184
- stateHistory: history,
185
- currentSegment: () => ({ kind: 'game', identity: 'game' }),
186
- checkpoint: () => undefined,
187
- progress: () => ({
188
- pluginId: 'clawclaw.behavior', completedThroughEpochSeq: 0, eventCursor: 0,
189
- updatedAt: new Date(0).toISOString(),
190
- }),
191
- capabilities: {
192
- provideObservation: () => { throw new Error('unused'); },
193
- provideAction: () => { throw new Error('unused'); },
194
- queryObservation: () => Promise.reject(new Error('unused')),
195
- performAction: (async (_capability: string, action: unknown) => {
196
- const request = action as Record<string, any>;
197
- if (request.action?.action === 'strategy') {
198
- return {
199
- scope,
200
- actionId: 'strategy-report-action',
201
- status: 'success',
202
- source: 'backend',
203
- actionOutcome: 'confirmed',
204
- value: { success: true, data: { ok: true } },
205
- };
206
- }
207
- actions.push(request);
208
- return {
209
- scope,
210
- actionId: `action-${actions.length}`,
211
- status: 'success',
212
- source: 'local',
213
- actionOutcome: 'unknown',
214
- value: { accepted: true, status: 'queued' },
215
- };
216
- }) as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
217
- },
218
- diagnostic: () => {},
219
- signal: new AbortController().signal,
220
- };
221
- }
222
-
223
- function successfulStrategyReportResult() {
224
- return {
225
- scope,
226
- actionId: 'strategy-report-action',
227
- status: 'success' as const,
228
- source: 'backend' as const,
229
- actionOutcome: 'confirmed' as const,
230
- value: { success: true, data: { ok: true } },
231
- };
232
- }
233
-
234
- function contextWithPerformAction(
235
- performAction: RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
236
- ): RuntimeEpochPluginContext<Record<string, any>> {
237
- const base = context();
238
- return {
239
- ...base,
240
- capabilities: { ...base.capabilities, performAction },
241
- };
242
- }
243
-
244
- async function step(
245
- plugin: ClawclawBehaviorPlugin,
246
- epoch: RuntimeEpochPluginInput<Record<string, any>>,
247
- ctx: RuntimeEpochPluginContext<Record<string, any>>,
248
- ): Promise<RuntimeEpochPluginResult> {
249
- const computation = await plugin.update(epoch, ctx);
250
- return plugin.commit(epoch, computation, ctx);
251
- }
252
-
253
- class LongBehavior extends ClawclawBehavior {
254
- static override readonly manifest = manifest('long');
255
- static instances = 0;
256
- readonly instance = ++LongBehavior.instances;
257
-
258
- override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
259
- return {
260
- status: { summary: `long instance ${this.instance}` },
261
- actions: [{ action: 'move', target_x: input.epochId, target_y: 1 }],
262
- };
263
- }
264
- }
265
-
266
- class ReportingLongBehavior extends ClawclawBehavior {
267
- static override readonly manifest = manifest('reporting-long', {
268
- name: 'Task only',
269
- description: 'Complete assigned tasks.',
270
- localizations: {
271
- 'zh-CN': { name: '纯任务', description: '专心完成分配的任务。' },
272
- },
273
- });
274
-
275
- override decide(): BehaviorDecision {
276
- return { status: { summary: 'working' } };
277
- }
278
- }
279
-
280
- class ReplacementLongBehavior extends ClawclawBehavior {
281
- static override readonly manifest = manifest('replacement-long', {
282
- name: '替代策略',
283
- description: '替代策略描述。',
284
- });
285
-
286
- override decide(): BehaviorDecision {
287
- return { status: { summary: 'replacement working' } };
288
- }
289
- }
290
-
291
- class ReportingOverlayBehavior extends ClawclawBehavior {
292
- static override readonly manifest = manifest('reporting-overlay', {
293
- name: '短任务',
294
- description: '不应上报为长程策略。',
295
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
296
- });
297
-
298
- override decide(): BehaviorDecision {
299
- return { status: { summary: 'overlay working' } };
300
- }
301
- }
302
-
303
- class FinishingShortBehavior extends ClawclawBehavior {
304
- static override readonly manifest = manifest('short', {
305
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
306
- });
307
-
308
- override decide(): BehaviorDecision {
309
- return {
310
- status: { summary: 'short finished' },
311
- finish: { outcome: 'completed', reason: 'done' },
312
- };
313
- }
314
- }
315
-
316
- class DelegatingLongBehavior extends ClawclawBehavior {
317
- static override readonly manifest = manifest('delegating-long');
318
- static frames: BehaviorInput[] = [];
319
- private continued = false;
320
-
321
- override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
322
- DelegatingLongBehavior.frames.push(input as BehaviorInput);
323
- if (input.continuation) {
324
- this.continued = true;
325
- return { status: { summary: `continued:${input.continuation.delegatedBehavior.outcome}` } };
326
- }
327
- if (this.continued) return { status: { summary: 'continued' } };
328
- return { delegate: { behavior: 'delegated-short', input: {} } };
329
- }
330
- }
331
-
332
- class DelegatedShortBehavior extends ClawclawBehavior {
333
- static override readonly manifest = manifest('delegated-short', {
334
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
335
- });
336
-
337
- override decide(): BehaviorDecision {
338
- return {
339
- finish: { outcome: 'completed', reason: 'delegated_done', summary: 'child summary' },
340
- };
341
- }
342
- }
343
-
344
- class InvalidDelegatingShortBehavior extends ClawclawBehavior {
345
- static override readonly manifest = manifest('invalid-delegating-short', {
346
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
347
- });
348
-
349
- override decide(): BehaviorDecision {
350
- return { delegate: { behavior: 'delegated-short' } };
351
- }
352
- }
353
-
354
- class OutcomeDelegatingLongBehavior extends ClawclawBehavior {
355
- static override readonly manifest = manifest('outcome-delegating-long');
356
- static target = 'delegated-short';
357
- static results: NonNullable<BehaviorInput['continuation']>['delegatedBehavior'][] = [];
358
- private continued = false;
359
-
360
- override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
361
- if (input.continuation) {
362
- this.continued = true;
363
- OutcomeDelegatingLongBehavior.results.push(input.continuation.delegatedBehavior);
364
- return { status: { summary: `outcome:${input.continuation.delegatedBehavior.outcome}` } };
365
- }
366
- if (this.continued) return { status: { summary: 'continued' } };
367
- return { delegate: { behavior: OutcomeDelegatingLongBehavior.target } };
368
- }
369
- }
370
-
371
- class FailingDelegatedShortBehavior extends ClawclawBehavior {
372
- static override readonly manifest = manifest('failing-delegated-short', {
373
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
374
- });
375
-
376
- override decide(): BehaviorDecision {
377
- return { finish: { outcome: 'failed', reason: 'child_failed', summary: 'failed summary' } };
378
- }
379
- }
380
-
381
- class WaitingDelegatedShortBehavior extends ClawclawBehavior {
382
- static override readonly manifest = manifest('waiting-delegated-short', {
383
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
384
- });
385
-
386
- override decide(): BehaviorDecision {
387
- return { status: { summary: 'waiting' } };
388
- }
389
- }
390
-
391
- class ReportBehavior extends ClawclawBehavior {
392
- static override readonly manifest = manifest('report', {
393
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
394
- });
395
- private submitted = false;
396
-
397
- override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
398
- if (this.submitted && input.gameState.phase === 'meeting') {
399
- return { finish: { outcome: 'completed', reason: 'corpse_reported' } };
400
- }
401
- this.submitted = true;
402
- return { actions: [{ action: 'report' }], status: { summary: 'reporting' } };
403
- }
404
- }
405
-
406
- class CadenceBehavior extends ClawclawBehavior {
407
- static override readonly manifest = manifest('cadence', { everyTicks: 3 });
408
- static frames: BehaviorInput[] = [];
409
- override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
410
- CadenceBehavior.frames.push(input as BehaviorInput);
411
- return { status: { summary: `cadence tick ${input.gameState.tick}` } };
412
- }
413
- }
414
-
415
- class GraceBehavior extends ClawclawBehavior {
416
- static override readonly manifest = manifest('grace', {
417
- runtime: { defaultMs: 5_000, deadlineOutcome: 'failed', controlGraceMs: 11_000 },
418
- });
419
- override decide(): void {}
420
- }
421
-
422
- class NormalizeFallbackBehavior extends ClawclawBehavior<Readonly<{ internal: string }>> {
423
- static override readonly manifest = manifest('normalized-fallback', {
424
- inputs: [{ id: 'public_value', type: 'string', required: true, description: 'value' }],
425
- });
426
- static normalizeCalls = 0;
427
- override normalize(input: Readonly<Record<string, unknown>>) {
428
- NormalizeFallbackBehavior.normalizeCalls += 1;
429
- return { internal: `normalized:${String(input.public_value)}` } as const;
430
- }
431
- override decide(input: Readonly<BehaviorInput<Readonly<{ internal: string }>>>): BehaviorDecision {
432
- return { status: { summary: input.input.internal } };
433
- }
434
- }
435
-
436
- class EventFinishBehavior extends ClawclawBehavior {
437
- static override readonly manifest = manifest('event-finish', {
438
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
439
- produces: ['fixture.finished'],
440
- });
441
- override decide(): BehaviorDecision {
442
- return {
443
- events: [{ type: 'fixture.finished', payload: { ok: true } }],
444
- finish: { outcome: 'completed', reason: 'done' },
445
- };
446
- }
447
- }
448
-
449
- class ActionFinishBehavior extends ClawclawBehavior {
450
- static override readonly manifest = manifest('action-finish', {
451
- runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
452
- });
453
- override decide(): BehaviorDecision {
454
- return {
455
- actions: [{ action: 'move', target_x: 1, target_y: 2 }],
456
- finish: { outcome: 'completed', reason: 'unsafe_same_decision' },
457
- };
458
- }
459
- }
460
-
461
- class ActionDelegatingBehavior extends ClawclawBehavior {
462
- static override readonly manifest = manifest('action-delegating');
463
- override decide(): BehaviorDecision {
464
- return {
465
- actions: [{ action: 'move', target_x: 1, target_y: 2 }],
466
- delegate: { behavior: 'delegated-short' },
467
- };
468
- }
469
- }
470
-
471
- class SlowBehavior extends ClawclawBehavior {
472
- static override readonly manifest = manifest('slow');
473
- static onDecide: (() => void) | undefined;
474
- override decide(): Promise<BehaviorDecision> {
475
- SlowBehavior.onDecide?.();
476
- return new Promise(() => {});
477
- }
478
- }
479
-
480
- describe('Clawclaw unified Behavior plugin', () => {
481
- it('runs a long Behavior and submits generic Behavior action preconditions', async () => {
482
- const actions: Array<Record<string, any>> = [];
483
- const plugin = new ClawclawBehaviorPlugin({
484
- catalog: catalog([LongBehavior]),
485
- driver: driver(),
486
- createActivationId: () => 'long-1',
487
- now: () => 0,
488
- });
489
- const ctx = context(actions);
490
- plugin.start(ctx);
491
- await plugin.startLong('long', {}, { source: 'agent' });
492
-
493
- const result = await step(plugin, input(1), ctx);
494
- expect(actions).toEqual([expect.objectContaining({
495
- behaviorOriginEpochSeq: 1,
496
- behaviorActionSafetyGeneration: 7,
497
- behaviorActivationGeneration: 1,
498
- action: { action: 'move', target_x: 1, target_y: 1 },
499
- })]);
500
- expect(result).toMatchObject({
501
- outcome: 'processed',
502
- states: [{
503
- topic: CLAWCLAW_BEHAVIOR_STATE_TOPIC,
504
- value: {
505
- running: true,
506
- activation_id: 'long-1',
507
- behavior: 'long',
508
- layer: 'long',
509
- status: { summary: 'long instance 1' },
510
- },
511
- }],
512
- events: [expect.objectContaining({ type: 'behavior.started' })],
513
- });
514
- });
515
-
516
- it('reports the persistent long Behavior asynchronously and ignores a short overlay', async () => {
517
- vi.useFakeTimers();
518
- try {
519
- let resolveReport!: (value: ReturnType<typeof successfulStrategyReportResult>) => void;
520
- const pendingReport = new Promise<ReturnType<typeof successfulStrategyReportResult>>((resolve) => {
521
- resolveReport = resolve;
522
- });
523
- const performAction = vi.fn(() => pendingReport);
524
- const ctx = contextWithPerformAction(
525
- performAction as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
526
- );
527
- let id = 0;
528
- const plugin = new ClawclawBehaviorPlugin({
529
- catalog: catalog([ReportingLongBehavior, ReportingOverlayBehavior]),
530
- driver: driver(),
531
- createActivationId: () => `reporting-${++id}`,
532
- now: () => 0,
533
- });
534
- await plugin.start(ctx);
535
- await plugin.startLong('reporting-long', {}, { source: 'agent' });
536
-
537
- await step(plugin, input(1), ctx);
538
- expect(performAction).not.toHaveBeenCalled();
539
- await vi.advanceTimersByTimeAsync(0);
540
- expect(performAction).toHaveBeenCalledTimes(1);
541
- expect(performAction).toHaveBeenCalledWith('clawclaw.action', {
542
- route: 'game',
543
- action: {
544
- action: 'strategy',
545
- name: '纯任务',
546
- description: '专心完成分配的任务。',
547
- },
548
- });
549
-
550
- resolveReport(successfulStrategyReportResult());
551
- await Promise.resolve();
552
- await Promise.resolve();
553
- await plugin.startShort('reporting-overlay', {}, { source: 'agent' });
554
- await step(plugin, input(2), ctx);
555
- await vi.advanceTimersByTimeAsync(5_000);
556
- expect(performAction).toHaveBeenCalledTimes(1);
557
- await plugin.stop('shutdown');
558
- } finally {
559
- vi.useRealTimers();
560
- }
561
- });
562
-
563
- it('retries an invalid backend Strategy report once per second until acknowledged', async () => {
564
- vi.useFakeTimers();
565
- try {
566
- const performAction = vi.fn()
567
- .mockResolvedValueOnce({
568
- ...successfulStrategyReportResult(),
569
- value: { success: true, data: { ok: false } },
570
- })
571
- .mockResolvedValue(successfulStrategyReportResult());
572
- const ctx = contextWithPerformAction(
573
- performAction as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
574
- );
575
- const plugin = new ClawclawBehaviorPlugin({
576
- catalog: catalog([ReportingLongBehavior]),
577
- driver: driver(),
578
- createActivationId: () => 'report-retry',
579
- now: () => 0,
580
- });
581
- await plugin.start(ctx);
582
- await plugin.startLong('reporting-long', {}, { source: 'agent' });
583
-
584
- await step(plugin, input(1), ctx);
585
- await vi.advanceTimersByTimeAsync(0);
586
- expect(performAction).toHaveBeenCalledTimes(1);
587
- await vi.advanceTimersByTimeAsync(999);
588
- expect(performAction).toHaveBeenCalledTimes(1);
589
- await vi.advanceTimersByTimeAsync(1);
590
- expect(performAction).toHaveBeenCalledTimes(2);
591
- await vi.advanceTimersByTimeAsync(5_000);
592
- expect(performAction).toHaveBeenCalledTimes(2);
593
- await plugin.stop('shutdown');
594
- } finally {
595
- vi.useRealTimers();
596
- }
597
- });
598
-
599
- it('does not let an old in-flight acknowledgement confirm a replacement long Behavior', async () => {
600
- vi.useFakeTimers();
601
- try {
602
- let resolveFirst!: (value: ReturnType<typeof successfulStrategyReportResult>) => void;
603
- const first = new Promise<ReturnType<typeof successfulStrategyReportResult>>((resolve) => {
604
- resolveFirst = resolve;
605
- });
606
- const performAction = vi.fn()
607
- .mockImplementationOnce(() => first)
608
- .mockResolvedValue(successfulStrategyReportResult());
609
- const ctx = contextWithPerformAction(
610
- performAction as RuntimeEpochPluginContext<Record<string, any>>['capabilities']['performAction'],
611
- );
612
- let id = 0;
613
- const plugin = new ClawclawBehaviorPlugin({
614
- catalog: catalog([ReportingLongBehavior, ReplacementLongBehavior]),
615
- driver: driver(),
616
- createActivationId: () => `replacement-${++id}`,
617
- now: () => 0,
618
- });
619
- await plugin.start(ctx);
620
- await plugin.startLong('reporting-long', {}, { source: 'agent' });
621
- await step(plugin, input(1), ctx);
622
- await vi.advanceTimersByTimeAsync(0);
623
- expect(performAction).toHaveBeenCalledTimes(1);
624
-
625
- await plugin.startLong('replacement-long', {}, { source: 'agent' });
626
- await step(plugin, input(2), ctx);
627
- await vi.advanceTimersByTimeAsync(0);
628
- expect(performAction).toHaveBeenCalledTimes(1);
629
-
630
- resolveFirst(successfulStrategyReportResult());
631
- await Promise.resolve();
632
- await Promise.resolve();
633
- await vi.advanceTimersByTimeAsync(0);
634
- expect(performAction).toHaveBeenCalledTimes(2);
635
- expect(performAction.mock.calls[1]?.[1]).toMatchObject({
636
- action: {
637
- action: 'strategy',
638
- name: '替代策略',
639
- description: '替代策略描述。',
640
- },
641
- });
642
- await plugin.stop('shutdown');
643
- } finally {
644
- vi.useRealTimers();
645
- }
646
- });
647
-
648
- it('fresh-restarts the suspended long only after the shared 500ms delay', async () => {
649
- LongBehavior.instances = 0;
650
- const manager = new BehaviorActivationManager();
651
- let id = 0;
652
- const plugin = new ClawclawBehaviorPlugin({
653
- catalog: catalog([LongBehavior, FinishingShortBehavior]),
654
- manager,
655
- driver: driver(),
656
- createActivationId: () => `activation-${++id}`,
657
- now: () => 0,
658
- });
659
- const ctx = context();
660
- plugin.start(ctx);
661
- await plugin.startLong('long', {}, { source: 'agent' });
662
- await step(plugin, input(1, { nowMs: 100 }), ctx);
663
- await plugin.startShort('short', {}, { source: 'agent' });
664
- const shortResult = await step(plugin, input(2, { nowMs: 200 }), ctx);
665
- expect(shortResult.events).toEqual(expect.arrayContaining([
666
- expect.objectContaining({ type: 'behavior.suspended' }),
667
- expect.objectContaining({ type: 'behavior.started' }),
668
- expect.objectContaining({ type: 'behavior.completed' }),
669
- ]));
670
- expect(manager.current()).toBeUndefined();
671
-
672
- await step(plugin, input(3, { nowMs: 699 }), ctx);
673
- expect(manager.current()).toBeUndefined();
674
- await step(plugin, input(4, { nowMs: 700 }), ctx);
675
- expect(manager.current()).toMatchObject({
676
- activationId: 'activation-1', instanceGeneration: 2,
677
- });
678
- const resumed = await step(plugin, input(5, { nowMs: 701 }), ctx);
679
- expect(resumed.states).toEqual([
680
- expect.objectContaining({
681
- value: expect.objectContaining({ status: { summary: 'long instance 2' } }),
682
- }),
683
- ]);
684
- });
685
-
686
- it('lets a long delegate one short and receives its terminal result once after fresh restart', async () => {
687
- DelegatingLongBehavior.frames = [];
688
- let id = 0;
689
- const plugin = new ClawclawBehaviorPlugin({
690
- catalog: catalog([DelegatingLongBehavior, DelegatedShortBehavior]),
691
- driver: driver(),
692
- createActivationId: () => `delegation-${++id}`,
693
- now: () => 0,
694
- });
695
- const ctx = context();
696
- await plugin.start(ctx);
697
- await plugin.startLong('delegating-long', {}, { source: 'agent' });
698
-
699
- const delegated = await step(plugin, input(1, { nowMs: 100 }), ctx);
700
- expect(plugin.status().current).toMatchObject({
701
- activationId: 'delegation-2',
702
- behaviorId: 'delegated-short',
703
- layer: 'short',
704
- source: 'behavior',
705
- });
706
- expect(delegated.events).toEqual(expect.arrayContaining([
707
- expect.objectContaining({ type: 'behavior.suspended' }),
708
- expect.objectContaining({ type: 'behavior.started' }),
709
- ]));
710
-
711
- await step(plugin, input(2, { nowMs: 200 }), ctx);
712
- await step(plugin, input(3, { nowMs: 699 }), ctx);
713
- await step(plugin, input(4, { nowMs: 700 }), ctx);
714
- const resumed = await step(plugin, input(5, { nowMs: 701 }), ctx);
715
- expect(resumed.states).toEqual([
716
- expect.objectContaining({
717
- value: expect.objectContaining({ status: { summary: 'continued:completed' } }),
718
- }),
719
- ]);
720
- expect(DelegatingLongBehavior.frames.at(-1)?.continuation).toEqual({
721
- delegatedBehavior: {
722
- activationId: 'delegation-2',
723
- behavior: 'delegated-short',
724
- outcome: 'completed',
725
- reason: 'delegated_done',
726
- summary: 'child summary',
727
- },
728
- });
729
-
730
- await step(plugin, input(6, { nowMs: 702 }), ctx);
731
- expect(DelegatingLongBehavior.frames.at(-1)?.continuation).toBeUndefined();
732
- });
733
-
734
- it('fails closed when a short Behavior attempts recursive delegation', async () => {
735
- let id = 0;
736
- const plugin = new ClawclawBehaviorPlugin({
737
- catalog: catalog([InvalidDelegatingShortBehavior, DelegatedShortBehavior]),
738
- driver: driver(),
739
- createActivationId: () => `invalid-delegation-${++id}`,
740
- now: () => 0,
741
- });
742
- const ctx = context();
743
- await plugin.start(ctx);
744
- await plugin.startShort('invalid-delegating-short', {}, { source: 'agent' });
745
-
746
- const result = await step(plugin, input(1), ctx);
747
- expect(result.events).toEqual(expect.arrayContaining([
748
- expect.objectContaining({
749
- type: 'behavior.failed',
750
- payload: expect.objectContaining({ reason: 'behavior_delegate_layer_invalid' }),
751
- }),
752
- ]));
753
- });
754
-
755
- it('returns failed, cancelled, and replaced delegated outcomes to the original long', async () => {
756
- const cases = [
757
- {
758
- outcome: 'failed',
759
- target: 'failing-delegated-short',
760
- prepare: async (_plugin: ClawclawBehaviorPlugin, _childId: string, _setNow: (value: number) => void) => {},
761
- reason: 'child_failed',
762
- summary: 'failed summary',
763
- },
764
- {
765
- outcome: 'cancelled',
766
- target: 'waiting-delegated-short',
767
- prepare: async (plugin: ClawclawBehaviorPlugin, childId: string, setNow: (value: number) => void) => {
768
- setNow(200);
769
- await plugin.cancel(childId, 'cancelled_by_test');
770
- },
771
- reason: 'cancelled_by_test',
772
- },
773
- {
774
- outcome: 'replaced',
775
- target: 'waiting-delegated-short',
776
- prepare: async (plugin: ClawclawBehaviorPlugin, _childId: string, setNow: (value: number) => void) => {
777
- setNow(200);
778
- await plugin.startShort('delegated-short', {}, { source: 'agent' });
779
- },
780
- reason: 'short_replaced',
781
- },
782
- ] as const;
783
-
784
- for (const [index, testCase] of cases.entries()) {
785
- let id = 0;
786
- let now = 100;
787
- OutcomeDelegatingLongBehavior.target = testCase.target;
788
- OutcomeDelegatingLongBehavior.results = [];
789
- const plugin = new ClawclawBehaviorPlugin({
790
- catalog: catalog([
791
- OutcomeDelegatingLongBehavior,
792
- DelegatedShortBehavior,
793
- FailingDelegatedShortBehavior,
794
- WaitingDelegatedShortBehavior,
795
- ]),
796
- driver: driver(),
797
- createActivationId: () => `terminal-${index}-${++id}`,
798
- now: () => now,
799
- });
800
- const ctx = context();
801
- await plugin.start(ctx);
802
- await plugin.startLong('outcome-delegating-long', {}, { source: 'agent' });
803
- await step(plugin, input(1, { nowMs: 100 }), ctx);
804
- const childId = plugin.status().current!.activationId;
805
- await testCase.prepare(plugin, childId, (value) => { now = value; });
806
- if (testCase.outcome !== 'cancelled') {
807
- await step(plugin, input(2, { nowMs: 200 }), ctx);
808
- }
809
- await step(plugin, input(3, { nowMs: 699 }), ctx);
810
- await step(plugin, input(4, { nowMs: 700 }), ctx);
811
- await step(plugin, input(5, { nowMs: 701 }), ctx);
812
-
813
- expect(OutcomeDelegatingLongBehavior.results).toEqual([
814
- expect.objectContaining({
815
- activationId: childId,
816
- behavior: testCase.target,
817
- outcome: testCase.outcome,
818
- reason: testCase.reason,
819
- ...('summary' in testCase ? { summary: testCase.summary } : {}),
820
- }),
821
- ]);
822
- await plugin.stop('shutdown');
823
- }
824
- });
825
-
826
- it('lets a report short observe meeting authority before cancelling the wandering boundary', async () => {
827
- const actions: Array<Record<string, any>> = [];
828
- const plugin = new ClawclawBehaviorPlugin({
829
- catalog: catalog([ReportBehavior]),
830
- driver: driver(),
831
- createActivationId: () => 'report-1',
832
- now: () => 0,
833
- });
834
- const ctx = context(actions);
835
- plugin.start(ctx);
836
- await plugin.startShort('report', {}, { source: 'agent' });
837
- await step(plugin, input(1, { nowMs: 100 }), ctx);
838
- expect(actions).toHaveLength(1);
839
-
840
- const result = await step(plugin, input(2, { phase: 'meeting', nowMs: 200 }), ctx);
841
- expect(result.events).toEqual(expect.arrayContaining([
842
- expect.objectContaining({
843
- type: 'behavior.completed',
844
- payload: expect.objectContaining({ reason: 'corpse_reported' }),
845
- }),
846
- ]));
847
- expect(result.events).not.toEqual(expect.arrayContaining([
848
- expect.objectContaining({ type: 'behavior.cancelled' }),
849
- ]));
850
- expect(plugin.status().running).toBe(false);
851
- });
852
-
853
- it('retains pending Events across cadence skips', async () => {
854
- CadenceBehavior.frames = [];
855
- const plugin = new ClawclawBehaviorPlugin({
856
- catalog: catalog([CadenceBehavior]),
857
- driver: driver(),
858
- createActivationId: () => 'cadence-1',
859
- now: () => 0,
860
- });
861
- const ctx = context();
862
- plugin.start(ctx);
863
- await plugin.startLong('cadence', {}, { source: 'agent' });
864
- const first = await step(plugin, input(1, {
865
- tick: 10, nowMs: 100, pendingEvents: [event(1)],
866
- }), ctx);
867
- expect(first.consumeEventsThroughCommitSeq).toBe(1);
868
-
869
- const skipped = await step(plugin, input(2, {
870
- tick: 12, nowMs: 200, pendingEvents: [event(2)],
871
- }), ctx);
872
- expect(skipped.consumeEventsThroughCommitSeq).toBeUndefined();
873
- expect(skipped.states).toEqual([
874
- expect.objectContaining({
875
- value: expect.objectContaining({ status: { summary: 'cadence tick 10' } }),
876
- }),
877
- ]);
878
- await step(plugin, input(3, {
879
- tick: 13, nowMs: 300, pendingEvents: [event(2)],
880
- }), ctx);
881
- expect(CadenceBehavior.frames.map(frame => frame.gameState.tick)).toEqual([10, 13]);
882
- expect(CadenceBehavior.frames[1]!.events.map(candidate => candidate.eventId)).toEqual(['event-2']);
883
- });
884
-
885
- it('extends a finite activation deadline by manifest controlGraceMs', async () => {
886
- const plugin = new ClawclawBehaviorPlugin({
887
- catalog: catalog([GraceBehavior]),
888
- driver: driver(),
889
- createActivationId: () => 'grace-1',
890
- now: () => 0,
891
- });
892
- await plugin.start(context());
893
- const activation = await plugin.startShort('grace', {}, { source: 'agent' });
894
- expect(activation).toMatchObject({
895
- maxRuntimeMs: 16_000,
896
- deadlineAt: 16_000,
897
- });
898
- });
899
-
900
- it('rearms a persisted fallback after a segment stop and normalizes its binding once', async () => {
901
- NormalizeFallbackBehavior.normalizeCalls = 0;
902
- let now = 0;
903
- const plugin = new ClawclawBehaviorPlugin({
904
- catalog: catalog([NormalizeFallbackBehavior]),
905
- driver: driver(),
906
- createActivationId: () => 'fallback-1',
907
- now: () => now,
908
- });
909
- const ctx = context();
910
- await plugin.start(ctx);
911
- await plugin.bindFallback('normalized-fallback', { public_value: 'one' });
912
- expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
913
- await step(plugin, input(1, { nowMs: 500 }), ctx);
914
- expect(plugin.status().current).toMatchObject({ behaviorId: 'normalized-fallback' });
915
- expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
916
-
917
- now = 600;
918
- await plugin.stop('segment_ending');
919
- now = 1_000;
920
- await plugin.start(ctx);
921
- await step(plugin, input(2, { nowMs: 1_499 }), ctx);
922
- expect(plugin.status().current).toBeUndefined();
923
- await step(plugin, input(3, { nowMs: 1_500 }), ctx);
924
- expect(plugin.status().current).toMatchObject({ behaviorId: 'normalized-fallback' });
925
- const restarted = await step(plugin, input(4, { nowMs: 1_501 }), ctx);
926
- expect(restarted.states).toEqual([
927
- expect.objectContaining({
928
- value: expect.objectContaining({ status: { summary: 'normalized:one' } }),
929
- }),
930
- ]);
931
- expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
932
- });
933
-
934
- it('lazily binds the configured fallback after the authoritative role is known', async () => {
935
- NormalizeFallbackBehavior.normalizeCalls = 0;
936
- const plugin = new ClawclawBehaviorPlugin({
937
- catalog: catalog([NormalizeFallbackBehavior]),
938
- driver: driver(),
939
- fallbackBehaviors: {
940
- shrimp_generic: {
941
- behaviorId: 'normalized-fallback',
942
- input: { public_value: 'role-default' },
943
- },
944
- },
945
- createActivationId: () => 'role-fallback-1',
946
- now: () => 0,
947
- });
948
- const ctx = context();
949
- await plugin.start(ctx);
950
-
951
- await step(plugin, input(1, { nowMs: 0 }), ctx);
952
- expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
953
- expect(plugin.status().current).toBeUndefined();
954
- await step(plugin, input(2, { nowMs: 499 }), ctx);
955
- expect(plugin.status().current).toBeUndefined();
956
- await step(plugin, input(3, { nowMs: 500 }), ctx);
957
- expect(plugin.status().current).toMatchObject({
958
- behaviorId: 'normalized-fallback',
959
- source: 'idle',
960
- });
961
- const running = await step(plugin, input(4, { nowMs: 501 }), ctx);
962
- expect(running.states).toEqual([
963
- expect.objectContaining({
964
- value: expect.objectContaining({ status: { summary: 'normalized:role-default' } }),
965
- }),
966
- ]);
967
- expect(NormalizeFallbackBehavior.normalizeCalls).toBe(1);
968
- });
969
-
970
- it('publishes decision Events before the completion lifecycle Event', async () => {
971
- const plugin = new ClawclawBehaviorPlugin({
972
- catalog: catalog([EventFinishBehavior]),
973
- driver: driver(),
974
- createActivationId: () => 'event-finish-1',
975
- now: () => 0,
976
- });
977
- const ctx = context();
978
- await plugin.start(ctx);
979
- await plugin.startShort('event-finish', {}, { source: 'agent' });
980
- const result = await step(plugin, input(1), ctx);
981
- expect(result.events?.map(candidate => candidate.type)).toEqual([
982
- 'behavior.started',
983
- 'fixture.finished',
984
- 'behavior.completed',
985
- ]);
986
- });
987
-
988
- it('rejects actions and finish in the same Decision before submitting an Action', async () => {
989
- const actions: Array<Record<string, any>> = [];
990
- const plugin = new ClawclawBehaviorPlugin({
991
- catalog: catalog([ActionFinishBehavior]),
992
- driver: driver(),
993
- createActivationId: () => 'action-finish-1',
994
- now: () => 0,
995
- });
996
- const ctx = context(actions);
997
- await plugin.start(ctx);
998
- await plugin.startShort('action-finish', {}, { source: 'agent' });
999
- const result = await step(plugin, input(1), ctx);
1000
- expect(actions).toEqual([]);
1001
- expect(result.events).toEqual(expect.arrayContaining([
1002
- expect.objectContaining({
1003
- type: 'behavior.failed',
1004
- payload: expect.objectContaining({ reason: 'behavior_finish_with_actions_invalid' }),
1005
- }),
1006
- ]));
1007
- });
1008
-
1009
- it('rejects actions and delegation in the same Decision before submitting an Action', async () => {
1010
- const actions: Array<Record<string, any>> = [];
1011
- const plugin = new ClawclawBehaviorPlugin({
1012
- catalog: catalog([ActionDelegatingBehavior, DelegatedShortBehavior]),
1013
- driver: driver(),
1014
- createActivationId: () => 'action-delegating-1',
1015
- now: () => 0,
1016
- });
1017
- const ctx = context(actions);
1018
- await plugin.start(ctx);
1019
- await plugin.startLong('action-delegating', {}, { source: 'agent' });
1020
- const result = await step(plugin, input(1), ctx);
1021
- expect(actions).toEqual([]);
1022
- expect(result.events).toEqual(expect.arrayContaining([
1023
- expect.objectContaining({
1024
- type: 'behavior.failed',
1025
- payload: expect.objectContaining({ reason: 'behavior_delegate_with_actions_invalid' }),
1026
- }),
1027
- ]));
1028
- });
1029
-
1030
- it('interrupts a slow serial Decision before admitting a higher reflex', async () => {
1031
- let entered!: () => void;
1032
- const deciding = new Promise<void>((resolve) => { entered = resolve; });
1033
- SlowBehavior.onDecide = entered;
1034
- let id = 0;
1035
- const plugin = new ClawclawBehaviorPlugin({
1036
- catalog: catalog([SlowBehavior, GraceBehavior]),
1037
- driver: driver(),
1038
- createActivationId: () => `preempt-${++id}`,
1039
- decisionTimeoutMs: 10_000,
1040
- now: () => 0,
1041
- });
1042
- const ctx = context();
1043
- await plugin.start(ctx);
1044
- await plugin.startLong('slow', {}, { source: 'agent' });
1045
- const slowStep = step(plugin, input(1), ctx);
1046
- await deciding;
1047
-
1048
- const reflex = await plugin.requestReflex({
1049
- source: 'trigger',
1050
- triggerId: 'danger',
1051
- scope: { sessionId: scope.sessionId, segmentId: scope.segmentId },
1052
- epochId: 2,
1053
- configGeneration: 1,
1054
- behavior: 'grace',
1055
- behaviorInput: {},
1056
- reflexPriority: 10,
1057
- maxRuntimeMs: 5_000,
1058
- reason: 'danger_detected',
1059
- }, { isCurrent: () => true });
1060
-
1061
- expect(reflex).toMatchObject({ accepted: true });
1062
- await slowStep;
1063
- expect(plugin.status().current).toMatchObject({
1064
- behaviorId: 'grace',
1065
- layer: 'reflex',
1066
- });
1067
- });
1068
-
1069
- it('rejects a Trigger request whose configuration changes during prepare', async () => {
1070
- let current = true;
1071
- const plugin = new ClawclawBehaviorPlugin({
1072
- catalog: catalog([GraceBehavior]),
1073
- driver: driver(),
1074
- createActivationId: () => 'stale-reflex',
1075
- now: () => 0,
1076
- });
1077
- await plugin.start(context());
1078
- const request = plugin.requestReflex({
1079
- source: 'trigger',
1080
- triggerId: 'changed-rule',
1081
- scope: { sessionId: scope.sessionId, segmentId: scope.segmentId },
1082
- epochId: 1,
1083
- configGeneration: 1,
1084
- behavior: 'grace',
1085
- behaviorInput: {},
1086
- reflexPriority: 1,
1087
- maxRuntimeMs: 5_000,
1088
- reason: 'old_configuration',
1089
- }, { isCurrent: () => current });
1090
- current = false;
1091
- await expect(request).resolves.toEqual({ accepted: false, reason: 'stale_request' });
1092
- expect(plugin.status().current).toBeUndefined();
1093
- });
1094
- });