@myclaw163/clawclaw-cli 0.9.1 → 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 (216) 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 +27 -40
  7. package/docs/custom-modules/api-reference.md +132 -273
  8. package/docs/custom-modules/behavior.md +185 -75
  9. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +46 -806
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +18 -19
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +54 -48
  19. package/docs/runtime/components-and-boundaries.md +87 -137
  20. package/docs/runtime/events-and-state.md +52 -17
  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 +12 -9
  26. package/docs/user-guide/api-reference.md +132 -180
  27. package/docs/user-guide/behavior.md +175 -65
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +46 -789
  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 +9 -14
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +50 -48
  37. package/skills/clawclaw/references/BEHAVIORS.md +45 -65
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +65 -87
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
  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 +49 -104
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +18 -25
  53. package/src/commands/module-runtime-control.ts +113 -0
  54. package/src/commands/perception.ts +23 -4
  55. package/src/commands/strategy.ts +2 -0
  56. package/src/commands/trigger.ts +1 -1
  57. package/src/lib/capability-load-diagnostics.ts +3 -3
  58. package/src/lib/perception-config.ts +18 -6
  59. package/src/lib/runtime-cadence-config.ts +16 -0
  60. package/src/lib/workspace-runtime-lock.ts +3 -46
  61. package/src/pipeline/canonical-event-presentation.ts +23 -124
  62. package/src/pipeline/event-format.ts +12 -21
  63. package/src/pipeline/event-hints.ts +6 -6
  64. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  65. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  66. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  67. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  68. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  69. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  70. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  71. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  72. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  73. package/src/runtime/clawclaw/owner.ts +67 -8
  74. package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
  75. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  76. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  77. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  78. package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
  79. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  82. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  83. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  84. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
  85. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
  86. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  87. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  88. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  89. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
  90. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
  91. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
  92. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  93. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  94. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  95. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
  96. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  97. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  98. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  99. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  100. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  101. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  102. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  103. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  104. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  105. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  106. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  107. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
  108. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
  109. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
  110. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
  111. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
  112. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  113. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
  114. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  115. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  116. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  117. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  118. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
  119. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  120. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  121. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  122. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  123. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  124. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  125. package/src/runtime/clawclaw/runtime-state.ts +12 -1
  126. package/src/runtime/clawclaw/runtime.ts +11 -3
  127. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
  128. package/src/runtime/clawclaw/strategy-memory.ts +1 -0
  129. package/src/runtime/clawclaw-event-catalog.ts +17 -17
  130. package/src/runtime/framework/action-diagnostics.ts +3 -83
  131. package/src/runtime/framework/capability-registry.ts +2 -395
  132. package/src/runtime/framework/contracts.ts +2 -144
  133. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  134. package/src/runtime/framework/control/domain-set.ts +2 -81
  135. package/src/runtime/framework/control/index.ts +1 -3
  136. package/src/runtime/framework/control/types.ts +2 -191
  137. package/src/runtime/framework/control-coordinator.ts +2 -11
  138. package/src/runtime/framework/events/event-catalog.ts +2 -74
  139. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  140. package/src/runtime/framework/events/event-ingress.ts +2 -99
  141. package/src/runtime/framework/events/event-repository.ts +2 -82
  142. package/src/runtime/framework/events/index.ts +2 -7
  143. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  144. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  145. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  146. package/src/runtime/framework/events/test-helpers.ts +1 -1
  147. package/src/runtime/framework/events/types.ts +2 -312
  148. package/src/runtime/framework/index.ts +3 -7
  149. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  150. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  151. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  152. package/src/runtime/framework/mailbox/identity.ts +2 -38
  153. package/src/runtime/framework/mailbox/index.ts +1 -7
  154. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  155. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  156. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  157. package/src/runtime/framework/mailbox/types.ts +2 -145
  158. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  159. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  160. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  161. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  162. package/src/runtime/framework/participation-manager.ts +2 -253
  163. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  164. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  165. package/src/runtime/framework/plugins/contracts.ts +2 -388
  166. package/src/runtime/framework/plugins/index.ts +1 -4
  167. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  168. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  169. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
  170. package/src/runtime/framework/runtime.ts +5 -1843
  171. package/src/runtime/framework/serial-task-queue.ts +2 -14
  172. package/src/runtime/framework/state/contracts.ts +2 -49
  173. package/src/runtime/framework/state/current-state-store.ts +2 -184
  174. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  175. package/src/runtime/framework/state/freshness.ts +2 -72
  176. package/src/runtime/framework/state/history/contracts.ts +2 -158
  177. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  178. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  179. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  180. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  181. package/src/runtime/framework/state/index.ts +1 -13
  182. package/src/runtime/framework/state/state-ingress.ts +2 -95
  183. package/src/runtime/framework/state/state-provider.ts +2 -62
  184. package/src/runtime/framework/state/types.ts +2 -155
  185. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  186. package/src/runtime/mailbox-host-relay.ts +1 -326
  187. package/src/runtime/observability/detail-capture.ts +4 -108
  188. package/src/runtime/observability/process-timing.ts +2 -59
  189. package/src/runtime/observability/recorder.ts +2 -238
  190. package/src/runtime/observability/redaction.ts +2 -181
  191. package/src/runtime/observability/reporter.ts +2 -154
  192. package/src/runtime/observability/sinks.ts +2 -135
  193. package/src/runtime/observability/types.ts +2 -92
  194. package/src/runtime/owner-control.ts +45 -315
  195. package/src/runtime/parent-process-watch.ts +1 -51
  196. package/src/runtime/process-identity.ts +1 -72
  197. package/src/sdk/behavior-plugin/index.ts +13 -4
  198. package/src/sdk/index.ts +44 -3
  199. package/src/sdk/module-input/index.ts +5 -0
  200. package/src/sdk/perception-plugin/index.ts +9 -5
  201. package/src/sdk/perception-plugin/module.ts +25 -6
  202. package/src/sdk/perception-plugin/reaction.ts +1 -1
  203. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  204. package/src/sdk/perception-plugin/reminder.ts +2 -1
  205. package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
  206. package/src/sdk/strategy-memory.ts +1 -0
  207. package/src/sdk/strategy-plugin/index.ts +36 -0
  208. package/src/sdk/trigger-plugin/index.ts +4 -3
  209. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  210. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  211. package/docs/custom-modules/trigger.md +0 -295
  212. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  213. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
  214. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
  215. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  216. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -0,0 +1 @@
