@myclaw163/clawclaw-cli 0.8.14 → 0.8.16

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 (61) hide show
  1. package/docs/custom-modules/perception.md +4 -4
  2. package/docs/runtime/README.md +1 -1
  3. package/docs/runtime/behavior-runtime.md +1 -1
  4. package/docs/runtime/official-perception-modules.md +23 -30
  5. package/docs/runtime/perception-replay.md +1 -1
  6. package/package.json +1 -1
  7. package/scripts/sync-bundled-skill.mjs +28 -57
  8. package/skills/clawclaw/SKILL.md +6 -2
  9. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  10. package/skills/clawclaw/references/COMMANDS.md +1 -1
  11. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +310 -0
  12. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +684 -0
  13. package/skills/clawclaw/references/CUSTOM-MODULES.md +125 -0
  14. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +331 -0
  15. package/skills/clawclaw/references/HUB.md +2 -1
  16. package/src/commands/account.ts +36 -0
  17. package/src/commands/capability.ts +6 -1
  18. package/src/commands/load.ts +11 -0
  19. package/src/lib/agent-workspace-runtime.ts +2 -1
  20. package/src/lib/agent-workspace-skills.ts +235 -23
  21. package/src/lib/agent-workspace-sync.ts +17 -5
  22. package/src/lib/capability-cloud-refresh.ts +10 -1
  23. package/src/lib/capability-cloud-sync.ts +71 -1
  24. package/src/lib/capability-workspace.ts +2 -0
  25. package/src/lib/game-client.ts +10 -0
  26. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  27. package/src/runtime/clawclaw/owner.ts +79 -2
  28. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  31. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  32. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +46 -50
  33. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +39 -9
  34. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +167 -7
  35. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +107 -0
  36. package/src/runtime/clawclaw/plugins/mailbox/index.ts +1 -0
  37. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  38. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  39. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +28 -4
  40. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  41. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  42. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +126 -17
  43. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  44. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  45. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +41 -12
  46. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +252 -20
  47. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +496 -0
  48. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +164 -0
  49. package/src/runtime/clawclaw-event-catalog.ts +1 -0
  50. package/src/runtime/framework/events/memory-event-repository.ts +12 -0
  51. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  52. package/src/runtime/framework/persistence/memory-first-persistence.ts +3 -0
  53. package/src/runtime/framework/plugins/contracts.ts +3 -0
  54. package/src/runtime/framework/plugins/runtime-input-journal.ts +12 -0
  55. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +150 -23
  56. package/src/runtime/framework/runtime.ts +18 -0
  57. package/src/runtime/framework/state/history/memory-state-history-repository.ts +10 -0
  58. package/src/runtime/game-sync-protocol.ts +47 -0
  59. package/src/runtime/observability/redaction.ts +28 -1
  60. package/src/runtime/ws-client.ts +7 -0
  61. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -0,0 +1,24 @@
