@myclaw163/clawclaw-cli 0.9.2 → 0.10.2

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 (224) hide show
  1. package/QUICKSTART.md +1 -1
  2. package/QUICKSTART_OTHER.md +13 -12
  3. package/README.md +7 -8
  4. package/bin/clawclaw-channel.mjs +2 -2
  5. package/bin/clawclaw-cli.mjs +2 -2
  6. package/docs/configuration.md +27 -101
  7. package/docs/custom-modules/README.md +23 -35
  8. package/docs/custom-modules/api-reference.md +95 -273
  9. package/docs/custom-modules/behavior.md +94 -78
  10. package/docs/custom-modules/examples/auto-escape.ts +5 -5
  11. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  12. package/docs/custom-modules/examples/nearby-reflex.ts +2 -2
  13. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  14. package/docs/custom-modules/perception.md +42 -603
  15. package/docs/custom-modules/skill.md +12 -10
  16. package/docs/desktop-event-push.md +3 -3
  17. package/docs/runtime/README.md +16 -17
  18. package/docs/runtime/agent-notifications.md +42 -12
  19. package/docs/runtime/behavior-runtime.md +47 -46
  20. package/docs/runtime/components-and-boundaries.md +70 -28
  21. package/docs/runtime/events-and-state.md +41 -18
  22. package/docs/runtime/framework-package.md +73 -0
  23. package/docs/runtime/official-perception-modules.md +5 -5
  24. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  25. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  26. package/docs/user-guide/README.md +10 -7
  27. package/docs/user-guide/api-reference.md +81 -164
  28. package/docs/user-guide/behavior.md +84 -68
  29. package/docs/user-guide/installation.md +7 -7
  30. package/docs/user-guide/perception.md +42 -586
  31. package/docs/user-guide/skill.md +12 -10
  32. package/package.json +24 -9
  33. package/scripts/check-framework-boundaries.mjs +27 -0
  34. package/scripts/check-skill-command-surface.mjs +20 -23
  35. package/scripts/enable_ccl_permissions.cjs +4 -0
  36. package/scripts/install-local-runtime.mjs +35 -0
  37. package/scripts/postinstall.mjs +1 -1
  38. package/scripts/qa-install.mjs +105 -0
  39. package/scripts/sync-bundled-skill.mjs +35 -28
  40. package/skills/clawclaw/SKILL.md +53 -57
  41. package/skills/clawclaw/references/BEHAVIORS.md +43 -83
  42. package/skills/clawclaw/references/CHANNELS.md +2 -2
  43. package/skills/clawclaw/references/COMMANDS.md +62 -103
  44. package/skills/clawclaw/references/HUB.md +2 -2
  45. package/skills/clawclaw/references/STREAM.md +8 -8
  46. package/skills/clawclaw/references/TACTICS.md +1 -1
  47. package/skills/clawclaw-creator/SKILL.md +82 -0
  48. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +95 -79
  49. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULE-API.md +95 -180
  50. package/skills/{clawclaw → clawclaw-creator}/references/CUSTOM-MODULES.md +26 -24
  51. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +126 -0
  52. package/skills/clawclaw-creator/references/CUSTOM-PERSONA-DEVELOPMENT.md +29 -0
  53. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +69 -0
  54. package/skills/clawclaw-creator/references/SYNC-AND-REPORT.md +36 -0
  55. package/src/channel/claude-channel-ipc-server.ts +1 -0
  56. package/src/cli.ts +4 -2
  57. package/src/commands/behavior.ts +26 -10
  58. package/src/commands/capability.ts +17 -14
  59. package/src/commands/load.ts +5 -3
  60. package/src/commands/perception.ts +5 -0
  61. package/src/commands/skill.ts +34 -29
  62. package/src/commands/strategy.ts +2 -0
  63. package/src/commands/upgrade.ts +2 -2
  64. package/src/lib/agent-workspace-skills.ts +20 -13
  65. package/src/lib/capability-cloud-sync.ts +2 -1
  66. package/src/lib/capability-discovery.ts +2 -1
  67. package/src/lib/capability-load-diagnostics.ts +3 -3
  68. package/src/lib/capability-workspace.ts +2 -1
  69. package/src/lib/game-client.ts +7 -1
  70. package/src/lib/package-skills.ts +4 -0
  71. package/src/lib/perception-config.ts +18 -6
  72. package/src/lib/runtime-cadence-config.ts +16 -0
  73. package/src/lib/skill-host.ts +1 -1
  74. package/src/lib/workspace-runtime-lock.ts +3 -46
  75. package/src/pipeline/canonical-event-presentation.ts +23 -124
  76. package/src/pipeline/event-format.ts +12 -21
  77. package/src/pipeline/event-hints.ts +6 -6
  78. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  79. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  80. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  81. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  82. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  83. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  84. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  85. package/src/runtime/clawclaw/owner.ts +47 -9
  86. package/src/runtime/clawclaw/perception-module-manifest.ts +8 -3
  87. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  88. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  89. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  90. package/src/runtime/clawclaw/plugins/assembly.ts +7 -9
  91. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -495
  92. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -190
  93. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  94. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1779
  95. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -276
  96. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  97. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  98. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  99. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -972
  100. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +8 -109
  101. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +2 -2
  102. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  103. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  104. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -3
  105. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -259
  106. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  107. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  108. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  109. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +15 -20
  110. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-runtime-report-adapter.ts +59 -0
  111. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  112. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  113. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  114. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  115. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  116. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  117. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  118. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  119. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  120. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +125 -297
  121. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +7 -56
  122. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +11 -33
  123. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +25 -10
  124. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +12 -6
  125. package/src/runtime/clawclaw/plugins/perception/report-content.ts +50 -0
  126. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  127. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +6 -0
  128. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  129. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  130. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +8 -3
  131. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  132. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  133. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  134. package/src/runtime/clawclaw/runtime-state.ts +11 -0
  135. package/src/runtime/clawclaw/runtime.ts +8 -0
  136. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -63
  137. package/src/runtime/clawclaw/strategy-memory.ts +1 -77
  138. package/src/runtime/clawclaw-event-catalog.ts +12 -12
  139. package/src/runtime/framework/action-diagnostics.ts +3 -83
  140. package/src/runtime/framework/capability-registry.ts +2 -395
  141. package/src/runtime/framework/contracts.ts +2 -144
  142. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  143. package/src/runtime/framework/control/domain-set.ts +2 -81
  144. package/src/runtime/framework/control/index.ts +1 -3
  145. package/src/runtime/framework/control/types.ts +2 -191
  146. package/src/runtime/framework/control-coordinator.ts +2 -11
  147. package/src/runtime/framework/events/event-catalog.ts +2 -74
  148. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  149. package/src/runtime/framework/events/event-ingress.ts +2 -99
  150. package/src/runtime/framework/events/event-repository.ts +2 -82
  151. package/src/runtime/framework/events/index.ts +2 -7
  152. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  153. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  154. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  155. package/src/runtime/framework/events/test-helpers.ts +1 -1
  156. package/src/runtime/framework/events/types.ts +2 -312
  157. package/src/runtime/framework/index.ts +3 -7
  158. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  159. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  160. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  161. package/src/runtime/framework/mailbox/identity.ts +2 -38
  162. package/src/runtime/framework/mailbox/index.ts +1 -7
  163. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  164. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  165. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  166. package/src/runtime/framework/mailbox/types.ts +2 -145
  167. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  168. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  169. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  170. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  171. package/src/runtime/framework/participation-manager.ts +2 -253
  172. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  173. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  174. package/src/runtime/framework/plugins/contracts.ts +2 -396
  175. package/src/runtime/framework/plugins/index.ts +1 -4
  176. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  177. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  178. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2071
  179. package/src/runtime/framework/runtime.ts +5 -1843
  180. package/src/runtime/framework/serial-task-queue.ts +2 -14
  181. package/src/runtime/framework/state/contracts.ts +2 -49
  182. package/src/runtime/framework/state/current-state-store.ts +2 -184
  183. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  184. package/src/runtime/framework/state/freshness.ts +2 -72
  185. package/src/runtime/framework/state/history/contracts.ts +2 -158
  186. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  187. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  188. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  189. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  190. package/src/runtime/framework/state/index.ts +1 -13
  191. package/src/runtime/framework/state/state-ingress.ts +2 -95
  192. package/src/runtime/framework/state/state-provider.ts +2 -62
  193. package/src/runtime/framework/state/types.ts +2 -155
  194. package/src/runtime/game-sync-ingress-protocol.ts +3 -2
  195. package/src/runtime/game-sync-ingress-worker.ts +7 -1
  196. package/src/runtime/game-sync-protocol.ts +64 -4
  197. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  198. package/src/runtime/mailbox-host-relay.ts +1 -326
  199. package/src/runtime/observability/detail-capture.ts +4 -108
  200. package/src/runtime/observability/process-timing.ts +2 -59
  201. package/src/runtime/observability/recorder.ts +2 -238
  202. package/src/runtime/observability/redaction.ts +2 -181
  203. package/src/runtime/observability/reporter.ts +2 -154
  204. package/src/runtime/observability/sinks.ts +2 -135
  205. package/src/runtime/observability/types.ts +2 -92
  206. package/src/runtime/owner-control.ts +45 -320
  207. package/src/runtime/parent-process-watch.ts +1 -51
  208. package/src/runtime/process-identity.ts +1 -72
  209. package/src/runtime/threaded-ws-client.ts +11 -2
  210. package/src/runtime/ws-client.ts +6 -0
  211. package/src/sdk/behavior-plugin/index.ts +9 -3
  212. package/src/sdk/index.ts +40 -2
  213. package/src/sdk/module-input/index.ts +5 -0
  214. package/src/sdk/perception-plugin/index.ts +3 -1
  215. package/src/sdk/perception-plugin/module.ts +12 -2
  216. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  217. package/src/sdk/perception-plugin/reminder.ts +2 -1
  218. package/src/sdk/perception-plugin/task-change-tracker.ts +258 -0
  219. package/src/sdk/strategy-memory.ts +1 -12
  220. package/src/sdk/strategy-plugin/index.ts +36 -0
  221. package/src/sdk/trigger-plugin/index.ts +1 -0
  222. package/docs/custom-modules/trigger.md +0 -295
  223. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +0 -692
  224. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +0 -67
