@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,114 +1,13 @@
1
+ import { PerceptionRuleRunner } from '../system-perception/rule-runner.js';
1
2
  import { PlayerChangesDerivedEventRule, TaskChangesDerivedEventRule } from './state-change-rules.js';
2
- import type {
3
- RuntimeEpochPlugin,
4
- RuntimeEpochPluginContext,
5
- RuntimeEpochPluginInput,
6
- RuntimeEpochPluginResult,
7
- RuntimeEventProposal,
8
- RuntimeSourceEvent,
9
- } from '../../../framework/plugins/index.js';
10
- import type { StoredStateFrame } from '../../../framework/state/index.js';
11
- import {
12
- AbilityStateDerivedEventRule,
13
- EmergencyCountdownDerivedEventRule,
14
- MeetingStateDerivedEventRule,
15
- RoomReadyDerivedEventRule,
16
- type ClawclawDerivedEventRule,
17
- } from './derived-event-rules.js';
18
-
3
+ import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule,
4
+ MeetingStateDerivedEventRule, RoomReadyDerivedEventRule, type ClawclawDerivedEventRule } from './derived-event-rules.js';
19
5
  export const CLAWCLAW_DERIVED_EVENT_PLUGIN_ID = 'clawclaw.derived-event';
20
-
21
- export class ClawclawDerivedEventPlugin
22
- implements RuntimeEpochPlugin<Record<string, any>> {
23
- readonly kind = 'epoch' as const;
24
- readonly id = CLAWCLAW_DERIVED_EVENT_PLUGIN_ID;
25
- readonly version = '2';
26
- readonly produces: { events: readonly string[] };
27
- readonly consumes: { events: readonly string[] };
28
- // Task/player changes must commit beside the backend facts from that input.
29
- // Coalescing them into a later epoch would split downstream notification causality.
30
- readonly catchUp = 'strict_ordered' as const;
31
- readonly timeoutMs = 1_000;
32
-
33
- private readonly rules: ClawclawDerivedEventRule[];
34
- private lastFrameSeq = 0;
35
-
6
+ /** Legacy rule harness. The production graph uses independent builtin perceptions. */
7
+ export class ClawclawDerivedEventPlugin extends PerceptionRuleRunner {
36
8
  constructor(rules?: readonly ClawclawDerivedEventRule[]) {
37
- this.rules = [...(rules ?? [
38
- new PlayerChangesDerivedEventRule(),
39
- new TaskChangesDerivedEventRule(),
40
- new AbilityStateDerivedEventRule(),
41
- new EmergencyCountdownDerivedEventRule(),
42
- new RoomReadyDerivedEventRule(),
43
- new MeetingStateDerivedEventRule(),
44
- ])].sort((left, right) => left.id.localeCompare(right.id));
45
- this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() };
46
- this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() };
47
- }
48
-
49
- start(): void {
50
- this.reset();
51
- }
52
-
53
- recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
54
- const completedThrough = context.progress().completedThroughEpochSeq;
55
- if (completedThrough <= 0) return;
56
- this.scanHistory(context, completedThrough, false);
57
- }
58
-
59
- update(
60
- input: RuntimeEpochPluginInput<Record<string, any>>,
61
- context: RuntimeEpochPluginContext<Record<string, any>>,
62
- ): RuntimeEpochPluginResult {
63
- const events = this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input);
64
- return { ...(events.length > 0 ? { outcome: 'processed' as const, events }
65
- : { outcome: 'noop' as const, reason: 'no_derived_event' }),
66
- ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
67
- }
68
-
69
- stop(): void {
70
- this.reset();
71
- }
72
-
73
- private scanHistory(
74
- context: RuntimeEpochPluginContext<Record<string, any>>,
75
- throughEpochSeq: number,
76
- collect: boolean,
77
- throughFrameSeq?: number,
78
- currentInput?: RuntimeEpochPluginInput<Record<string, any>>,
79
- ): RuntimeEventProposal[] {
80
- const proposals: RuntimeEventProposal[] = [];
81
- let afterFrameSeq = this.lastFrameSeq;
82
- while (true) {
83
- const page = context.stateHistory.queryStateFrames({
84
- scope: context.scope,
85
- afterFrameSeq,
86
- toEpochSeq: throughEpochSeq,
87
- ...(throughFrameSeq === undefined ? {} : { beforeFrameSeq: throughFrameSeq + 1 }),
88
- order: 'asc',
89
- limit: 500,
90
- });
91
- if (page.frames.length === 0) break;
92
- for (const frame of page.frames) {
93
- const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq)
94
- ?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []);
95
- const frameEvents = this.inspectFrame(frame, facts);
96
- if (collect) proposals.push(...frameEvents);
97
- afterFrameSeq = frame.frameSeq;
98
- }
99
- if (!page.page.hasMore) break;
100
- }
101
- return proposals;
102
- }
103
-
104
- private inspectFrame(frame: StoredStateFrame<Record<string, any>>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
105
- if (frame.frameSeq <= this.lastFrameSeq) return [];
106
- this.lastFrameSeq = frame.frameSeq;
107
- return this.rules.flatMap((rule) => rule.inspect(frame, facts));
108
- }
109
-
110
- private reset(): void {
111
- this.lastFrameSeq = 0;
112
- for (const rule of this.rules) rule.reset();
9
+ super(CLAWCLAW_DERIVED_EVENT_PLUGIN_ID, rules ?? [new PlayerChangesDerivedEventRule(),
10
+ new TaskChangesDerivedEventRule(), new AbilityStateDerivedEventRule(),
11
+ new EmergencyCountdownDerivedEventRule(), new RoomReadyDerivedEventRule(), new MeetingStateDerivedEventRule()]);
113
12
  }