1
+ export * from '@myclaw163/game-agent-runtime/perception/map-concurrent.js';
@@ -0,0 +1,60 @@
1
+ import type { EventNotificationContent } from '../../../framework/events/types.js';
2
+ import type { RuntimeEpochPluginContext } from '../../../framework/plugins/index.js';
3
+ import { compactEventForChannel, formatEventMessage } from '../../../../pipeline/event-format.js';
4
+ import { formatCanonicalEventHint, type EventHintOrigin } from '../../../../pipeline/event-hints.js';
5
+ import { buildLocalGameStartedEnrichment } from '../../../../lib/game-context.js';
6
+ import { projectClawclawCurrentState } from '../../runtime-state.js';
7
+
8
+ export type NotificationOwner = 'builtin' | 'custom' | 'system';
9
+
10
+ /** Policy belongs to the producing perception/system notification, not EventIngress or delivery. */
11
+ export function prepareNotificationContent(
12
+ type: string,
13
+ payload: Readonly<Record<string, unknown>>,
14
+ state: Record<string, any> | null,
15
+ owner: NotificationOwner,
16
+ origin: EventHintOrigin = { producer: 'local_synth' },
17
+ ): EventNotificationContent {
18
+ const { hint, next_step: _next, notice: _notice, ...facts } = structuredClone(payload);
19
+ const event = compactEventForChannel({ ...facts, type }, { summary: state });
20
+ if (owner === 'builtin' && type === 'game_started') Object.assign(event, buildLocalGameStartedEnrichment());
21
+ // meeting_briefing.speech_order is exclusively backend-owned. Never fill a missing order from State.
22
+ const ownedHint = owner === 'custom'
23
+ ? typeof hint === 'string' && hint.trim() ? hint : undefined
24
+ : formatCanonicalEventHint(origin, event, { summary: state });
25
+ if (ownedHint !== undefined) event.hint = ownedHint;
26
+ const content: EventNotificationContent = {
27
+ event,
28
+ monitorText: type.startsWith('visual.') ? `${type} | ${String(event.text ?? '')}`.trimEnd()
29
+ : formatEventMessage(event, { summary: state, maxTextLength: Number.MAX_SAFE_INTEGER }),
30
+ };
31
+ if (owner === 'system' && ['joined', 'room_created', 'room_joined', 'session_resumed'].includes(type)) {
32
+ const omitLinks = (value: any): any => Array.isArray(value) ? value.map(omitLinks)
33
+ : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value)
34
+ .filter(([key]) => !['url', 'spectate_url', 'spectateUrl'].includes(key)).map(([key, item]) => [key, omitLinks(item)])) : value;
35
+ const desktop = omitLinks(event);
36
+ if (type === 'joined') desktop.hint = event.recovered === true || event.resumed === true
37
+ ? 'The game runtime reattached; do not start a duplicate runtime.' : 'The game runtime is attached; do not start a duplicate runtime.';
38
+ if (type === 'room_created') desktop.hint = 'Keep the room runtime attached.';
39
+ if (type === 'room_joined') desktop.hint = event.recovered === true || event.resumed === true
40
+ ? 'The room runtime reattached; keep it attached.' : 'Keep the room runtime attached.';
41
+ content.desktopEvent = desktop;
42
+ }
43
+ return content;
44
+ }
45
+
46
+ /** The event's accepted State boundary, never the newer State at delivery time. */
47
+ export function notificationStateAt(context: RuntimeEpochPluginContext<Record<string, any>>, epochSeq: number | undefined): Record<string, any> | null {
48
+ if (epochSeq === undefined) return null;
49
+ let beforeFrameSeq: number | undefined;
50
+ while (true) {
51
+ const page = context.stateHistory.queryStateFrames({ scope: context.scope, toEpochSeq: epochSeq,
52
+ ...(beforeFrameSeq === undefined ? {} : { beforeFrameSeq }), order: 'desc', limit: 64 });
53
+ for (const frame of page.frames) {
54
+ const state = projectClawclawCurrentState(frame.state);
55
+ if (state) return state;
56
+ }
57
+ if (!page.page.hasMore || !page.frames.length) return null;
58
+ beforeFrameSeq = page.frames.at(-1)!.frameSeq;
59
+ }
60
+ }
@@ -0,0 +1,136 @@
1
+ import { normalizePerceptionStrategyNames } from '../../perception-strategy-names.js';
2
+ import { prepareNotificationContent } from './notification-content.js';
3
+ import { isNotificationTurn } from '../../notification-turn.js';
4
+ import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
5
+ import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
6
+ import { type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
7
+ import { ObservationFrameProjector } from '../../observation-frame-projector.js';
8
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
9
+ import { createCanonicalGameState } from '../../behavior-input.js';
10
+ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
11
+ import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
12
+ import { PerceptionModuleRunner } from './perception-module-runner.js';
13
+ import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
14
+ import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
15
+ import { comparePerceptionTasks, type PerceptionTaskBaseline } from './task-baseline.js';
16
+ import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
17
+ import type { PerceptionAdapter, PerceptionSource } from '@myclaw163/game-agent-runtime/perception/contracts.js';
18
+ import type { ClawclawResolvedResourceMetadata } from '../../../../sdk/resource-metadata.js';
19
+ export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
20
+ export { REACTION_HOST_EVENT_TYPES } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
21
+ export interface PerceptionModulePluginOptions {
22
+ /** Unified execution, including verified v2 Reaction consumers, at the source/system observation boundary. */
23
+ sources: readonly ResolvedClawclawPerceptionSource[];
24
+ after: readonly string[];
25
+ behaviors?: () => readonly ReactionBehaviorCandidate[];
26
+ runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
27
+ }
28
+ interface GameCheckpoint {
29
+ gameId?: string;
30
+ phase?: string;
31
+ connectionId?: string;
32
+ previousTick?: number;
33
+ modules: Record<string, {
34
+ value?: unknown;
35
+ bindings: Record<string, {
36
+ armed: boolean;
37
+ lastAcceptedAt?: number;
38
+ failedAttempt?: string;
39
+ }>;
40
+ }>;
41
+ }
42
+ function sourceValue(source: PerceptionSource): ResolvedClawclawPerceptionSource { return source.value as ResolvedClawclawPerceptionSource; }
43
+ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapter {
44
+ const projector = new ObservationFrameProjector();
45
+ function prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown) {
46
+ let checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint;
47
+ checkpoint.modules = {};
48
+ const oldGame = checkpoint.gameId, oldPhase = checkpoint.phase;
49
+ const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
50
+ const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
51
+ const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
52
+ const initial = !!game && checkpoint.gameId !== game.game_id;
53
+ const boundary = initial ? 'initial' as const : checkpoint.connectionId !== undefined
54
+ && checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
55
+ if (game && checkpoint.gameId !== game.game_id)
56
+ checkpoint = { gameId: game.game_id, modules: {} };
57
+ if ((!game && checkpoint.phase !== undefined)
58
+ || (game && checkpoint.phase !== game.phase)) {
59
+ checkpoint.previousTick = undefined;
60
+ for (const state of Object.values(checkpoint.modules)) {
61
+ state.value = undefined;
62
+ for (const binding of Object.values(state.bindings)) {
63
+ binding.armed = true;
64
+ binding.lastAcceptedAt = undefined;
65
+ binding.failedAttempt = undefined;
66
+ }
67
+ }
68
+ checkpoint.phase = game?.phase;
69
+ }
70
+ const frame = projector.project(input.frame);
71
+ if (frame) {
72
+ const delta = checkpoint.previousTick === undefined ? null : frame.tick - checkpoint.previousTick;
73
+ Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
74
+ && checkpoint.connectionId === input.epoch.connectionId });
75
+ checkpoint.previousTick = frame.tick;
76
+ }
77
+ const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
78
+ const facts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined).map(event => ({
79
+ eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
80
+ type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
81
+ payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
82
+ }));
83
+ const resetScope = !!game && oldGame !== game.game_id;
84
+ const resetModules = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase);
85
+ checkpoint.connectionId = input.epoch.connectionId;
86
+ return { state: checkpoint, identity: game?.game_id, resetScope, resetModules, notificationOnly: false, nowMs,
87
+ reflexAllowed: !!game && game.phase === 'wandering' && game.you?.is_alive === true && connected,
88
+ value: { input, game, frame, facts, boundary } };
89
+ }
90
+ type Prepared = ReturnType<typeof prepare>['value'];
91
+ return {
92
+ reset: () => projector.reset(),
93
+ recover: saved => {
94
+ const value = saved as {
95
+ adapterState?: unknown;
96
+ modules?: Record<string, Record<string, unknown>>;
97
+ } & GameCheckpoint;
98
+ for (const state of Object.values(value.modules ?? {}))
99
+ if (state.inputState === undefined && 'taskBaseline' in state) {
100
+ state.inputState = state.taskBaseline;
101
+ delete state.taskBaseline;
102
+ }
103
+ return value.adapterState ?? { gameId: value.gameId, phase: value.phase, connectionId: value.connectionId, previousTick: value.previousTick, modules: {} };
104
+ },
105
+ prepare: (input, previous) => isNotificationTurn(input.epoch.state)
106
+ ? { state: previous, resetScope: false, resetModules: false, notificationOnly: true, nowMs: 0, reflexAllowed: false, value: null }
107
+ : prepare(input, previous),
108
+ configure: (source, value) => normalizeBehaviorInput(value, sourceValue(source).module!.inputs ?? []),
109
+ describe: (source, locale) => { const value = sourceValue(source); return resolveClawclawResourceMetadata({ ...value.manifest, display: value.display }, locale); },
110
+ createRunner: (source, bindMemory) => {
111
+ const value = sourceValue(source);
112
+ const runner = options.runnerFactory?.(value) ?? new PerceptionModuleRunner(value, (input, active) => bindMemory({ scope: input.scope, value: input }, active));
113
+ return { start: () => runner.start(), stop: () => runner.stop(), evaluate: async (input) => normalizePerceptionStrategyNames(await runner.evaluate(input.value as PerceptionModuleInput)) };
114
+ },
115
+ input: (source, prepared, baseline, state, config, bindings) => {
116
+ const { input, game, frame, facts, boundary } = prepared.value as Prepared;
117
+ const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
118
+ const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
119
+ ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
120
+ events: facts.filter(event => source.module.consumes?.includes(event.type)), nowMs: prepared.nowMs,
121
+ state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
122
+ return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
123
+ evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || moduleInput.events.length > 0 };
124
+ },
125
+ notification: (event, prepared) => prepareNotificationContent(event.type, event.payload, (prepared.value as Prepared).game, 'custom'),
126
+ };
127
+ }
128
+ export class ClawclawPerceptionModulePlugin extends PerceptionHost {
129
+ constructor(options: PerceptionModulePluginOptions) {
130
+ super({ id: CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID, after: options.after, behaviors: options.behaviors, adapter: createAdapter(options),
131
+ sources: options.sources.filter(source => source.module).map(source => ({ id: source.id, name: source.name, module: source.module!, value: source })) });
132
+ }
133
+ override localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
134
+ return super.localizedModuleDescriptors(locale) as ClawclawResolvedResourceMetadata[];
135
+ }
136
+ }
@@ -0,0 +1,13 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { PerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker.js';
3
+ import type { PerceptionModuleInput, PerceptionModuleResult } from '../../../../sdk/perception-plugin/module.js';
4
+ import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
5
+ import { runtimeModuleThreadLoaderConfig } from '../../../framework/modules/runtime-module-loader.js';
6
+ import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
7
+ export class PerceptionModuleRunner extends PerceptionWorker<PerceptionModuleInput, PerceptionModuleResult> {
8
+ constructor(readonly source: ResolvedClawclawPerceptionSource, bindMemory?: (input: PerceptionModuleInput, active: () => boolean) => StrategyMemory) {
9
+ super({ compatibilityError: source.compatibilityError, workerData: { modulePath: source.sourcePath, expectedManifest: source.module,
10
+ legacy: !!source.reaction, runtimeModuleBootstrap: { hostUrl: new URL('./perception-module-worker.ts', import.meta.url).href,
11
+ ...runtimeModuleThreadLoaderConfig(), esmModuleRoots: [new URL('.', pathToFileURL(source.sourcePath)).href] } } }, bindMemory);
12
+ }
13
+ }
@@ -1,28 +1,17 @@
1
- import { parentPort, workerData } from 'node:worker_threads';
2
1
  import { pathToFileURL } from 'node:url';
3
- import { ClawclawPerception } from '../../../../sdk/perception-plugin/index.js';
2
+ import { runPerceptionWorker } from '@myclaw163/game-agent-runtime/perception/perception-worker-host.js';
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
+ import { normalizeReactionManifest } from '../../reaction-manifest.js';
6
7
 
7
- function freeze<T>(value: T): T {
8
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
9
- for (const child of Object.values(value)) freeze(child); Object.freeze(value);
10
- }
11
- return value;
12
- }
13
- try {
14
- const Module = (await import(pathToFileURL(workerData.modulePath).href)).default;
15
- if (!(Module?.prototype instanceof ClawclawPerception)
16
- || Module.prototype.evaluate === ClawclawPerception.prototype.evaluate) throw new Error('PERCEPTION_MODULE_CLASS_INVALID');
17
- const manifest = normalizePerceptionModuleManifest(Module.manifest);
18
- if (JSON.stringify(manifest) !== JSON.stringify(workerData.expectedManifest)) throw new Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
19
- parentPort!.postMessage({ type: 'ready' });
20
- parentPort!.on('message', async ({ id, input }: { id: number; input: PerceptionModuleInput }) => {
21
- try {
22
- const result = await new Module().evaluate(freeze({ ...input, config: manifest.config ?? {},
23
- events: input.events.filter(event => manifest.consumes?.includes(event.type)) }));
24
- if (Buffer.byteLength(JSON.stringify(result) ?? '') > 128_000) throw new Error('PERCEPTION_MODULE_OUTPUT_TOO_LARGE');
25
- parentPort!.postMessage({ type: 'result', id, result });
26
- } catch { parentPort!.postMessage({ type: 'error', id }); }
27
- });
28
- } 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,
@@ -327,7 +329,7 @@ function createModuleSlots(
327
329
  const source = sources.get(id);
328
330
  if (!source) throw new Error(`Unknown perception module '${id}'.`);
329
331
  return source;
330
- }).filter(source => !source.reminder && !source.reaction && !source.module);
332
+ }).filter(source => !source.reminder && !source.module);
331
333
  const reducerPool = selected.length > 0
