@myclaw163/clawclaw-cli 0.8.13 → 0.8.15

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 (68) 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/skills/clawclaw/SKILL.md +8 -4
  8. package/skills/clawclaw/references/BEHAVIORS.md +16 -1
  9. package/skills/clawclaw/references/CHANNELS.md +1 -1
  10. package/skills/clawclaw/references/COMMANDS.md +2 -2
  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/STREAM.md +4 -2
  16. package/src/lib/game-client.ts +12 -4
  17. package/src/pipeline/event-format.ts +5 -0
  18. package/src/pipeline/event-hints.ts +10 -0
  19. package/src/runtime/clawclaw/agent-event-policy.ts +2 -0
  20. package/src/runtime/clawclaw/behavior-decision.ts +4 -1
  21. package/src/runtime/clawclaw/behavior-input.ts +5 -0
  22. package/src/runtime/clawclaw/owner.ts +64 -1
  23. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +150 -18
  24. package/src/runtime/clawclaw/plugins/assembly.ts +4 -0
  25. package/src/runtime/clawclaw/plugins/behavior/behavior-action.ts +8 -0
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +35 -2
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -7
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-decision-history.ts +88 -0
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -2
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +201 -43
  31. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +45 -9
  32. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +170 -8
  33. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +5 -1
  34. package/src/runtime/clawclaw/plugins/perception/module-runner.ts +86 -89
  35. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +157 -41
  36. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +33 -9
  37. package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +3 -1
  38. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +30 -0
  39. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +327 -23
  40. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +660 -0
  41. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-worker.ts +262 -0
  42. package/src/runtime/clawclaw/plugins/source/game-transport.ts +29 -4
  43. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +153 -0
  44. package/src/runtime/clawclaw/plugins/source/types.ts +1 -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/runtime.ts +31 -3
  50. package/src/runtime/clawclaw-event-catalog.ts +3 -0
  51. package/src/runtime/framework/events/event-repository.ts +1 -1
  52. package/src/runtime/framework/events/memory-event-repository.ts +71 -1
  53. package/src/runtime/framework/events/sqlite-event-repository.ts +23 -1
  54. package/src/runtime/framework/mailbox/types.ts +2 -0
  55. package/src/runtime/framework/modules/runtime-module-output.ts +24 -0
  56. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +58 -0
  57. package/src/runtime/framework/persistence/memory-first-persistence.ts +383 -0
  58. package/src/runtime/framework/plugins/contracts.ts +5 -2
  59. package/src/runtime/framework/plugins/runtime-input-journal.ts +185 -17
  60. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +173 -34
  61. package/src/runtime/framework/runtime.ts +75 -4
  62. package/src/runtime/framework/state/history/contracts.ts +9 -1
  63. package/src/runtime/framework/state/history/memory-state-history-repository.ts +59 -7
  64. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +16 -0
  65. package/src/runtime/observability/redaction.ts +28 -1
  66. package/src/sdk/behavior-plugin/index.ts +5 -24
  67. package/src/sdk/module-input/index.ts +47 -0
  68. package/src/sdk/perception-plugin/index.ts +13 -8
@@ -13,8 +13,9 @@ const MIN_RUNTIME_MS = 1_000;
13
13
  const MAX_RUNTIME_MS = 120_000;
14
14
 