@@ -1,72 +1 @@
1
- import { execFileSync } from 'node:child_process';
2
- import { readFileSync, readlinkSync } from 'node:fs';
3
- import { join } from 'node:path';
4
-
5
- export interface ProcessIdentity {
6
- /** OS process creation value, never the time the lock file was written. */
7
- birth: string;
8
- startedAtMs: number;
9
- executable: string;
10
- }
11
-
12
- export function inspectProcessIdentity(pid: number): ProcessIdentity | null {
13
- if (!Number.isSafeInteger(pid) || pid <= 0) return null;
14
- try {
15
- if (process.platform === 'win32') {
16
- const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
17
- const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
18
- + '$t=$p.StartTime.ToUniversalTime(); '
19
- + '@{birth=$t.Ticks.ToString();startedAtMs=([DateTimeOffset]$t).ToUnixTimeMilliseconds();executable=$p.ProcessName} | ConvertTo-Json -Compress';
20
- const output = execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
21
- ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
22
- { encoding: 'utf8', windowsHide: true, timeout: 5_000, stdio: ['ignore', 'pipe', 'ignore'] });
23
- return JSON.parse(output) as ProcessIdentity;
24
- }
25
- if (process.platform === 'linux') {
26
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
27
- const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]);
28
- const boot = Number(/^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]);
29
- const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8', timeout: 2_000 }));
30
- return { birth: `${boot}:${ticks}`, startedAtMs: (boot + ticks / hz) * 1_000,
31
- executable: readlinkSync(`/proc/${pid}/exe`) };
32
- }
33
- if (process.platform === 'darwin') {
34
- const options = { encoding: 'utf8' as const, timeout: 2_000, env: { ...process.env, LC_ALL: 'C' } };
35
- const birth = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'lstart='], options).trim();
36
- const executable = execFileSync('/bin/ps', ['-p', String(pid), '-o', 'comm='], options).trim();
37
- const startedAtMs = Date.parse(birth);
38
- return birth && executable && Number.isFinite(startedAtMs) ? { birth, startedAtMs, executable } : null;
39
- }
40
- } catch {}
41
- return null;
42
- }
43
-
44
- export function sameProcessIdentity(a: ProcessIdentity | null, b: ProcessIdentity | null): boolean {
45
- return !!a && !!b && a.birth === b.birth && a.executable === b.executable;
46
- }
47
-
48
- /** Recheck immediately before signalling; a PID alone never authorizes a kill. */
49
- export function terminateVerifiedProcess(pid: number, identity: ProcessIdentity, signal: NodeJS.Signals): void {
50
- if (pid === process.pid || !sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
51
- throw new Error(`Refusing to terminate an unverified ClawClaw runtime (pid ${pid}).`);
52
- }
53
- if (process.platform === 'win32') {
54
- const systemRoot = process.env.SystemRoot ?? 'C:\\Windows';
55
- if (!/^\d+$/.test(identity.birth)) throw new Error('Invalid Windows process creation identity.');
56
- // Retain the kernel handle before validating creation time. Killing via that
57
- // Process object cannot target a later process that happens to reuse the PID.
58
- // Runtime computation workers are threads of this process, so they exit too.
59
- const script = `$ErrorActionPreference='Stop'; $p=[System.Diagnostics.Process]::GetProcessById(${pid}); `
60
- + `try { $null=$p.Handle; if ($p.StartTime.ToUniversalTime().Ticks.ToString() -ne '${identity.birth}') `
61
- + "{ throw 'runtime_identity_changed' }; $p.Kill(); } finally { $p.Dispose() }";
62
- execFileSync(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
63
- ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
64
- { stdio: 'ignore', windowsHide: true, timeout: 5_000 });
65
- return;
66
- }
67
- if (sameProcessIdentity(identity, inspectProcessIdentity(pid))) {
68
- try { process.kill(pid, signal); } catch (error) {
69
- if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
70
- }
71
- }
72
- }
1
+ export * from '@myclaw163/game-agent-runtime/owner/process-identity.js';
@@ -1,7 +1,7 @@
1
1
  import { Worker } from 'node:worker_threads';
