@myclaw163/clawclaw-cli 0.9.0 → 0.9.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 (86) hide show
  1. package/README.md +5 -3
  2. package/docs/custom-modules/README.md +19 -24
  3. package/docs/custom-modules/api-reference.md +85 -33
  4. package/docs/custom-modules/behavior.md +116 -22
  5. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  6. package/docs/custom-modules/examples/first-sighting-v3.ts +29 -0
  7. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  8. package/docs/custom-modules/perception.md +158 -276
  9. package/docs/custom-modules/trigger.md +5 -3
  10. package/docs/runtime/README.md +17 -8
  11. package/docs/runtime/agent-notifications.md +32 -15
  12. package/docs/runtime/behavior-runtime.md +36 -24
  13. package/docs/runtime/components-and-boundaries.md +56 -108
  14. package/docs/runtime/events-and-state.md +55 -3
  15. package/docs/runtime/owner-lifecycle-and-observability.md +5 -3
  16. package/docs/user-guide/README.md +6 -6
  17. package/docs/user-guide/api-reference.md +80 -30
  18. package/docs/user-guide/behavior.md +116 -22
  19. package/docs/user-guide/perception.md +157 -275
  20. package/package.json +1 -1
  21. package/scripts/check-skill-command-surface.mjs +2 -2
  22. package/skills/clawclaw/SKILL.md +9 -7
  23. package/skills/clawclaw/references/BEHAVIORS.md +19 -6
  24. package/skills/clawclaw/references/COMMANDS.md +19 -0
  25. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +116 -22
  26. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +82 -35
  27. package/skills/clawclaw/references/CUSTOM-MODULES.md +18 -23
  28. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +158 -276
  29. package/skills/clawclaw/references/STREAM.md +1 -1
  30. package/src/commands/behavior.ts +28 -99
  31. package/src/commands/load.ts +23 -29
  32. package/src/commands/module-runtime-control.ts +113 -0
  33. package/src/commands/perception.ts +20 -6
  34. package/src/commands/trigger.ts +1 -1
  35. package/src/lib/agent-workspace-sync.ts +2 -2
  36. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  37. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  38. package/src/runtime/clawclaw/owner.ts +51 -5
  39. package/src/runtime/clawclaw/perception-module-manifest.ts +36 -0
  40. package/src/runtime/clawclaw/plugins/assembly.ts +25 -23
  41. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +16 -3
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +4 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  45. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +129 -57
  46. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +7 -2
  47. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -1
  48. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +21 -18
  49. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +3 -2
  50. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +2 -0
  51. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  52. package/src/runtime/clawclaw/plugins/{source → derived-event}/task-change-tracker.ts +1 -1
  53. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +314 -0
  54. package/src/runtime/clawclaw/plugins/perception/{reaction-runner.ts → perception-module-runner.ts} +26 -13
  55. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +39 -0
  56. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -1
  57. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +30 -7
  58. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2 -103
  59. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  60. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  61. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +61 -10
  62. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  63. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  64. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  65. package/src/runtime/clawclaw/runtime-state.ts +1 -1
  66. package/src/runtime/clawclaw/runtime.ts +3 -3
  67. package/src/runtime/clawclaw/strategy-memory-rpc.ts +63 -0
  68. package/src/runtime/clawclaw/strategy-memory.ts +77 -0
  69. package/src/runtime/clawclaw-event-catalog.ts +9 -6
  70. package/src/runtime/framework/plugins/contracts.ts +8 -0
  71. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +17 -6
  72. package/src/runtime/owner-control.ts +5 -0
  73. package/src/sdk/behavior-plugin/index.ts +4 -1
  74. package/src/sdk/index.ts +5 -0
  75. package/src/sdk/perception-plugin/index.ts +29 -10
  76. package/src/sdk/perception-plugin/module.ts +55 -0
  77. package/src/sdk/perception-plugin/reaction.ts +2 -1
  78. package/src/sdk/perception-plugin/reminder.ts +1 -0
  79. package/src/sdk/strategy-memory.ts +12 -0
  80. package/src/sdk/trigger-plugin/index.ts +3 -2
  81. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  82. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  83. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  84. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -198
  85. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  86. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { ClawclawStrategyMemory } from '../../strategy-memory.js';
2
3
  import { resolveDetailCapture } from '../../../observability/detail-capture.js';
3
4
  import { performance } from 'node:perf_hooks';