15
15
  export interface PreparedClawclawBehavior {
16
- readonly module: ClawclawBehavior;
17
- readonly createModule: () => ClawclawBehavior;
16
+ /** Owner-local instance exists only for explicitly serial trusted execution. */
17
+ readonly module?: ClawclawBehavior;
18
+ readonly createModule?: () => ClawclawBehavior;
18
19
  readonly manifest: Readonly<ClawclawBehaviorManifest>;
19
20
  readonly input: Readonly<Record<string, unknown>>;
20
21
  /** Static source identity required only by isolated parallel execution. */
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { performance } from 'node:perf_hooks';
2
3
  import type {
3
4
  BehaviorContinuation,
4
5
  BehaviorDecision,
@@ -41,6 +42,7 @@ import {
41
42
  } from './activation-manager.js';
42
43
  import { normalizeClawclawBehaviorAction } from './behavior-action.js';
43
44
  import type { ClawclawBehaviorCatalog } from './behavior-catalog.js';
45
+ import { BehaviorDecisionHistory } from './behavior-decision-history.js';
44
46
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
45
47
  import { ClawclawBehaviorRunner } from './behavior-runner.js';
46
48
  import type {
@@ -114,6 +116,7 @@ export interface ClawclawBehaviorPluginOptions {
114
116
  readonly timeoutMs?: number;
115
117
  readonly decisionTimeoutMs?: number;
116
118
  readonly catchUp?: RuntimeEpochCatchUp;
119
+ readonly diagnosticsEnabled?: boolean;
117
120
  readonly now?: () => number;
118
121
  readonly createActivationId?: () => string;
119
122
  }
@@ -138,6 +141,7 @@ interface ActivationRuntime {
138
141
  lastCommittedBackendTick?: number;
139
142
  lastStatus?: Readonly<BehaviorStatus>;
140
143
  pendingContinuation?: Readonly<BehaviorContinuation>;
144
+ readonly decisionHistory: BehaviorDecisionHistory;
141
145
  committedActionDedupeKeys: Map<string, number>;
142
146
  }
143
147
 
@@ -276,6 +280,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
276
280
  readonly capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY] } as const;
277
281
  readonly catchUp: RuntimeEpochCatchUp;
278
282
  readonly maxInFlight = 10;
283
+ readonly maxPendingEpochs = 10;
279
284
  readonly timeoutMs: number;
280
285
  readonly failurePolicy = 'failed_completion' as const;
281
286
 
@@ -284,6 +289,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
284
289
  private readonly now: () => number;
285
290
  private readonly createActivationId: () => string;
286
291
  private readonly decisionTimeoutMs: number;
292
+ private readonly diagnosticsEnabled: boolean;
287
293
  private readonly observationMemory = new ClawclawBehaviorObservationMemory();
288
294
  private readonly runtimes = new Map<string, ActivationRuntime>();
289
295
  private readonly delegatedShorts = new Map<string, Readonly<DelegatedShort>>();
@@ -320,6 +326,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
320
326
  this.now = options.now ?? Date.now;
321
327
  this.createActivationId = options.createActivationId ?? randomUUID;
322
328
  this.decisionTimeoutMs = options.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
329
+ this.diagnosticsEnabled = options.diagnosticsEnabled === true;
323
330
  this.after = [...(options.after ?? [
324
331
  CLAWCLAW_ACTION_PLUGIN_ID,
325
332
  CLAWCLAW_DERIVED_EVENT_PLUGIN_ID,
@@ -327,7 +334,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
327
334
  CLAWCLAW_PERCEPTION_PLUGIN_ID,
328
335
  CLAWCLAW_TRIGGER_PLUGIN_ID,
329
336
  ])];
330
- this.catchUp = options.catchUp ?? 'strict_ordered';
337
+ this.catchUp = options.catchUp ?? 'every_epoch';
331
338
  this.timeoutMs = options.timeoutMs ?? Math.max(this.decisionTimeoutMs + 1_000, 5_000);
332
339
  const eventTypes = new Set([
333
340
  ...CLAWCLAW_BEHAVIOR_LIFECYCLE_EVENT_TYPES,
@@ -360,6 +367,23 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
360
367
  });
361
368
  }
362
369
 
