@myclaw163/clawclaw-cli 0.9.2 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +23 -35
  7. package/docs/custom-modules/api-reference.md +95 -273
  8. package/docs/custom-modules/behavior.md +94 -78
  9. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +42 -603
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +16 -17
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +47 -46
  19. package/docs/runtime/components-and-boundaries.md +70 -28
  20. package/docs/runtime/events-and-state.md +41 -18
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +10 -7
  26. package/docs/user-guide/api-reference.md +81 -164
  27. package/docs/user-guide/behavior.md +84 -68
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +42 -586
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +8 -13
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +49 -49
  37. package/skills/clawclaw/references/BEHAVIORS.md +42 -73
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +60 -101
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +94 -78
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +95 -180
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +24 -24
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +42 -608
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +26 -10
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +3 -2
  53. package/src/commands/perception.ts +5 -0
  54. package/src/commands/strategy.ts +2 -0
  55. package/src/lib/capability-load-diagnostics.ts +3 -3
  56. package/src/lib/perception-config.ts +18 -6
  57. package/src/lib/runtime-cadence-config.ts +16 -0
  58. package/src/lib/workspace-runtime-lock.ts +3 -46
  59. package/src/pipeline/canonical-event-presentation.ts +23 -124
  60. package/src/pipeline/event-format.ts +12 -21
  61. package/src/pipeline/event-hints.ts +6 -6
  62. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  63. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  64. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  65. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  66. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  67. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  68. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  69. package/src/runtime/clawclaw/owner.ts +18 -4
  70. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  71. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  72. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  73. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  74. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  75. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  76. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  77. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  78. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  79. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  82. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  83. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  84. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  85. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  86. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +25 -17
  87. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  88. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  89. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  90. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  91. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  92. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  93. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  94. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  95. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  96. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  97. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  98. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  99. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  100. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  101. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +119 -297
  102. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  103. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  104. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +18 -7
  105. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  106. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  107. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  108. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  109. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  110. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  111. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  112. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  113. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  114. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  115. package/src/runtime/clawclaw/runtime.ts +8 -0
  116. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  117. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  118. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  119. package/src/runtime/framework/action-diagnostics.ts +3 -83
  120. package/src/runtime/framework/capability-registry.ts +2 -395
  121. package/src/runtime/framework/contracts.ts +2 -144
  122. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  123. package/src/runtime/framework/control/domain-set.ts +2 -81
  124. package/src/runtime/framework/control/index.ts +1 -3
  125. package/src/runtime/framework/control/types.ts +2 -191
  126. package/src/runtime/framework/control-coordinator.ts +2 -11
  127. package/src/runtime/framework/events/event-catalog.ts +2 -74
  128. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  129. package/src/runtime/framework/events/event-ingress.ts +2 -99
  130. package/src/runtime/framework/events/event-repository.ts +2 -82
  131. package/src/runtime/framework/events/index.ts +2 -7
  132. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  133. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  134. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  135. package/src/runtime/framework/events/test-helpers.ts +1 -1
  136. package/src/runtime/framework/events/types.ts +2 -312
  137. package/src/runtime/framework/index.ts +3 -7
  138. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  139. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  140. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  141. package/src/runtime/framework/mailbox/identity.ts +2 -38
  142. package/src/runtime/framework/mailbox/index.ts +1 -7
  143. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  144. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  145. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  146. package/src/runtime/framework/mailbox/types.ts +2 -145
  147. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  148. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  149. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  150. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  151. package/src/runtime/framework/participation-manager.ts +2 -253
  152. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  153. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  154. package/src/runtime/framework/plugins/contracts.ts +2 -396
  155. package/src/runtime/framework/plugins/index.ts +1 -4
  156. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  157. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  158. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  159. package/src/runtime/framework/runtime.ts +5 -1843
  160. package/src/runtime/framework/serial-task-queue.ts +2 -14
  161. package/src/runtime/framework/state/contracts.ts +2 -49
  162. package/src/runtime/framework/state/current-state-store.ts +2 -184
  163. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  164. package/src/runtime/framework/state/freshness.ts +2 -72
  165. package/src/runtime/framework/state/history/contracts.ts +2 -158
  166. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  167. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  168. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  169. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  170. package/src/runtime/framework/state/index.ts +1 -13
  171. package/src/runtime/framework/state/state-ingress.ts +2 -95
  172. package/src/runtime/framework/state/state-provider.ts +2 -62
  173. package/src/runtime/framework/state/types.ts +2 -155
  174. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  175. package/src/runtime/mailbox-host-relay.ts +1 -326
  176. package/src/runtime/observability/detail-capture.ts +4 -108
  177. package/src/runtime/observability/process-timing.ts +2 -59
  178. package/src/runtime/observability/recorder.ts +2 -238
  179. package/src/runtime/observability/redaction.ts +2 -181
  180. package/src/runtime/observability/reporter.ts +2 -154
  181. package/src/runtime/observability/sinks.ts +2 -135
  182. package/src/runtime/observability/types.ts +2 -92
  183. package/src/runtime/owner-control.ts +45 -320
  184. package/src/runtime/parent-process-watch.ts +1 -51
  185. package/src/runtime/process-identity.ts +1 -72
  186. package/src/sdk/behavior-plugin/index.ts +9 -3
  187. package/src/sdk/index.ts +40 -2
  188. package/src/sdk/module-input/index.ts +5 -0
  189. package/src/sdk/perception-plugin/index.ts +3 -1
  190. package/src/sdk/perception-plugin/module.ts +12 -2
  191. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  192. package/src/sdk/perception-plugin/reminder.ts +2 -1
  193. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  194. package/src/sdk/strategy-memory.ts +1 -12
  195. package/src/sdk/strategy-plugin/index.ts +36 -0
  196. package/src/sdk/trigger-plugin/index.ts +1 -0
  197. package/docs/custom-modules/trigger.md +0 -295