2
2
  import { EventEmitter } from 'node:events';
3
3
  import { WsConnectionState } from '../sdk/types.js';
4
- import { gameSyncPerceptionReportMessage, type GameSyncPerceptionReport } from './game-sync-protocol.js';
4
+ import { gameSyncPerceptionReportMessage, gameSyncRuntimeReportMessage, type GameSyncPerceptionReport, type GameSyncRuntimeReport } from './game-sync-protocol.js';
5
5
  import type { GameSyncIngressConfig, IngressCommand, IngressEvent } from './game-sync-ingress-protocol.js';
6
6
  import type { GameSyncResumeState, WsClient, WsClientConfig, WsInputFrame, WsCloseInfo, WsProtocolErrorInfo, WsRecoveryStartedInfo } from './ws-client.js';
7
7
 
@@ -155,7 +155,16 @@ export class ThreadedWsClient implements Pick<WsClient, keyof WsClient> {
155
155
  const message = gameSyncPerceptionReportMessage(perceptions);
156
156
  if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
157
157
  this.pendingReports++;
158
- this.post({ type: 'report', perceptions });
158
+ this.post({ type: 'report', perceptions: message.data.perceptions, connectionId: this.connectionId });
159
+ return true;
160
+ }
161
+
162
+ reportRuntime(report: GameSyncRuntimeReport): boolean {
163
+ if (!this.connected || this.stopped || this.pendingReports >= 16) return false;
164
+ const message = gameSyncRuntimeReportMessage(report);
165
+ if (Buffer.byteLength(JSON.stringify(message)) > 256 * 1024) return false;
166
+ this.pendingReports++;
167
+ this.post({ type: 'runtime_report', report: message.data, connectionId: this.connectionId });
159
168
  return true;
160
169
  }