332
334
  ? new PerceptionReducerThreadPool({
333
335
  modules: selected.map((source) => loader.threadSpec(source)),
@@ -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'
@@ -23,11 +23,11 @@ import type {
23
23
  import { PERCEPTION_PLUGIN_API_VERSION } from './contracts.js';
24
24
  import { literalPluginApiVersion } from '../plugin-api-version.js';
25
25
  import { parseLiteralModuleManifest } from '../behavior-input-source.js';
26
+ import { normalizeReactionManifest } from '../../reaction-manifest.js';
27
+ import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
26
28
  import { normalizeReminderManifest } from '../../reminder-manifest.js';
27
29
  import type { ClawclawReminderManifest } from '../../../../sdk/perception-plugin/reminder.js';
28
- import type { ClawclawReactionManifest } from '../../../../sdk/perception-plugin/reaction.js';
29
- import { normalizeReactionManifest } from '../../reaction-manifest.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;
@@ -48,17 +49,17 @@ export interface ResolvedClawclawPerceptionSource {
48
49
  readonly manifest: ClawclawPerceptionManifest;
49
50
  /** Non-visual execution contract; manifest above is the common resource descriptor. */
50
51
  readonly reminder?: ClawclawReminderManifest;
51
- readonly reaction?: ClawclawReactionManifest;
52
52
  readonly module?: PerceptionModuleManifest;
53
+ readonly reaction?: ClawclawReactionManifest;
53
54
  readonly sourcePath: string;
54
55
  readonly sourceRoot: string;
55
56
  }
56
57
 
57
58
  export function expectedPerceptionApiVersion(source: ResolvedClawclawPerceptionSource): number {
58
- return source.module ? 3 : 2;
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 ?? [] } };
@@ -375,19 +376,21 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
375
376
  if (classMatch[1] === 'ClawclawReaction') {
376
377
  try {
377
378
  const reaction = normalizeReactionManifest(parseLiteralModuleManifest(manifestBlock), false);
378
- const { id, description, localizations } = reaction;
379
- const name = reaction.name ?? id;
380
- return { apiVersion: reaction.apiVersion, id, name, description, reaction, sourcePath, sourceRoot,
381
- manifest: { apiVersion: reaction.apiVersion, id, name, description, localizations,
382
- subjectScope: 'self_and_others', produces: [] } };
379
+ const { kind: _kind, ...common } = reaction;
380
+ const module: PerceptionModuleManifest = { ...common, apiVersion: 3 };
381
+ return { apiVersion: reaction.apiVersion, id: reaction.id, name: reaction.name ?? reaction.id,
382
+ description: reaction.description, module, reaction, sourcePath, sourceRoot,
383
+ manifest: { apiVersion: 2, id: reaction.id, name: reaction.name ?? reaction.id,
384
+ description: reaction.description, localizations: reaction.localizations,
385
+ subjectScope: 'self_and_others', produces: reaction.produces } };
383
386
  } catch { return null; }
384
387
  }
385
388
  if (classMatch[1] === 'ClawclawReminder') {
386
389
  try {
387
- const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false);
390
+ const reminder = normalizeReminderManifest(parseLiteralModuleManifest(manifestBlock), false, true);
388
391
  const { id, description, localizations } = reminder;
389
392
  const name = reminder.name ?? id;
390
- return { apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
393
+ return { ...removedInputDiagnosis(reminder.consumes), apiVersion: reminder.apiVersion, id, name, description, reminder, sourcePath, sourceRoot,
391
394
  manifest: { apiVersion: reminder.apiVersion, id, name, description, localizations,
392
395
  subjectScope: 'self_and_others', produces: [] } };
393
396
  } catch { return null; }
@@ -511,3 +514,8 @@ export function resolveClawclawPerceptionSource(
511
514
  if (!source) throw new Error(`Unknown perception module '${id}'.`);
512
515
  return source;
513
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
+ }