370
+ diagnosticSnapshot(): Readonly<Record<string, unknown>> {
371
+ const status = this.status();
372
+ return Object.freeze({
373
+ running: status.running,
374
+ current_activation_id: status.current?.activationId ?? null,
375
+ current_behavior_id: status.current?.behaviorId ?? null,
376
+ current_layer: status.current?.layer ?? null,
377
+ runtime_count: this.runtimes.size,
378
+ runtimes: [...this.runtimes.values()].map((runtime) => ({
379
+ activation_id: runtime.activationId,
380
+ behavior_id: runtime.behaviorId,
381
+ instance_generation: runtime.instanceGeneration ?? null,
382
+ runner: runtime.runner?.diagnosticSnapshot() ?? null,
383
+ })),
384
+ });
385
+ }
386
+
363
387
  setIdleMs(idleMs: number): Promise<void> {
364
388
  return this.enqueueControl(async () => {
365
389
  await this.applyTransitions(this.manager.setIdleMs(idleMs, this.now()));
@@ -490,6 +514,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
490
514
  activationId,
491
515
  behaviorId: request.behavior,
492
516
  prepared,
517
+ decisionHistory: new BehaviorDecisionHistory(),
493
518
  committedActionDedupeKeys: new Map(),
494
519
  });
495
520
  const replaced = transitions.find((entry) => entry.type === 'replaced');
@@ -519,69 +544,150 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
519
544
  return { outcome: 'processed', proposal: { ...base, kind: 'inactive' } satisfies BehaviorComputationProposal };
520
545
  }
521
546
  const runtime = this.runtimes.get(current.activationId);
522
- const frame = createBehaviorInput(input, current.input, runtime?.pendingContinuation);
547
+ if (
548
+ runtime
549
+ && runtime.instanceGeneration === current.instanceGeneration
550
+ && isClawclawRuntimeState(input.epoch.state)
551
+ && input.epoch.state.game_snapshot.status === 'fresh'
552
+ ) {
553
+ const tick = Number(
554
+ input.epoch.domainTick
555
+ ?? input.epoch.state.game_snapshot.state.tick
556
+ ?? input.epoch.epochSeq,
557
+ );
558
+ runtime.decisionHistory.begin({
559
+ epochId: input.epoch.epochSeq,
560
+ tick,
561
+ instanceGeneration: current.instanceGeneration,
562
+ });
563
+ const history = runtime.decisionHistory.snapshot();
564
+ context.diagnostic('behavior.decision_history.frame_pending', {
565
+ behavior_id: current.behaviorId,
566
+ activation_id: current.activationId,
567
+ instance_generation: current.instanceGeneration,
568
+ epoch_id: input.epoch.epochSeq,
569
+ tick,
570
+ retained_frame_count: history.length,
571
+ pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
572
+ }, 'debug');
573
+ }
574
+ const frame = createBehaviorInput(
575
+ input,
576
+ current.input,
577
+ runtime?.pendingContinuation,
578
+ runtime?.decisionHistory.snapshot(),
579
+ );
523
580
  if (!frame) {
524
581
  return { outcome: 'processed', proposal: { ...base, kind: 'waiting_for_state' } satisfies BehaviorComputationProposal };
525
582
  }
583
+ const noDecision = (
584
+ kind: BehaviorComputationProposal['kind'],
585
+ reason: string,
586
+ ): RuntimeEpochPluginResult => {
587
+ const resolved = runtime?.decisionHistory.notComputed(frame.epochId, reason);
588
+ if (resolved) {
589
+ const history = runtime!.decisionHistory.snapshot();
590
+ context.diagnostic('behavior.decision_history.frame_resolved', {
591
+ behavior_id: current.behaviorId,
592
+ activation_id: current.activationId,
593
+ instance_generation: current.instanceGeneration,
594
+ epoch_id: frame.epochId,
595
+ tick: resolved.tick,
596
+ status: resolved.status,
597
+ reason,
598
+ action_count: 0,
599
+ retained_frame_count: history.length,
600
+ pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
601
+ }, 'debug');
602
+ }
603
+ return {
604
+ outcome: 'processed',
605
+ proposal: { ...base, kind } satisfies BehaviorComputationProposal,
606
+ };
607
+ };
526
608
  if (frame.gameState.phase === 'game_over') {
527
- return { outcome: 'processed', proposal: { ...base, kind: 'game_over' } satisfies BehaviorComputationProposal };
609
+ return noDecision('game_over', 'game_over');
528
610
  }
529
611
  if (frame.gameState.you?.is_alive === false) {
530
- return { outcome: 'processed', proposal: { ...base, kind: 'player_inactive' } satisfies BehaviorComputationProposal };
612
+ return noDecision('player_inactive', 'player_inactive');
531
613
  }
532
614
  const meetingShort = frame.gameState.phase === 'meeting' && current.layer === 'short';