4
5
  import type {
@@ -25,8 +26,6 @@ import type {
25
26
  import { createBehaviorInput } from '../../behavior-input.js';
26
27
  import { ClawclawBehaviorObservationMemory } from '../../behavior-observation-memory.js';
27
28
  import { isClawclawRuntimeState } from '../../runtime-state.js';
28
- import { BEHAVIOR_ACTIVATION_CAPABILITY, type PerceptionBehaviorActivation,
29
- type PerceptionBehaviorActivationResult } from '../../behavior-activation-capability.js';
30
29
  import { CLAWCLAW_ACTION_CAPABILITY, CLAWCLAW_ACTION_PLUGIN_ID } from '../action/index.js';
31
30
  import { CLAWCLAW_DERIVED_EVENT_PLUGIN_ID } from '../derived-event/index.js';
32
31
  import { CLAWCLAW_GAME_QUERY_PLUGIN_ID } from '../game-query/index.js';
@@ -111,7 +110,7 @@ function isSuccessfulBackendStrategyReport(value: unknown): boolean {
111
110
  }
112
111
 
113
112
  export interface ClawclawBehaviorPluginOptions {
114
- readonly perceptionActivations?: boolean;
113
+ readonly memory?: ClawclawStrategyMemory;
115
114
  readonly catalog: Pick<ClawclawBehaviorCatalog, 'has' | 'prepare'>;
116
115
  readonly fallbackBehaviors?: ClawclawRoleFallbackBehaviors;
117
116
  readonly manager?: BehaviorActivationManager;
@@ -127,7 +126,7 @@ export interface ClawclawBehaviorPluginOptions {
127
126
  }
128
127
 
129
128
  export interface StartBehaviorOptions {
130
- readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system' | 'perception'>;
129
+ readonly source: Extract<BehaviorActivationSource, 'agent' | 'user' | 'system'>;
131
130
  readonly maxRuntimeMs?: number;
132
131
  /** Revalidate scope/phase after asynchronous preparation, before changing control. */
133
132
  readonly isCurrent?: () => boolean;
@@ -286,7 +285,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
286
285
  readonly consumes = { events: ['*'] } as const;
287
286
  readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
288
287
  readonly capabilities: { uses: readonly string[]; provides?: readonly string[] };
289
- private releasePerceptionActivation?: () => void;
290
288
  readonly catchUp: RuntimeEpochCatchUp;
291
289
  readonly backlogPolicy = 'finish_started' as const;
292
290
  get maxInFlight(): number {
@@ -305,7 +303,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
305
303
  private readonly captureActions = resolveDetailCapture().actions;
306
304
  private readonly diagnosticsEnabled: boolean;
307
305
  private readonly observationMemory = new ClawclawBehaviorObservationMemory();
306
+ private memory: ClawclawStrategyMemory;
308
307
  private readonly runtimes = new Map<string, ActivationRuntime>();
308
+ private readonly inputDefaults = new Map<string, Readonly<Record<string, unknown>>>();
309
309
  private readonly delegatedShorts = new Map<string, Readonly<DelegatedShort>>();
310
310
  private readonly finishSummaries = new Map<string, string>();
311
311
  private readonly controls = new Map<string, ClawclawBehaviorControlHandle>();
@@ -319,6 +319,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
319
319
  private stopped = false;
320
320
  private lastCommittedEpochSeq = 0;
321
321
  private fallbackPrepared?: PreparedClawclawBehavior;
322
+ private fallbackBaseInput?: Readonly<{ behaviorId: string; input: Readonly<Record<string, unknown>> }>;
322
323
  private fallbackPreparedUsed = false;
323
324
  private fallbackBehaviors = new Map<string, Readonly<ClawclawRoleFallbackBehavior>>();
324
325
  private fallbackConfigGeneration = 1;
@@ -333,8 +334,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
333
334
  private backendStrategyReportLifecycleGeneration = 0;
334
335
 
335
336
  constructor(options: ClawclawBehaviorPluginOptions) {
336
- this.capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY],
337
- ...(options.perceptionActivations ? { provides: [BEHAVIOR_ACTIVATION_CAPABILITY] } : {}) };
337
+ this.memory = options.memory ?? new ClawclawStrategyMemory();
338
+ this.capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY] };
338
339
  this.catalog = options.catalog;
339
340
  this.fallbackBehaviors = normalizeRoleFallbackBehaviors(options.fallbackBehaviors);
340
341
  this.manager = options.manager ?? new BehaviorActivationManager();
@@ -362,6 +363,11 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
362
363
  };
363
364
  }
364
365
 