@@ -1,39 +1,17 @@
1
- import { parentPort, workerData } from 'node:worker_threads';
2
1
  import { pathToFileURL } from 'node:url';
2
+ import { runPerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker-host.js';
3
3
  import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception-plugin/index.js';
4
4
  import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
5
5
  import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
6
6
  import { normalizeReactionManifest } from '../../reaction-manifest.js';
7
- import { StrategyMemoryRpcClient } from '../../strategy-memory-rpc.js';
8
7
 
9
- function freeze<T>(value: T): T {
10
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
11
- for (const child of Object.values(value)) freeze(child); Object.freeze(value);
12
- }
13
- return value;
14
- }
15
- try {
16
- const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
17
- if (!(Module?.prototype instanceof (workerData.legacy ? ClawclawReaction : ClawclawPerception))
18
- || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw new Error('PERCEPTION_MODULE_CLASS_INVALID');
19
- const legacy = workerData.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
20
- const { kind: _kind, ...common } = legacy ?? {} as any;
21
- const manifest = legacy ? { ...common, apiVersion: 3 } : normalizePerceptionModuleManifest(Module.manifest);
22
- if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
23
- parentPort!.postMessage({ type: 'ready' });
24
- const memory = new StrategyMemoryRpcClient(message => parentPort!.postMessage(message));
25
- let active: number | undefined;
26
- parentPort!.on('message', async (message: any) => {
27
- if (memory.receive(message)) return;
28
- const { id, input }: { id: number; input: PerceptionModuleInput } = message;
29
- active = id;
30
- try {
31
- const result = await new Module().evaluate(freeze({ ...input,
32
- events: input.events.filter(event => manifest.consumes?.includes(event.type)) }),
33
- Object.freeze({ memory: memory.bind(String(id), () => active === id) })) ?? {};
34
- if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
35
- parentPort!.postMessage({ type: 'result', id, result });
36
- } catch { parentPort!.postMessage({ type: 'error', id }); }
37
- finally { if (active === id) active = undefined; }
38
- });
39
- } catch { parentPort!.postMessage({ type: 'error' }); }
8
+ await runPerceptionWorker<PerceptionModuleInput>(async data => {
9
+ const Module = (await import(pathToFileURL(data.modulePath).href)).default;
10
+ if (!(Module?.prototype instanceof (data.legacy ? ClawclawReaction : ClawclawPerception))
11
+ || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw Error('PERCEPTION_MODULE_CLASS_INVALID');
12
+ const legacy = data.legacy ? normalizeReactionManifest(Module.manifest) : undefined;
13
+ const {kind: _kind, ...common} = legacy ?? {} as any;
14
+ const manifest = legacy ? {...common,apiVersion:3} : normalizePerceptionModuleManifest(Module.manifest);
15
+ if (JSON.stringify(manifest) !== JSON.stringify(data.expectedManifest)) throw Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
16
+ return { create: () => new Module(), prepareInput: input => ({...input,events:input.events.filter(event=>manifest.consumes?.includes(event.type))}) };
17
+ });
@@ -1,3 +1,5 @@
1
+ import { prepareNotificationContent } from './notification-content.js';
2
+ import { isNotificationTurn } from '../../notification-turn.js';
1
3
  import type {
2
4
  RuntimeEpochFlushReason,
3
5
  RuntimeEpochPlugin,
@@ -362,6 +364,7 @@ function proposals(value: readonly PerceptionEventProposal[] | void): RuntimeEve
362
364
 
363
365
  /** One Runtime plugin that projects each frame once and fans it out to perception modules. */
364
366
  export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<string, any>> {
367
+ readonly agentNotificationProducer = true;
365
368
  readonly kind = 'epoch' as const;
366
369
  readonly id = CLAWCLAW_PERCEPTION_PLUGIN_ID;
367
370
  readonly version = String(PERCEPTION_PLUGIN_API_VERSION);
@@ -480,6 +483,11 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
480
483
  input: RuntimeEpochPluginInput<Record<string, any>>,
481
484
  context: RuntimeEpochPluginContext<Record<string, any>>,
482
485
  ): Promise<RuntimeEpochPluginResult> {
486
+ if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' };
487
+ if (input.epoch.state.cycle && !input.epoch.state.cycle.hasNewState
488
+ && input.epoch.state.connection === 'connected' && input.epoch.state.stage !== 'ended') {
489
+ return { outcome: 'noop', reason: 'unchanged_observation' };
490
+ }
483
491
  const updateStartedAt = performance.now();
484
492
  const projectionStartedAt = performance.now();
485
493
  const visual = this.projector.project(input.frame);
@@ -513,6 +521,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
513
521
  computation: Readonly<RuntimeEpochPluginResult>,
514
522
  context: RuntimeEpochPluginContext<Record<string, any>>,
515
523
  ): Promise<RuntimeEpochPluginResult> {
524
+ if (isNotificationTurn(input.epoch.state) || computation.reason === 'unchanged_observation') return computation;
516
525
  const proposal = this.computationProposal(computation.proposal);
517
526
  const commitStartedAt = performance.now();
518
527
  const previousFrameSeq = this.lastFrameSeq;
@@ -522,7 +531,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
522
531
  analyses: proposal.analyses,
523
532
  analysisTiming: proposal.timing ?? this.emptyAnalysisTiming(),
524
533
  }, context.signal, context.diagnostic);
525
- if (input.frame.frameSeq > previousFrameSeq + 1) {
534
+ if (!input.epoch.state.cycle && input.frame.frameSeq > previousFrameSeq + 1) {
526
535
  context.diagnostic('perception.catchup_frames_dropped', {
527
536
  target_epoch_seq: input.epoch.epochSeq,
528
537
  max_backfill_visual_frames: this.maxBackfillVisualFrames,
@@ -546,7 +555,8 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
546
555
  ? {
547
556
  outcome: 'processed',
548
557
  ...(inspected.reason ? { reason: inspected.reason } : {}),
549
- events: inspected.proposals,
558
+ events: inspected.proposals.map(event => ({ ...event,
559
+ notificationContent: prepareNotificationContent(event.type, event.payload, input.currentState.state, 'custom') })),
550
560
  checkpoint,
551
561
  }
552
562
  : { outcome: 'noop', reason: inspected.reason ?? 'not_visual_state', checkpoint };
@@ -585,7 +595,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
585
595
  if (input.stored.frameSeq <= this.lastFrameSeq) {
586
596
  return { visual: null, proposals: [], moduleStates: this.moduleStateSnapshot() };
587
597
  }
588
- const stateFrameGap = this.lastFrameSeq > 0
598
+ const stateFrameGap = !input.stored.state.cycle && this.lastFrameSeq > 0
589
599
  && input.stored.frameSeq > this.lastFrameSeq + 1;
590
600
  this.lastFrameSeq = input.stored.frameSeq;
591
601
  const runtimeState = input.stored.state;
@@ -635,7 +645,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
635
645
  reason: 'segment_ending',
636
646
  };
637
647
  }
638
- if (runtimeState.game_snapshot.status !== 'fresh') {
648
+ if (runtimeState.game_snapshot.status !== 'fresh' && runtimeState.game_snapshot.status !== 'cached') {
639
649
  return {
640
650
  visual: null,
641
651
  proposals: [],
@@ -1159,7 +1169,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1159
1169
  context: RuntimeEpochPluginContext<Record<string, any>>,
1160
1170
  ): PerceptionAnalysisInput {
1161
1171
  this.rememberProjectedFrame(stored, currentVisual);
1162
- const cached = [...this.projectedFrameCache.values()]
1172
+ const cached = (context.processingIntervalMs !== undefined ? [] : [...this.projectedFrameCache.values()])
1163
1173
  .filter((value) => value.stored.frameSeq <= stored.frameSeq)
1164
1174
  .sort((left, right) => left.stored.frameSeq - right.stored.frameSeq)
1165
1175
  .slice(-(PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1));
@@ -1180,7 +1190,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1180
1190
  stored: StoredStateFrame<Record<string, any>>;
1181
1191
  visual: PerceptionFrame;
1182
1192
  }>();
1183
- let beforeFrameSeq = stored.frameSeq + 1;
1193
+ let beforeFrameSeq = stored.state.cycle?.stateFrameSeq ?? stored.frameSeq + 1;
1184
1194
  while (projected.size < PERCEPTION_ANALYSIS_WINDOW_FRAMES + 1 && beforeFrameSeq > 1) {
1185
1195
  context.signal.throwIfAborted();
1186
1196
  const page = context.stateHistory.queryStateFrames({
@@ -1191,6 +1201,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1191
1201
  });
1192
1202
  if (page.frames.length === 0) break;
1193
1203
  for (const candidate of page.frames) {
1204
+ if (stored.state.cycle && candidate.state.cycle) continue;
1194
1205
  if (candidate.frameSeq > stored.frameSeq) continue;
1195
1206
  const visual = candidate.frameSeq === stored.frameSeq
1196
1207
  ? currentVisual
@@ -1276,7 +1287,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1276
1287
  if (!isClawclawRuntimeState(runtimeState)) return true;
1277
1288
  return runtimeState.connection === 'connected'
1278
1289
  && runtimeState.stage !== 'ended'
1279
- && runtimeState.game_snapshot.status === 'fresh'
1290
+ && (runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')
1280
1291
  && !(
1281
1292
  runtimeState.cause === 'agent_events_query'
1282
1293
  && runtimeState.control?.type === 'events_query'
@@ -27,7 +27,7 @@ import { normalizeReactionManifest } from '../../reaction-manifest.js';
27
27
  import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
28
28
  import { normalizeReminderManifest } from '../../reminder-manifest.js';
29
29
  import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
30
- import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
30
+ import { normalizePerceptionModuleManifest, REMOVED_PERCEPTION_INPUT_TYPES } from '../../perception-module-manifest.js';
31
31
  import type { PerceptionModuleManifest } from '../../../../sdk/perception-plugin/module.js';
32
32
 
33
33
  export const MAX_PERCEPTION_FILES = 512;
@@ -39,6 +39,7 @@ const STATIC_MANIFEST = /\bstatic\s+(?:readonly\s+)?manifest\s*=\s*\{/;
39
39
  export interface ResolvedClawclawPerceptionSource {
40
40
  /** Literal source declaration; retained so the loader can diagnose unsupported modules. */
41
41
  readonly apiVersion?: number;
42
+ readonly compatibilityError?: string;
42
43
  readonly id: string;
43
44
  readonly declaredId?: string;
44
45
  readonly workingCopyPath?: string;
@@ -58,7 +59,7 @@ export function expectedPerceptionApiVersion(source: ResolvedClawclawPerceptionS
58
59
  return source.reaction ? 2 : source.module ? 3 : 2;
59
60
  }
60
61
  export function isSupportedPerceptionSource(source: ResolvedClawclawPerceptionSource): boolean {
61
- return source.apiVersion === expectedPerceptionApiVersion(source);
62
+ return !source.compatibilityError && source.apiVersion === expectedPerceptionApiVersion(source);
62
63
  }
63
64
 
64
65
  function pathInside(root: string, candidate: string): boolean {
@@ -364,9 +365,9 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
364
365
  if (classMatch[1] === 'ClawclawPerception' && /\bevaluate\s*\(/.test(classBody)
365
366
  && literalPluginApiVersion(manifestBlock) !== 2) {
366
367
  try {
367
- const module = normalizePerceptionModuleManifest(parseLiteralModuleManifest(manifestBlock), false);
368
+ const module = normalizePerceptionModuleManifest(parseLiteralModuleManifest(manifestBlock), false, true);
368
369
  const { id, description, localizations } = module;
369
- return { apiVersion: module.apiVersion, id, name: module.name ?? id, description, module, sourcePath, sourceRoot,
370
+ return { ...removedInputDiagnosis(module.consumes ?? []), apiVersion: module.apiVersion, id, name: module.name ?? id, description, module, sourcePath, sourceRoot,
370
371
  // Existing resource metadata consumers use this v2-shaped descriptor; executable v3 stays in module.
371
372
  manifest: { apiVersion: PERCEPTION_PLUGIN_API_VERSION, id, name: module.name ?? id, description, localizations,
372
373
  subjectScope: 'self_and_others', produces: module.produces ?? [] } };
@@ -386,10 +387,10 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
386
387
  }
387
388
  if (classMatch[1] === 'ClawclawReminder') {
388
389
  try {
389
- const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
390
+ const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false, true);
390
391
  const { id, description, localizations } = reminder;
391
392
  const name = reminder.name ?? id;
392
- return { apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
393
+ return { ...removedInputDiagnosis(reminder.consumes), apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
393
394
  manifest: { apiVersion: reminder.apiVersion, id, name, description, localizations,
394
395
  subjectScope: 'self_and_others', produces: [] } };
395
396
  } catch { return null; }
@@ -513,3 +514,8 @@ export function resolveClawclawPerceptionSource(
513
514
  if (!source) throw new Error(`Unknown perception module '${id}'.`);
514
515
  return source;
515
516
  }
517
+
518
+ function removedInputDiagnosis(consumes: readonly string[]): { compatibilityError?: string } {
519
+ const removed = consumes.filter(type => REMOVED_PERCEPTION_INPUT_TYPES.has(type));
520
+ return removed.length ? { compatibilityError: `perception_input_removed:${removed.join(',')}:use gameState, frame or module-local taskChanges` } : {};
521
+ }
@@ -0,0 +1,29 @@
1
+ import type { ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
2
+ import { nextTaskProjection, type TaskSnapshot } from '../../../../sdk/perception-plugin/task-change-tracker.js';
3
+ import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
4
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
5
+
6
+ /** Private to one perception/checkpoint. It does not subscribe to another perception. */
7
+ export interface PerceptionTaskBaseline { projection: TaskSnapshot[]; initialized: boolean }
8
+ export function comparePerceptionTasks(
9
+ baseline: PerceptionTaskBaseline | undefined,
10
+ input: RuntimeEpochPluginInput<Record<string, any>>,
11
+ boundary: 'initial' | 'recovery' | null,
12
+ ): { baseline: PerceptionTaskBaseline; changes: ReminderTaskChange[] } {
13
+ const previous = boundary === 'initial' ? undefined : baseline;
14
+ const game = clawclawComputationGameState(input.frame.state);
15
+ if (!game) return { baseline: previous ?? { projection: [], initialized: false }, changes: [] };
16
+ const update = nextTaskProjection({ previous: previous?.projection ?? [], initialized: previous?.initialized ?? false,
17
+ summary: { ...game, ...(input.frame.backendTick === undefined ? {} : { tick: input.frame.backendTick }) },
18
+ events: (input.epoch.state.cycle ? input.pendingEvents.filter(event => !event.notificationOf && !event.producerPluginId)
19
+ : input.epoch.events).map(event => ({ ...event.payload, type: event.type })),
20
+ selfName: game.you?.player?.name ?? game.you?.name,
21
+ allowUntickedInitialRole: isClawclawRuntimeState(input.frame.state)
22
+ && (input.frame.state.game_snapshot.status === 'fresh' || input.frame.state.game_snapshot.status === 'cached') && input.frame.state.game_snapshot.origin === 'update' });
23
+ // Stable local comparison identity; it is not an ID of a fabricated backend Event.
24
+ const eventId = `task-comparison:${input.epoch.scope.segmentId}:${input.epoch.epochSeq}`;
25
+ return { baseline: { projection: update.projection, initialized: update.initialized },
26
+ changes: (update.payload?.delta ?? []).map((change, index) => ({ ...change,
27
+ key: `${eventId}:${index}`, eventId, epochId: input.epoch.epochSeq,
28
+ baseline: !!boundary || update.payload!.baseline || update.payload!.reason === 'role_assigned' })) };
29
+ }
@@ -2063,6 +2063,12 @@ implements RuntimeSourcePlugin<Record<string, any>, Record<string, unknown>> {
2063
2063
  ): RuntimeSourceEvent<Record<string, unknown>>[] {
2064
2064
  const events: RuntimeSourceEvent<Record<string, unknown>>[] = [];
2065
2065
  const normalizedValues = normalizeGameSyncEventsSafely(values);
2066
+ for (const warning of normalizedValues.warnings ?? []) {
2067
+ this.diagnostic('runtime.source.event_field_preserved', {
2068
+ source_id: sourceId, source_seq: meta.sourceSeq, event_index: warning.index,
2069
+ field: warning.field, reason: warning.reason,
2070
+ }, 'warn');
2071
+ }
2066
2072
  normalizedValues.rejected.forEach(({ index, error }) => {
2067
2073
  const value = values[index];
2068
2074
  const raw = value && typeof value === 'object' && !Array.isArray(value)
@@ -0,0 +1,107 @@
1
+ import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput,
2
+ RuntimeEpochPluginResult, RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js';
3
+ import type { StoredStateFrame } from '../../../framework/state/index.js';
4
+ import type { ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
5
+
6
+ export class PerceptionRuleRunner
7
+ implements RuntimeEpochPlugin<Record<string, any>> {
8
+ readonly kind = 'epoch' as const;
9
+ readonly id: string;
10
+ readonly version = '2';
11
+ readonly produces: { events: readonly string[] };
12
+ readonly consumes: { events: readonly string[] };
13
+ // Never skip a computation boundary. Fixed-cadence boundaries may contain multiple Source inputs.
14
+ readonly catchUp = 'strict_ordered' as const;
15
+ readonly timeoutMs = 1_000;
16
+
17
+ private readonly rules: ClawclawDerivedEventRule[];
18
+ private lastFrameSeq = 0;
19
+
20
+ constructor(id: string, rules: readonly ClawclawDerivedEventRule[]) {
21
+ this.id = id;
22
+ this.rules = [...rules].sort((left, right) => left.id.localeCompare(right.id));
23
+ this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() };
24
+ this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() };
25
+ }
26
+
27
+ start(): void {
28
+ this.reset();
29
+ }
30
+
31
+ recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
32
+ const completedThrough = context.progress().completedThroughEpochSeq;
33
+ if (completedThrough <= 0) return;
34
+ if (context.processingIntervalMs !== undefined) {
35
+ const frame = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: completedThrough, order: 'desc', limit: 1 }).frames[0];
36
+ if (frame) {
37
+ const sourceEpoch = frame.state.cycle?.stateVersion ?? frame.epochSeq;
38
+ this.inspectFrame(frame, sourceEpoch ? context.sourceEventsAt?.(sourceEpoch) ?? [] : []);
39
+ }
40
+ return;
41
+ }
42
+ this.scanHistory(context, completedThrough, false);
43
+ }
44
+
45
+ update(
46
+ input: RuntimeEpochPluginInput<Record<string, any>>,
47
+ context: RuntimeEpochPluginContext<Record<string, any>>,
48
+ ): RuntimeEpochPluginResult {
49
+ const facts = input.pendingEvents.filter(event => !event.producerPluginId && !event.notificationOf)
50
+ .map(event => ({ type: event.type, payload: event.payload, producer: event.producer,
51
+ sourceEventId: event.sourceEventId, sourceSeq: event.sourceSequence, observedAt: event.occurredAt,
52
+ receivedAt: event.receivedAt, replayed: event.replayed }));
53
+ const events = context.processingIntervalMs !== undefined
54
+ ? this.inspectFrame(input.frame, facts)
55
+ : this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input);
56
+ return { ...(events.length > 0 ? { outcome: 'processed' as const, events }
57
+ : { outcome: 'noop' as const, reason: 'no_derived_event' }),
58
+ ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
59
+ }
60
+
61
+ stop(): void {
62
+ this.reset();
63
+ }
64
+
65
+ private scanHistory(
66
+ context: RuntimeEpochPluginContext<Record<string, any>>,
67
+ throughEpochSeq: number,
68
+ collect: boolean,
69
+ throughFrameSeq?: number,
70
+ currentInput?: RuntimeEpochPluginInput<Record<string, any>>,
71
+ ): RuntimeEventProposal[] {
72
+ if (this.rules.length === 0) return [];
73
+ const proposals: RuntimeEventProposal[] = [];
74
+ let afterFrameSeq = this.lastFrameSeq;
75
+ while (true) {
76
+ const page = context.stateHistory.queryStateFrames({
77
+ scope: context.scope,
78
+ afterFrameSeq,
79
+ toEpochSeq: throughEpochSeq,
80
+ ...(throughFrameSeq === undefined ? {} : { beforeFrameSeq: throughFrameSeq + 1 }),
81
+ order: 'asc',
82
+ limit: 500,
83
+ });
84
+ if (page.frames.length === 0) break;
85
+ for (const frame of page.frames) {
86
+ const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq)
87
+ ?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []);
88
+ const frameEvents = this.inspectFrame(frame, facts);
89
+ if (collect) proposals.push(...frameEvents);
90
+ afterFrameSeq = frame.frameSeq;
91
+ }
92
+ if (!page.page.hasMore) break;
93
+ }
94
+ return proposals;
95
+ }
96
+
97
+ private inspectFrame(frame: StoredStateFrame<Record<string, any>>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
98
+ if (frame.frameSeq <= this.lastFrameSeq) return [];
99
+ this.lastFrameSeq = frame.frameSeq;
100
+ return this.rules.flatMap((rule) => rule.inspect(frame, facts));
101
+ }
102
+
103
+ private reset(): void {
104
+ this.lastFrameSeq = 0;
105
+ for (const rule of this.rules) rule.reset();
106
+ }
107
+ }
@@ -0,0 +1,107 @@
1
+ import { prepareNotificationContent, notificationStateAt } from '../perception/notification-content.js';
2
+ import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
+ import { CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
4
+ import { BUILTIN_PERCEPTION_PREFIX, CLAWCLAW_SYSTEM_CONTROL_EVENTS } from '../../notification-policy.js';
5
+ import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule, RoomReadyDerivedEventRule,
6
+ type ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
7
+ import { PlayerChangesDerivedEventRule } from '../derived-event/state-change-rules.js';
8
+ import { PerceptionRuleRunner } from './rule-runner.js';
9
+ import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perception-plugin/reminder-rules.js';
10
+ import { clawclawComputationGameState } from '../../runtime-state.js';
11
+ import { createCanonicalGameState } from '../../behavior-input.js';
12
+ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
13
+
14
+ export const BUILTIN_PERCEPTION_NAMES = {
15
+ players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务',
16
+ flow: '房间与游戏流程', meeting: '会议', behavior: '策略消息',
17
+ } as const;
18
+ type Domain = keyof typeof BUILTIN_PERCEPTION_NAMES;
19
+ interface TaskCheckpoint { gameId?: string; connectionId?: string }
20
+
21
+ /** Native mandatory perception. Public resource loadouts cannot replace or disable it. */
22
+ export class SystemPerceptionPlugin extends PerceptionRuleRunner {
23
+ readonly agentNotificationProducer = true;
24
+ override readonly consumes: { events: readonly string[] };
25
+ override readonly produces: { events: readonly string[] };
26
+ readonly notificationRelay: { sourceEvents?: boolean; producerPluginIds?: readonly string[]; previousEpochOnly?: boolean };
27
+ private taskState: TaskCheckpoint = {};
28
+ constructor(readonly domain: Domain, private readonly forwardedTypes: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) {
29
+ super(`${BUILTIN_PERCEPTION_PREFIX}${domain}`, rules);
30
+ this.notificationRelay = domain === 'behavior'
31
+ ? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true };
32
+ this.consumes = { events: [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwardedTypes,
33
+ ...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])] };
34
+ this.produces = { events: [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwardedTypes,
35
+ ...(domain === 'tasks' ? ['reminder.task'] : [])])] };
36
+ }
37
+ override start(): void { super.start(); this.taskState = {}; }
38
+ override recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
39
+ super.recover(context);
40
+ if (this.domain === 'tasks') this.taskState = structuredClone(context.checkpoint() as TaskCheckpoint ?? {});
41
+ }
42
+ override update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): RuntimeEpochPluginResult {
43
+ const ruleResult = super.update(input, context);
44
+ const events: RuntimeEventProposal[] = [...(ruleResult.events ?? [])];
45
+ let cursor: number | undefined;
46
+ for (const event of input.pendingEvents) {
47
+ // A same-round Behavior output is deliberately held for the next round.
48
+ // Do not move the cursor past it, even if commit order overlaps epochs.
49
+ if (this.domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior'
50
+ && (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break;
51
+ cursor = event.commitSeq;
52
+ if (event.notificationOf || !this.forwardedTypes.includes(event.type)) continue;
53
+ if (this.domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
54
+ events.push({ type: event.type, forwardEventId: event.eventId, dedupeKey: event.eventId, payload: {},
55
+ notificationContent: prepareNotificationContent(event.type, event.payload, notificationStateAt(context, event.epochSeq), 'builtin', event) });
56
+ }
57
+ if (this.domain === 'tasks') {
58
+ const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
59
+ const game = raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
60
+ const boundary = game && this.taskState.gameId !== game.game_id ? 'initial'
61
+ : this.taskState.connectionId !== undefined && this.taskState.connectionId !== input.epoch.connectionId ? 'recovery' : null;
62
+ this.taskState = { gameId: game?.game_id ?? this.taskState.gameId, connectionId: input.epoch.connectionId };
63
+ // Task facts have one notification owner. Do not recreate them from State differences.
64
+ const result = defaultReminder('tasks', { scope: input.epoch.scope, gameState: game, frame: null,
65
+ facts: input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({
66
+ eventId: event.eventId, epochId: event.epochSeq, type: event.type, occurredAt: event.occurredAt,
67
+ producer: event.producer, replayed: event.replayed, payload: projectTaskChoiceEventPayload(game, event.type, event.payload),
68
+ })), taskChanges: [], boundary, config: {}, state: undefined,
69
+ nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs });
70
+ for (const event of result.events ?? []) events.push({ type: event.type, dedupeKey: event.key,
71
+ wakeAgent: event.wakeAgent, payload: { ...event.payload }, occurredAt: new Date(input.frame.receivedAtMs).toISOString() });
72
+ }
73
+ const notifications = events.map(event => event.notificationContent ? event : { ...event,
74
+ notificationContent: prepareNotificationContent(event.type, event.payload,
75
+ notificationStateAt(context, input.epoch.epochSeq), 'builtin', { producer: 'local_synth', producerPluginId: this.id }),
76
+ });
77
+ return { outcome: events.length ? 'processed' : 'noop', events: notifications,
78
+ ...(this.domain === 'tasks' ? { checkpoint: structuredClone(this.taskState) } : {}),
79
+ ...(cursor === undefined ? {} : { consumeEventsThroughCommitSeq: cursor }) };
80
+ }
81
+ }
82
+
83
+ /** Every currently public Source gameplay Event has exactly one builtin owner. */
84
+ export function createSystemPerceptions(behaviorEventTypes: readonly string[] = []): SystemPerceptionPlugin[] {
85
+ const groups: Record<Exclude<Domain, 'behavior'>, string[]> = {
86
+ players: ['kill', 'killed', 'murder_witnessed', 'body_dropped', 'corpse_spotted', 'warrior_shrimp_self_destruct', 'role_assigned'],
87
+ tasks: [], abilities: [],
88
+ emergency: ['emergency_started', 'emergency_resolved', 'emergency_interrupted'],
89
+ meeting: ['exile', 'no_exile', 'vote_speech_phase_ended', 'death_speech', 'meeting_briefing',
90
+ 'speech', 'speech_skipped', 'speech_your_turn', 'speech_next_turn', 'vote_phase_start'],
91
+ flow: [],
92
+ };
93
+ const assigned = new Set(Object.values(groups).flat());
94
+ groups.flow = [...CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, 'game_over_recovered', 'robot_speak_rule']
95
+ .filter(type => !assigned.has(type) && !CLAWCLAW_SYSTEM_CONTROL_EVENTS.has(type));
96
+ const behaviorTypes = [...new Set([...CLAWCLAW_LOCAL_AGENT_EVENT_TYPES.filter(type => type.startsWith('behavior.') || type === 'strategy_alert'),
97
+ ...behaviorEventTypes])];
98
+ return [
99
+ new SystemPerceptionPlugin('players', groups.players, [new PlayerChangesDerivedEventRule()]),
100
+ new SystemPerceptionPlugin('tasks', groups.tasks),
101
+ new SystemPerceptionPlugin('abilities', groups.abilities, [new AbilityStateDerivedEventRule()]),
102
+ new SystemPerceptionPlugin('emergency', groups.emergency, [new EmergencyCountdownDerivedEventRule()]),
103
+ new SystemPerceptionPlugin('flow', groups.flow, [new RoomReadyDerivedEventRule()]),
104
+ new SystemPerceptionPlugin('meeting', groups.meeting),
105
+ new SystemPerceptionPlugin('behavior', behaviorTypes),
106
+ ];
107
+ }
@@ -1,3 +1,4 @@
1
+ import { isNotificationTurn } from '../../notification-turn.js';
1
2
  import type {
2
3
  ClawclawTrigger,
3
4
  TriggerInput,
@@ -205,6 +206,7 @@ function triggerInputFor(
205
206
  : semanticInput.events.filter((event) => consumes.has(event.type));
206
207
  return Object.freeze({
207
208
  frame,
209
+ ...(semanticInput.cycle ? { cycle: semanticInput.cycle } : {}),
208
210
  events: Object.freeze(events),
209
211
  input: config.input,
210
212
  });
@@ -218,7 +220,8 @@ function behaviorInputForTrigger(
218
220
  return Object.freeze({
219
221
  epochId: semanticInput.epochId,
220
222
  scope: semanticInput.scope,
221
- nowMs: frame.timeMs,
223
+ nowMs: semanticInput.nowMs,
224
+ ...(semanticInput.cycle ? { cycle: semanticInput.cycle } : {}),
222
225
  gameState: frame.gameState,
223
226
  events: triggerInput.events,
224
227
  input: triggerInput.input,
@@ -401,6 +404,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
401
404
  input: RuntimeEpochPluginInput<Record<string, any>>,
402
405
  context: RuntimeEpochPluginContext<Record<string, any>>,
403
406
  ): Promise<RuntimeEpochPluginResult> {
407
+ if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' };
404
408
  this.currentScope = input.epoch.scope;
405
409
  // Keep the live configure/enable entry point, but do no observation or Worker work while empty.
406
410
  if (![...this.registrations.values()].some(config => this.isEnabled(config))) {
@@ -419,7 +423,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
419
423
  // excluded so rule evaluation has no hidden computation-plugin dependency.
420
424
  const triggerVisibleInput = {
421
425
  ...input,
422
- pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push'),
426
+ pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push' && !event.notificationOf && event.producerPluginId === undefined),
423
427
  } satisfies RuntimeEpochPluginInput<Record<string, any>>;
424
428
  const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({}));
425
429
  if (
@@ -556,7 +560,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
556
560
  const eventCursor = input.pendingEvents.at(-1)?.commitSeq;
557
561
  const triggerVisibleInput = {
558
562
  ...input,
559
- pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push'),
563
+ pendingEvents: input.pendingEvents.filter((event) => event.producer === 'backend_push' && !event.notificationOf && event.producerPluginId === undefined),
560
564
  } satisfies RuntimeEpochPluginInput<Record<string, any>>;
561
565
  const emptyInput = createBehaviorInput(triggerVisibleInput, Object.freeze({}));
562
566
  const baseProposal = (nowMs: number, evaluations: readonly ClawclawTriggerEvaluation[]) => ({
@@ -668,6 +672,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
668
672
  computation: Readonly<RuntimeEpochPluginResult>,
669
673
  context: RuntimeEpochPluginContext<Record<string, any>>,
670
674
  ): Promise<RuntimeEpochPluginResult> {
675
+ if (isNotificationTurn(input.epoch.state)) return computation;
671
676
  const computed = proposal(computation.proposal);
672
677
  if (computed.configGeneration !== this.configGeneration) {
673
678
  return {
@@ -1,23 +1 @@
1
- import type { ReactionBehaviorBinding } from '../../sdk/perception-plugin/reaction.js';
2
-
3
- export interface ReactionBehaviorCandidate {
4
- readonly id: string;
5
- readonly declaredId?: string;
6
- readonly resourceId?: string;
7
- readonly loadable: boolean;
8
- }
9
-
10
- /** Shared by load diagnostics and the live activation path. Never selects disabled/unloaded entries. */
11
- export function resolveReactionBehavior(binding: ReactionBehaviorBinding, candidates: readonly ReactionBehaviorCandidate[]): string | undefined {
12
- const available = candidates.filter(candidate => candidate.loadable);
13
- const compare = (a: ReactionBehaviorCandidate, b: ReactionBehaviorCandidate) =>
14
- Number(b.id === binding.name) - Number(a.id === binding.name)
15
- || a.id.localeCompare(b.id, 'en', { numeric: true }) || String(a.resourceId).localeCompare(String(b.resourceId));
16
- const preferred = binding.resourceId && available.filter(candidate => candidate.resourceId === binding.resourceId).sort(compare)[0];
17
- if (preferred) return preferred.id;
18
- // Declared source identity distinguishes real duplicate aliases from an unrelated literal escape_1.
19
- const named = available.filter(candidate => candidate.id === binding.name || candidate.declaredId === binding.name
20
- || candidate.declaredId === undefined && candidate.id.startsWith(`${binding.name}_`)
21
- && /^[1-9][0-9]*$/.test(candidate.id.slice(binding.name.length + 1))).sort(compare);
22
- return named[0]?.id;
23
- }
1
+ export * from '@myclaw163/game-agent-runtime/perception/binding-resolution.js';
@@ -1,10 +1,11 @@
1
+ import { REMOVED_PERCEPTION_INPUT_TYPES } from './perception-module-manifest.js';
1
2
  import { REMINDER_PLUGIN_API_VERSION, type ClawclawReminderManifest } from '../../sdk/perception-plugin/reminder.js';
2
3
  import { REMINDER_FACT_TYPES_BY_TOPIC, REMINDER_TOPICS } from '../../sdk/perception-plugin/reminder-rules.js';
3
4
  import { hasValidClawclawResourceLocalizations } from '../../sdk/resource-metadata.js';
4
5
  import { normalizeBehaviorInput, normalizeBehaviorInputFields } from './behavior-input-fields.js';
5
6
 
6
7
  /** Used by both static Perception discovery and the isolated runtime loader. */
7
- export function normalizeReminderManifest(value: unknown, requireCurrentVersion = true): ClawclawReminderManifest {
8
+ export function normalizeReminderManifest(value: unknown, requireCurrentVersion = true, discoverRemovedInputs = false): ClawclawReminderManifest {
8
9
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid perception reminder manifest.');
9
10
  const m = value as ClawclawReminderManifest;
10
11
  if (m.kind !== 'reminder' || !Number.isInteger(m.apiVersion)
@@ -15,10 +16,12 @@ export function normalizeReminderManifest(value: unknown, requireCurrentVersion
15
16
  || !hasValidClawclawResourceLocalizations(m.localizations)
16
17
  || !REMINDER_TOPICS.includes(m.topic)
17
18
  || !Array.isArray(m.consumes) || new Set(m.consumes).size !== m.consumes.length
18
- || m.consumes.some(type => !(REMINDER_FACT_TYPES_BY_TOPIC[m.topic] as readonly string[]).includes(type))
19
+ || m.consumes.some(type => !(REMINDER_FACT_TYPES_BY_TOPIC[m.topic] as readonly string[]).includes(type)
20
+ && !(discoverRemovedInputs && REMOVED_PERCEPTION_INPUT_TYPES.has(type)))
19
21
  || (m.config !== undefined && (!m.config || typeof m.config !== 'object' || Array.isArray(m.config)))
20
22
  || Object.keys(m).some(key => !['apiVersion', 'kind', 'id', 'name', 'description', 'localizations',
21
23
  'topic', 'consumes', 'inputs', 'config'].includes(key))) throw new Error('Invalid perception reminder manifest.');
24
+ if (!discoverRemovedInputs && m.consumes.some(type => REMOVED_PERCEPTION_INPUT_TYPES.has(type))) throw new Error('perception_input_removed: use gameState or module-local taskChanges');
22
25
  const inputs = m.inputs === undefined ? undefined : normalizeBehaviorInputFields(m.inputs);
23
26
  const config = inputs ? normalizeBehaviorInput(m.config ?? {}, inputs) : structuredClone(m.config ?? {});
24
27
  return { apiVersion: m.apiVersion, kind: 'reminder', id: m.id, description: m.description,
@@ -0,0 +1,24 @@
1
+ import type { RuntimeProcessingCadence } from '../framework/runtime.js';
2
+ import { freshClawclawGameState, isClawclawRuntimeState } from './runtime-state.js';
3
+
4
+ /** A local cycle reuses an observation; it never claims a new backend snapshot. */
5
+ export function createClawclawProcessingCadence(intervalMs: number): RuntimeProcessingCadence {
6
+ return { intervalMs,
7
+ isStateUpdate: input => isClawclawRuntimeState(input.state)
8
+ && input.state.cause !== 'agent_events_query' && input.state.cause !== 'control',
9
+ createState: ({ latestInput, latestStateFrame, cycle }) => {
10
+ const latest = latestInput.state;
11
+ if (!isClawclawRuntimeState(latest)) throw new Error('CCL processing cycles require ClawClaw Runtime State.');
12
+ const previous = latestStateFrame?.state;
13
+ const game = previous && freshClawclawGameState(previous);
14
+ const canReuse = game && latestStateFrame?.connectionId === latestInput.connectionId
15
+ && latest.stage !== 'room' && latest.stage !== 'matching';
16
+ const { control: _control, ...state } = latest;
17
+ return { ...state, cause: cycle.notificationOnly ? 'control' : 'processing_cycle',
18
+ ...(cycle.notificationOnly ? { control: { type: 'perception_notifications' } } : {}),
19
+ game_snapshot: canReuse ? { status: 'cached', state: structuredClone(game),
20
+ ...(isClawclawRuntimeState(previous) && previous.game_snapshot.status === 'fresh'
21
+ ? { origin: previous.game_snapshot.origin } : {}) } : { status: 'not_updated' },
22
+ };
23
+ } };
24
+ }