533
615
  if (frame.gameState.phase !== 'wandering' && !meetingShort) {
534
- return { outcome: 'processed', proposal: { ...base, kind: 'boundary' } satisfies BehaviorComputationProposal };
616
+ return noDecision('boundary', 'phase_boundary');
535
617
  }
536
618
  const control = this.controls.get(current.activationId);
537
619
  if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration) {
538
- return { outcome: 'processed', proposal: { ...base, kind: 'control_held' } satisfies BehaviorComputationProposal };
620
+ return noDecision('control_held', 'runner_unavailable');
539
621
  }
540
622
  if (!control?.isAuthorized()) {
541
- return { outcome: 'processed', proposal: { ...base, kind: 'control_held' } satisfies BehaviorComputationProposal };
623
+ return noDecision('control_held', 'control_held');
542
624
  }
543
625
  const backendTick = Number(frame.gameState.tick ?? frame.epochId);
544
626
  if (
545
627
  runtime.lastCommittedBackendTick !== undefined
546
628
  && backendTick - runtime.lastCommittedBackendTick < runtime.runner.everyTicks
547
629
  ) {
548
- return { outcome: 'processed', proposal: { ...base, kind: 'cadence_skip' } satisfies BehaviorComputationProposal };
630
+ return noDecision('cadence_skip', 'cadence_skip');
549
631
  }
550
632
  const observation = this.observationMemory.capture(frame);
551
- if (runtime.runner.execution === 'serial') {
552
- return {
553
- outcome: 'processed',
554
- proposal: {
555
- ...base,
556
- kind: 'serial',
557
- eventIds: eventIds(frame),
558
- observationRevision: observation.revision,
559
- } satisfies BehaviorComputationProposal,
560
- };
561
- }
562
633
  try {
563
634
  const decision = await this.withDecisionTimeout(
564
- signal => runtime.runner!.decideParallel(frame, signal, observation),
635
+ signal => runtime.runner!.execution === 'serial'
636
+ ? runtime.runner!.decideSerial(frame, signal, observation)
637
+ : runtime.runner!.decideParallel(frame, signal, observation),
565
638
  context.signal,
566
639
  current.activationId,
567
640
  );
641
+ const resolved = runtime.decisionHistory.complete(frame.epochId, decision.actions);
642
+ if (resolved) {
643
+ const history = runtime.decisionHistory.snapshot();
644
+ context.diagnostic('behavior.decision_history.frame_resolved', {
645
+ behavior_id: current.behaviorId,
646
+ activation_id: current.activationId,
647
+ instance_generation: current.instanceGeneration,
648
+ epoch_id: frame.epochId,
649
+ tick: resolved.tick,
650
+ status: resolved.status,
651
+ action_count: resolved.actions?.length ?? 0,
652
+ action_kinds: (resolved.actions ?? []).map((action) => action.action),
653
+ retained_frame_count: history.length,
654
+ pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
655
+ }, 'debug');
656
+ }
568
657
  return {
569
658
  outcome: 'processed',
570
659
  proposal: {
571
660
  ...base,
572
- kind: 'parallel',
661
+ kind: runtime.runner.execution,
573
662
  eventIds: eventIds(frame),
574
663
  observationRevision: observation.revision,
575
664
  decision,
576
665
  } satisfies BehaviorComputationProposal,
577
666
  };
578
667
  } catch (error) {
668
+ const failure = errorCode(error, 'BEHAVIOR_DECIDE_FAILED');
669
+ const resolved = runtime.decisionHistory.fail(frame.epochId, failure);
670
+ if (resolved) {
671
+ const history = runtime.decisionHistory.snapshot();
672
+ context.diagnostic('behavior.decision_history.frame_resolved', {
673
+ behavior_id: current.behaviorId,
674
+ activation_id: current.activationId,
675
+ instance_generation: current.instanceGeneration,
676
+ epoch_id: frame.epochId,
677
+ tick: resolved.tick,
678
+ status: resolved.status,
679
+ reason: failure,
680
+ action_count: 0,
681
+ retained_frame_count: history.length,
682
+ pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
683
+ }, 'debug');
684
+ }
579
685
  return {
580
686
  outcome: 'processed',
581
687
  proposal: {
582
688
  ...base,
583
689
  kind: 'module_error',
584
- errorCode: errorCode(error, 'BEHAVIOR_DECIDE_FAILED'),
690
+ errorCode: failure,
585
691
  } satisfies BehaviorComputationProposal,
586
692
  };
587
693
  }