366
+ attachMemory(memory: ClawclawStrategyMemory): void {
367
+ if (this.scope) throw Error('strategy_memory_already_started');
368
+ this.memory = memory;
369
+ }
370
+
365
371
  attachDriver(driver: ClawclawBehaviorControlDriver): void {
366
372
  if (this.driver && this.driver !== driver) throw new Error('behavior_control_driver_already_attached');
367
373
  this.driver = driver;
@@ -369,51 +375,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
369
375
 
370
376
  async start(context: RuntimeEpochPluginContext<Record<string, any>>): Promise<void> {
371
377
  this.scope = context.scope;
378
+ this.memory.open(context.scope);
372
379
  this.diagnostic = context.diagnostic;
373
380
  this.stopped = false;
374
- if (this.capabilities.provides?.includes(BEHAVIOR_ACTIVATION_CAPABILITY)) {
375
- this.releasePerceptionActivation = context.capabilities.provideAction<PerceptionBehaviorActivation, PerceptionBehaviorActivationResult>({
376
- capability: BEHAVIOR_ACTIVATION_CAPABILITY,
377
- describeControl: () => ({ domains: [] }),
378
- perform: async (request, scope, _caller, execution) => {
379
- const activationBeforePreparation = this.manager.current();
380
- const current = () => {
381
- if (execution.signal.aborted || this.stopped || scope.sessionId !== this.scope?.sessionId
382
- || scope.segmentId !== this.scope?.segmentId || request.epochId <= this.lastCommittedEpochSeq) return false;
383
- const active = this.manager.current();
384
- if (active?.activationId !== activationBeforePreparation?.activationId
385
- || active?.instanceGeneration !== activationBeforePreparation?.instanceGeneration) return false;
386
- const latest = execution.latestAcceptedState();
387
- if (!latest) return false;
388
- const state = latest.state as Record<string, any>;
389
- const game = isClawclawRuntimeState(state)
390
- ? state.connection === 'connected' && state.stage === 'game' && state.game_snapshot.status === 'fresh'
391
- ? state.game_snapshot.state : undefined
392
- : state;
393
- return !!game && game.game_id === request.gameId && game.phase === 'wandering' && game.you?.is_alive === true;
394
- };
395
- let value: PerceptionBehaviorActivationResult = { accepted: false, reason: 'stale_request' };
396
- if (current()) {
397
- try {
398
- if (!this.catalog.has(request.behavior)) value = { accepted: false, reason: 'behavior_not_loaded' };
399
- else if (request.layer === 'reflex') value = await this.requestReflex({
400
- source: 'trigger', triggerId: `perception:${request.moduleId}:${request.bindingKey}`,
401
- scope: { sessionId: scope.sessionId, segmentId: scope.segmentId }, epochId: request.epochId,
402
- configGeneration: 0, behavior: request.behavior, behaviorInput: request.input,
403
- reflexPriority: request.reflexPriority, maxRuntimeMs: request.maxRuntimeMs ?? 10_000,
404
- reason: request.reason,
405
- }, { isCurrent: current });
406
- else {
407
- const activation = await this.startLayer(request.layer, request.behavior, request.input,
408
- { source: 'perception', maxRuntimeMs: request.maxRuntimeMs, isCurrent: current });
409
- value = { accepted: true, activationId: activation.activationId };
410
- }
411
- } catch { value = { accepted: false, reason: current() ? 'binding_invalid' : 'stale_request' }; }
412
- }
413
- return { scope, actionId: randomUUID(), status: 'success', source: 'local', value };
414
- },
415
- });
416
- }
417
381
  await this.applyTransitions(this.manager.leaveBoundary(this.now()));
418
382
  }
419
383
 
@@ -470,9 +434,10 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
470
434
  input: Readonly<Record<string, unknown>>,
471
435
  ): Promise<void> {
472
436
  return this.enqueueControl(async () => {
473
- const prepared = await this.catalog.prepare(behaviorId, input);
437
+ const prepared = await this.prepareInput(behaviorId, input);
474
438
  this.manualFallbackOverride = true;
475
439
  this.fallbackPrepared = prepared;
440
+ this.fallbackBaseInput = { behaviorId, input: structuredClone(input) };
476
441
  this.fallbackPreparedUsed = false;
477
442
  await this.applyTransitions(this.manager.bindFallback({
478
443
  behaviorId,
@@ -485,6 +450,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
485
450
  return this.enqueueControl(async () => {
486
451
  this.manualFallbackOverride = true;
487
452
  this.fallbackPrepared = undefined;
453
+ this.fallbackBaseInput = undefined;
488
454
  this.fallbackPreparedUsed = false;
489
455
  await this.applyTransitions(this.manager.bindFallback(undefined, this.now()));
490
456
  });
@@ -518,6 +484,98 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
518
484
  });
519
485
  }
520
486
 
487
+ async updateReflex(triggerId: string, patch: Readonly<Record<string, unknown>> | undefined,
488
+ guard: () => boolean = () => true): Promise<boolean> {
489
+ return this.enqueueControl(async () => {
490
+ if (!guard()) throw new Error('stale_runtime_scope');
491
+ const active = this.manager.snapshot().reflex;
492
+ if (!active || active.triggerId !== triggerId) return false;
493
+ if (patch === undefined) {
494
+ this.interruptDecisions(active.activationId, 'reflex_disabled');
495
+ await this.applyTransitions(this.manager.cancel(active.activationId, 'reflex_disabled', this.now()));
496
+ return true;
497
+ }
498
+ await this.updateActivationInput(active.activationId, patch, guard);
499
+ return true;
500
+ });
501
+ }
502
+
503
+ /** Update one execution in any layer; background watch configuration is a separate target. */
504
+ updateInput(activationId: string, patch: Readonly<Record<string, unknown>>,
505
+ guard: () => boolean = () => true): Promise<Readonly<BehaviorActivationSnapshot>> {
506
+ return this.enqueueControl(() => this.updateActivationInput(activationId, patch, guard));
507
+ }
508
+
509
+ /** Owner-controlled match-local inputs. Explicit start/delegation input and dynamic Trigger targets take precedence. */
510
+ configureInput(behaviorId: string, input: Readonly<Record<string, unknown>>, patch: Readonly<Record<string, unknown>>,
511
+ guard: () => boolean = () => true, beforeApply?: () => void): Promise<number> {
512
+ return this.enqueueControl(async () => {
513
+ if (!guard()) throw new Error('stale_runtime_scope');
514
+ const defaults = await this.catalog.prepare(behaviorId, input);
515
+ const stack = this.manager.snapshot();
516
+ const active = [stack.long, stack.short, stack.reflex].filter(
517
+ (entry): entry is BehaviorActivationSnapshot => entry?.behaviorId === behaviorId);
518
+ const updates = [];
519
+ for (const activation of active) updates.push({ activation,
520
+ prepared: await this.catalog.prepare(behaviorId, {
521
+ ...(this.runtimes.get(activation.activationId)?.prepared.rawInput ?? activation.input), ...patch }) });
522
+ if (!guard()) throw new Error('stale_runtime_scope');
523
+ beforeApply?.();
524
+ await this.replacePreparedInputs(updates, guard);
525
+ this.inputDefaults.set(behaviorId, structuredClone(input));
526
+ if (this.manager.snapshot().fallback?.behaviorId === behaviorId) {
527
+ this.fallbackPrepared = defaults;
528
+ this.fallbackPreparedUsed = false;
529
+ this.manager.updateFallbackInput(behaviorId, defaults.input);
530
+ }
531
+ return updates.length;
532
+ });
533
+ }
534
+
535
+ private prepareInput(behaviorId: string, input: Readonly<Record<string, unknown>>) {
536
+ return this.catalog.prepare(behaviorId, { ...this.inputDefaults.get(behaviorId), ...input });
537
+ }
538
+
539
+ private async updateActivationInput(activationId: string, patch: Readonly<Record<string, unknown>>,
540
+ guard: () => boolean): Promise<Readonly<BehaviorActivationSnapshot>> {
541
+ if (!guard()) throw new Error('stale_runtime_scope');
542
+ const active = currentRuntimeSnapshot(this.manager, activationId);
543
+ if (!active) throw new Error('behavior_activation_not_found');
544
+ const prepared = await this.catalog.prepare(active.behaviorId, {
545
+ ...(this.runtimes.get(activationId)?.prepared.rawInput ?? active.input), ...patch });
546
+ if (!guard()) throw new Error('stale_runtime_scope');
547
+ await this.replacePreparedInputs([{ activation: active, prepared }], guard);
548
+ const updated = currentRuntimeSnapshot(this.manager, activationId);
549
+ if (!updated) throw new Error('behavior_activation_update_failed');
550
+ return updated;
551
+ }
552
+
553
+ private async replacePreparedInputs(updates: readonly Readonly<{
554
+ activation: Readonly<BehaviorActivationSnapshot>; prepared: PreparedClawclawBehavior;
555
+ }>[], guard: () => boolean): Promise<void> {
556
+ if (!guard()) throw new Error('stale_runtime_scope');
557
+ for (const { activation } of updates) {
558
+ const latest = currentRuntimeSnapshot(this.manager, activation.activationId);
559
+ if (!latest || latest.instanceGeneration !== activation.instanceGeneration) throw new Error('behavior_activation_changed');
560
+ }
561
+ for (const { activation } of updates) {
562
+ this.interruptDecisions(activation.activationId, 'behavior_input_updated');
563
+ this.controls.get(activation.activationId)?.release('behavior_input_updated');
564
+ this.controls.delete(activation.activationId);
565
+ await this.runtimes.get(activation.activationId)?.runner?.stop('switched');
566
+ }
567
+ if (!guard()) throw new Error('stale_runtime_scope');
568
+ const transitions: BehaviorActivationTransition[] = [];
569
+ for (const { activation, prepared } of updates) {
570
+ const activationId = activation.activationId, previous = this.runtimes.get(activationId);
571
+ this.runtimes.set(activationId, { activationId, behaviorId: activation.behaviorId, prepared,
572
+ pendingContinuation: previous?.pendingContinuation,
573
+ decisionHistory: new BehaviorDecisionHistory(), committedActionDedupeKeys: new Map() });
574
+ transitions.push(...this.manager.updateInput(activationId, prepared.input, this.now()));
575
+ }
576
+ await this.applyTransitions(transitions);
577
+ }
578
+
521
579
  async requestReflex(
522
580
  request: Readonly<BehaviorReflexActivationRequest>,
523
581
  guard?: Readonly<{ isCurrent(): boolean }>,
@@ -532,7 +590,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
532
590
  if (!this.catalog.has(request.behavior)) return { accepted: false, reason: 'binding_invalid' };
533
591
  let prepared: PreparedClawclawBehavior;
534
592
  try {
535
- prepared = await this.catalog.prepare(request.behavior, request.behaviorInput);
593
+ prepared = await this.prepareInput(request.behavior, request.behaviorInput);
536
594
  } catch {
537
595
  return { accepted: false, reason: 'binding_invalid' };
538
596
  }
@@ -564,6 +622,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
564
622
  requestedAt: this.now(),
565
623
  maxRuntimeMs: request.maxRuntimeMs,
566
624
  deadlineOutcome: 'failed',
625
+ source: request.source,
567
626
  triggerId: request.triggerId,
568
627
  reflexPriority: request.reflexPriority,
569
628
  }, this.now());
@@ -779,9 +838,9 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
779
838
  }
780
839
 
781
840
  async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
782
- this.releasePerceptionActivation?.(); this.releasePerceptionActivation = undefined;
783
841
  await this.enqueueControl(async () => {
784
842
  this.stopped = true;
843
+ if (this.scope) this.memory.close(this.scope);
785
844
  this.resetBackendStrategyReporting();
786
845
  for (const controllers of this.decisionControllers.values()) {
787
846
  for (const controller of controllers) controller.abort(new Error(reason));
@@ -797,6 +856,14 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
797
856
  await Promise.all(runners.map((runner) => runner.stop(runnerReason)));
798
857
  await this.applyTransitions(this.manager.clearScope(reason, this.now()));
799
858
  this.runtimes.clear();
859
+ const parameterizedFallback = this.inputDefaults.has(this.manager.snapshot().fallback?.behaviorId ?? '');
860
+ this.inputDefaults.clear();
861
+ if (parameterizedFallback) {
862
+ if (this.fallbackBaseInput) this.manager.updateFallbackInput(this.fallbackBaseInput.behaviorId, this.fallbackBaseInput.input);
863
+ this.fallbackPrepared = undefined;
864
+ this.fallbackPreparedUsed = false;
865
+ this.appliedFallbackKey = undefined;
866
+ }
800
867
  this.delegatedShorts.clear();
801
868
  this.finishSummaries.clear();
802
869
  for (const handle of this.controls.values()) handle.release(reason);
@@ -818,7 +885,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
818
885
  ): Promise<Readonly<BehaviorActivationSnapshot>> {
819
886
  return this.enqueueControl(async () => {
820
887
  if (this.stopped || !this.scope) throw new Error('behavior_host_not_active');
821
- const prepared = await this.catalog.prepare(behaviorId, input);
888
+ const prepared = await this.prepareInput(behaviorId, input);
822
889
  if (options.isCurrent && !options.isCurrent()) throw new Error('perception_activation_stale');
823
890
  const activationId = this.createActivationId();
824
891
  const maxRuntimeMs = layer === 'short'
@@ -897,6 +964,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
897
964
  : frameForClock;
898
965
  if (frame?.gameState.phase === 'game_over' || computed.kind === 'game_over') {
899
966
  await this.applyTransitions(this.manager.clearScope('game_over', now));
967
+ if (this.scope) this.memory.close(this.scope);
900
968
  this.boundaryActive = true;
901
969
  return this.output(cursor);
902
970
  }
@@ -1157,7 +1225,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1157
1225
  prepared: PreparedClawclawBehavior;
1158
1226
  }>> {
1159
1227
  const rawInput = delegation.input ?? Object.freeze({});
1160
- const prepared = await this.catalog.prepare(delegation.behavior, rawInput);
1228
+ const prepared = await this.prepareInput(delegation.behavior, rawInput);
1161
1229
  return Object.freeze({
1162
1230
  behaviorId: delegation.behavior,
1163
1231
  rawInput: Object.freeze(structuredClone(rawInput)),
@@ -1349,7 +1417,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1349
1417
  : this.fallbackPrepared;
1350
1418
  this.fallbackPreparedUsed = true;
1351
1419
  } else {
1352
- prepared = await this.catalog.prepare(activation.behaviorId, activation.input);
1420
+ prepared = await this.prepareInput(activation.behaviorId, activation.input);
1353
1421
  }
1354
1422
  runtime = {
1355
1423
  activationId: activation.activationId,
@@ -1370,6 +1438,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1370
1438
  : {}),
1371
1439
  });
1372
1440
  runtime.runner = new ClawclawBehaviorRunner({
1441
+ memory: (input, active) => this.memory.bind(input.scope, `behavior:${activation.behaviorId}`, active),
1373
1442
  snapshotStore: runtime.snapshotStore ??= new BehaviorSnapshotStore(),
1374
1443
  behaviorId: activation.behaviorId,
1375
1444
  activationId: activation.activationId,
@@ -1402,13 +1471,15 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1402
1471
  this.appliedFallbackKey = key;
1403
1472
  if (!configured) {
1404
1473
  this.fallbackPrepared = undefined;
1474
+ this.fallbackBaseInput = undefined;
1405
1475
  this.fallbackPreparedUsed = false;
1406
1476
  await this.applyTransitions(this.manager.bindFallback(undefined, now));
1407
1477
  return;
1408
1478
  }
1409
1479
  try {
1410
- const prepared = await this.catalog.prepare(configured.behaviorId, configured.input ?? {});
1480
+ const prepared = await this.prepareInput(configured.behaviorId, configured.input ?? {});
1411
1481
  this.fallbackPrepared = prepared;
1482
+ this.fallbackBaseInput = { behaviorId: configured.behaviorId, input: structuredClone(configured.input ?? {}) };
1412
1483
  this.fallbackPreparedUsed = false;
1413
1484
  await this.applyTransitions(this.manager.bindFallback({
1414
1485
  behaviorId: configured.behaviorId,
@@ -1416,6 +1487,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1416
1487
  }, now, true));
1417
1488
  } catch (error) {
1418
1489
  this.fallbackPrepared = undefined;
1490
+ this.fallbackBaseInput = undefined;
1419
1491
  this.fallbackPreparedUsed = false;
1420
1492
  await this.applyTransitions(this.manager.bindFallback(undefined, now));
1421
1493
  this.diagnostic?.('behavior.fallback.invalid', {
@@ -12,8 +12,10 @@ import type { PreparedClawclawBehavior } from './behavior-normalization.js';
12
12
  import { ThreadBehaviorExecutor } from './thread-behavior-executor.js';
13
13
  import { DetailCapture } from '../../../observability/detail-capture.js';
14
14
  import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
15
+ import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
15
16
 
16
17
  export interface ClawclawBehaviorRunnerOptions {
18
+ readonly memory?: (input: Readonly<BehaviorInput>, isActive: () => boolean) => StrategyMemory;
17
19
  readonly snapshotStore?: BehaviorSnapshotStore;
18
20
  readonly behaviorId: string;
19
21
  readonly activationId: string;
@@ -42,8 +44,8 @@ function abortError(signal: AbortSignal): Error {
42
44
  }
43
45
 
44
46
  /**
45
- * One Activation-generation runner. Serial uses one owner-thread instance;
46
- * parallel creates an isolated module instance for every computation.
47
+ * One Activation-generation runner. Serial retains one instance; parallel
48
+ * creates an isolated instance per computation. Source modules run in Workers.
47
49
  */
48
50
  export class ClawclawBehaviorRunner {
49
51
  readonly behaviorId: string;
@@ -181,6 +183,8 @@ export class ClawclawBehaviorRunner {
181
183
  throw new Error('behavior_thread_source_invalid');
182
184
  }
183
185
  const executor = new ThreadBehaviorExecutor({
186
+ memory: this.options.memory && ((frame, active) => this.options.memory!(frame,
187
+ () => active() && !this.stopped && this.options.isActive())),
184
188
  fixedWorkers: true,
185
189
  snapshotStore: this.options.snapshotStore,
186
190
  source,
@@ -205,6 +209,7 @@ export class ClawclawBehaviorRunner {
205
209
  let invocationActive = true;
206
210
  let queryCount = 0;
207
211
  const api: BehaviorReadApi = createBehaviorReadApi(input, {
212
+ memory: this.options.memory?.(input, () => invocationActive && !signal.aborted && !this.stopped && this.options.isActive()),
208
213
  isActive: () => invocationActive
209
214
  && !signal.aborted
210
215
  && !this.stopped
@@ -19,6 +19,8 @@ import {
19
19
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
20
20
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
21
21
  import { BehaviorSnapshotStore, type BehaviorInstanceSnapshot } from './behavior-instance-snapshot.js';
22
+ import type { StrategyMemory } from '../../../../sdk/strategy-memory.js';
23
+ import { serveStrategyMemoryRequest, unavailableStrategyMemory, type StrategyMemoryRequest } from '../../strategy-memory-rpc.js';
22
24
 
23
25
  export const PARALLEL_BEHAVIOR_THREAD_POOL_SIZE = 10;
24
26
  const INITIAL_WORKER_COUNT = 2;
@@ -34,6 +36,7 @@ const WORKER_BOOTSTRAP = realpathSync(fileURLToPath(
34
36
  const WORKER_HOST_URL = new URL('./behavior-analysis-thread-host.ts', import.meta.url).href;
35
37
 
36
38
  export interface ThreadBehaviorExecutorOptions {
39
+ readonly memory?: (frame: Readonly<BehaviorInput>, isActive: () => boolean) => StrategyMemory;
37
40
  readonly fixedWorkers?: boolean;
38
41
  readonly snapshotStore?: BehaviorSnapshotStore;
39
42
  readonly source: ResolvedClawclawBehaviorSource;
@@ -591,11 +594,20 @@ export class ThreadBehaviorExecutor {
591
594
  }
592
595
  const message = value as WorkerReadyMessage
593
596
  | WorkerResultMessage
594
- | WorkerErrorMessage;
597
+ | WorkerErrorMessage
598
+ | (StrategyMemoryRequest & WorkerMessageBase & { readonly heapUsedBytes?: number });
595
599
  if (message.poolId !== this.runtimeInstanceId || message.slotId !== slot.id) {
596
600
  this.failSlot(slot, new Error('behavior_thread_protocol_identity_mismatch'));
597
601
  return;
598
602
  }
603
+ if (message.type === 'strategy_memory') {
604
+ const request = slot.current;
605
+ const isActive = () => this.state === 'running' && !!request && request === slot.current
606
+ && message.requestId === request.requestId && !request.settled && !request.signal.aborted;
607
+ void serveStrategyMemoryRequest(message, () => request && this.options.memory
608
+ ? this.options.memory(request.frame, isActive) : unavailableStrategyMemory, reply => slot.worker.postMessage(reply));
609
+ return;
610
+ }
599
611
  if (message.type === 'ready') {
600
612
  if (
601
613
  slot.state !== 'starting'
@@ -1,9 +1,11 @@
1
+ import { PlayerChangesDerivedEventRule, TaskChangesDerivedEventRule } from './state-change-rules.js';
1
2
  import type {
2
3
  RuntimeEpochPlugin,
3
4
  RuntimeEpochPluginContext,
4
5
  RuntimeEpochPluginInput,
5
6
  RuntimeEpochPluginResult,
6
7
  RuntimeEventProposal,
8
+ RuntimeSourceEvent,
7
9
  } from '../../../framework/plugins/index.js';
8
10
  import type { StoredStateFrame } from '../../../framework/state/index.js';
9
11
  import {
@@ -21,17 +23,11 @@ implements RuntimeEpochPlugin<Record<string, any>> {
21
23
  readonly kind = 'epoch' as const;
22
24
  readonly id = CLAWCLAW_DERIVED_EVENT_PLUGIN_ID;
23
25
  readonly version = '2';
24
- readonly produces = {
25
- events: [
26
- 'room_ready_to_start',
27
- 'meeting_state',
28
- 'emergency_countdown_warning',
29
- 'ability.ready',
30
- 'ability.remaining_uses_changed',
31
- 'ability.exhausted',
32
- ],
33
- } as const;
34
- readonly catchUp = 'every_epoch' as const;
26
+ readonly produces: { events: readonly string[] };
27
+ readonly consumes: { events: readonly string[] };
28
+ // Task/player changes must commit beside the backend facts from that input.
29
+ // Coalescing them into a later epoch would split downstream notification causality.
30
+ readonly catchUp = 'strict_ordered' as const;
35
31
  readonly timeoutMs = 1_000;
36
32
 
37
33
  private readonly rules: ClawclawDerivedEventRule[];
@@ -39,11 +35,15 @@ implements RuntimeEpochPlugin<Record<string, any>> {
39
35
 
40
36
  constructor(rules?: readonly ClawclawDerivedEventRule[]) {
41
37
  this.rules = [...(rules ?? [
38
+ new PlayerChangesDerivedEventRule(),
39
+ new TaskChangesDerivedEventRule(),
42
40
  new AbilityStateDerivedEventRule(),
43
41
  new EmergencyCountdownDerivedEventRule(),
44
42
  new RoomReadyDerivedEventRule(),
45
43
  new MeetingStateDerivedEventRule(),
46
44
  ])].sort((left, right) => left.id.localeCompare(right.id));
45
+ this.produces = { events: [...new Set(this.rules.flatMap(rule => rule.eventTypes))].sort() };
46
+ this.consumes = { events: [...new Set(this.rules.flatMap(rule => rule.consumes ?? []))].sort() };
47
47
  }
48
48
 
49
49
  start(): void {
@@ -60,10 +60,10 @@ implements RuntimeEpochPlugin<Record<string, any>> {
60
60
  input: RuntimeEpochPluginInput<Record<string, any>>,
61
61
  context: RuntimeEpochPluginContext<Record<string, any>>,
62
62
  ): RuntimeEpochPluginResult {
63
- const events = this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq);
64
- return events.length > 0
65
- ? { outcome: 'processed', events }
66
- : { outcome: 'noop', reason: 'no_derived_event' };
63
+ const events = this.scanHistory(context, input.epoch.epochSeq, true, input.frame.frameSeq, input);
64
+ return { ...(events.length > 0 ? { outcome: 'processed' as const, events }
65
+ : { outcome: 'noop' as const, reason: 'no_derived_event' }),
66
+ ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
67
67
  }
68
68
 
69
69
  stop(): void {
@@ -75,6 +75,7 @@ implements RuntimeEpochPlugin<Record<string, any>> {
75
75
  throughEpochSeq: number,
76
76
  collect: boolean,
77
77
  throughFrameSeq?: number,
78
+ currentInput?: RuntimeEpochPluginInput<Record<string, any>>,
78
79
  ): RuntimeEventProposal[] {
79
80
  const proposals: RuntimeEventProposal[] = [];
80
81
  let afterFrameSeq = this.lastFrameSeq;
@@ -89,7 +90,9 @@ implements RuntimeEpochPlugin<Record<string, any>> {
89
90
  });
90
91
  if (page.frames.length === 0) break;
91
92
  for (const frame of page.frames) {
92
- const frameEvents = this.inspectFrame(frame);
93
+ const facts = frame.epochSeq === undefined ? [] : context.sourceEventsAt?.(frame.epochSeq)
94
+ ?? (frame.epochSeq === currentInput?.epoch.epochSeq ? currentInput.epoch.events : []);
95
+ const frameEvents = this.inspectFrame(frame, facts);
93
96
  if (collect) proposals.push(...frameEvents);
94
97
  afterFrameSeq = frame.frameSeq;
95
98
  }
@@ -98,10 +101,10 @@ implements RuntimeEpochPlugin<Record<string, any>> {
98
101
  return proposals;
99
102
  }
100
103
 
101
- private inspectFrame(frame: StoredStateFrame<Record<string, any>>): RuntimeEventProposal[] {
104
+ private inspectFrame(frame: StoredStateFrame<Record<string, any>>, facts: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
102
105
  if (frame.frameSeq <= this.lastFrameSeq) return [];
103
106
  this.lastFrameSeq = frame.frameSeq;
104
- return this.rules.flatMap((rule) => rule.inspect(frame));
107
+ return this.rules.flatMap((rule) => rule.inspect(frame, facts));
105
108
  }
106
109
 
107
110
  private reset(): void {
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
- import type { RuntimeEventProposal } from '../../../framework/plugins/index.js';
2
+ import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js';
3
3
  import type { StoredStateFrame } from '../../../framework/state/index.js';
4
4
  import { isClawclawRuntimeState } from '../../runtime-state.js';
5
5
  import {
@@ -12,8 +12,9 @@ type UnknownRecord = Record<string, unknown>;
12
12
  export interface ClawclawDerivedEventRule {
13
13
  readonly id: string;
14
14
  readonly eventTypes: readonly string[];
15
+ readonly consumes?: readonly string[];
15
16
  reset(): void;
16
- inspect(frame: StoredStateFrame<Record<string, any>>): RuntimeEventProposal[];
17
+ inspect(frame: StoredStateFrame<Record<string, any>>, events?: readonly RuntimeSourceEvent[]): RuntimeEventProposal[];
17
18
  }
18
19
 
19
20
  function record(value: unknown): UnknownRecord | null {
@@ -71,6 +71,8 @@ export class ClawclawReminderPlugin implements RuntimeEpochPlugin<Record<string,
71
71
  ));
72
72
  }
73
73
  async update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): Promise<RuntimeEpochPluginResult> {
74
+ if (this.sources.size === 0) return { outcome: 'noop', reason: 'no_reminder_modules',
75
+ ...(input.pendingEvents.length ? {consumeEventsThroughCommitSeq: input.pendingEvents.at(-1)!.commitSeq} : {}) };
74
76
  const snapshot = freshClawclawGameState(input.frame.state);
75
77
  const game = snapshot ? createCanonicalGameState(snapshot, input.frame.backendTick) : null;
76
78
  let next = structuredClone(this.checkpoint);
@@ -0,0 +1,84 @@
1
+ import type { RuntimeEventProposal, RuntimeSourceEvent } from '../../../framework/plugins/index.js';
2
+ import type { StoredStateFrame } from '../../../framework/state/index.js';
3
+ import type { PlayerProjection } from '../../../../pipeline/player-projection.js';
4
+ import { CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
5
+ import { freshClawclawGameState, isClawclawRuntimeState } from '../../runtime-state.js';
6
+ import type { ClawclawDerivedEventRule } from './derived-event-rules.js';
7
+ import { nextPlayerProjection, type PlayerSnapshot } from './player-change-tracker.js';
8
+ import { nextTaskProjection, type TaskSnapshot } from './task-change-tracker.js';
9
+
10
+ /** Adapt validated canonical Source facts to the existing player projection's PlayerRef inputs. */
11
+ function trackerFacts(events: readonly RuntimeSourceEvent[]): Array<Record<string, any>> {
12
+ return events.filter(event => event.producer !== 'local_synth').map(event => {
13
+ const value: Record<string, any> = { ...event.payload, type: event.type };
14
+ for (const [field, name, seat] of [
15
+ ['actor','actor_name','actor_seat'], ['target','target_name','target_seat'],
16
+ ['caller','meeting_caller_name','meeting_caller_seat'], ['resolver','resolver_name','resolver_seat'],
17
+ ['current_speaker','current_speaker','current_speaker_seat'], ['result_target','result_target','result_target_seat'],
18
+ ]) {
19
+ if (typeof value[name] === 'string' && Number.isInteger(value[seat])) {
20
+ value[field] = { name: value[name], seat: value[seat] };
21
+ }
22
+ }
23
+ if (value.killer_kind === 'player' && typeof value.killer_name === 'string' && Number.isInteger(value.killer_seat)) {
24
+ value.killer = { kind: 'player', player: { name: value.killer_name, seat: value.killer_seat } };
25
+ } else if (value.killer_kind === 'system' && typeof value.killer_name === 'string') {
26
+ value.killer = { kind: 'system', name: value.killer_name };
27
+ }
28
+ return value;
29
+ });
30
+ }
31
+
32
+ function gameState(frame: StoredStateFrame<Record<string, any>>): Record<string, any> | null {
33
+ const game = freshClawclawGameState(frame.state);
34
+ if (!game) return null;
35
+ return { ...game, ...(frame.backendTick === undefined ? {} : { tick: frame.backendTick }) };
36
+ }
37
+
38
+ function proposal(type: string, frame: StoredStateFrame<Record<string, any>>, payload: Record<string, unknown>,
39
+ sourceEvents: readonly RuntimeSourceEvent[]): RuntimeEventProposal[] {
40
+ // An open epoch written by the previous Source implementation may already contain this fact.
41
+ // Rebuild rule state, but keep its original Source identity and delivery instead of publishing it twice.
42
+ if (sourceEvents.some(event => event.type === type && event.producer === 'local_synth')) return [];
43
+ return [{ type, payload, dedupeKey: `${type}:${frame.sourceKey}`, dedupeScope: 'segment',
44
+ occurredAt: new Date(frame.observedAtMs ?? frame.receivedAtMs).toISOString() }];
45
+ }
46
+
47
+ export class PlayerChangesDerivedEventRule implements ClawclawDerivedEventRule {
48
+ readonly id = 'player-changes';
49
+ readonly eventTypes = ['players_changed'] as const;
50
+ readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'players_changed'];
51
+ private initialized = false;
52
+ private projection: PlayerProjection[] = [];
53
+ private snapshots: PlayerSnapshot[] = [];
54
+ reset(): void { this.initialized = false; this.projection = []; this.snapshots = []; }
55
+ inspect(frame: StoredStateFrame<Record<string, any>>, events: readonly RuntimeSourceEvent[] = []): RuntimeEventProposal[] {
56
+ const game = gameState(frame);
57
+ if (!game) return [];
58
+ const update = nextPlayerProjection({ previous: this.projection, previousSnapshots: this.snapshots,
59
+ initialized: this.initialized, summary: game, events: trackerFacts(events),
60
+ selfName: game.you?.player?.name ?? game.you?.name });
61
+ this.projection = update.projection; this.snapshots = update.snapshots; this.initialized = true;
62
+ return update.payload ? proposal('players_changed', frame, update.payload, events) : [];
63
+ }
64
+ }
65
+
66
+ export class TaskChangesDerivedEventRule implements ClawclawDerivedEventRule {
67
+ readonly id = 'task-changes';
68
+ readonly eventTypes = ['tasks_changed'] as const;
69
+ readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'tasks_changed'];
70
+ private initialized = false;
71
+ private projection: TaskSnapshot[] = [];
72
+ reset(): void { this.initialized = false; this.projection = []; }
73
+ inspect(frame: StoredStateFrame<Record<string, any>>, events: readonly RuntimeSourceEvent[] = []): RuntimeEventProposal[] {
74
+ const game = gameState(frame);
75
+ if (!game) return [];
76
+ const state = frame.state;
77
+ const update = nextTaskProjection({ previous: this.projection, initialized: this.initialized, summary: game,
78
+ events: trackerFacts(events), selfName: game.you?.player?.name ?? game.you?.name,
79
+ allowUntickedInitialRole: isClawclawRuntimeState(state) && state.game_snapshot.status === 'fresh'
80
+ && state.game_snapshot.origin === 'update' });
81
+ this.projection = update.projection; this.initialized = update.initialized;
82
+ return update.payload ? proposal('tasks_changed', frame, update.payload, events) : [];
83
+ }
84
+ }
@@ -208,7 +208,7 @@ function updateReason(
208
208
 
209
209
  /**
210
210
  * Diff the authoritative task list carried by one complete GameSync State.
211
- * Source emits a private tasks_changed input, separate from backend facts.
211
+ * Derived Event emits tasks_changed from the same accepted input, separate from backend facts.
212
212
  * Reminder scripts own Agent-facing task notifications.
213
213
  */
214
214
  export function nextTaskProjection(input: {