161
170
 
@@ -13,6 +13,8 @@ import {
13
13
  parseGameSyncMessage,
14
14
  type GameSyncErrorData,
15
15
  type GameSyncPerceptionReport,
16
+ gameSyncRuntimeReportMessage,
17
+ type GameSyncRuntimeReport,
16
18
  } from './game-sync-protocol.js';
17
19
 
18
20
  export interface GameSyncResumeState {
@@ -194,6 +196,10 @@ export class WsClient {
194
196
  return this.send(gameSyncPerceptionReportMessage(perceptions));
195
197
  }
196
198
 
199
+ reportRuntime(report: GameSyncRuntimeReport): boolean {
200
+ return this.send(gameSyncRuntimeReportMessage(report));
201
+ }
202
+
197
203
  /**
198
204
  * Advance the resume/ACK watermark after the consumer has accepted the frame.
199
205
  * The threaded consumer retains it in memory before ACK; this is not a disk flush.
@@ -1,3 +1,4 @@
1
+ import { Strategy } from '@myclaw163/game-agent-runtime/sdk/strategy.js';
1
2
  import type {
2
3
  BehaviorInput,
3
4
  BehaviorDecisionAction,
@@ -217,6 +218,10 @@ export interface BehaviorDelegation {
217
218
  readonly behavior: string;
218
219
  readonly input?: Readonly<Record<string, unknown>>;
219
220
  }
221
+ export interface StrategyDelegation {
222
+ readonly strategy: string;
223
+ readonly input?: Readonly<Record<string, unknown>>;
224
+ }
220
225
 
221
226
  /** All semantic effects of one Behavior decision. */
222
227
  export interface BehaviorDecision {
@@ -224,7 +229,7 @@ export interface BehaviorDecision {
224
229
  readonly status?: Readonly<BehaviorStatus>;
225
230
  readonly events?: readonly Readonly<BehaviorEventProposal>[];
226
231
  /** Suspends this long Activation and starts one validated short Activation. */
227
- readonly delegate?: Readonly<BehaviorDelegation>;
232
+ readonly delegate?: Readonly<BehaviorDelegation | StrategyDelegation>;
228
233
  /** Ends this Activation after the Decision's preceding effects are committed. */
229
234
  readonly finish?: Readonly<BehaviorFinish>;
230
235
  }
@@ -268,7 +273,7 @@ export interface ClawclawBehaviorManifest {
268
273
  readonly inputs: readonly BehaviorInputFieldSpec[];
269
274
  /** Omitted means isolated parallel decide(); serial retains one Activation instance. */
270
275
  readonly execution?: BehaviorExecution;
271
- /** Positive backend-tick cadence. The first eligible tick always runs. Defaults to 1. */
276
+ /** Legacy input-driven cadence. The fixed-cadence Owner does not use this as a decision gate. */
272
277
  readonly everyTicks?: number;
273
278
  /** Event types this Behavior may propose. Omit when it produces no custom Events. */
274
279
  readonly produces?: readonly string[];
@@ -308,7 +313,7 @@ export interface BehaviorNormalizationApi {
308
313
  */
309
314
  export abstract class ClawclawBehavior<
310
315
  TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
311
- > {
316
+ > extends Strategy<BehaviorInput<TInput>, BehaviorReadApi, BehaviorDecision> {
312
317
  static readonly manifest?: ClawclawBehaviorManifest;
313
318
 
314
319
  /** Optional one-time normalization. Schema defaults and validation run first. */
@@ -333,3 +338,4 @@ export interface ClawclawBehaviorClass<
333
338
  readonly manifest?: ClawclawBehaviorManifest;
334
339
  new(): ClawclawBehavior<TInput>;
335
340
  }
341
+ export type { ProcessingCycleInfo } from '../module-input/index.js';
package/src/sdk/index.ts CHANGED
@@ -17,8 +17,8 @@
17
17
  * · MapRoom / GameResult / WsConnectionState / ActionErrorCode(客户端类型)
18
18
  *
19
19
  * 自定义模块的基类也可以从根入口导入;希望依赖更小的模块面时,从
20
- * `behavior-plugin`、`trigger-plugin` 或 `perception-plugin` 导入。Behavior 使用
21
- * `BehaviorInput`;Perception 与 Trigger 共享 `ObservationFrame` / `GameState`
20
+ * `strategy-plugin` 或 `perception-plugin` 导入。Strategy 使用
21
+ * `StrategyInput`;感知通过 `PerceptionModuleInput` 读取 `ObservationFrame` / `GameState`
22
22
  * 数据边界。包内 `src/...` 深路径仍不是公开 API。
23
23
  *
24
24
  * 新增 / 删除本文件的 export 必须走 minor / major 版本号;字段语义变更同理。
@@ -96,3 +96,41 @@ export type {
96
96
  MapRoom, GameResult,
97
97
  WsConnectionState, ActionErrorCode,
98
98
  } from './types.js';
99
+
100
+ export { ClawclawStrategy, STRATEGY_PLUGIN_API_VERSION } from './strategy-plugin/index.js';
101
+ export type {
102
+ StrategyActivationLayer,
103
+ StrategyBooleanInputField,
104
+ StrategyContinuation,
105
+ StrategyDecide,
106
+ StrategyDecision,
107
+ StrategyDecisionAction,
108
+ StrategyDecisionFrame,
109
+ StrategyDecisionFrameStatus,
110
+ StrategyDelegatedStrategyResult,
111
+ StrategyDelegation,
112
+ StrategyEnumInputField,
113
+ StrategyEventProposal,
114
+ StrategyExecution,
115
+ StrategyFinish,
116
+ StrategyInput,
117
+ StrategyInputFieldSpec,
118
+ StrategyNormalizationApi,
119
+ StrategyNumberInputField,
120
+ StrategyPathQuery,
121
+ StrategyPlayerSeatInputField,
122
+ StrategyPlayerSeatsInputField,
123
+ StrategyReadApi,
124
+ StrategyRuntimeDefaults,
125
+ StrategyScope,
126
+ StrategyStateMode,
127
+ StrategyStatus,
128
+ StrategyStringInputField,
129
+ StrategyStringListInputField,
130
+ StrategyTiming,
131
+ ClawclawStrategyClass,
132
+ ClawclawStrategyManifest,
133
+ FiniteStrategyDecision,
134
+ } from './strategy-plugin/index.js';
135
+
136
+ export type { PerceptionStrategyBinding, PerceptionStrategyActivation } from './perception-plugin/module.js';
@@ -288,6 +288,8 @@ export interface BehaviorDecisionFrame {
288
288
  export interface BehaviorInput<
289
289
  TInput extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>,
290
290
  > {
291
+ /** Local cadence metadata; backend tick and observation age remain authoritative. */
292
+ readonly cycle?: ProcessingCycleInfo;
291
293
  readonly epochId: number;
292
294
  readonly scope: Readonly<BehaviorScope>;
293
295
  /** Runtime-observed time for this accepted input, suitable for deterministic logic. */
@@ -303,3 +305,6 @@ export interface BehaviorInput<
303
305
  /** Present for the first committed decision after delegated short work ends. */
304
306
  readonly continuation?: Readonly<BehaviorContinuation>;
305
307
  }
308
+ /** Local call timing and the provenance of the latest backend observation; not a State-history API. */
309
+ export type ProcessingCycleInfo = Readonly<Pick<import('../../runtime/framework/plugins/contracts.js').RuntimeCycleInfo,
310
+ 'id' | 'intervalMs' | 'nowMs' | 'hasNewState' | 'stateVersion' | 'stateReceivedAtMs' | 'stateAgeMs' | 'connectionState'>>;
@@ -1,6 +1,7 @@
1
1
  /** Frozen API v2 compatibility version; new modules use PERCEPTION_MODULE_API_VERSION (3). */
2
2
  export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
3
3
  export * from './module.js';
4
+ import { Perception } from '@myclaw163/game-agent-runtime/sdk/perception.js';
4
5
  import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleApi } from './module.js';
5
6
  export { ClawclawReaction } from './reaction.js';
6
7
  export type { ClawclawReactionManifest, ReactionBehaviorBinding, ReactionActivation, ReactionInput, ReactionResult, ReactionEvent, ReactionFact } from './reaction.js';
@@ -169,7 +170,7 @@ export interface ClawclawPerceptionManifest {
169
170
  * retains its original persistent reducer semantics on the compatibility path.
170
171
  * A slow call can be terminated without blocking the Runtime Owner.
171
172
  */
172
- export abstract class ClawclawPerception {
173
+ export abstract class ClawclawPerception extends Perception<PerceptionModuleInput, PerceptionModuleApi, PerceptionModuleResult> {
173
174
  static readonly manifest?: ClawclawPerceptionManifest | PerceptionModuleManifest;
174
175
 
175
176
  /** API v3 combines observation, notification and fixed Behavior activation. */
@@ -246,3 +247,4 @@ export interface ClawclawPerceptionClass {
246
247
  readonly manifest?: ClawclawPerceptionManifest;
247
248
  new(): ClawclawPerception;
248
249
  }
250
+ export type { ProcessingCycleInfo } from '../module-input/index.js';
@@ -7,6 +7,12 @@ import type { StrategyMemory } from '../strategy-memory.js';
7
7
 
8
8
  /** Unified perception contract with optional fixed Reflex bindings. */
9
9
  export const PERCEPTION_MODULE_API_VERSION = 3 as const;
10
+ export type PerceptionStrategyBinding = ReactionBehaviorBinding;
11
+ export interface PerceptionStrategyActivation {
12
+ readonly strategy: string;
13
+ readonly input?: Readonly<Record<string, unknown>>;
14
+ readonly reason?: string;
15
+ }
10
16
  export interface PerceptionModuleManifest {
11
17
  readonly apiVersion: typeof PERCEPTION_MODULE_API_VERSION;
12
18
  readonly id: string;
@@ -17,15 +23,18 @@ export interface PerceptionModuleManifest {
17
23
  readonly produces?: readonly string[];
18
24
  readonly inputs?: readonly BehaviorInputFieldSpec[];
19
25
  readonly config?: Readonly<Record<string, unknown>>;
26
+ readonly strategies?: Readonly<Record<string, PerceptionStrategyBinding>>;
20
27
  readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
21
28
  }
22
29
  export interface PerceptionModuleInput {
30
+ readonly cycle?: import('../module-input/index.js').ProcessingCycleInfo;
23
31
  readonly moduleId: string;
24
32
  readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
25
33
  readonly gameState: Readonly<GameState> | null;
26
34
  readonly frame: Readonly<ObservationFrame> | null;
27
- /** Source/backend and system-derived facts only; never another perception's output. */
35
+ /** Original Source/backend facts only; never another perception's output or a forwarded copy. */
28
36
  readonly events: readonly Readonly<ReminderFact>[];
37
+ /** Compared independently against this module's own durable task baseline. */
29
38
  readonly taskChanges: readonly ReminderTaskChange[];
30
39
  readonly boundary: 'initial' | 'recovery' | null;
31
40
  readonly nowMs: number;
@@ -34,6 +43,7 @@ export interface PerceptionModuleInput {
34
43
  /** Equipped, loadable dependencies; independent of the automatic-activation switch. */
35
44
  readonly availableBindings?: readonly string[];
36
45
  readonly availableBehaviors?: readonly string[];
46
+ readonly availableStrategies?: readonly string[];
37
47
  readonly enabledBindings?: readonly string[];
38
48
  }
39
49
  export interface PerceptionModuleApi {
@@ -51,5 +61,5 @@ export interface PerceptionModuleResult {
51
61
  readonly state?: unknown;
52
62
  readonly events?: readonly PerceptionModuleEvent[];
53
63
  /** Keys in manifest.behaviors; never arbitrary strategy names or executable Actions. */
54
- readonly activations?: readonly ReactionActivation[];
64
+ readonly activations?: readonly (PerceptionStrategyActivation | ReactionActivation)[];
55
65
  }
@@ -1,8 +1,10 @@
1
- import type { ReminderInput, ReminderMode, ReminderResult, ReminderTopic, ReminderFact, ReminderTaskChange, ReminderEvent } from './reminder.js';
1
+ import type { ReminderInput, ReminderMode, ReminderResult, ReminderTopic, ReminderEvent } from './reminder.js';
2
2
 
3
- export const TASK_REMINDER_FACT_TYPES = [
4
- 'ability.ready', 'ability.remaining_uses_changed', 'ability.exhausted', 'tasks_changed',
3
+ export const TASK_LIFECYCLE_FACT_TYPES = [
5
4
  'task_started', 'task_progress', 'task_assigned', 'task_completed', 'task_interrupted', 'task_sabotaged',
5
+ ] as const;
6
+ export const TASK_REMINDER_FACT_TYPES = [
7
+ ...TASK_LIFECYCLE_FACT_TYPES,
6
8
  'role_assigned', 'emergency_started', 'emergency_resolved', 'emergency_interrupted', 'meeting_briefing',
7
9
  ] as const;
8
10
  export const REMINDER_FACT_TYPES_BY_TOPIC = {
@@ -18,6 +20,7 @@ export function isReminderMode(value: unknown): value is ReminderMode {
18
20
  }
19
21
  export function defaultConfig(topic: ReminderTopic): Record<string, ReminderMode> {
20
22
  if (topic !== 'tasks') throw new Error('Unsupported reminder topic; countdown and ability notifications are owned by CCL.');
23
+ // removed/updated remain accepted for existing installed v2 configs; this helper does not emit them.
21
24
  return { started: 'state_only', progress: 'state_only', added: 'silent', completed: 'silent',
22
25
  interrupted: 'wake', sabotaged: 'wake', removed: 'silent', updated: 'silent' };
23
26
  }
@@ -36,37 +39,6 @@ const labels: Record<string, string> = { started: '开始任务', progress: '任
36
39
  function record(value: unknown): Record<string, unknown> {
37
40
  return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
38
41
  }
39
- function ownFact(fact: ReminderFact, input: ReminderInput): boolean {
40
- const actor = record(fact.payload.actor);
41
- const seat = actor.seat ?? fact.payload.actor_seat;
42
- const name = actor.name ?? fact.payload.actor_name;
43
- const self = input.gameState?.you?.player;
44
- if (seat !== undefined && self?.seat !== undefined) return seat === self.seat;
45
- if (name !== undefined && self?.name !== undefined) return name === self.name;
46
- return seat === undefined && name === undefined;
47
- }
48
- function matches(fact: ReminderFact, change: ReminderTaskChange, input: ReminderInput): boolean {
49
- if (fact.epochId !== change.epochId || (fact.type.startsWith('task_') && !ownFact(fact, input))) return false;
50
- const p = fact.payload;
51
- if (p.task_id && change.task.task_id) return p.task_id === change.task.task_id;
52
- const name = p.task_name;
53
- if (!name || name !== change.task.name) return false;
54
- if (p.room && change.task.room && p.room !== change.task.room) return false;
55
- // Without IDs, only correlate an unambiguous task in this physical frame.
56
- return input.taskChanges.filter(c => c.epochId === change.epochId && c.task.name === name
57
- && (!p.room || !c.task.room || c.task.room === p.room)).length === 1;
58
- }
59
- function explained(fact: ReminderFact, change: ReminderTaskChange, input: ReminderInput): boolean {
60
- if (!matches(fact, change, input)) return false;
61
- if (change.change === 'added') return fact.type === 'task_assigned' || fact.type === 'emergency_started';
62
- if (change.change === 'removed') return ['task_completed', 'task_sabotaged', 'emergency_resolved', 'emergency_interrupted'].includes(fact.type);
63
- if (change.change === 'status_changed') {
64
- if (change.to_status === 'completed') return ['task_completed', 'task_sabotaged'].includes(fact.type);
65
- if (change.to_status === 'in_progress') return fact.type === 'task_started';
66
- if (change.from_status === 'in_progress' && change.to_status === 'normal') return fact.type === 'task_interrupted';
67
- }
68
- return false;
69
- }
70
42
  /** Nearby speech is a backend fact; only its Agent notification is optional. */
71
43
  export function speechReminder(input: ReminderInput): ReminderResult {
72
44
  if (Object.keys(input.config).some(key => key !== 'receive')
@@ -111,13 +83,7 @@ export function defaultReminder(topic: ReminderTopic, input: ReminderInput): Rem
111
83
  const kind = kinds[fact.type];
112
84
  if (kind) emit(kind, `fact:${fact.eventId}`, { ...fact.payload }, fact.eventId);
113
85
  }
114
- for (const change of input.taskChanges) {
115
- if (change.baseline || input.facts.some(f => explained(f, change, input))) continue;
116
- const kind = change.change === 'added' ? 'added' : change.change === 'removed' ? 'removed'
117
- : change.change === 'status_changed' && change.to_status === 'in_progress' ? 'started'
118
- : change.change === 'status_changed' && change.to_status === 'completed' ? 'completed' : 'updated';
119
- emit(kind, change.key, { ...change.task, change: change.change,
120
- from_status: change.from_status, to_status: change.to_status }, change.eventId);
121
- }
86
+ // Task lifecycle facts belong to this helper. State-only list changes stay
87
+ // available as input; emergency lifecycle notifications belong to emergency perception.
122
88
  return { events };
123
89
  }
@@ -22,11 +22,12 @@ export interface ReminderTaskChange {
22
22
  readonly baseline: boolean;
23
23
  }
24
24
  export interface ReminderInput {
25
+ readonly cycle?: import('../module-input/index.js').ProcessingCycleInfo;
25
26
  readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
26
27
  readonly frame: Readonly<ObservationFrame> | null;
27
28
  readonly gameState: Readonly<GameState> | null;
28
29
  readonly facts: readonly Readonly<ReminderFact>[];
29
- /** Reuses Source task comparison; independent of the facts subscription. */
30
+ /** Module-local comparison of consecutive task snapshots; no cross-perception dependency. */
30
31
  readonly taskChanges: readonly ReminderTaskChange[];
31
32
  /** Establish private baselines without replaying notifications. */
32
33
  readonly boundary: 'initial' | 'recovery' | null;
@@ -0,0 +1,258 @@
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
+ * Each perception owns its comparison baseline. This pure helper publishes no shared Event.
212
+ */
213
+ export function nextTaskProjection(input: {
214
+ previous: readonly TaskSnapshot[];
215
+ initialized: boolean;
216
+ summary?: Record<string, any> | null;
217
+ events?: readonly Record<string, any>[];
218
+ selfName?: string;
219
+ selfSeat?: number;
220
+ allowUntickedInitialRole?: boolean;
221
+ }): TaskProjectionUpdate {
222
+ const current = tasksFromState(input.summary);
223
+ if (!current) {
224
+ return {
225
+ projection: [...input.previous].map((task) => structuredClone(task)),
226
+ initialized: input.initialized,
227
+ payload: null,
228
+ };
229
+ }
230
+ const delta = taskDelta(input.previous, current);
231
+ if (input.initialized && delta.length === 0) {
232
+ return { projection: current, initialized: true, payload: null };
233
+ }
234
+ const selfSeat = input.selfSeat ?? (Number.isInteger(input.summary?.you?.player?.seat)
235
+ ? Number(input.summary!.you.player.seat)
236
+ : undefined);
237
+ const selfName = input.selfName ?? nonEmptyString(input.summary?.you?.player?.name);
238
+ const tick = finiteNumber(input.summary?.tick);
239
+ const reason = updateReason(
240
+ input.initialized,
241
+ input.events ?? [],
242
+ selfName,
243
+ selfSeat,
244
+ tick,
245
+ input.allowUntickedInitialRole === true,
246
+ );
247
+ return {
248
+ projection: current,
249
+ initialized: true,
250
+ payload: {
251
+ baseline: !input.initialized,
252
+ ...(tick === undefined ? {} : { tick }),
253
+ reason: reason.reason,
254
+ delta,
255
+ tasks: current.map((task) => structuredClone(task)),
256
+ },
257
+ };
258
+ }