@@ -657,6 +763,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
657
763
  activationId,
658
764
  behaviorId,
659
765
  prepared,
766
+ decisionHistory: new BehaviorDecisionHistory(),
660
767
  committedActionDedupeKeys: new Map(),
661
768
  });
662
769
  const transitions = layer === 'long'
@@ -687,11 +794,15 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
687
794
 
688
795
  await this.applyTransitions(this.manager.advance(now));
689
796
  const currentForFrame = this.manager.current();
797
+ const currentFrameRuntime = currentForFrame
798
+ ? this.runtimes.get(currentForFrame.activationId)
799
+ : undefined;
690
800
  const frame = currentForFrame
691
801
  ? createBehaviorInput(
692
802
  input,
693
803
  currentForFrame.input,
694
- this.runtimes.get(currentForFrame.activationId)?.pendingContinuation,
804
+ currentFrameRuntime?.pendingContinuation,
805
+ currentFrameRuntime?.decisionHistory.snapshot(),
695
806
  )
696
807
  : frameForClock;
697
808
  if (frame?.gameState.phase === 'game_over' || computed.kind === 'game_over') {
@@ -727,7 +838,15 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
727
838
  || computed.activationId !== current.activationId
728
839
  || computed.instanceGeneration !== current.instanceGeneration
729
840
  || !this.manager.isCurrent(current.activationId, current.instanceGeneration)
730
- ) return this.output(undefined);
841
+ ) {
842
+ if (computed.activationId) {
843
+ this.runtimes.get(computed.activationId)?.decisionHistory.notComputed(
844
+ input.epoch.epochSeq,
845
+ 'activation_superseded_before_commit',
846
+ );
847
+ }
848
+ return this.output(undefined);
849
+ }
731
850
 
732
851
  if (!frame) return this.output(undefined);
733
852
  const runtime = this.runtimes.get(current.activationId);
@@ -753,28 +872,40 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
753
872
 
754
873
  const observation = this.observationMemory.snapshot(frame.epochId)
755
874
  ?? this.observationMemory.capture(frame);
756
- let decision = computed.decision;
757
- const mustRecompute = computed.kind === 'serial'
758
- || !sameStrings(computed.eventIds ?? [], eventIds(frame))
875
+ const decision = computed.decision;
876
+ const proposalIsStale = !sameStrings(computed.eventIds ?? [], eventIds(frame))
759
877
  || computed.observationRevision !== observation.revision;