114
13
  }
@@ -43,7 +43,7 @@ function roomSnapshot(
43
43
  frame: StoredStateFrame<Record<string, any>>,
44
44
  ): UnknownRecord | null | undefined {
45
45
  const state = frame.state;
46
- if (!isClawclawRuntimeState(state) || state.cause !== 'room_update') return undefined;
46
+ if (!isClawclawRuntimeState(state) || state.stage !== 'room') return undefined;
47
47
  return record(record(state.room)?.room);
48
48
  }
49
49
 
@@ -116,7 +116,7 @@ function freshGameSnapshot(
116
116
  ): UnknownRecord | null | undefined {
117
117
  const state = frame.state;
118
118
  if (!isClawclawRuntimeState(state)) return record(state);
119
- if (state.game_snapshot.status !== 'fresh') return undefined;
119
+ if ((state.game_snapshot.status !== 'fresh' && state.game_snapshot.status !== 'cached')) return undefined;
120
120
  return record(state.game_snapshot.state);
121
121
  }
122
122
 
@@ -1,8 +1,10 @@
1
+ import { prepareNotificationContent } from '../perception/notification-content.js';
2
+ import { isNotificationTurn } from '../../notification-turn.js';
1
3
  import type { RuntimeEpochPlugin, RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult } from '../../../framework/plugins/index.js';
2
4
  import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
3
- import type { ReminderInput, ReminderResult, ReminderTopic, ReminderTaskChange } from '../../../../sdk/perception-plugin/reminder.js';
5
+ import type { ReminderInput, ReminderResult, ReminderTopic } from '../../../../sdk/perception-plugin/reminder.js';
4
6
  import type { ResolvedClawclawPerceptionSource } from '../perception/perception-source.js';
5
- import { freshClawclawGameState } from '../../runtime-state.js';
7
+ import { clawclawComputationGameState } from '../../runtime-state.js';
6
8
  import { createCanonicalGameState } from '../../behavior-input.js';
7
9
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
8
10
  import { ObservationFrameProjector } from '../../observation-frame-projector.js';
