@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
@@ -294,8 +294,11 @@ function voteTargetLabel(target: unknown, ctx: EventFormatContext): string {
294
294
  return raw === 'skip' ? 'skip' : playerLabel(raw, undefined, ctx);
295
295
  }
296
296
 
297
- function formatVotes(votes: unknown, ctx: EventFormatContext): Record<string, string> | undefined {
298
- if (!votes || typeof votes !== 'object' || Array.isArray(votes)) return undefined;
297
+ function formatVotes(votes: unknown, ctx: EventFormatContext): unknown[] | Record<string, string> | undefined {
298
+ // GameSync supplies [voter seat, target seat | null]. These identities already
299
+ // address players directly; do not reinterpret them as names or rebuild them from State.
300
+ if (Array.isArray(votes)) return structuredClone(votes);
301
+ if (!votes || typeof votes !== 'object') return undefined;
299
302
  const out: Record<string, string> = {};
300
303
  for (const [voter, target] of Object.entries(votes)) {
301
304
  out[playerLabel(voter, undefined, ctx)] = voteTargetLabel(target, ctx);
@@ -412,21 +415,7 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
412
415
  return `你误杀了${playerLabel(event.target_name, firstNumber(event, ['target_seat', 'target_player_seat']), ctx)},武士虾自爆出局。`;
413
416
  case 'task_completed': {
414
417
  const fakeNote = event.is_fake_shrimp ? '(伪装)' : '';
415
- const assigned = event.newly_assigned_task;
416
- const assignedTask = assigned && typeof assigned === 'object' && !Array.isArray(assigned)
417
- ? assigned as Record<string, any>
418
- : null;
419
- const assignedName = assignedTask ? firstString(assignedTask, ['name', 'task_name'], '') : '';
420
- const assignedDetails = assignedTask
421
- ? [
422
- stringValue(assignedTask.room),
423
- assignedTask.is_fake_shrimp === true ? '伪装' : undefined,
424
- ].filter((value): value is string => value !== undefined)
425
- : [];
426
- const assignmentText = assignedName
427
- ? `;新分配任务:${assignedName}${assignedDetails.length > 0 ? `(${assignedDetails.join(',')})` : ''}`
428
- : '';
429
- return `任务完成:${firstString(event, ['task_name'])}${fakeNote}${assignmentText}。`;
418
+ return `任务完成:${firstString(event, ['task_name'])}${fakeNote}。`;
430
419
  }
431
420
  case 'task_sabotaged':
432
421
  return `破坏任务完成:${firstString(event, ['task_name'])}(${firstString(event, ['room'])})。`;
@@ -509,8 +498,8 @@ function shortBody(event: Record<string, any>, ctx: EventFormatContext): string
509
498
  case 'vote_speech_phase_ended':
510
499
  return '投票弹幕窗口已关闭。';
511
500
  case 'exile': {
512
- const exiledName = event.result_target ?? event.actor_name;
513
- const exiledSeat = firstNumber(event, ['result_target_seat', 'actor_seat', 'seat']);
501
+ const exiledName = event.exiled_player?.name ?? event.result_target ?? event.actor_name;
502
+ const exiledSeat = numberValue(event.exiled_player?.seat) ?? firstNumber(event, ['result_target_seat', 'actor_seat', 'seat']);
514
503
  return `会议结束:${playerLabel(exiledName, exiledSeat, ctx)}被放逐。`;
515
504
  }
516
505
  case 'no_exile':
@@ -759,13 +748,15 @@ function compactVoteCastForEvents(event: Record<string, any>, ctx: EventFormatCo
759
748
  function compactMeetingResultForEvents(event: Record<string, any>, ctx: EventFormatContext): FormattedEvent {
760
749
  const {
761
750
  votes: _votes,
751
+ actor_name: _actorName,
752
+ actor_seat: _actorSeat,
762
753
  ...rest
763
754
  } = event;
764
755
  const exiledName = event.type === 'exile'
765
- ? event.result_target ?? event.actor_name
756
+ ? event.exiled_player?.name ?? event.result_target ?? event.actor_name
766
757
  : undefined;
767
758
  const exiledSeat = event.type === 'exile'
768
- ? firstNumber(event, ['result_target_seat', 'actor_seat', 'seat'])
759
+ ? numberValue(event.exiled_player?.seat) ?? firstNumber(event, ['result_target_seat', 'actor_seat', 'seat'])
769
760
  : undefined;
770
761
  return cleanObject({
771
762
  ...rest,
@@ -16,7 +16,7 @@ export interface EventHintOrigin {
16
16
  }
17
17
 
18
18
  export const CLAWCLAW_SOURCE_PLUGIN_ID = 'clawclaw.source';
19
- export const CLAWCLAW_DERIVED_EVENT_PLUGIN_ID = 'clawclaw.derived-event';
19
+ export const CLAWCLAW_FLOW_PERCEPTION_PLUGIN_ID = 'clawclaw.perception.system.flow';
20
20
 
21
21
  const ROOM_GAME_OVER_HINT = 'This room round has ended. Review the result with the user, wait for the room lifecycle to resume, and do not start normal matchmaking.';
22
22
 
@@ -222,13 +222,13 @@ export const BACKEND_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFor
222
222
  + 'The emergency is still active and needs another response.'
223
223
  ),
224
224
  exile: (event) => (
225
- `Meeting ended — ${actorName(event, text(event.result_target, 'Someone'))} was exiled by the table. `
225
+ `Meeting ended — ${text(event.exiled_player?.name, actorName(event, text(event.result_target, 'Someone')))} was exiled by the table. `
226
226
  + 'If this is you, your influence is dead — tell your user and ask whether to spectate or leave.'
227
227
  ),
228
228
  no_exile: () => 'Meeting ended — no one was exiled. The table failed to strike, and every hidden threat gets another turn.',
229
229
  meeting_briefing: (event) => meetingBriefingHint(event),
230
230
  speech_skipped: (event) => `${actorName(event, 'Someone')} lost the floor — silence becomes evidence`,
231
- speech_your_turn: () => 'Submit `ccl speak "<draft>"` immediately. Server skips you after 45s.',
231
+ speech_your_turn: () => 'Submit `ccl speak "<draft>"` immediately, before any query or narration. Server skips you after 45s.',
232
232
  speech_next_turn: (event) => (
233
233
  `You speak next after ${text(event.current_speaker, 'the current speaker')}. Prepare your response now.`
234
234
  ),
@@ -369,7 +369,7 @@ export const LOCAL_LIFECYCLE_EVENT_HINT_FORMATTERS: Readonly<Record<string, Even
369
369
  ),
370
370
  });
371
371
 
372
- export const DERIVED_EVENT_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
372
+ export const FLOW_PERCEPTION_HINT_FORMATTERS: Readonly<Record<string, EventHintFormatter>> = Object.freeze({
373
373
  room_ready_to_start: (event) => (
374
374
  `The room is ready to start and you are the owner. Ask the user whether to start now before running \`${isTrainingRoomMode(event.room_type) ? 'ccl game training start' : 'ccl game start-room'}\`.`
375
375
  ),
@@ -387,8 +387,8 @@ export function formatCanonicalEventHint(
387
387
  }
388
388
  if (origin.producer !== 'local_synth') return undefined;
389
389
 
390
- if (origin.producerPluginId === CLAWCLAW_DERIVED_EVENT_PLUGIN_ID) {
391
- return DERIVED_EVENT_HINT_FORMATTERS[event.type]?.(event, ctx);
390
+ if (origin.producerPluginId === CLAWCLAW_FLOW_PERCEPTION_PLUGIN_ID) {
391
+ return FLOW_PERCEPTION_HINT_FORMATTERS[event.type]?.(event, ctx);
392
392
  }
393
393
  // Source input Events currently enter the Runtime without a plugin id;
394
394
  // epoch-plugin proposals always carry one, so Strategy/Perception cannot
@@ -16,8 +16,20 @@ export interface RejectedGameSyncEventEntry {
16
16
  export interface GameSyncEventNormalizationResult {
17
17
  events: NormalizedGameSyncEventEntry[];
18
18
  rejected: RejectedGameSyncEventEntry[];
19
+ /** Non-fatal format ambiguity; the original field remains available. */
20
+ warnings?: Array<GameSyncEventNormalizationWarning & { index: number }>;
19
21
  }
20
22
 
23
+ export interface SpeechOrderNormalizationWarning {
24
+ field: 'speech_order';
25
+ reason: 'missing_roster' | 'invalid_roster' | 'ambiguous_name' | 'unmatched_name' | 'invalid_order';
26
+ }
27
+
28
+ export type GameSyncEventNormalizationWarning = SpeechOrderNormalizationWarning | {
29
+ field: 'votes';
30
+ reason: 'invalid_vote_pairs';
31
+ };
32
+
21
33
  interface PlayerRefProjection {
22
34
  wireField: string;
23
35
  nameField: string;
@@ -158,7 +170,10 @@ function playerRefArray(value: unknown, field: string): CanonicalPlayerRef[] {
158
170
  * PlayerRef collections stay as compact `{ name, seat }` records. This
159
171
  * function never reads `hint`: presentation text is not a source of facts.
160
172
  */
161
- export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
173
+ export function normalizeGameSyncEvent(
174
+ value: unknown,
175
+ warn?: (warning: GameSyncEventNormalizationWarning) => void,
176
+ ): Record<string, any> {
162
177
  if (!isRecord(value)) {
163
178
  throw new TypeError('GameSync Event must be an object');
164
179
  }
@@ -240,14 +255,15 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
240
255
  );
241
256
  }
242
257
 
243
- // origin/dev currently emits meeting_briefing.speech_order as a comma-
244
- // separated string even though the protocol document specifies PlayerRef[].
245
- // Accept that one current-v2 wire shape without weakening other ref arrays.
258
+ // The current backend joins names with ", ". Convert only using this
259
+ // event's own complete roster; never infer missing data from current State.
246
260
  if (Object.hasOwn(normalized, 'speech_order') && Array.isArray(normalized.speech_order)) {
247
261
  normalized.speech_order = playerRefArray(
248
262
  normalized.speech_order,
249
263
  'GameSync Event.speech_order',
250
264
  );
265
+ } else if (normalized.type === 'meeting_briefing' && typeof normalized.speech_order === 'string') {
266
+ normalized.speech_order = normalizeSpeechOrderNames(normalized.speech_order, normalized.all_seats, warn);
251
267
  } else if (
252
268
  Object.hasOwn(normalized, 'speech_order')
253
269
  && typeof normalized.speech_order !== 'string'
@@ -255,40 +271,47 @@ export function normalizeGameSyncEvent(value: unknown): Record<string, any> {
255
271
  throw new TypeError('GameSync Event.speech_order must be a string or PlayerRef array');
256
272
  }
257
273
 
274
+ if ((normalized.type === 'exile' || normalized.type === 'no_exile')
275
+ && Array.isArray(normalized.votes)
276
+ && normalized.votes.some((pair: unknown) => !Array.isArray(pair) || pair.length !== 2
277
+ || !Number.isInteger(pair[0]) || (pair[1] !== null && !Number.isInteger(pair[1])))) {
278
+ // Do not discard an authoritative exile result because its optional tally is malformed.
279
+ // Keep the supplied field for inspection; never invent a seat or turn an invalid target into abstention.
280
+ warn?.({ field: 'votes', reason: 'invalid_vote_pairs' });
281
+ }
258
282
  return normalized;
259
283
  }
260
284
 
261
- function taskEventActorKey(event: Record<string, any>): string | null {
262
- if (Number.isInteger(event.actor_seat)) return `seat:${String(event.actor_seat)}`;
263
- return typeof event.actor_name === 'string' && event.actor_name.length > 0
264
- ? `name:${event.actor_name}`
265
- : null;
266
- }
267
-
268
- function newlyAssignedTask(event: Record<string, any>): Record<string, any> | null {
269
- if (typeof event.task_name !== 'string' || event.task_name.length === 0) return null;
270
- return {
271
- name: event.task_name,
272
- ...(typeof event.room === 'string' && event.room.length > 0 ? { room: event.room } : {}),
273
- ...(typeof event.x === 'number' && Number.isFinite(event.x) ? { x: event.x } : {}),
274
- ...(typeof event.y === 'number' && Number.isFinite(event.y) ? { y: event.y } : {}),
275
- ...(typeof event.is_fake_shrimp === 'boolean'
276
- ? { is_fake_shrimp: event.is_fake_shrimp }
277
- : {}),
285
+ function normalizeSpeechOrderNames(
286
+ order: string,
287
+ roster: unknown,
288
+ warn?: (warning: SpeechOrderNormalizationWarning) => void,
289
+ ): string | CanonicalPlayerRef[] {
290
+ const unchanged = (reason: SpeechOrderNormalizationWarning['reason']): string => {
291
+ warn?.({ field: 'speech_order', reason });
292
+ return order;
278
293
  };
294
+ if (order === '') return [];
295
+ if (roster === undefined) return unchanged('missing_roster');
296
+ let refs: CanonicalPlayerRef[];
297
+ try { refs = playerRefArray(roster, 'GameSync Event.all_seats'); }
298
+ catch { return unchanged('invalid_roster'); }
299
+ const byName = new Map<string, CanonicalPlayerRef>();
300
+ const seats = new Set<number>();
301
+ for (const ref of refs) {
302
+ if (!ref.name || seats.has(ref.seat)) return unchanged('invalid_roster');
303
+ if (ref.name.includes(',') || byName.has(ref.name)) return unchanged('ambiguous_name');
304
+ byName.set(ref.name, ref); seats.add(ref.seat);
305
+ }
306
+ const names = order.split(', ');
307
+ if (names.some(name => !name) || new Set(names).size !== names.length) return unchanged('invalid_order');
308
+ if (names.some(name => !byName.has(name))) return unchanged('unmatched_name');
309
+ return names.map(name => ({ ...byName.get(name)! }));
279
310
  }
280
311
 
281
- /**
282
- * Normalize one GameSync frame and enrich a completed task with its private,
283
- * same-frame replacement assignment. The raw task_assigned Event remains in
284
- * the batch for internal consumers; Agent delivery is still owned by the
285
- * Event Catalog.
286
- */
312
+ /** Normalize each backend fact independently; perceptions own task notifications. */
287
313
  export function normalizeGameSyncEvents(values: readonly unknown[]): Record<string, any>[] {
288
- return enrichTaskAssignments(values.map((value, index) => ({
289
- index,
290
- event: normalizeGameSyncEvent(value),
291
- }))).map(({ event }) => event);
314
+ return values.map(value => normalizeGameSyncEvent(value));
292
315
  }
293
316
 
294
317
  /** Normalize independent Events without rejecting their valid frame siblings. */
@@ -297,42 +320,13 @@ export function normalizeGameSyncEventsSafely(
297
320
  ): GameSyncEventNormalizationResult {
298
321
  const events: NormalizedGameSyncEventEntry[] = [];
299
322
  const rejected: RejectedGameSyncEventEntry[] = [];
323
+ const warnings: NonNullable<GameSyncEventNormalizationResult['warnings']> = [];
300
324
  values.forEach((value, index) => {
301
325
  try {
302
- events.push({ index, event: normalizeGameSyncEvent(value) });
326
+ events.push({ index, event: normalizeGameSyncEvent(value, warning => warnings.push({ index, ...warning })) });
303
327
  } catch (error) {
304
328
  rejected.push({ index, error });
305
329
  }
306
330
  });
307
- return { events: enrichTaskAssignments(events), rejected };
308
- }
309
-
310
- function enrichTaskAssignments(
311
- entries: readonly NormalizedGameSyncEventEntry[],
312
- ): NormalizedGameSyncEventEntry[] {
313
- const claimedAssignments = new Set<number>();
314
-
315
- return entries.map((entry, index) => {
316
- const { event } = entry;
317
- if (event.type !== 'task_completed' || !Number.isInteger(event.tick)) return entry;
318
- const actorKey = taskEventActorKey(event);
319
- if (!actorKey) return entry;
320
-
321
- const assignmentIndex = entries.findIndex(({ event: candidate }, candidateIndex) => (
322
- candidateIndex > index
323
- && !claimedAssignments.has(candidateIndex)
324
- && candidate.type === 'task_assigned'
325
- && candidate.tick === event.tick
326
- && taskEventActorKey(candidate) === actorKey
327
- ));
328
- if (assignmentIndex < 0) return entry;
329
-
330
- const task = newlyAssignedTask(entries[assignmentIndex]!.event);
331
- if (!task) return entry;
332
- claimedAssignments.add(assignmentIndex);
333
- return {
334
- ...entry,
335
- event: { ...event, newly_assigned_task: task },
336
- };
337
- });
331
+ return { events, rejected, ...(warnings.length ? { warnings } : {}) };
338
332
  }
@@ -7,7 +7,7 @@ import { assertRuntimeModuleOutputSize } from '../framework/modules/runtime-modu
7
7
  const DECISION_KEYS = new Set(['actions', 'status', 'events', 'delegate', 'finish']);
8
8
  const STATUS_KEYS = new Set(['summary', 'activity', 'room', 'task', 'targetPlayer', 'data']);
9
9
  const EVENT_KEYS = new Set(['type', 'payload', 'occurredAt']);
10
- const DELEGATE_KEYS = new Set(['behavior', 'input']);
10
+ const DELEGATE_KEYS = new Set(['behavior', 'strategy', 'input']);
11
11
  const FINISH_KEYS = new Set(['outcome', 'reason', 'summary']);
12
12
 
13
13
  function objectRecord(value: unknown, code: string): Record<string, unknown> {
@@ -69,11 +69,14 @@ export function normalizeBehaviorDecision(
69
69
  }
70
70
  }
71
71
  }
72
+ let normalizedDelegate: Record<string, unknown> | undefined;
72
73
  if (source.delegate !== undefined) {
73
74
  const delegate = objectRecord(source.delegate, 'behavior_delegate_invalid');
74
75
  rejectUnknownFields(delegate, DELEGATE_KEYS, 'behavior_delegate_field_unknown');
75
- nonEmptyString(delegate.behavior, 'behavior_delegate_id_invalid');
76
+ if (delegate.behavior !== undefined && delegate.strategy !== undefined) throw new Error('strategy_delegate_name_conflict');
77
+ const target = nonEmptyString(delegate.strategy ?? delegate.behavior, 'behavior_delegate_id_invalid');
76
78
  if (delegate.input !== undefined) objectRecord(delegate.input, 'behavior_delegate_input_invalid');
79
+ normalizedDelegate = { behavior: target, ...(delegate.input === undefined ? {} : { input: delegate.input }) };
77
80
  }
78
81
  if (source.finish !== undefined) {
79
82
  const finish = objectRecord(source.finish, 'behavior_finish_invalid');
@@ -86,7 +89,8 @@ export function normalizeBehaviorDecision(
86
89
  throw new Error('behavior_finish_summary_invalid');
87
90
  }
88
91
  }
89
- const normalized = Object.freeze(structuredClone(source)) as BehaviorDecision | FiniteBehaviorDecision;
92
+ const normalized = Object.freeze(structuredClone({ ...source,
93
+ ...(normalizedDelegate ? { delegate: normalizedDelegate } : {}) })) as BehaviorDecision | FiniteBehaviorDecision;
90
94
  assertRuntimeModuleOutputSize(normalized, 'behavior_output');
91
95
  return normalized;
92
96
  }
@@ -20,7 +20,8 @@ function behaviorEvents(
20
20
  input: RuntimeEpochPluginInput<Record<string, any>>,
21
21
  gameState: GameState,
22
22
  ): readonly Readonly<GameEvent>[] {
23
- return input.pendingEvents.map((event) => ({
23
+ return input.pendingEvents.filter(event => !event.notificationOf
24
+ && !event.producerPluginId?.startsWith('clawclaw.perception.system.')).map((event) => ({
24
25
  eventId: event.eventId,
25
26
  ...(event.epochSeq === undefined ? {} : { epochId: event.epochSeq }),
26
27
  type: event.type,
@@ -42,9 +43,10 @@ export function createCanonicalGameState(
42
43
  }
43
44
 
44
45
  /**
45
- * Build the one player-module input from a fresh GameSync epoch.
46
+ * Build the player-module input from the latest authoritative observation.
46
47
  * Lifecycle plugins decide when a Behavior is eligible to run; modules never
47
- * receive Runtime State or a nullable/stale Game State through this contract.
48
+ * receive Runtime State or a nullable Game State. A cycle reports the actual
49
+ * age/version when this observation is cached rather than newly received.
48
50
  */
49
51
  export function createBehaviorInput<
50
52
  TInput extends Readonly<Record<string, unknown>>,
@@ -55,7 +57,8 @@ export function createBehaviorInput<
55
57
  decisionHistory: readonly Readonly<BehaviorDecisionFrame>[] = [],
56
58
  ): BehaviorInput<TInput> | null {
57
59
  const runtimeState = input.epoch.state;
58
- if (!isClawclawRuntimeState(runtimeState) || runtimeState.game_snapshot.status !== 'fresh') {
60
+ if (!isClawclawRuntimeState(runtimeState)
61
+ || (runtimeState.game_snapshot.status !== 'fresh' && runtimeState.game_snapshot.status !== 'cached')) {
59
62
  return null;
60
63
  }
61
64
  const gameState = createCanonicalGameState(
@@ -69,6 +72,7 @@ export function createBehaviorInput<
69
72
  segmentId: input.epoch.scope.segmentId,
70
73
  },
71
74
  nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
75
+ ...(runtimeState.cycle ? { cycle: structuredClone(runtimeState.cycle) } : {}),
72
76
  gameState,
73
77
  events: behaviorEvents(input, gameState),
74
78
  input: structuredClone(behaviorInput),
@@ -71,6 +71,7 @@ export class ClawclawBehaviorObservationMemory {
71
71
  }
72
72
  const existing = this.snapshots.get(input.epochId);
73
73
  if (existing) return existing;
74
+ const observedAtMs = input.cycle?.stateReceivedAtMs ?? input.nowMs;
74
75
 
75
76
  for (const visible of input.gameState.visible_players ?? []) {
76
77
  const ref = playerRef(visible);
@@ -88,7 +89,7 @@ export class ClawclawBehaviorObservationMemory {
88
89
  ...(knownAlive(input, ref) === undefined
89
90
  ? {}
90
91
  : { isAlive: knownAlive(input, ref) }),
91
- observedAtMs: input.nowMs,
92
+ observedAtMs,
92
93
  });
93
94
  }
94
95
  for (const visible of input.gameState.visible_corpses ?? []) {
@@ -103,7 +104,7 @@ export class ClawclawBehaviorObservationMemory {
103
104
  y: visible.y,
104
105
  room: visible.room,
105
106
  ...(visible.distance === undefined ? {} : { distance: visible.distance }),
106
- observedAtMs: input.nowMs,
107
+ observedAtMs,
107
108
  });
108
109
  }
109
110
 
@@ -0,0 +1,42 @@
1
+ import { prepareNotificationContent } from './plugins/perception/notification-content.js';
2
+ import type { CanonicalEvent } from '../framework/events/index.js';
3
+ import type { EventIngressOptions } from '../framework/events/event-ingress.js';
4
+ import type { RuntimeEpochPlugin } from '../framework/plugins/index.js';
5
+ import { createClawclawEventCatalog } from '../clawclaw-event-catalog.js';
6
+
7
+ /** Fixed host lifecycle exception. Game facts and Behavior outputs are not in this list. */
8
+ export const CLAWCLAW_SYSTEM_CONTROL_EVENTS = new Set([
9
+ 'service_status', 'joined', 'room_created', 'room_joined', 'session_resumed', 'session_recovered',
10
+ 'not_in_queue', 'poll_error', 'error', 'game_start_failed', 'game_terminal_missing',
11
+ 'game_stream_disconnected', 'game_stream_reconnected', 'stop_requested', 'quit_requested',
12
+ 'match_start', 'match_waiting', 'match_timeout', 'user_left_game', 'session_left', 'quit_failed',
13
+ 'room_attached', 'room_lobby_reconnect_failed', 'room_lobby_missing', 'room_returning_to_lobby',
14
+ 'room_ping_timeout', 'room_destroyed', 'room.self_left', 'room.game_start_failed',
15
+ ]);
16
+
17
+ export const BUILTIN_PERCEPTION_PREFIX = 'clawclaw.perception.system.';
18
+
19
+ export function createClawclawNotificationPolicy(
20
+ plugins: readonly RuntimeEpochPlugin<Record<string, any>>[],
21
+ ): NonNullable<EventIngressOptions['notificationPolicy']> {
22
+ const producers = new Set(plugins.filter(plugin => plugin.agentNotificationProducer).map(plugin => plugin.id));
23
+ const systemCatalog = createClawclawEventCatalog();
24
+ return input => {
25
+ if (input.producerPluginId && producers.has(input.producerPluginId)) {
26
+ // Mandatory builtin notifications are not controlled by user visual delivery preferences.
27
+ const fixed = input.producerPluginId.startsWith(BUILTIN_PERCEPTION_PREFIX)
28
+ ? systemCatalog.get(input.type) : undefined;
29
+ return { source: 'perception', ...(fixed
30
+ ? { deliveryClass: fixed.deliveryClass, wakeAgent: input.wakeAgent ?? true } : {}) };
31
+ }
32
+ if (input.producerPluginId === undefined && CLAWCLAW_SYSTEM_CONTROL_EVENTS.has(input.type)) {
33
+ return { source: 'system', content: prepareNotificationContent(input.type, input.payload ?? {}, null, 'system', input) };
34
+ }
35
+ return undefined;
36
+ };
37
+ }
38
+
39
+ export function isClawclawAgentNotification(event: CanonicalEvent): boolean {
40
+ return event.deliveryClass !== 'internal_only'
41
+ && (event.notificationSource === 'perception' || event.notificationSource === 'system');
42
+ }
@@ -0,0 +1,19 @@
1
+ import type { RuntimeOptions } from '../framework/runtime.js';
2
+ import { isClawclawRuntimeState } from './runtime-state.js';
3
+
4
+ export function isNotificationTurn(state: Record<string, any>): boolean {
5
+ return isClawclawRuntimeState(state) && state.cause === 'control' && state.control?.type === 'perception_notifications';
6
+ }
7
+
8
+ /** A notification round has no fresh snapshot, backend tick, or new game action. */
9
+ export const clawclawNotificationFollowUp: NonNullable<RuntimeOptions['followUpInput']> = (epoch, latest, events) => {
10
+ if (!events.some(event => event.producerPluginId === 'clawclaw.behavior' && !event.notificationOf)) return;
11
+ if (!isClawclawRuntimeState(latest.state)) return;
12
+ return {
13
+ scope: epoch.scope, sourceId: 'clawclaw.notification-turn', connectionId: latest.connectionId,
14
+ sourceKey: `notification-after:${epoch.epochSeq}`,
15
+ state: { ...latest.state, cause: 'control', control: { type: 'perception_notifications', after_epoch: epoch.epochSeq },
16
+ game_snapshot: { status: 'not_updated' } },
17
+ events: [], completeness: 'complete', coalescing: 'forbidden', receivedAt: new Date().toISOString(),
18
+ };
19
+ };
@@ -8,7 +8,7 @@ import type {
8
8
  import type { StoredStateFrame } from '../framework/state/history/contracts.js';
9
9
  import { createCanonicalGameState } from './behavior-input.js';
10
10
  import { resolveRoom } from './plugins/perception/spatial-facts.js';
11
- import { freshClawclawGameState } from './runtime-state.js';
11
+ import { clawclawComputationGameState } from './runtime-state.js';
12
12
 
13
13
  function finite(value: unknown): value is number {
14
14
  return typeof value === 'number' && Number.isFinite(value);
@@ -42,7 +42,7 @@ export class ObservationFrameProjector {
42
42
  reset(): void {}
43
43
 
44
44
  project(frame: StoredStateFrame<Record<string, any>>): ObservationFrame | null {
45
- const freshState = freshClawclawGameState(frame.state);
45
+ const freshState = clawclawComputationGameState(frame.state);
46
46
  if (!freshState) return null;
47
47
  const gameState = createCanonicalGameState(freshState, frame.backendTick);
48
48
  const players: VisualPlayer[] = [];
@@ -71,7 +71,7 @@ export class ObservationFrameProjector {
71
71
  frameKey: frame.sourceKey,
72
72
  frameSeq: frame.frameSeq,
73
73
  tick,
74
- timeMs: frame.observedAtMs ?? frame.receivedAtMs,
74
+ timeMs: frame.state.cycle?.stateReceivedAtMs ?? frame.observedAtMs ?? frame.receivedAtMs,
75
75
  tickDelta: null,
76
76
  continuousFromPrevious: false,
77
77
  gameState,
@@ -1,3 +1,8 @@
1
+ import { BUILTIN_PERCEPTION_NAMES } from './plugins/system-perception/system-perceptions.js';
2
+ import { BUILTIN_PERCEPTION_PREFIX } from './notification-policy.js';
3
+ import { isClawclawAgentNotification } from './notification-policy.js';
4
+ import { createClawclawProcessingCadence } from './runtime-cadence.js';
5
+ import { readRuntimeCycleIntervalMs } from '../../lib/runtime-cadence-config.js';
1
6
  import { randomUUID } from 'node:crypto';
2
7
  import { BehaviorReflexControl } from './behavior-reflex-control.js';
3
8
  import { acquireOwnerLock, type OwnerLock } from './owner-lock.js';
@@ -652,6 +657,7 @@ export async function runClawclawOwner(
652
657
  const reflexControl = new BehaviorReflexControl(assembly.modules,
653
658
  assembly.behavior, behaviorCatalog, () => runtime!.publicScope());
654
659
  runtime = createClawclawRuntime(options.profile, {
660
+ processingCadence: createClawclawProcessingCadence(readRuntimeCycleIntervalMs()),
655
661
  initialSegment: runtimeStart.initialSegment,
656
662
  mode: runtimeStart.mode,
657
663
  resume: runtimeStart.resume,
@@ -744,6 +750,7 @@ export async function runClawclawOwner(
744
750
  onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
745
751
  presentEvent: ownerAgentEventPresenter('ccl_events', !!options.desktopEvents),
746
752
  compactState: compactStateForEvents,
753
+ admitEvent: isClawclawAgentNotification,
747
754
  eventFilter: clawclawEventRequiresDetails,
748
755
  delegatedMonitorConsumerId: MONITOR_MAILBOX_CONSUMER_ID,
749
756
  consumerId: CCL_EVENTS_MAILBOX_CONSUMER_ID,
@@ -755,6 +762,7 @@ export async function runClawclawOwner(
755
762
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
756
763
  });
757
764
  mailboxService = new ClawclawMailboxService({
765
+ notificationOnly: true,
758
766
  repository: mailboxRepository,
759
767
  readyView: () => runtime!.readReadyView(0, 1),
760
768
  agentMailbox: cclEventsMailbox,
@@ -769,11 +777,12 @@ export async function runClawclawOwner(
769
777
  ];
770
778
  if (options.desktopEvents) {
771
779
  desktopMailbox = new AgentMailboxCoordinator({
780
+ admitEvent: isClawclawAgentNotification,
772
781
  repository: mailboxRepository,
773
782
  readyView: () => runtime!.readReadyView(0, 1),
774
783
  onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
775
784
  presentEvent: ownerAgentEventPresenter('desktop_ipc', true),
776
- compactState: compactStateForEvents,
785
+ compactState: () => null,
777
786
  consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID,
778
787
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
779
788
  });
@@ -816,7 +825,7 @@ export async function runClawclawOwner(
816
825
  ownerIdPrefix: 'desktop_ipc',
817
826
  }),
818
827
  renew: (deliveryToken) => desktopMailbox!.renew(deliveryToken),
819
- ack: (deliveryToken) => desktopMailbox!.ack(deliveryToken),
828
+ ack: (deliveryToken, level) => desktopMailbox!.ack(deliveryToken, level),
820
829
  release: (deliveryToken) => desktopMailbox!.release(deliveryToken),
821
830
  },
822
831
  sink: desktopSink,
@@ -828,6 +837,7 @@ export async function runClawclawOwner(
828
837
  assembly.behavior.attachDriver(createClawclawBehaviorControlDriver(runtime));
829
838
  if (channelPolicy.enabled) {
830
839
  channelAdapter = new ClaudeChannelMailboxAdapter({
840
+ notificationOnly: true,
831
841
  onDelivered: (events) => perceptionReportAdapter.reportDelivered(events),
832
842
  repository: mailboxRepository,
833
843
  readyView: () => runtime!.readReadyView(0, 1),
@@ -841,7 +851,7 @@ export async function runClawclawOwner(
841
851
  source: {
842
852
  prepare: () => channelAdapter!.prepare(),
843
853
  renew: (deliveryToken) => channelAdapter!.renew(deliveryToken),
844
- ack: (deliveryToken) => channelAdapter!.ack(deliveryToken),
854
+ ack: (deliveryToken, level) => channelAdapter!.ack(deliveryToken, level),
845
855
  release: (deliveryToken) => channelAdapter!.release(deliveryToken),
846
856
  },
847
857
  sink: channelSink,
@@ -1126,7 +1136,10 @@ export async function runClawclawOwner(
1126
1136
  return { ok: true, type: 'action', result };
1127
1137
  }
1128
1138
  if (request.type === 'perception_status') {
1129
- return { ok: true, type: request.type, status: assembly.modules?.status(request.perception) ?? [] };
1139
+ return { ok: true, type: request.type, status: [...Object.entries(BUILTIN_PERCEPTION_NAMES).map(([id, name]) => ({
1140
+ id: `${BUILTIN_PERCEPTION_PREFIX}${id}`, name, mandatory: true, configurable: false,
1141
+ outcome: runtime!.readReadyView().pluginOutcomes[`${BUILTIN_PERCEPTION_PREFIX}${id}`]?.outcome,
1142
+ })).filter(item => !request.perception || item.id === request.perception), ...(assembly.modules?.status(request.perception) ?? [])] };
1130
1143
  }
1131
1144
  if (request.type === 'perception_update') {
1132
1145
  const expected = ownerExpectedScope(request.expected_scope);
@@ -1135,6 +1148,7 @@ export async function runClawclawOwner(
1135
1148
  if (runtime!.currentSegment().kind !== 'game') return { ok: false, type: request.type, error: 'no_active_game' };
1136
1149
  if (!ownerScopeIsCurrent(runtime!,expected)) return { ok: false, type: request.type, error: 'stale_runtime_scope' };
1137
1150
  try {
1151
+ if (request.perception.startsWith(BUILTIN_PERCEPTION_PREFIX)) throw Error('builtin_perception_readonly');
1138
1152
  if (!assembly.modules) throw Error('perception_not_found');
1139
1153
  const result = assembly.modules.configure(request.perception,request.input,() => ownerScopeIsCurrent(runtime!,expected));
1140
1154
  return { ok: true, type: request.type, result };
@@ -5,32 +5,37 @@ import { normalizeBehaviorInputFields, normalizeBehaviorInput } from './behavior
5
5
  import { isClawclawFixedEventType, CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES,
6
6
  CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES, CLAWCLAW_VISUAL_EVENT_TYPES } from '../clawclaw-event-catalog.js';
7
7
 
8
+ export const REMOVED_PERCEPTION_INPUT_TYPES = new Set(['players_changed', 'tasks_changed', 'meeting_state', 'ability.ready',
9
+ 'ability.remaining_uses_changed', 'ability.exhausted', 'emergency_countdown_warning', 'room_ready_to_start']);
8
10
  const INPUT_TYPES = new Set<string>([...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, ...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES,
9
11
  ...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter(type => !/^(behavior|reminder|perception)\./.test(type)),
10
12
  'tasks_changed', 'meeting_state']);
11
13
  const PERCEPTION_OWNED_TYPES = new Set<string>([...CLAWCLAW_VISUAL_EVENT_TYPES, 'reminder.task', 'reminder.speech']);
12
14
 
13
15
  const record = (value: unknown): value is Record<string, any> => !!value && typeof value === 'object' && !Array.isArray(value);
14
- export function normalizePerceptionModuleManifest(value: unknown, current = true): PerceptionModuleManifest {
16
+ export function normalizePerceptionModuleManifest(value: unknown, current = true, discoverRemovedInputs = false): PerceptionModuleManifest {
15
17
  if (!record(value) || !Number.isInteger(value.apiVersion) || current && value.apiVersion !== 3
16
18
  || Object.keys(value).some(key => !['apiVersion', 'id', 'name', 'description', 'localizations', 'consumes',
17
- 'produces', 'inputs', 'config', 'behaviors'].includes(key))
19
+ 'produces', 'inputs', 'config', 'behaviors', 'strategies'].includes(key))
18
20
  || typeof value.id !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(value.id)
19
21
  || typeof value.description !== 'string' || !value.description.trim()
20
22
  || value.name !== undefined && (typeof value.name !== 'string' || !value.name.trim())
21
23
  || !hasValidClawclawResourceLocalizations(value.localizations)
22
24
  || value.config !== undefined && !record(value.config)) throw new Error('perception_module_manifest_invalid');
23
25
  const consumes = value.consumes ?? [], produces = value.produces ?? [];
26
+ if (value.strategies !== undefined && value.behaviors !== undefined) throw new Error('perception_strategy_bindings_conflict');
27
+ const bindings = value.strategies ?? value.behaviors;
24
28
  if (!Array.isArray(produces) || produces.some(type => typeof type !== 'string'
25
29
  || !/^[a-z0-9][a-z0-9._-]*$/.test(type)
26
30
  || isClawclawFixedEventType(type) && !PERCEPTION_OWNED_TYPES.has(type))
27
31
  || !Array.isArray(consumes) || consumes.some(type => typeof type !== 'string' || !INPUT_TYPES.has(type)
28
32
  || /^(visual|reminder|reaction|perception|behavior|decision)\./.test(type))) throw new Error('perception_module_event_contract_invalid');
33
+ if (!discoverRemovedInputs && consumes.some(type => REMOVED_PERCEPTION_INPUT_TYPES.has(type))) throw new Error('perception_input_removed: use gameState, frame or module-local taskChanges; perceptions cannot subscribe to other perceptions');
29
34
  const inputs = value.inputs ? normalizeBehaviorInputFields(value.inputs) : undefined;
30
35
  const config = inputs ? normalizeBehaviorInput(value.config ?? {}, inputs) : structuredClone(value.config ?? {});
31
36
  return { apiVersion: value.apiVersion, id: value.id, description: value.description,
32
37
  ...(value.name === undefined ? {} : { name: value.name }),
33
38
  ...(value.localizations === undefined ? {} : { localizations: structuredClone(value.localizations) }),
34
- ...(value.behaviors === undefined ? {} : { behaviors: normalizePerceptionBehaviorBindings(value.behaviors) }),
39
+ ...(bindings === undefined ? {} : { behaviors: normalizePerceptionBehaviorBindings(bindings) }),
35
40
  consumes: [...new Set(consumes)], produces: [...new Set(produces)], ...(inputs ? { inputs } : {}), config };
36
41
  }
@@ -0,0 +1,17 @@
1
+ import type { PerceptionModuleResult } from '../../sdk/perception-plugin/module.js';
2
+ import type { ReactionActivation } from '../../sdk/perception-plugin/reaction.js';
3
+
4
+ export type NormalizedPerceptionModuleResult = Omit<PerceptionModuleResult, 'activations'> & {
5
+ readonly activations?: readonly ReactionActivation[];
6
+ };
7
+
8
+ /** Resolve public names once before the existing admission/arbitration path. */
9
+ export function normalizePerceptionStrategyNames(value: PerceptionModuleResult): NormalizedPerceptionModuleResult {
10
+ if (!value || typeof value !== 'object' || !Array.isArray(value.activations)) return value as NormalizedPerceptionModuleResult;
11
+ return { ...value, activations: value.activations.map(activation => {
12
+ if (!activation || typeof activation !== 'object' || !Object.hasOwn(activation, 'strategy')) return activation as ReactionActivation;
13
+ if (Object.hasOwn(activation, 'behavior')) throw new Error('perception_strategy_activation_conflict');
14
+ const { strategy, ...rest } = activation as Record<string, unknown>;
15
+ return { ...rest, behavior: strategy } as unknown as ReactionActivation;
16
+ }) };
17
+ }