760
- if (mustRecompute) {
761
- try {
762
- decision = await this.withDecisionTimeout(
763
- signal => runtime.runner!.execution === 'serial'
764
- ? runtime.runner!.decideSerial(frame, signal, observation)
765
- : runtime.runner!.decideParallel(frame, signal, observation),
766
- context.signal,
767
- current.activationId,
768
- );
769
- } catch (error) {
770
- if (errorCode(error) === 'behavior_reflex_preempted') return this.output(undefined);
771
- await this.failCurrent(current, errorCode(error, 'BEHAVIOR_DECIDE_FAILED'), now);
772
- return this.output(cursor);
773
- }
878
+ if (proposalIsStale) {
879
+ context.diagnostic('behavior.decision.stale_before_commit', {
880
+ behavior_id: current.behaviorId,
881
+ activation_id: current.activationId,
882
+ instance_generation: current.instanceGeneration,
883
+ epoch_id: frame.epochId,
884
+ tick: frame.gameState.tick,
885
+ event_input_changed: !sameStrings(computed.eventIds ?? [], eventIds(frame)),
886
+ observation_revision_changed: computed.observationRevision !== observation.revision,
887
+ }, 'debug');
888
+ return this.output(undefined);
774
889
  }
775
890
  if (!decision || !this.manager.isCurrent(current.activationId, current.instanceGeneration)) {
776
891
  return this.output(undefined);
777
892
  }
893
+ const resolvedDecision = runtime.decisionHistory.complete(frame.epochId, decision.actions);
894
+ if (resolvedDecision) {
895
+ const history = runtime.decisionHistory.snapshot();
896
+ context.diagnostic('behavior.decision_history.frame_resolved', {
897
+ behavior_id: current.behaviorId,
898
+ activation_id: current.activationId,
899
+ instance_generation: current.instanceGeneration,
900
+ epoch_id: frame.epochId,
901
+ tick: resolvedDecision.tick,
902
+ status: resolvedDecision.status,
903
+ action_count: resolvedDecision.actions?.length ?? 0,
904
+ action_kinds: (resolvedDecision.actions ?? []).map((action) => action.action),
905
+ retained_frame_count: history.length,
906
+ pending_frame_count: history.filter((entry) => entry.status === 'pending').length,
907
+ }, 'debug');
908
+ }
778
909
  runtime.lastCommittedBackendTick = backendTick;
779
910
  let output: Readonly<{
780
911
  status?: Readonly<BehaviorStatus>;
@@ -851,13 +982,29 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
851
982
  frame.epochId,
852
983
  safetyGeneration,
853
984
  activation.instanceGeneration,
985
+ frame.gameState.tick,
854
986
  );
987
+ const receiptStartedAt = performance.now();
855
988
  try {
856
989
  const result = await context.capabilities.performAction(
857
990
  CLAWCLAW_ACTION_CAPABILITY,
858
991
  request,
859
992
  asActionCaller(control.caller),
860
993
  );
994
+ context.diagnostic('behavior.action.receipt', {
995
+ behavior_id: activation.behaviorId,
996
+ activation_id: activation.activationId,
997
+ instance_generation: activation.instanceGeneration,
998
+ epoch_id: frame.epochId,
999
+ tick: frame.gameState.tick,
1000
+ action_index: index,
1001
+ action_kind: action.action,
1002
+ action_id: result.actionId,
1003
+ status: result.status,
1004
+ ...(result.source ? { action_source: result.source } : {}),
1005
+ ...(result.actionOutcome ? { action_outcome: result.actionOutcome } : {}),
1006
+ receipt_wait_ms: Math.round((performance.now() - receiptStartedAt) * 1_000) / 1_000,
1007
+ }, result.status === 'failure' ? 'warn' : 'debug');
861
1008
  if (result.actionOutcome !== 'not_submitted') {
862
1009
  runtime.committedActionDedupeKeys.set(dedupeKey, frame.epochId);
863
1010
  while (runtime.committedActionDedupeKeys.size > 2_048) {
@@ -873,6 +1020,10 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
873
1020
  activation_id: activation.activationId,
874
1021
  instance_generation: activation.instanceGeneration,
875
1022
  epoch_id: frame.epochId,
1023
+ tick: frame.gameState.tick,
1024
+ action_index: index,
1025
+ action_kind: action.action,
1026
+ receipt_wait_ms: Math.round((performance.now() - receiptStartedAt) * 1_000) / 1_000,
876
1027
  error_code: errorCode(error, 'BEHAVIOR_ACTION_FAILED'),
877
1028
  }, 'error');
878
1029
  }
@@ -942,6 +1093,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
942
1093
  activationId,
943
1094
  behaviorId: delegated.behaviorId,
944
1095
  prepared: delegated.prepared,
1096
+ decisionHistory: new BehaviorDecisionHistory(),
945
1097
  committedActionDedupeKeys: new Map(),
946
1098
  });