1
+ import { serialize } from 'node:v8';
2
+
3
+ export const MAX_RUNTIME_MODULE_OUTPUT_BYTES = 1024 * 1024;
4
+
5
+ export interface RuntimeModuleOutputSize {
6
+ readonly bytes: number;
7
+ readonly limitBytes: number;
8
+ }
9
+
10
+ /** Bounds cloneable external-module output before it is copied into the Owner. */
11
+ export function assertRuntimeModuleOutputSize(
12
+ value: unknown,
13
+ code: string,
14
+ limitBytes = MAX_RUNTIME_MODULE_OUTPUT_BYTES,
15
+ ): RuntimeModuleOutputSize {
16
+ let bytes: number;
17
+ try {
18
+ bytes = serialize(value).byteLength;
19
+ } catch {
20
+ throw new Error(`${code}_not_serializable`);
21
+ }
22
+ if (bytes > limitBytes) throw new Error(`${code}_too_large:${bytes}:${limitBytes}`);
23
+ return { bytes, limitBytes };
24
+ }
@@ -232,6 +232,7 @@ abstract class MirroredStore {
232
232
 
233
233
  class MemoryFirstEventRepository extends MirroredStore implements EventRepository, MailboxRepository {
234
234
  constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryEventRepository) { super(mirror); }
235
+ diagnosticCounts() { return this.memory.diagnosticCounts(); }
235
236
  saveSession(value: PlaySessionRecord): void { this.memory.saveSession(value); this.persist('events', 'saveSession', value); }
236
237
  saveSegment(value: EventSegmentRecord): void { this.memory.saveSegment(value); this.persist('events', 'saveSegment', value); }
237
238
  currentScope(account?: EventAccountScope) { return this.memory.currentScope(account); }
@@ -302,6 +303,7 @@ class MemoryFirstEventRepository extends MirroredStore implements EventRepositor
302
303
  class MemoryFirstStateHistory<TPosition, TState extends Record<string, unknown>> extends MirroredStore
303
304
  implements StateHistoryRepository<TPosition, TState> {
304
305
  constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryStateHistoryRepository<TPosition, TState>) { super(mirror); }
306
+ diagnosticCounts() { return this.memory.diagnosticCounts(); }
305
307
  openScope(scope: RuntimeScope, openedAtMs = Date.now(), historyComplete = true) {
306
308
  const result = this.memory.openScope(scope, openedAtMs, historyComplete);
307
309
  this.persist('history', 'openScope', scope, openedAtMs, historyComplete); return result;
@@ -319,6 +321,7 @@ implements StateHistoryRepository<TPosition, TState> {
319
321
  class MemoryFirstInputJournal<TState extends Record<string, unknown>, TEvent extends Record<string, unknown>>
320
322
  extends MirroredStore implements RuntimePersistenceStore<TState, TEvent> {
321
323
  constructor(mirror: AsyncSqliteMirror, private readonly memory: MemoryRuntimeInputJournal<TState, TEvent>) { super(mirror); }
324
+ diagnosticCounts() { return this.memory.diagnosticCounts(); }
322
325
  accept(batch: RuntimeInputBatch<TState, TEvent>) { const result = this.memory.accept(batch); if (result.inserted) this.persist('input', 'accept', batch); return result; }
323
326
  epoch(epochSeq: number) { return this.memory.epoch(epochSeq); }
324
327
  list(scope: RuntimeScope, afterEpochSeq?: number, limit?: number) { return this.memory.list(scope, afterEpochSeq, limit); }
@@ -201,6 +201,8 @@ extends RuntimePluginIdentity<'epoch'> {
201
201
  * in-flight capacity delays newer computation instead of discarding work.
202
202
  */
203
203
  readonly maxInFlight?: number;
204
+ /** Maximum retained epochs for non-strict catch-up before oldest work is coalesced. */
205
+ readonly maxPendingEpochs?: number;
204
206
  readonly failurePolicy?: RuntimePluginFailureMode | RuntimePluginFailurePolicy;
205
207
  /** Per-call deadline; Runtime still owns cancellation and stale-output rejection. */
206
208
  readonly timeoutMs?: number;
@@ -298,6 +300,7 @@ export interface RuntimeEpochPluginDescriptor extends RuntimePluginIdentity<'epo
298
300
  readonly after: readonly string[];
299
301
  readonly catchUp: RuntimeEpochCatchUp;
300
302
  readonly maxInFlight: number;
303
+ readonly maxPendingEpochs: number;
301
304
  readonly consumes: Readonly<NonNullable<RuntimeEpochPlugin['consumes']>>;
302
305
  readonly produces: Readonly<NonNullable<RuntimeEpochPlugin['produces']>>;
303
306
  readonly capabilities: Readonly<RuntimePluginCapabilityDeclaration>;
@@ -187,6 +187,18 @@ implements RuntimePersistenceStore<TState, TEvent> {
187
187
  private readonly pluginOutcomeRecordsByEpoch = new Map<number, RuntimeEpochPluginRecord[]>();
188
188
  private readonly stateRecords: RuntimeEpochStateRecord[] = [];
189
189
  private readonly stateRecordsByEpoch = new Map<number, RuntimeEpochStateRecord[]>();
190
+
191
+ diagnosticCounts(): Readonly<Record<string, number>> {
192
+ return {
193
+ epochs: this.epochs.length,
194
+ closed_epochs: this.closed.size,
195
+ input_event_commits: this.inputEventCommits.size,
196
+ event_watermarks: this.eventWatermarks.size,
197
+ plugin_progress: this.progress.size,
198
+ plugin_records: this.pluginOutcomeRecords.length,
199
+ plugin_states: this.stateRecords.length,
200
+ };
201
+ }
190
202
  private nextEpochSeq = 1;
191
203
 
192
204
  constructor(snapshot?: RuntimeInputJournalSnapshot<TState, TEvent>) {
@@ -88,6 +88,32 @@ export interface RuntimePluginSchedulerOptions<
88
88
  nowMs?: () => number;
89
89
  }
90
90
 
91
+ export interface RuntimePluginDiagnosticProgress {
92
+ readonly plugin_id: string;
93
+ readonly catch_up: RuntimeEpochPlugin<any, any>['catchUp'];
94
+ readonly max_in_flight: number;
95
+ readonly max_pending_epochs: number;
96
+ readonly completed_through_epoch_seq: number;
97
+ readonly ready_through_epoch_seq: number;
98
+ readonly lag_epoch_count: number;
99
+ readonly active_invocation_count: number;
100
+ readonly buffered_invocation_count: number;
101
+ readonly active_commit: boolean;
102
+ readonly paused: boolean;
103
+ }
104
+
105
+ export interface RuntimePluginSchedulerDiagnosticSnapshot {
106
+ readonly pending_epoch_count: number;
107
+ readonly oldest_pending_epoch_seq: number | null;
108
+ readonly newest_pending_epoch_seq: number | null;
109
+ readonly oldest_pending_age_ms: number;
110
+ readonly active_invocation_count: number;
111
+ readonly active_commit_count: number;
112
+ readonly buffered_invocation_count: number;
113
+ readonly input_event_commit_count: number;
114
+ readonly plugins: readonly RuntimePluginDiagnosticProgress[];
115
+ }
116
+
91
117
  interface PendingWork<TState, TEvent> {
92
118
  work: RuntimeEpochWork<TState, TEvent>;
93
119
  queuedAtMs: number;
@@ -264,6 +290,19 @@ function normalizedMaxInFlight(plugin: RuntimeEpochPlugin<any, any>): number {
264
290
  return maxInFlight;
265
291
  }
266
292
 
293
+ function normalizedMaxPendingEpochs(
294
+ plugin: RuntimeEpochPlugin<any, any>,
295
+ fallback: number,
296
+ ): number {
297
+ const maxPendingEpochs = plugin.maxPendingEpochs ?? fallback;
298
+ if (!Number.isInteger(maxPendingEpochs) || maxPendingEpochs <= 0 || maxPendingEpochs > 10_000) {
299
+ throw new TypeError(
300
+ `Runtime Epoch Plugin ${plugin.id} maxPendingEpochs must be an integer between 1 and 10000.`,
301
+ );
302
+ }
303
+ return maxPendingEpochs;
304
+ }
305
+
267
306
  function pluginLayers<TState, TEvent>(
268
307
  plugins: readonly RuntimeEpochPlugin<TState, TEvent>[],
269
308
  ): RuntimeEpochPlugin<TState, TEvent>[][] {
@@ -278,6 +317,7 @@ function pluginLayers<TState, TEvent>(
278
317
  byId.set(plugin.id, plugin);
279
318
  normalizedFailurePolicy(plugin);
280
319
  normalizedMaxInFlight(plugin);
320
+ if (plugin.maxPendingEpochs !== undefined) normalizedMaxPendingEpochs(plugin, 1);
281
321
  for (const topic of plugin.produces?.states ?? []) {
282
322
  assertNonEmpty(topic, `Runtime Epoch Plugin ${plugin.id} State output`);
283
323
  const owner = stateOwners.get(topic);
@@ -394,7 +434,7 @@ export class RuntimeEpochPluginSupersededError extends Error {
394
434
  readonly pluginId: string,
395
435
  readonly epochSeq: number,
396
436
  readonly newerEpochSeq: number,
397
- readonly reasonCode: 'newer_epoch_available' | 'catch_up_limit' = 'newer_epoch_available',
437
+ readonly reasonCode: 'newer_epoch_available' | 'catch_up_limit' | 'required_epoch_boundary' = 'newer_epoch_available',
398
438
  ) {
399
439
  super(`Runtime Epoch Plugin "${pluginId}" epoch ${epochSeq} was superseded by epoch ${newerEpochSeq}.`);
400
440
  this.name = 'RuntimeEpochPluginSupersededError';
@@ -510,6 +550,7 @@ export class RuntimePluginScheduler<
510
550
  after: [...(plugin.after ?? [])],
511
551
  catchUp: plugin.catchUp ?? 'every_epoch',
512
552
  maxInFlight: normalizedMaxInFlight(plugin),
553
+ maxPendingEpochs: normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
513
554
  consumes: cloneCanonical(plugin.consumes ?? {}),
514
555
  produces: cloneCanonical(plugin.produces ?? {}),
515
556
  capabilities: cloneCanonical(plugin.capabilities ?? {}),
@@ -521,6 +562,75 @@ export class RuntimePluginScheduler<
521
562
  }));
522
563
  }
523
564
 
565
+ /**
566
+ * Exact, on-demand scheduler state for full local diagnostics.
567
+ * The Owner calls this only while full observability is enabled so the
568
+ * per-plugin backlog scan has zero cost in the default runtime path.
569
+ */
570
+ diagnosticSnapshot(scope = this.activeScope ?? undefined): RuntimePluginSchedulerDiagnosticSnapshot {
571
+ const pending = scope
572
+ ? [...this.pending.values()].filter(({ work }) => (
573
+ runtimeScopeKey(work.epoch.scope) === runtimeScopeKey(scope)
574
+ ))
575
+ : [...this.pending.values()];
576
+ let oldest: PendingWork<TState, TEvent> | undefined;
577
+ let oldestEpochSeq: number | null = null;
578
+ let newestEpochSeq: number | null = null;
579
+ for (const entry of pending) {
580
+ if (!oldest || entry.queuedAtMs < oldest.queuedAtMs) oldest = entry;
581
+ const epochSeq = entry.work.epoch.epochSeq;
582
+ oldestEpochSeq = oldestEpochSeq === null ? epochSeq : Math.min(oldestEpochSeq, epochSeq);
583
+ newestEpochSeq = newestEpochSeq === null ? epochSeq : Math.max(newestEpochSeq, epochSeq);
584
+ }
585
+ const effectiveScope = scope ?? pending[0]?.work.epoch.scope;
586
+ const progressByPlugin = effectiveScope
587
+ ? new Map(this.plugins.map((plugin) => [
588
+ plugin.id,
589
+ this.pluginStore.pluginProgress(plugin.id, effectiveScope),
590
+ ]))
591
+ : new Map<string, ReturnType<RuntimePluginStore['pluginProgress']>>();
592
+ const latestEpochSeq = newestEpochSeq ?? 0;
593
+ const plugins = this.plugins.map((plugin): RuntimePluginDiagnosticProgress => {
594
+ const progress = progressByPlugin.get(plugin.id);
595
+ const completedThroughEpochSeq = progress?.completedThroughEpochSeq ?? 0;
596
+ const dependencies = (plugin.after ?? []).map((id) => (
597
+ progressByPlugin.get(id)?.completedThroughEpochSeq ?? 0
598
+ ));
599
+ const readyThroughEpochSeq = dependencies.length === 0
600
+ ? latestEpochSeq
601
+ : Math.min(latestEpochSeq, ...dependencies);
602
+ return {
603
+ plugin_id: plugin.id,
604
+ catch_up: plugin.catchUp ?? 'every_epoch',
605
+ max_in_flight: normalizedMaxInFlight(plugin),
606
+ max_pending_epochs: normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
607
+ completed_through_epoch_seq: completedThroughEpochSeq,
608
+ ready_through_epoch_seq: readyThroughEpochSeq,
609
+ lag_epoch_count: pending.filter(({ work }) => (
610
+ work.epoch.epochSeq > completedThroughEpochSeq
611
+ )).length,
612
+ active_invocation_count: [...this.activeInvocations.values()]
613
+ .filter(({ pluginId }) => pluginId === plugin.id).length,
614
+ buffered_invocation_count: this.bufferedInvocations.get(plugin.id)?.size ?? 0,
615
+ active_commit: this.activeCommits.has(plugin.id),
616
+ paused: this.pausedPlugins.has(plugin.id),
617
+ };
618
+ });
619
+ return {
620
+ pending_epoch_count: pending.length,
621
+ oldest_pending_epoch_seq: oldestEpochSeq,
622
+ newest_pending_epoch_seq: newestEpochSeq,
623
+ oldest_pending_age_ms: oldest
624
+ ? Math.max(0, this.nowMs() - oldest.queuedAtMs)
625
+ : 0,
626
+ active_invocation_count: this.activeInvocations.size,
627
+ active_commit_count: this.activeCommits.size,
628
+ buffered_invocation_count: this.bufferedInvocationCount(),
629
+ input_event_commit_count: this.inputEventCommits.size,
630
+ plugins,
631
+ };
632
+ }
633
+
524
634
  async activateScope(scope: RuntimeScope): Promise<void> {
525
635
  if (this.activeScope && runtimeScopeKey(this.activeScope) === runtimeScopeKey(scope)) return;
526
636
  if (this.activeInvocations.size > 0 || this.activeCommits.size > 0 || this.bufferedInvocationCount() > 0) {
@@ -680,7 +790,6 @@ export class RuntimePluginScheduler<
680
790
  let launched = 0;
681
791
  for (const plugin of this.plugins) {
682
792
  const maxInFlight = normalizedMaxInFlight(plugin);
683
- if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0) continue;
684
793
  let candidates = this.launchCandidates(plugin, scope);
685
794
  if (candidates.length === 0) continue;
686
795
  if (this.pausedPlugins.has(plugin.id)) {
@@ -698,14 +807,20 @@ export class RuntimePluginScheduler<
698
807
  continue;
699
808
  }
700
809
 
701
- if (maxInFlight > 1) {
702
- if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
703
- this.trimParallelBacklog(plugin, scope);
704
- }
810
+ if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
811
+ this.trimBoundedBacklog(plugin, scope);
705
812
  candidates = this.launchCandidates(plugin, scope);
813
+ if (candidates.length === 0) continue;
814
+ }
815
+ if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0) continue;
816
+
817
+ if (maxInFlight > 1) {
706
818
  const reorderCapacity = (plugin.catchUp ?? 'every_epoch') === 'strict_ordered'
707
819
  ? maxInFlight
708
- : Math.min(maxInFlight, this.maxCatchUpEpochs);
820
+ : Math.min(
821
+ maxInFlight,
822
+ normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs),
823
+ );
709
824
  let slots = reorderCapacity - this.scheduledInvocationCount(plugin.id);
710
825
  for (const candidate of candidates) {
711
826
  if (slots <= 0) break;
@@ -719,9 +834,15 @@ export class RuntimePluginScheduler<
719
834
  const catchUp = plugin.catchUp ?? 'every_epoch';
720
835
  const count = this.catchUpCounts.get(plugin.id) ?? 0;
721
836
  const requiredIndex = candidates.findIndex((candidate) => forbidsCoalescing(candidate.work));
722
- const shouldJump = requiredIndex > 0
723
- || (requiredIndex < 0 && (catchUp === 'latest_only'
724
- || (catchUp === 'every_epoch' && count >= this.maxCatchUpEpochs && candidates.length > 1)));
837
+ const shouldJump = requiredIndex > 0 || (
838
+ requiredIndex < 0 && (
839
+ catchUp === 'latest_only' || (
840
+ catchUp === 'every_epoch'
841
+ && count >= normalizedMaxPendingEpochs(plugin, this.maxCatchUpEpochs)
842
+ && candidates.length > 1
843
+ )
844
+ )
845
+ );
725
846
  if (shouldJump && candidates.length > 1) {
726
847
  const targetIndex = requiredIndex >= 0 ? requiredIndex : candidates.length - 1;
727
848
  const skipped = candidates.slice(0, targetIndex);
@@ -782,12 +903,10 @@ export class RuntimePluginScheduler<
782
903
  // A parallel update may finish while an earlier ordered commit is still
783
904
  // performing effects. Apply the same catch-up window to those completed
784
905
  // proposals before granting the next commit lease; otherwise buffered
785
- // results can bypass trimParallelBacklog and replay an arbitrarily stale
906
+ // results can bypass trimBoundedBacklog and replay an arbitrarily stale
786
907
  // sequence of Actions after the head commit settles.
787
- if (normalizedMaxInFlight(plugin) > 1) {
788
- if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
789
- this.trimParallelBacklog(plugin, scope);
790
- }
908
+ if ((plugin.catchUp ?? 'every_epoch') !== 'strict_ordered') {
909
+ this.trimBoundedBacklog(plugin, scope);
791
910
  }
792
911
  if (this.activeCommits.has(plugin.id)) continue;
793
912
  const progress = this.pluginStore.pluginProgress(plugin.id, scope);
@@ -1320,24 +1439,32 @@ export class RuntimePluginScheduler<
1320
1439
  ));
1321
1440
  }
1322
1441
 
1323
- private trimParallelBacklog(
1442
+ private trimBoundedBacklog(
1324
1443
  plugin: RuntimeEpochPlugin<TState, TEvent>,
1325
1444
  scope: RuntimeScope,
1326
1445
  ): void {
1446
+ const maxInFlight = normalizedMaxInFlight(plugin);
1327
1447
  const catchUpWindow = Math.min(
1328
- normalizedMaxInFlight(plugin),
1329
- this.maxCatchUpEpochs,
1448
+ normalizedMaxPendingEpochs(
1449
+ plugin,
1450
+ maxInFlight > 1
1451
+ ? Math.min(maxInFlight, this.maxCatchUpEpochs)
1452
+ : this.maxCatchUpEpochs,
1453
+ ),
1454
+ 10_000,
1330
1455
  );
1331
1456
  while (true) {
1332
1457
  const ready = this.readyCandidates(plugin, scope);
1333
1458
  const earliest = ready[0];
1334
1459
  const latest = ready.at(-1);
1460
+ const requiredIndex = ready.findIndex(({ work }) => forbidsCoalescing(work));
1335
1461
  if (
1336
1462
  !earliest
1337
1463
  || !latest
1338
- || latest.work.epoch.epochSeq - earliest.work.epoch.epochSeq < catchUpWindow
1464
+ || ready.length <= catchUpWindow
1339
1465
  ) return;
1340
- if (forbidsCoalescing(earliest.work)) return;
1466
+ if (requiredIndex === 0 || forbidsCoalescing(earliest.work)) return;
1467
+ const reason = requiredIndex > 0 ? 'required_epoch_boundary' : 'catch_up_limit';
1341
1468
  // commit() is the atomic reducer/effect boundary. Once it has started we
1342
1469
  // must let it finish; only a completed proposal that has not obtained the
1343
1470
  // commit lease may be discarded.
@@ -1354,7 +1481,7 @@ export class RuntimePluginScheduler<
1354
1481
  || buffered.invocation.error !== undefined
1355
1482
  ) return;
1356
1483
  buffer.delete(earliest.work.epoch.epochSeq);
1357
- this.recordCoalesced(plugin, [earliest.work], 'catch_up_limit');
1484
+ this.recordCoalesced(plugin, [earliest.work], reason);
1358
1485
  continue;
1359
1486
  }
1360
1487
  const active = this.activeInvocations.get(
@@ -1366,12 +1493,12 @@ export class RuntimePluginScheduler<
1366
1493
  plugin.id,
1367
1494
  earliest.work.epoch.epochSeq,
1368
1495
  latest.work.epoch.epochSeq,
1369
- 'catch_up_limit',
1496
+ reason,
1370
1497
  ));
1371
1498
  }
1372
1499
  return;
1373
1500
  }
1374
- this.recordCoalesced(plugin, [earliest.work], 'catch_up_limit');
1501
+ this.recordCoalesced(plugin, [earliest.work], reason);
1375
1502
  }
1376
1503
  }
1377
1504
 
@@ -608,6 +608,24 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
608
608
  return this.pluginScheduler.descriptors();
609
609
  }
610
610
 
611
+ /** Full-diagnostic, on-demand scheduler state; never sampled by default. */
612
+ runtimeEpochDiagnosticSnapshot(): ReturnType<RuntimePluginScheduler['diagnosticSnapshot']> {
613
+ return this.pluginScheduler.diagnosticSnapshot(this.scope());
614
+ }
615
+
616
+ /** Full-only retained row counts; implementations without a hot cache report an empty object. */
617
+ runtimeRetainedRecordCounts(): Readonly<Record<string, unknown>> {
618
+ const counts = (value: unknown): Readonly<Record<string, number>> => (
619
+ (value as { diagnosticCounts?: () => Readonly<Record<string, number>> })
620
+ ?.diagnosticCounts?.() ?? {}
621
+ );
622
+ return {
623
+ event_repository: counts(this.repository),
624
+ state_history: counts(this.stateHistoryRepository),
625
+ input_journal: counts(this.inputJournal),
626
+ };
627
+ }
628
+
611
629
  runtimePluginDescriptors(): RuntimePluginDescriptor[] {
612
630
  return [
613
631
  ...[...this.sourcePlugins.values()].map(({ plugin }) => ({
@@ -29,6 +29,16 @@ export class MemoryStateHistoryRepository<
29
29
  private readonly records: Array<TrajectoryRecord<TPosition> & { recordSeq: number }> = [];
30
30
  private readonly recordsByScope = new Map<string, Array<TrajectoryRecord<TPosition> & { recordSeq: number }>>();
31
31
  private readonly dedupe = new Set<string>();
32
+
33
+ diagnosticCounts(): Readonly<Record<string, number>> {
34
+ return {
35
+ scopes: this.scopes.size,
36
+ state_frames: this.stateFrames.length,
37
+ trajectory_records: this.records.length,
38
+ state_frame_dedupe_keys: this.stateFrameDedupe.size,
39
+ trajectory_dedupe_keys: this.dedupe.size,
40
+ };
41
+ }
32
42
  private nextFrameSeq = 1;
33
43
  private nextRecordSeq = 1;
34
44
 
@@ -31,6 +31,20 @@ export interface GameSyncErrorData {
31
31
  readonly message?: string;
32
32
  }
33
33
 
34
+ export interface GameSyncPerceptionReport {
35
+ readonly id: string;
36
+ readonly name: string;
37
+ readonly output: string;
38
+ readonly source_tick: number;
39
+ }
40
+
41
+ export interface GameSyncPerceptionReportMessage {
42
+ readonly type: 'game.sync.perception.report';
43
+ readonly data: {
44
+ readonly perceptions: readonly GameSyncPerceptionReport[];
45
+ };
46
+ }
47
+
34
48
  export type GameSyncServerMessage =
35
49
  | { readonly type: 'game.sync.snapshot'; readonly data: GameSyncSnapshotData }
36
50
  | { readonly type: 'game.sync.update'; readonly data: GameSyncUpdateData }
@@ -71,6 +85,39 @@ function eventArray(value: unknown, field: string): Record<string, any>[] {
71
85
  });
72
86
  }
73
87
 
88
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
89
+
90
+ /** Build one client perception report frame using the backend's all-or-nothing validation rules. */
91
+ export function gameSyncPerceptionReportMessage(
92
+ perceptions: readonly GameSyncPerceptionReport[],
93
+ ): GameSyncPerceptionReportMessage {
94
+ if (perceptions.length < 1 || perceptions.length > 20) {
95
+ throw new TypeError('GameSync perception report must contain between 1 and 20 items');
96
+ }
97
+ const ids = new Set<string>();
98
+ const detached = perceptions.map((perception, index) => {
99
+ if (!UUID_PATTERN.test(perception.id)) {
100
+ throw new TypeError(`GameSync perception report[${index}].id must be a UUID`);
101
+ }
102
+ if (ids.has(perception.id)) {
103
+ throw new TypeError('GameSync perception report IDs must be unique within a batch');
104
+ }
105
+ ids.add(perception.id);
106
+ if (typeof perception.name !== 'string' || perception.name.length === 0) {
107
+ throw new TypeError(`GameSync perception report[${index}].name must be a non-empty string`);
108
+ }
109
+ if (typeof perception.output !== 'string') {
110
+ throw new TypeError(`GameSync perception report[${index}].output must be a string`);
111
+ }
112
+ integer(perception.source_tick, `GameSync perception report[${index}].source_tick`);
113
+ return { ...perception };
114
+ });
115
+ return {
116
+ type: 'game.sync.perception.report',
117
+ data: { perceptions: detached },
118
+ };
119
+ }
120
+
74
121
  /** Validate only the envelope and sequencing fields CCL must trust. */
75
122
  export function parseGameSyncMessage(value: unknown): GameSyncServerMessage {
76
123
  const envelope = record(value, 'GameSync message');
@@ -6,6 +6,9 @@ const PRIVATE_TEXT_KEY = /(?:^|_)(?:speech|comment|think|thinking|chat|knowledge
6
6
  const RAW_PAYLOAD_KEY = /(?:^|_)(?:raw|raw_frame|raw_payload|raw_ws|frame|frame_payload|payload|state|game_state|state_payload|room_payload|event_payload|request_body|response_body|environment|env)$/;
7
7
  const PATH_KEY = /(?:^|_)(?:path|cwd|workspace|directory|dir|filename|file_path|file_name)$/;
8
8
  const IDENTITY_KEY = /(?:^|_)(?:account|account_id|player_name|room_code|agent_name|user_id)$/;
9
+ const DIAGNOSTIC_CODE_KEY = /^(?:code|error_code|.*_error_code)$/;
10
+ const DIAGNOSTIC_CODE = /^[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)+$/;
11
+ const SECRET_CODE_PREFIX = /^(?:claw_|sk[-_]|ghp_|github_pat_|eyj)/i;
9
12
  const TOKEN_IN_TEXT = /\b(?:Bearer\s+)?[A-Za-z0-9_-]{24,}\b/g;
10
13
  const FILE_URL = /file:\/\/\/?[^"'\r\n<>\)\]]+/gi;
11
14
  const WINDOWS_PATH = /\b[A-Za-z]:[\\\/][^"'\r\n<>\)\]]+/g;
@@ -84,6 +87,24 @@ function safeString(value: string, maxLength: number): string {
84
87
  : `${withoutQuery.slice(0, maxLength)}...[truncated:${withoutQuery.length}]`;
85
88
  }
86
89
 
90
+ /**
91
+ * Preserve bounded semantic codes such as `behavior_activation_superseded`
92
+ * without turning an error-code field into a credential escape hatch. Tokens
93
+ * usually have a known secret prefix or one long high-entropy segment, while
94
+ * Runtime diagnostic codes are made from multiple short semantic segments.
95
+ */
96
+ function safeDiagnosticCode(value: string): string | null {
97
+ if (
98
+ value.length === 0
99
+ || value.length > 160
100
+ || value.trim() !== value
101
+ || !DIAGNOSTIC_CODE.test(value)
102
+ || SECRET_CODE_PREFIX.test(value)
103
+ || value.split(/[._-]/).some((segment) => segment.length >= 24)
104
+ ) return null;
105
+ return value;
106
+ }
107
+
87
108
  /**
88
109
  * Redacts before persistence. It is deliberately defensive: cycles, deep
89
110
  * objects and oversized collections are bounded rather than allowed to break
@@ -121,7 +142,13 @@ export class ObservabilityRedactor {
121
142
  if (IDENTITY_KEY.test(policyKey) && value !== null && value !== undefined) return this.stableHash(value);
122
143
  if (value === null || value === undefined || typeof value === 'boolean' || typeof value === 'number') return value;
123
144
  if (typeof value === 'bigint') return value.toString();
124
- if (typeof value === 'string') return safeString(value, this.maxStringLength);
145
+ if (typeof value === 'string') {
146
+ if (DIAGNOSTIC_CODE_KEY.test(policyKey)) {
147
+ const code = safeDiagnosticCode(value);
148
+ if (code) return code;
149
+ }
150
+ return safeString(value, this.maxStringLength);
151
+ }
125
152
  if (depth >= this.maxDepth) return '[MAX_DEPTH]';
126
153
  if (value instanceof Error) {
127
154
  return this.visit({
@@ -7,9 +7,11 @@ import { WsConnectionState } from '../sdk/types.js';
7
7
  import type { RawWsMessageSink } from './raw-ws-log.js';
8
8
  import {
9
9
  applyGameSyncDelta,
10
+ gameSyncPerceptionReportMessage,
10
11
  gameSyncUrl,
11
12
  parseGameSyncMessage,
12
13
  type GameSyncErrorData,
14
+ type GameSyncPerceptionReport,
13
15
  } from './game-sync-protocol.js';
14
16
 
15
17
  export interface GameSyncResumeState {
@@ -163,6 +165,11 @@ export class WsClient {
163
165
  return this.committedBaseline ? structuredClone(this.committedBaseline) : undefined;
164
166
  }
165
167
 
168
+ /** Best-effort perception output; the server intentionally sends no acknowledgement. */
169
+ reportPerceptions(perceptions: readonly GameSyncPerceptionReport[]): boolean {
170
+ return this.send(gameSyncPerceptionReportMessage(perceptions));
171
+ }
172
+
166
173
  /**
167
174
  * Advance the resume/ACK watermark only after Source has durably accepted the
168
175
  * matching frame. Reading a socket frame is not sufficient authority.
@@ -102,6 +102,8 @@ export interface PerceptionBoundary {
102
102
  readonly mode: 'snapshot' | 'close';
103
103
  /** Last visual frame the module may include in this output. */
104
104
  readonly through: Readonly<PerceptionFrame> | null;
105
+ /** First frame after a close boundary, when one exists; never part of the closing slice. */
106
+ readonly next?: Readonly<PerceptionFrame> | null;
105
107
  }
106
108
 
107
109
  export interface PerceptionEventProposal {
@@ -125,9 +127,10 @@ export interface ClawclawPerceptionManifest {
125
127
  /** Optional display metadata for every Event in `produces`. */
126
128
  readonly eventMetadata?: Readonly<Record<string, ClawclawPerceptionEventMetadata>>;
127
129
  /**
128
- * Omit for the main-thread, persistent, ordered `update()` contract.
130
+ * Omit for the persistent, ordered `update()` contract.
129
131
  * `parallel_analysis` batches every enabled parallel module for one frame on
130
- * a reusable Worker Thread, then applies each persistent reducer in order.
132
+ * reusable analysis Workers, then applies each persistent reducer in order
133
+ * on its reducer Worker lane.
131
134
  */
132
135
  readonly execution?: 'parallel_analysis';
133
136
  /**
@@ -142,9 +145,10 @@ export interface ClawclawPerceptionManifest {
142
145
  /**
143
146
  * Canonical authoring surface for one independent perception module.
144
147
  *
145
- * CCL directly imports this trusted local code. Without `parallel_analysis`,
146
- * one persistent instance runs `update()` on the Runtime main thread in frame
147
- * order; it is not a sandbox and must keep each call short.
148
+ * CCL imports this local code inside a memory-bounded Worker lane. Without
149
+ * `parallel_analysis`, one persistent instance runs `update()` in frame order.
150
+ * A slow call can be terminated without blocking the Runtime Owner, but authors
151
+ * should still keep each call short so the module can keep up with live frames.
148
152
  */
149
153
  export abstract class ClawclawPerception {
150
154
  static readonly manifest?: ClawclawPerceptionManifest;
@@ -179,8 +183,8 @@ export abstract class ClawclawPerception {
179
183
  * instance for every module/frame job, so `analyze()` must depend only on its
180
184
  * arguments and cannot rely on an earlier instance having run.
181
185
  *
182
- * A separate long-lived reducer instance lives on the Runtime main thread and
183
- * receives successful analysis values through `commit()` in frame order.
186
+ * A separate long-lived reducer instance lives on a memory-bounded Worker lane
187
+ * and receives successful analysis values through `commit()` in frame order.
184
188
  * `commit()` is the only place this module may mutate cross-frame state or emit
185
189
  * Events and must remain short. A completed analysis is still only a proposal:
186
190
  * when the 1-10 frame window is exhausted, CCL may discard it before `commit()`.
@@ -190,7 +194,8 @@ export abstract class ClawclawPerception {
190
194
  *
191
195
  * Analysis values cross the Worker boundary and therefore must be supported by
192
196
  * `structuredClone`. CCL rejects a value that cannot be cloned. Worker Threads
193
- * are an execution mechanism, not a security sandbox; load only trusted code.
197
+ * isolate failures and bound V8 old-generation memory, but are not an
198
+ * operating-system security sandbox; load only trusted code.
194
199
  */
195
200
  export abstract class ClawclawParallelPerception<TAnalysis = unknown>
196
201
  extends ClawclawPerception {