@@ -10,22 +12,26 @@ import { REMINDER_EVENT_TYPES, REMINDER_EVENT_TYPE_BY_TOPIC, REMINDER_FACT_TYPES
10
12
  import { ReminderRunner } from './reminder-runner.js';
11
13
  import { resolveClawclawResourceMetadata } from '../../../../sdk/resource-metadata.js';
12
14
 
15
+ import { comparePerceptionTasks, type PerceptionTaskBaseline } from '../perception/task-baseline.js';
16
+
13
17
  export const CLAWCLAW_REMINDER_PLUGIN_ID = 'clawclaw.derived-event.reminders';
14
18
  export interface ReminderPluginOptions {
15
19
  /** Already selected by the ordinary local/Hub perception loadout. No separate settings. */
16
20
  sources?: readonly ResolvedClawclawPerceptionSource[];
17
21
  }
18
22
  interface Checkpoint {
23
+ taskBaseline?: PerceptionTaskBaseline;
19
24
  gameId?: string;
20
25
  previousTick?: number; previousConnectionId?: string;
21
26
  states: Partial<Record<ReminderTopic, { provider: string; value: unknown }>>;
22
27
  }
23
28
  function empty(): Checkpoint { return { states: {} }; }
24
29
  export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string, any>> {
30
+ readonly agentNotificationProducer = true;
25
31
  readonly kind = 'epoch' as const;
26
32
  readonly id = CLAWCLAW_REMINDER_PLUGIN_ID;
27
33
  readonly version = '2';
28
- readonly after = ['clawclaw.derived-event'];
34
+ readonly after: readonly string[] = [];
29
35
  readonly consumes = { events: REMINDER_FACT_TYPES };
30
36
  readonly produces = { events: REMINDER_EVENT_TYPES } as const;
31
37
  readonly catchUp = 'strict_ordered' as const;
@@ -57,7 +63,7 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
57
63
  recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
58
64
  const checkpoint = context.checkpoint() as Checkpoint | undefined;
59
65
  if (checkpoint?.states) this.checkpoint = structuredClone({
60
- gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
66
+ taskBaseline: checkpoint.taskBaseline, gameId: checkpoint.gameId, previousTick: checkpoint.previousTick,
61
67
  previousConnectionId: checkpoint.previousConnectionId,
62
68
  states: Object.fromEntries(REMINDER_TOPICS.filter(topic => checkpoint.states[topic])
63
69
  .map(topic => [topic, checkpoint.states[topic]])),
@@ -71,9 +77,10 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
71
77
  ));
72
78
  }
73
79
  async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
80
+ if (isNotificationTurn(input.epoch.state)) return { outcome: 'noop', reason: 'notification_only' };
74
81
  if (this.sources.size === 0) return { outcome: 'noop', reason: 'no_reminder_modules',
75
82
  ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
76
- const snapshot = freshClawclawGameState(input.frame.state);
83
+ const snapshot = clawclawComputationGameState(input.frame.state);
77
84
  const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null;
78
85
  let next = structuredClone(this.checkpoint);
79
86
  const initial = !!game && next.gameId !== game.game_id;
@@ -93,21 +100,19 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
93
100
  next.previousTick = undefined; next.previousConnectionId = undefined;
94
101
  }
95
102
  next.previousConnectionId = input.epoch.connectionId;
96
- const facts = input.pendingEvents.map(event => ({ ...event,
103
+ const facts = input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({ ...event,
97
104
  payload: projectTaskChoiceEventPayload(game, event.type, event.payload) }));
98
105
  const events: RuntimeEventProposal[] = [];
99
- const taskChanges: ReminderTaskChange[] = facts.filter(e => e.type === 'tasks_changed').flatMap(e => {
100
- const delta = Array.isArray(e.payload.delta) ? e.payload.delta : [];
101
- return delta.map((change, index) => ({ ...change, key: `change:${e.eventId}:${index}`,
102
- eventId: e.eventId, epochId: e.epochSeq,
103
- baseline: e.payload.baseline === true || ['tasks_initialized', 'role_assigned'].includes(String(e.payload.reason)),
104
- } as ReminderTaskChange));
105
- });
106
- for (const topic of REMINDER_TOPICS) {
106
+ const comparison = comparePerceptionTasks(next.taskBaseline, input, boundary);
107
+ next.taskBaseline = comparison.baseline;
108
+ const taskChanges = comparison.changes;
109
+ const outputs = await Promise.all(REMINDER_TOPICS.map(async topic => {
110
+ const events: RuntimeEventProposal[] = [];
107
111
  const selected = this.sources.get(topic)?.[0];
108
- if (!selected || this.failed.has(topic)) continue;
112
+ if (!selected || this.failed.has(topic)) return events;
109
113
  const previous = next.states[topic];
110
114
  const moduleInput: ReminderInput = {
115
+ ...(input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
111
116
  scope: input.epoch.scope, frame, gameState: game, taskChanges, boundary,
112
117
  facts: facts.filter(e => topic !== 'speech' || !e.replayed)
113
118
  .map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type,
@@ -140,9 +145,12 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
140
145
  if (game && (topic === 'speech' || !boundary)) events.push(...accepted);
141
146
  next.states[topic] = { provider: selected.id, value: structuredClone(result.state) };
142
147
  } catch (error) { this.markFailed(topic, context, error); }
143
- }
148
+ return events;
149
+ }));
150
+ events.push(...outputs.flat());
144
151
  this.checkpoint = next;
145
- return { outcome: 'processed', events, checkpoint: next,
152
+ return { outcome: 'processed', events: events.map(event => ({ ...event,
153
+ notificationContent: prepareNotificationContent(event.type, event.payload, game, 'custom') })), checkpoint: next,
146
154
  ...(input.pendingEvents.length ? { consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq } : {}) };
147
155
  }
148
156
  private markFailed(topic: ReminderTopic, context: RuntimeEpochPluginContext<Record<string, any>>, error: unknown): void {
@@ -14,6 +14,7 @@ export class ReminderRunner {
14
14
  if (!source.reminder) throw new Error('Not a reminder perception source.');
15
15
  }
16
16
  async start(): Promise<{ manifest: ClawclawReminderManifest; config: Record<string, unknown> }> {
17
+ if (this.source.compatibilityError) throw new Error(this.source.compatibilityError);
17
18
  const loader = runtimeModuleThreadLoaderConfig();
18
19
  const promise = this.wait(8_000);
19
20
  this.worker = new Worker(new URL('../../../framework/modules/runtime-module-worker-bootstrap.mjs', import.meta.url), {
@@ -2,7 +2,7 @@ import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framewor
2
2
  import type { StoredStateFrame } from '../../../framework/state/index.js';
3
3
  import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
4
4
  import { CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
5
- import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
5
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
6
6
  import type { ClawclawDerivedEventRule } from './derived-event-rules.js';
7
7
  import { nextPlayerProjection, type PlayerSnapshot } from './player-change-tracker.js';
8
8
  import { nextTaskProjection, type TaskSnapshot } from './task-change-tracker.js';
@@ -30,7 +30,7 @@ function trackerFacts(events: readonly RuntimeSourceEvent[]): Array<Record<strin
30
30
  }
31
31
 
32
32
  function gameState(frame: StoredStateFrame<Record<string, any>>): Record<string, any> | null {
33
- const game = freshClawclawGameState(frame.state);
33
+ const game = clawclawComputationGameState(frame.state);
34
34
  if (!game) return null;
35
35
  return { ...game, ...(frame.backendTick === undefined ? {} : { tick: frame.backendTick }) };
36
36
  }
@@ -76,7 +76,7 @@ export class TaskChangesDerivedEventRule implements ClawclawDerivedEventRule {
76
76
  const state = frame.state;
77
77
  const update = nextTaskProjection({ previous: this.projection, initialized: this.initialized, summary: game,
78
78
  events: trackerFacts(events), selfName: game.you?.player?.name ?? game.you?.name,
79
- allowUntickedInitialRole: isClawclawRuntimeState(state) && state.game_snapshot.status === 'fresh'
79
+ allowUntickedInitialRole: isClawclawRuntimeState(state) && (state.game_snapshot.status === 'fresh' || state.game_snapshot.status === 'cached')
80
80
  && state.game_snapshot.origin === 'update' });
81
81
  this.projection = update.projection; this.initialized = update.initialized;
82
82
  return update.payload ? proposal('tasks_changed', frame, update.payload, events) : [];
@@ -1,259 +1 @@
1
- export interface TaskSnapshot extends Record<string, unknown> {
2
- task_id?: string;
3
- name: string;
4
- room?: string;
5
- x?: number;
6
- y?: number;
7
- status?: string;
8
- is_fake_shrimp?: boolean;
9
- task_note?: string;
10
- faction?: 'lobster' | 'crab';
11
- }
12
-
13
- export interface TaskChangeDetail extends Record<string, unknown> {
14
- change: 'added' | 'removed' | 'status_changed' | 'updated';
15
- task: TaskSnapshot;
16
- before?: TaskSnapshot;
17
- from_status?: string;
18
- to_status?: string;
19
- }
20
-
21
- export interface TasksChangedPayload extends Record<string, unknown> {
22
- baseline: boolean;
23
- tick?: number;
24
- reason:
25
- | 'role_assigned'
26
- | 'task_completed'
27
- | 'task_sabotaged'
28
- | 'task_assigned'
29
- | 'emergency_started'
30
- | 'emergency_resolved'
31
- | 'emergency_interrupted'
32
- | 'meeting_started'
33
- | 'task_state_changed'
34
- | 'tasks_initialized';
35
- delta: TaskChangeDetail[];
36
- tasks: TaskSnapshot[];
37
- }
38
-
39
- export interface TaskProjectionUpdate {
40
- projection: TaskSnapshot[];
41
- initialized: boolean;
42
- payload: TasksChangedPayload | null;
43
- }
44
-
45
- function record(value: unknown): Record<string, any> | null {
46
- return value && typeof value === 'object' && !Array.isArray(value)
47
- ? value as Record<string, any>
48
- : null;
49
- }
50
-
51
- function finiteNumber(value: unknown): number | undefined {
52
- return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
53
- }
54
-
55
- function nonEmptyString(value: unknown): string | undefined {
56
- return typeof value === 'string' && value.length > 0 ? value : undefined;
57
- }
58
-
59
- function taskSnapshot(value: unknown): TaskSnapshot | null {
60
- const task = record(value);
61
- const name = nonEmptyString(task?.name) ?? nonEmptyString(task?.task_name);
62
- if (!task || !name) return null;
63
- const faction = task.faction === 'lobster' || task.faction === 'crab'
64
- ? task.faction
65
- : undefined;
66
- return {
67
- ...(nonEmptyString(task.task_id) ? { task_id: task.task_id } : {}),
68
- name,
69
- ...(nonEmptyString(task.room) ? { room: task.room } : {}),
70
- ...(finiteNumber(task.x) === undefined ? {} : { x: task.x }),
71
- ...(finiteNumber(task.y) === undefined ? {} : { y: task.y }),
72
- ...(nonEmptyString(task.status) ? { status: task.status } : {}),
73
- ...(typeof task.is_fake_shrimp === 'boolean'
74
- ? { is_fake_shrimp: task.is_fake_shrimp }
75
- : {}),
76
- ...(nonEmptyString(task.task_note) ? { task_note: task.task_note } : {}),
77
- ...(faction ? { faction } : {}),
78
- };
79
- }
80
-
81
- function tasksFromState(summary: Record<string, any> | null | undefined): TaskSnapshot[] | null {
82
- if (!Array.isArray(summary?.you?.tasks)) return null;
83
- return summary.you.tasks
84
- .map((task: unknown) => taskSnapshot(task))
85
- .filter((task: TaskSnapshot | null): task is TaskSnapshot => task !== null);
86
- }
87
-
88
- function taskKey(task: TaskSnapshot): string {
89
- if (task.task_id) return `id:${task.task_id}`;
90
- return JSON.stringify([
91
- task.name,
92
- task.room ?? null,
93
- task.x ?? null,
94
- task.y ?? null,
95
- task.faction ?? null,
96
- task.is_fake_shrimp ?? null,
97
- ]);
98
- }
99
-
100
- function sameTask(left: TaskSnapshot, right: TaskSnapshot): boolean {
101
- return JSON.stringify(left) === JSON.stringify(right);
102
- }
103
-
104
- function taskDelta(
105
- previous: readonly TaskSnapshot[],
106
- current: readonly TaskSnapshot[],
107
- ): TaskChangeDetail[] {
108
- const previousByKey = new Map(previous.map((task) => [taskKey(task), task]));
109
- const currentByKey = new Map(current.map((task) => [taskKey(task), task]));
110
- const delta: TaskChangeDetail[] = [];
111
- for (const task of previous) {
112
- if (!currentByKey.has(taskKey(task))) {
113
- delta.push({ change: 'removed', task: structuredClone(task) });
114
- }
115
- }
116
- for (const task of current) {
117
- const before = previousByKey.get(taskKey(task));
118
- if (!before) {
119
- delta.push({ change: 'added', task: structuredClone(task) });
120
- continue;
121
- }
122
- if (before.status !== task.status) {
123
- delta.push({
124
- change: 'status_changed',
125
- before: structuredClone(before),
126
- task: structuredClone(task),
127
- ...(before.status === undefined ? {} : { from_status: before.status }),
128
- ...(task.status === undefined ? {} : { to_status: task.status }),
129
- });
130
- continue;
131
- }
132
- if (!sameTask(before, task)) {
133
- delta.push({ change: 'updated', task: structuredClone(task), before: structuredClone(before) });
134
- }
135
- }
136
- return delta;
137
- }
138
-
139
- function actorMatches(
140
- event: Record<string, any>,
141
- selfName: string | undefined,
142
- selfSeat: number | undefined,
143
- ): boolean {
144
- const actor = record(event.actor);
145
- const name = nonEmptyString(actor?.name) ?? nonEmptyString(event.actor_name);
146
- const seat = Number.isInteger(actor?.seat)
147
- ? Number(actor!.seat)
148
- : Number.isInteger(event.actor_seat) ? Number(event.actor_seat) : undefined;
149
- if (selfSeat !== undefined && seat !== undefined) return seat === selfSeat;
150
- if (selfName && name) return name === selfName;
151
- return false;
152
- }
153
-
154
- function findLastEventIndex(
155
- events: readonly Record<string, any>[],
156
- predicate: (event: Record<string, any>) => boolean,
157
- ): number {
158
- for (let index = events.length - 1; index >= 0; index -= 1) {
159
- if (predicate(events[index]!)) return index;
160
- }
161
- return -1;
162
- }
163
-
164
- function updateReason(
165
- initialized: boolean,
166
- events: readonly Record<string, any>[],
167
- selfName: string | undefined,
168
- selfSeat: number | undefined,
169
- currentTick: number | undefined,
170
- allowUntickedInitialRole: boolean,
171
- ): Pick<TasksChangedPayload, 'reason'> {
172
- const roleIndex = findLastEventIndex(events, (event) => event.type === 'role_assigned');
173
- const roleTick = roleIndex >= 0 ? finiteNumber(events[roleIndex]?.tick) : undefined;
174
- const currentRole = roleIndex >= 0 && (
175
- (roleTick !== undefined && currentTick !== undefined && roleTick === currentTick)
176
- || (roleTick === undefined && allowUntickedInitialRole)
177
- );
178
- if (currentRole) {
179
- return { reason: 'role_assigned' };
180
- }
181
- // A first snapshot may replay historical task Events. Its current list is
182
- // an initialization fact, not the after-state of any one historical Event.
183
- if (!initialized) return { reason: 'tasks_initialized' };
184
- const visibleReasons = events
185
- .map((event, index) => ({ event, index }))
186
- .filter(({ event }) => (
187
- (event.type === 'task_completed' || event.type === 'task_sabotaged')
188
- ? actorMatches(event, selfName, selfSeat)
189
- : [
190
- 'emergency_started',
191
- 'emergency_resolved',
192
- 'emergency_interrupted',
193
- 'meeting_briefing',
194
- ].includes(event.type)
195
- ));
196
- const visible = visibleReasons[visibleReasons.length - 1];
197
- if (visible) {
198
- const reason = visible.event.type === 'meeting_briefing'
199
- ? 'meeting_started'
200
- : visible.event.type as TasksChangedPayload['reason'];
201
- return { reason };
202
- }
203
- if (events.some((event) => (
204
- event.type === 'task_assigned' && actorMatches(event, selfName, selfSeat)
205
- ))) return { reason: 'task_assigned' };
206
- return { reason: 'task_state_changed' };
207
- }
208
-
209
- /**
210
- * Diff the authoritative task list carried by one complete GameSync State.
211
- * Derived Event emits tasks_changed from the same accepted input, separate from backend facts.
212
- * Reminder scripts own Agent-facing task notifications.
213
- */
214
- export function nextTaskProjection(input: {
215
- previous: readonly TaskSnapshot[];
216
- initialized: boolean;
217
- summary?: Record<string, any> | null;
218
- events?: readonly Record<string, any>[];
219
- selfName?: string;
220
- selfSeat?: number;
221
- allowUntickedInitialRole?: boolean;
222
- }): TaskProjectionUpdate {
223
- const current = tasksFromState(input.summary);
224
- if (!current) {
225
- return {
226
- projection: [...input.previous].map((task) => structuredClone(task)),
227
- initialized: input.initialized,
228
- payload: null,
229
- };
230
- }
231
- const delta = taskDelta(input.previous, current);
232
- if (input.initialized && delta.length === 0) {
233
- return { projection: current, initialized: true, payload: null };
234
- }
235
- const selfSeat = input.selfSeat ?? (Number.isInteger(input.summary?.you?.player?.seat)
236
- ? Number(input.summary!.you.player.seat)
237
- : undefined);
238
- const selfName = input.selfName ?? nonEmptyString(input.summary?.you?.player?.name);
239
- const tick = finiteNumber(input.summary?.tick);
240
- const reason = updateReason(
241
- input.initialized,
242
- input.events ?? [],
243
- selfName,
244
- selfSeat,
245
- tick,
246
- input.allowUntickedInitialRole === true,
247
- );
248
- return {
249
- projection: current,
250
- initialized: true,
251
- payload: {
252
- baseline: !input.initialized,
253
- ...(tick === undefined ? {} : { tick }),
254
- reason: reason.reason,
255
- delta,
256
- tasks: current.map((task) => structuredClone(task)),
257
- },
258
- };
259
- }
1
+ export * from '../../../../sdk/perception-plugin/task-change-tracker.js';
@@ -127,12 +127,12 @@ export class ClawclawGameQueryPlugin implements RuntimeEpochPlugin<Record<string
127
127
  }
128
128
  const snapshot = queryContext.stateFrame;
129
129
  if (!snapshot || !isClawclawRuntimeState(snapshot.state)
130
- || snapshot.state.game_snapshot.status !== 'fresh') {
130
+ || (snapshot.state.game_snapshot.status !== 'fresh' && snapshot.state.game_snapshot.status !== 'cached')) {
131
131
  return { state: null, receivedAt: null };
132
132
  }
133
133
  return {
134
134
  state: snapshot.state.game_snapshot.state,
135
- receivedAt: new Date(snapshot.receivedAtMs).toISOString(),
135
+ receivedAt: new Date(snapshot.state.cycle?.stateReceivedAtMs ?? snapshot.receivedAtMs).toISOString(),
136
136
  };
137
137
  }
138
138
 
@@ -234,9 +234,9 @@ export class ClawclawGameQueryPlugin implements RuntimeEpochPlugin<Record<string
234
234
  }
235
235
  const runtimeState = input.epoch.state;
236
236
  if (isClawclawRuntimeState(runtimeState)
237
- && runtimeState.game_snapshot.status === 'fresh') {
237
+ && (runtimeState.game_snapshot.status === 'fresh' || runtimeState.game_snapshot.status === 'cached')) {
238
238
  this.latestFreshGameState = structuredClone(runtimeState.game_snapshot.state);
239
- this.latestFreshReceivedAt = new Date(input.frame.receivedAtMs).toISOString();
239
+ this.latestFreshReceivedAt = new Date(runtimeState.cycle?.stateReceivedAtMs ?? input.frame.receivedAtMs).toISOString();
240
240
  }
241
241
  return { outcome: 'noop', reason: 'query_provider' };
242
242
  }