947
1099
  this.delegatedShorts.set(activationId, Object.freeze({
@@ -1092,7 +1244,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1092
1244
  prepared = this.fallbackPreparedUsed
1093
1245
  ? Object.freeze({
1094
1246
  ...this.fallbackPrepared,
1095
- module: this.fallbackPrepared.createModule(),
1247
+ ...(this.fallbackPrepared.createModule
1248
+ ? { module: this.fallbackPrepared.createModule() }
1249
+ : {}),
1096
1250
  })
1097
1251
  : this.fallbackPrepared;
1098
1252
  this.fallbackPreparedUsed = true;
@@ -1103,6 +1257,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1103
1257
  activationId: activation.activationId,
1104
1258
  behaviorId: activation.behaviorId,
1105
1259
  prepared,
1260
+ decisionHistory: new BehaviorDecisionHistory(),
1106
1261
  committedActionDedupeKeys: new Map(),
1107
1262
  };
1108
1263
  this.runtimes.set(activation.activationId, runtime);
@@ -1112,7 +1267,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1112
1267
  ? runtime.prepared
1113
1268
  : Object.freeze({
1114
1269
  ...runtime.prepared,
1115
- module: runtime.prepared.createModule(),
1270
+ ...(runtime.prepared.createModule
1271
+ ? { module: runtime.prepared.createModule() }
1272
+ : {}),
1116
1273
  });
1117
1274
  runtime.runner = new ClawclawBehaviorRunner({
1118
1275
  behaviorId: activation.behaviorId,
@@ -1120,6 +1277,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1120
1277
  instanceGeneration: activation.instanceGeneration,
1121
1278
  prepared,
1122
1279
  diagnostic: this.diagnostic,
1280
+ diagnosticsEnabled: this.diagnosticsEnabled,
1123
1281
  isActive: () => this.manager.isCurrent(
1124
1282
  activation.activationId,
1125
1283
  activation.instanceGeneration,
@@ -22,6 +22,7 @@ export interface ClawclawBehaviorRunnerOptions {
22
22
  severity?: RuntimeDiagnosticSeverity,
23
23
  ) => void;
24
24
  readonly isActive: () => boolean;
25
+ readonly diagnosticsEnabled?: boolean;
25
26
  }
26
27
 
27
28
  function errorCode(error: unknown): string {
@@ -47,7 +48,7 @@ export class ClawclawBehaviorRunner {
47
48
  readonly instanceGeneration: number;
48
49
  readonly prepared: PreparedClawclawBehavior;
49
50
 
50
- private serialModule: ClawclawBehavior;
51
+ private serialModule?: ClawclawBehavior;
51
52
  private serialTail = Promise.resolve();
52
53
  private readonly parallelLifecycle = new AbortController();
53
54
  private parallelExecutor?: ThreadBehaviorExecutor;
@@ -71,12 +72,40 @@ export class ClawclawBehaviorRunner {
71
72
  return this.prepared.manifest.everyTicks ?? 1;
72
73
  }
73
74
 
75
+ diagnosticSnapshot(): Readonly<Record<string, unknown>> {
76
+ const pool = this.parallelExecutor?.snapshot();
77
+ return Object.freeze({
78
+ execution: this.execution,
79
+ every_ticks: this.everyTicks,
80
+ stopped: this.stopped,
81
+ worker_pool: pool
82
+ ? {
83
+ state: pool.state,
84
+ worker_count: pool.workerCount,
85
+ idle_worker_count: pool.idleWorkerCount,
86
+ busy_worker_count: pool.busyWorkerCount,
87
+ queued_request_count: pool.queuedRequestCount,
88
+ in_flight_request_count: pool.inFlightRequestCount,
89
+ started_worker_count: pool.startedWorkerCount,
90
+ retired_worker_count: pool.retiredWorkerCount,
91
+ worker_heap_used_bytes: pool.workerHeapUsedBytes,
92
+ peak_worker_heap_used_bytes: pool.peakWorkerHeapUsedBytes,
93
+ }
94
+ : null,
95
+ });
96
+ }
97
+
74
98
  decideSerial(
75
99
  input: Readonly<BehaviorInput>,
76
100
  signal: AbortSignal,
77
101
  observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
78
102
  ): Promise<BehaviorDecision> {
79
- return this.enqueue(() => this.invoke(this.serialModule, input, signal, observationSnapshot));
103
+ if (this.prepared.source) {
104
+ return this.enqueue(() => this.invokeThread(input, signal, observationSnapshot));
105
+ }
106
+ const module = this.serialModule;
107
+ if (!module) return Promise.reject(new Error('behavior_serial_module_missing'));
108
+ return this.enqueue(() => this.invoke(module, input, signal, observationSnapshot));
80
109
  }
81
110
 
82
111
  decideParallel(
@@ -84,7 +113,7 @@ export class ClawclawBehaviorRunner {
84
113
  signal: AbortSignal,
85
114
  observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
86
115
  ): Promise<BehaviorDecision> {
87
- return this.invokeParallel(input, signal, observationSnapshot);
116
+ return this.invokeThread(input, signal, observationSnapshot);
88
117
  }
89
118
 
90
119
  stop(reason: 'switched' | 'scope_ended' | 'shutdown' = 'switched'): Promise<void> {
@@ -98,7 +127,7 @@ export class ClawclawBehaviorRunner {
98
127
  return this.parallelStop;
99
128
  }
100
129
 
101
- private async invokeParallel(
130
+ private async invokeThread(
102
131
  input: Readonly<BehaviorInput>,
103
132
  signal: AbortSignal,
104
133
  observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
@@ -106,7 +135,7 @@ export class ClawclawBehaviorRunner {
106
135
  if (this.stopped) throw new Error('behavior_runner_stopped');
107
136
  if (signal.aborted) throw abortError(signal);
108
137
  if (!this.options.isActive()) throw new Error('behavior_activation_superseded');
109
- const executor = this.ensureParallelExecutor();
138
+ const executor = this.ensureThreadExecutor();
110
139
  await this.parallelReady;
111
140
  if (this.stopped) throw new Error('behavior_runner_stopped');
112
141
  if (signal.aborted) throw abortError(signal);
@@ -117,16 +146,17 @@ export class ClawclawBehaviorRunner {
117
146
  return decision;
118
147
  }
119
148
 
120
- private ensureParallelExecutor(): ThreadBehaviorExecutor {
149
+ private ensureThreadExecutor(): ThreadBehaviorExecutor {
121
150
  if (this.parallelExecutor) return this.parallelExecutor;
122
151
  const source = this.prepared.source;
123
- if (!source) throw new Error('behavior_parallel_source_missing');
124
- if (source.id !== this.behaviorId || source.execution !== 'parallel') {
125
- throw new Error('behavior_parallel_source_invalid');
152
+ if (!source) throw new Error('behavior_thread_source_missing');
153
+ if (source.id !== this.behaviorId || source.execution !== this.execution) {
154
+ throw new Error('behavior_thread_source_invalid');
126
155
  }
127
156
  const executor = new ThreadBehaviorExecutor({
128
157
  source,
129
158
  diagnostic: this.options.diagnostic,
159
+ diagnosticsEnabled: this.options.diagnosticsEnabled,
130
160
  });
131
161
  this.parallelExecutor = executor;
132
162
  this.parallelReady = executor.start(this.parallelLifecycle.signal);
@@ -169,11 +199,15 @@ export class ClawclawBehaviorRunner {
169
199
  activation_id: this.activationId,
170
200
  instance_generation: this.instanceGeneration,
171
201
  epoch_id: input.epochId,
202
+ tick: input.gameState.tick,
172
203
  duration_ms: Math.round(performance.now() - startedAt),
173
204
  read_query_count: queryCount,
174
205
  action_count: decision.actions?.length ?? 0,
206
+ action_kinds: (decision.actions ?? []).map((action) => action.action),
207
+ empty_decision: (decision.actions?.length ?? 0) === 0,
175
208
  event_count: decision.events?.length ?? 0,
176
209
  finished: decision.finish !== undefined,
210
+ execution: this.execution,
177
211
  }, 'debug');
178
212
  return decision;
179
213
  } catch (error) {
@@ -182,9 +216,11 @@ export class ClawclawBehaviorRunner {
182
216
  activation_id: this.activationId,
183
217
  instance_generation: this.instanceGeneration,
184
218
  epoch_id: input.epochId,
219
+ tick: input.gameState.tick,
185
220
  duration_ms: Math.round(performance.now() - startedAt),
186
221
  read_query_count: queryCount,
187
222
  error_code: errorCode(error),
223
+ execution: this.execution,
188
224
  }, signal.aborted ? 'debug' : 'error');
189
225
  throw error;
190
226
  } finally {