@myclaw163/clawclaw-cli 0.8.2 → 0.8.4

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 (81) hide show
  1. package/README.md +1 -1
  2. package/docs/configuration.md +1 -1
  3. package/docs/custom-modules/README.md +4 -4
  4. package/docs/custom-modules/api-reference.md +20 -10
  5. package/docs/custom-modules/behavior.md +10 -6
  6. package/docs/custom-modules/perception.md +26 -3
  7. package/docs/custom-modules/trigger.md +1 -1
  8. package/docs/runtime/README.md +1 -1
  9. package/docs/runtime/behavior-runtime.md +6 -2
  10. package/docs/runtime/owner-lifecycle-and-observability.md +1 -1
  11. package/package.json +1 -1
  12. package/skills/clawclaw/SKILL.md +30 -37
  13. package/skills/clawclaw/references/COMMANDS.md +2 -3
  14. package/skills/clawclaw/references/GAME-MECHANICS.md +16 -18
  15. package/skills/clawclaw/references/STREAM.md +25 -10
  16. package/src/behaviors/official-finite/do-task.ts +70 -0
  17. package/src/behaviors/official-finite/index.test.ts +69 -22
  18. package/src/behaviors/official-finite/index.ts +0 -3
  19. package/src/commands/behavior.test.ts +1 -1
  20. package/src/commands/load.ts +8 -3
  21. package/src/commands/trigger.ts +12 -5
  22. package/src/lib/behavior-export.test.ts +53 -9
  23. package/src/lib/behavior-export.ts +26 -3
  24. package/src/lib/clawclaw-skill-spectate-guidance.test.ts +21 -0
  25. package/src/lib/trigger-export.test.ts +80 -0
  26. package/src/lib/trigger-export.ts +210 -0
  27. package/src/lib/user-data.test.ts +4 -0
  28. package/src/lib/user-data.ts +4 -0
  29. package/src/pipeline/canonical-event-presentation.test.ts +2 -0
  30. package/src/pipeline/event-format.test.ts +113 -0
  31. package/src/pipeline/event-format.ts +51 -5
  32. package/src/pipeline/event-hints.test.ts +28 -3
  33. package/src/pipeline/event-hints.ts +20 -6
  34. package/src/pipeline/game-sync-event-normalization.test.ts +49 -1
  35. package/src/pipeline/game-sync-event-normalization.ts +9 -0
  36. package/src/pipeline/role-display.ts +22 -0
  37. package/src/runtime/clawclaw/agent-ability-state.ts +69 -0
  38. package/src/runtime/clawclaw/agent-event-policy.test.ts +6 -0
  39. package/src/runtime/clawclaw/agent-event-policy.ts +5 -0
  40. package/src/runtime/clawclaw/behavior-decision.test.ts +14 -0
  41. package/src/runtime/clawclaw/behavior-decision.ts +8 -1
  42. package/src/runtime/clawclaw/behavior-input.test.ts +22 -0
  43. package/src/runtime/clawclaw/behavior-input.ts +3 -0
  44. package/src/runtime/clawclaw/owner.test.ts +16 -0
  45. package/src/runtime/clawclaw/owner.ts +21 -8
  46. package/src/runtime/clawclaw/plugins/action/action-plugin.test.ts +24 -0
  47. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +8 -1
  48. package/src/runtime/clawclaw/plugins/action/automated-action-normalization.ts +0 -1
  49. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -1
  50. package/src/runtime/clawclaw/plugins/behavior/behavior-action.test.ts +3 -0
  51. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.test.ts +246 -0
  52. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +135 -6
  53. package/src/runtime/clawclaw/plugins/behavior/official-goal-behavior.ts +0 -9
  54. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +118 -1
  55. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +13 -2
  56. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +156 -0
  57. package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +0 -1
  58. package/src/runtime/clawclaw-event-catalog.test.ts +6 -0
  59. package/src/runtime/clawclaw-event-catalog.ts +6 -0
  60. package/src/runtime/framework/action-diagnostics.ts +1 -0
  61. package/src/runtime/framework/modules/runtime-module-loader.test.ts +1 -1
  62. package/src/runtime/framework/modules/runtime-module-loader.ts +0 -1
  63. package/src/sdk/action.test.ts +8 -0
  64. package/src/sdk/action.ts +8 -6
  65. package/src/sdk/behavior-plugin/index.ts +11 -2
  66. package/src/sdk/behavior-toolkit/model.ts +2 -0
  67. package/src/sdk/module-input/index.ts +16 -2
  68. package/src/strategies/custom-module.test.ts +0 -1
  69. package/src/strategies/game-utils.test.ts +0 -1
  70. package/src/strategies/goals/avoid-players-top.test.ts +0 -1
  71. package/src/strategies/goals/crab-sabotage-top.test.ts +11 -25
  72. package/src/strategies/goals/crab-sabotage-top.ts +5 -61
  73. package/src/strategies/goals/kill-lone-top.test.ts +0 -1
  74. package/src/strategies/goals/kill-target-top.test.ts +0 -1
  75. package/src/strategies/goals/lone-kill-task-top.test.ts +0 -1
  76. package/src/strategies/goals/normal-shrimp-top.test.ts +0 -1
  77. package/src/strategies/goals/paradise-fish-top.test.ts +0 -1
  78. package/src/strategies/goals/task-only-top.test.ts +0 -1
  79. package/src/strategies/goals/warrior-shrimp-top.test.ts +0 -1
  80. package/src/strategies/types.ts +0 -6
  81. package/src/behaviors/official-finite/trigger-alarm.ts +0 -53
@@ -84,6 +84,7 @@ import {
84
84
  CCL_EVENTS_MAILBOX_CONSUMER_ID,
85
85
  DESKTOP_IPC_MAILBOX_CONSUMER_ID,
86
86
  MONITOR_MAILBOX_CONSUMER_ID,
87
+ type AgentMailboxCoordinatorOptions,
87
88
  type ClawclawMailboxDriver,
88
89
  type DesktopEventSocketConfig,
89
90
  } from './plugins/mailbox/index.js';
@@ -94,9 +95,11 @@ import {
94
95
  syncOfficialBehaviors,
95
96
  } from '../../lib/behavior-export.js';
96
97
  import { syncOfficialPerceptions } from '../../lib/perception-export.js';
97
- import { getUserDataTriggersDir } from '../../lib/user-data.js';
98
98
  import {
99
- listClawclawTriggerSources,
99
+ listWorkspaceClawclawTriggerSources,
100
+ syncOfficialTriggers,
101
+ } from '../../lib/trigger-export.js';
102
+ import {
100
103
  type ClawclawTriggerRegistration,
101
104
  type ResolvedClawclawTriggerSource,
102
105
  } from './plugins/trigger/index.js';
@@ -128,6 +131,17 @@ export interface ChannelOwnerDeliveryPolicy {
128
131
  drainOnNaturalCompletion: boolean;
129
132
  }
130
133
 
134
+ export type OwnerAgentEventDelivery = 'ccl_events' | 'desktop_ipc';
135
+
136
+ export function ownerAgentEventPresenter(
137
+ delivery: OwnerAgentEventDelivery,
138
+ desktopHost: boolean,
139
+ ): AgentMailboxCoordinatorOptions['presentEvent'] {
140
+ return delivery === 'desktop_ipc' || desktopHost
141
+ ? presentCanonicalEventForDesktop
142
+ : presentCanonicalEventForCclEvents;
143
+ }
144
+
131
145
  export function channelOwnerDeliveryPolicy(
132
146
  channelDelivery: boolean | undefined,
133
147
  localStopRequested = false,
@@ -698,6 +712,7 @@ export async function runClawclawOwner(
698
712
  const workspaceDir = getWorkspaceDir();
699
713
  await syncOfficialBehaviors({ workspaceDir });
700
714
  await syncOfficialPerceptions({ workspaceDir });
715
+ await syncOfficialTriggers({ workspaceDir });
701
716
  const perceptionConfig = readWorkspacePerceptionConfig();
702
717
  const gameplayConfig = readGameplayConfig(workspaceDir);
703
718
  const configurationWarning: ConfigurationWarning = (code, details) => {
@@ -720,7 +735,7 @@ export async function runClawclawOwner(
720
735
  behaviorCatalog,
721
736
  configurationWarning,
722
737
  );
723
- const triggerSources = listClawclawTriggerSources(getUserDataTriggersDir(workspaceDir));
738
+ const triggerSources = listWorkspaceClawclawTriggerSources(workspaceDir);
724
739
  const triggers = triggerRegistrations(
725
740
  triggerSources,
726
741
  gameplayConfig,
@@ -760,9 +775,7 @@ export async function runClawclawOwner(
760
775
  cclEventsMailbox = new AgentMailboxCoordinator({
761
776
  repository: mailboxRepository,
762
777
  readyView: () => runtime!.readReadyView(0, 1),
763
- presentEvent: options.desktopEvents
764
- ? presentCanonicalEventForDesktop
765
- : presentCanonicalEventForCclEvents,
778
+ presentEvent: ownerAgentEventPresenter('ccl_events', !!options.desktopEvents),
766
779
  compactState: compactStateForEvents,
767
780
  eventFilter: clawclawEventRequiresDetails,
768
781
  delegatedMonitorConsumerId: MONITOR_MAILBOX_CONSUMER_ID,
@@ -788,7 +801,7 @@ export async function runClawclawOwner(
788
801
  desktopMailbox = new AgentMailboxCoordinator({
789
802
  repository: mailboxRepository,
790
803
  readyView: () => runtime!.readReadyView(0, 1),
791
- presentEvent: presentCanonicalEventForCclEvents,
804
+ presentEvent: ownerAgentEventPresenter('desktop_ipc', true),
792
805
  compactState: compactStateForEvents,
793
806
  consumerId: DESKTOP_IPC_MAILBOX_CONSUMER_ID,
794
807
  diagnostic: (name, attributes) => runtime?.diagnostic(name, attributes),
@@ -1252,7 +1265,7 @@ export async function runClawclawOwner(
1252
1265
  return { ok: false, type: 'trigger_configure', error: 'stale_runtime_scope' };
1253
1266
  }
1254
1267
  const latest = readGameplayConfig(workspaceDir);
1255
- const currentTriggerSources = listClawclawTriggerSources(getUserDataTriggersDir(workspaceDir));
1268
+ const currentTriggerSources = listWorkspaceClawclawTriggerSources(workspaceDir);
1256
1269
  if (!currentTriggerSources.some((source) => source.id === request.trigger)) {
1257
1270
  return { ok: false, type: 'trigger_configure', error: 'trigger_source_unavailable' };
1258
1271
  }
@@ -301,4 +301,28 @@ describe('ClawclawActionPlugin automated provider FIFO', () => {
301
301
  error: { error: { code: 'STALE_BEHAVIOR_ACTION' } },
302
302
  });
303
303
  });
304
+
305
+ it('rejects the removed trigger_alarm action locally without calling the backend', () => {
306
+ const client = {
307
+ prepareActionForConfirmedSubmission: vi.fn(),
308
+ submitPreparedActionConfirmed: vi.fn(),
309
+ } as unknown as GameClient;
310
+ const plugin = new ClawclawActionPlugin(client);
311
+ (plugin as any).connection = 'connected';
312
+ (plugin as any).stage = 'game';
313
+ const perform = (plugin as any).perform.bind(plugin) as (
314
+ action: ClawclawActionRequest,
315
+ actionScope: ScopeRef,
316
+ caller: ActionCaller,
317
+ context: ActionExecutionContext,
318
+ ) => { status: string; error?: unknown };
319
+
320
+ expect(perform({ route: 'game', action: { action: 'trigger_alarm' } }, scope, {
321
+ kind: 'agent', id: 'agent-1',
322
+ }, actionContext())).toMatchObject({
323
+ status: 'failure',
324
+ error: { error: { code: 'TRIGGER_ALARM_REMOVED_USE_TASK' } },
325
+ });
326
+ expect(client.prepareActionForConfirmedSubmission).not.toHaveBeenCalled();
327
+ });
304
328
  });
@@ -45,7 +45,6 @@ export function describeClawclawActionControl(
45
45
  case 'task':
46
46
  case 'kill':
47
47
  case 'report':
48
- case 'trigger_alarm':
49
48
  domains = ['physical'];
50
49
  break;
51
50
  case 'speech':
@@ -370,6 +369,14 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
370
369
  const staleAtStart = this.automationSafetyRejection(request, scope, actionId, caller, context);
371
370
  if (staleAtStart) return staleAtStart;
372
371
  const action = { ...request.action };
372
+ if (action.action === 'trigger_alarm') {
373
+ return actionResult(scope, actionId, 'failure', undefined, {
374
+ error: {
375
+ code: 'TRIGGER_ALARM_REMOVED_USE_TASK',
376
+ message: 'Crab sabotage emergencies now start when an assigned sabotage task completes.',
377
+ },
378
+ }, { source: 'local', actionOutcome: 'not_submitted' });
379
+ }
373
380
  const route = request.route === 'auto'
374
381
  ? (this.stage === 'room' && action.action === 'speech' ? 'room_chat' : 'game')
375
382
  : request.route ?? 'game';
@@ -5,7 +5,6 @@ const ACTION_FIELDS: Readonly<Record<string, readonly string[]>> = Object.freeze
5
5
  task: ['action', 'task_name', 'thinking_content'],
6
6
  report: ['action', 'thinking_content'],
7
7
  think: ['action', 'thinking_content'],
8
- trigger_alarm: ['action', 'thinking_content'],
9
8
  });
10
9
 
11
10
  const ERRORS: Readonly<{
@@ -1,6 +1,6 @@
1
1
  import type { BehaviorActivationLayer } from '../../../../sdk/behavior-plugin/index.js';
2
2
 
3
- export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'system';
3
+ export type BehaviorActivationSource = 'user' | 'agent' | 'idle' | 'trigger' | 'behavior' | 'system';
4
4
  export type BehaviorActivationState = 'running' | 'suspended';
5
5
 
6
6
  export interface BehaviorActivationSpec {
@@ -27,6 +27,9 @@ describe('normalizeClawclawBehaviorAction', () => {
27
27
  expect(() => normalizeClawclawBehaviorAction({
28
28
  action: 'vote', target_seat: 3,
29
29
  }, 12, 4, 1)).toThrowError('unsupported_behavior_action');
30
+ expect(() => normalizeClawclawBehaviorAction({
31
+ action: 'trigger_alarm',
32
+ }, 12, 4, 1)).toThrowError('unsupported_behavior_action');
30
33
  });
31
34
 
32
35
  it('requires epoch, safety, and activation-generation fences', () => {
@@ -313,6 +313,81 @@ class FinishingShortBehavior extends ClawclawBehavior {
313
313
  }
314
314
  }
315
315
 
316
+ class DelegatingLongBehavior extends ClawclawBehavior {
317
+ static override readonly manifest = manifest('delegating-long');
318
+ static frames: BehaviorInput[] = [];
319
+ private continued = false;
320
+
321
+ override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
322
+ DelegatingLongBehavior.frames.push(input as BehaviorInput);
323
+ if (input.continuation) {
324
+ this.continued = true;
325
+ return { status: { summary: `continued:${input.continuation.delegatedBehavior.outcome}` } };
326
+ }
327
+ if (this.continued) return { status: { summary: 'continued' } };
328
+ return { delegate: { behavior: 'delegated-short', input: {} } };
329
+ }
330
+ }
331
+
332
+ class DelegatedShortBehavior extends ClawclawBehavior {
333
+ static override readonly manifest = manifest('delegated-short', {
334
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
335
+ });
336
+
337
+ override decide(): BehaviorDecision {
338
+ return {
339
+ finish: { outcome: 'completed', reason: 'delegated_done', summary: 'child summary' },
340
+ };
341
+ }
342
+ }
343
+
344
+ class InvalidDelegatingShortBehavior extends ClawclawBehavior {
345
+ static override readonly manifest = manifest('invalid-delegating-short', {
346
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
347
+ });
348
+
349
+ override decide(): BehaviorDecision {
350
+ return { delegate: { behavior: 'delegated-short' } };
351
+ }
352
+ }
353
+
354
+ class OutcomeDelegatingLongBehavior extends ClawclawBehavior {
355
+ static override readonly manifest = manifest('outcome-delegating-long');
356
+ static target = 'delegated-short';
357
+ static results: NonNullable<BehaviorInput['continuation']>['delegatedBehavior'][] = [];
358
+ private continued = false;
359
+
360
+ override decide(input: Readonly<BehaviorInput>): BehaviorDecision {
361
+ if (input.continuation) {
362
+ this.continued = true;
363
+ OutcomeDelegatingLongBehavior.results.push(input.continuation.delegatedBehavior);
364
+ return { status: { summary: `outcome:${input.continuation.delegatedBehavior.outcome}` } };
365
+ }
366
+ if (this.continued) return { status: { summary: 'continued' } };
367
+ return { delegate: { behavior: OutcomeDelegatingLongBehavior.target } };
368
+ }
369
+ }
370
+
371
+ class FailingDelegatedShortBehavior extends ClawclawBehavior {
372
+ static override readonly manifest = manifest('failing-delegated-short', {
373
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
374
+ });
375
+
376
+ override decide(): BehaviorDecision {
377
+ return { finish: { outcome: 'failed', reason: 'child_failed', summary: 'failed summary' } };
378
+ }
379
+ }
380
+
381
+ class WaitingDelegatedShortBehavior extends ClawclawBehavior {
382
+ static override readonly manifest = manifest('waiting-delegated-short', {
383
+ runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
384
+ });
385
+
386
+ override decide(): BehaviorDecision {
387
+ return { status: { summary: 'waiting' } };
388
+ }
389
+ }
390
+
316
391
  class ReportBehavior extends ClawclawBehavior {
317
392
  static override readonly manifest = manifest('report', {
318
393
  runtime: { defaultMs: 10_000, deadlineOutcome: 'failed' },
@@ -383,6 +458,16 @@ class ActionFinishBehavior extends ClawclawBehavior {
383
458
  }
384
459
  }
385
460
 
461
+ class ActionDelegatingBehavior extends ClawclawBehavior {
462
+ static override readonly manifest = manifest('action-delegating');
463
+ override decide(): BehaviorDecision {
464
+ return {
465
+ actions: [{ action: 'move', target_x: 1, target_y: 2 }],
466
+ delegate: { behavior: 'delegated-short' },
467
+ };
468
+ }
469
+ }
470
+
386
471
  class SlowBehavior extends ClawclawBehavior {
387
472
  static override readonly manifest = manifest('slow');
388
473
  static onDecide: (() => void) | undefined;
@@ -598,6 +683,146 @@ describe('Clawclaw unified Behavior plugin', () => {
598
683
  ]);
599
684
  });
600
685
 
686
+ it('lets a long delegate one short and receives its terminal result once after fresh restart', async () => {
687
+ DelegatingLongBehavior.frames = [];
688
+ let id = 0;
689
+ const plugin = new ClawclawBehaviorPlugin({
690
+ catalog: catalog([DelegatingLongBehavior, DelegatedShortBehavior]),
691
+ driver: driver(),
692
+ createActivationId: () => `delegation-${++id}`,
693
+ now: () => 0,
694
+ });
695
+ const ctx = context();
696
+ await plugin.start(ctx);
697
+ await plugin.startLong('delegating-long', {}, { source: 'agent' });
698
+
699
+ const delegated = await step(plugin, input(1, { nowMs: 100 }), ctx);
700
+ expect(plugin.status().current).toMatchObject({
701
+ activationId: 'delegation-2',
702
+ behaviorId: 'delegated-short',
703
+ layer: 'short',
704
+ source: 'behavior',
705
+ });
706
+ expect(delegated.events).toEqual(expect.arrayContaining([
707
+ expect.objectContaining({ type: 'behavior.suspended' }),
708
+ expect.objectContaining({ type: 'behavior.started' }),
709
+ ]));
710
+
711
+ await step(plugin, input(2, { nowMs: 200 }), ctx);
712
+ await step(plugin, input(3, { nowMs: 699 }), ctx);
713
+ await step(plugin, input(4, { nowMs: 700 }), ctx);
714
+ const resumed = await step(plugin, input(5, { nowMs: 701 }), ctx);
715
+ expect(resumed.states).toEqual([
716
+ expect.objectContaining({
717
+ value: expect.objectContaining({ status: { summary: 'continued:completed' } }),
718
+ }),
719
+ ]);
720
+ expect(DelegatingLongBehavior.frames.at(-1)?.continuation).toEqual({
721
+ delegatedBehavior: {
722
+ activationId: 'delegation-2',
723
+ behavior: 'delegated-short',
724
+ outcome: 'completed',
725
+ reason: 'delegated_done',
726
+ summary: 'child summary',
727
+ },
728
+ });
729
+
730
+ await step(plugin, input(6, { nowMs: 702 }), ctx);
731
+ expect(DelegatingLongBehavior.frames.at(-1)?.continuation).toBeUndefined();
732
+ });
733
+
734
+ it('fails closed when a short Behavior attempts recursive delegation', async () => {
735
+ let id = 0;
736
+ const plugin = new ClawclawBehaviorPlugin({
737
+ catalog: catalog([InvalidDelegatingShortBehavior, DelegatedShortBehavior]),
738
+ driver: driver(),
739
+ createActivationId: () => `invalid-delegation-${++id}`,
740
+ now: () => 0,
741
+ });
742
+ const ctx = context();
743
+ await plugin.start(ctx);
744
+ await plugin.startShort('invalid-delegating-short', {}, { source: 'agent' });
745
+
746
+ const result = await step(plugin, input(1), ctx);
747
+ expect(result.events).toEqual(expect.arrayContaining([
748
+ expect.objectContaining({
749
+ type: 'behavior.failed',
750
+ payload: expect.objectContaining({ reason: 'behavior_delegate_layer_invalid' }),
751
+ }),
752
+ ]));
753
+ });
754
+
755
+ it('returns failed, cancelled, and replaced delegated outcomes to the original long', async () => {
756
+ const cases = [
757
+ {
758
+ outcome: 'failed',
759
+ target: 'failing-delegated-short',
760
+ prepare: async (_plugin: ClawclawBehaviorPlugin, _childId: string, _setNow: (value: number) => void) => {},
761
+ reason: 'child_failed',
762
+ summary: 'failed summary',
763
+ },
764
+ {
765
+ outcome: 'cancelled',
766
+ target: 'waiting-delegated-short',
767
+ prepare: async (plugin: ClawclawBehaviorPlugin, childId: string, setNow: (value: number) => void) => {
768
+ setNow(200);
769
+ await plugin.cancel(childId, 'cancelled_by_test');
770
+ },
771
+ reason: 'cancelled_by_test',
772
+ },
773
+ {
774
+ outcome: 'replaced',
775
+ target: 'waiting-delegated-short',
776
+ prepare: async (plugin: ClawclawBehaviorPlugin, _childId: string, setNow: (value: number) => void) => {
777
+ setNow(200);
778
+ await plugin.startShort('delegated-short', {}, { source: 'agent' });
779
+ },
780
+ reason: 'short_replaced',
781
+ },
782
+ ] as const;
783
+
784
+ for (const [index, testCase] of cases.entries()) {
785
+ let id = 0;
786
+ let now = 100;
787
+ OutcomeDelegatingLongBehavior.target = testCase.target;
788
+ OutcomeDelegatingLongBehavior.results = [];
789
+ const plugin = new ClawclawBehaviorPlugin({
790
+ catalog: catalog([
791
+ OutcomeDelegatingLongBehavior,
792
+ DelegatedShortBehavior,
793
+ FailingDelegatedShortBehavior,
794
+ WaitingDelegatedShortBehavior,
795
+ ]),
796
+ driver: driver(),
797
+ createActivationId: () => `terminal-${index}-${++id}`,
798
+ now: () => now,
799
+ });
800
+ const ctx = context();
801
+ await plugin.start(ctx);
802
+ await plugin.startLong('outcome-delegating-long', {}, { source: 'agent' });
803
+ await step(plugin, input(1, { nowMs: 100 }), ctx);
804
+ const childId = plugin.status().current!.activationId;
805
+ await testCase.prepare(plugin, childId, (value) => { now = value; });
806
+ if (testCase.outcome !== 'cancelled') {
807
+ await step(plugin, input(2, { nowMs: 200 }), ctx);
808
+ }
809
+ await step(plugin, input(3, { nowMs: 699 }), ctx);
810
+ await step(plugin, input(4, { nowMs: 700 }), ctx);
811
+ await step(plugin, input(5, { nowMs: 701 }), ctx);
812
+
813
+ expect(OutcomeDelegatingLongBehavior.results).toEqual([
814
+ expect.objectContaining({
815
+ activationId: childId,
816
+ behavior: testCase.target,
817
+ outcome: testCase.outcome,
818
+ reason: testCase.reason,
819
+ ...('summary' in testCase ? { summary: testCase.summary } : {}),
820
+ }),
821
+ ]);
822
+ await plugin.stop('shutdown');
823
+ }
824
+ });
825
+
601
826
  it('lets a report short observe meeting authority before cancelling the wandering boundary', async () => {
602
827
  const actions: Array<Record<string, any>> = [];
603
828
  const plugin = new ClawclawBehaviorPlugin({
@@ -781,6 +1006,27 @@ describe('Clawclaw unified Behavior plugin', () => {
781
1006
  ]));
782
1007
  });
783
1008
 
1009
+ it('rejects actions and delegation in the same Decision before submitting an Action', async () => {
1010
+ const actions: Array<Record<string, any>> = [];
1011
+ const plugin = new ClawclawBehaviorPlugin({
1012
+ catalog: catalog([ActionDelegatingBehavior, DelegatedShortBehavior]),
1013
+ driver: driver(),
1014
+ createActivationId: () => 'action-delegating-1',
1015
+ now: () => 0,
1016
+ });
1017
+ const ctx = context(actions);
1018
+ await plugin.start(ctx);
1019
+ await plugin.startLong('action-delegating', {}, { source: 'agent' });
1020
+ const result = await step(plugin, input(1), ctx);
1021
+ expect(actions).toEqual([]);
1022
+ expect(result.events).toEqual(expect.arrayContaining([
1023
+ expect.objectContaining({
1024
+ type: 'behavior.failed',
1025
+ payload: expect.objectContaining({ reason: 'behavior_delegate_with_actions_invalid' }),
1026
+ }),
1027
+ ]));
1028
+ });
1029
+
784
1030
  it('interrupts a slow serial Decision before admitting a higher reflex', async () => {
785
1031
  let entered!: () => void;
786
1032
  const deciding = new Promise<void>((resolve) => { entered = resolve; });
@@ -1,6 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import type {
3
+ BehaviorContinuation,
3
4
  BehaviorDecision,
5
+ BehaviorDelegation,
4
6
  BehaviorFinish,
5
7
  BehaviorInput,
6
8
  BehaviorStatus,
@@ -135,9 +137,14 @@ interface ActivationRuntime {
135
137
  instanceGeneration?: number;
136
138
  lastCommittedBackendTick?: number;
137
139
  lastStatus?: Readonly<BehaviorStatus>;
140
+ pendingContinuation?: Readonly<BehaviorContinuation>;
138
141
  committedActionDedupeKeys: Map<string, number>;
139
142
  }
140
143
 
144
+ interface DelegatedShort {
145
+ readonly parentActivationId: string;
146
+ }
147
+
141
148
  interface BehaviorComputationProposal {
142
149
  readonly schema: typeof BEHAVIOR_COMPUTATION_SCHEMA;
143
150
  readonly kind:
@@ -279,6 +286,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
279
286
  private readonly decisionTimeoutMs: number;
280
287
  private readonly observationMemory = new ClawclawBehaviorObservationMemory();
281
288
  private readonly runtimes = new Map<string, ActivationRuntime>();
289
+ private readonly delegatedShorts = new Map<string, Readonly<DelegatedShort>>();
290
+ private readonly finishSummaries = new Map<string, string>();
282
291
  private readonly controls = new Map<string, ClawclawBehaviorControlHandle>();
283
292
  private readonly pendingLifecycleEvents: RuntimeEventProposal[] = [];
284
293
  private readonly decisionControllers = new Map<string, Set<AbortController>>();
@@ -509,7 +518,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
509
518
  if (!current) {
510
519
  return { outcome: 'processed', proposal: { ...base, kind: 'inactive' } satisfies BehaviorComputationProposal };
511
520
  }
512
- const frame = createBehaviorInput(input, current.input);
521
+ const runtime = this.runtimes.get(current.activationId);
522
+ const frame = createBehaviorInput(input, current.input, runtime?.pendingContinuation);
513
523
  if (!frame) {
514
524
  return { outcome: 'processed', proposal: { ...base, kind: 'waiting_for_state' } satisfies BehaviorComputationProposal };
515
525
  }
@@ -523,7 +533,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
523
533
  if (frame.gameState.phase !== 'wandering' && !meetingShort) {
524
534
  return { outcome: 'processed', proposal: { ...base, kind: 'boundary' } satisfies BehaviorComputationProposal };
525
535
  }
526
- const runtime = this.runtimes.get(current.activationId);
527
536
  const control = this.controls.get(current.activationId);
528
537
  if (!runtime?.runner || runtime.instanceGeneration !== current.instanceGeneration) {
529
538
  return { outcome: 'processed', proposal: { ...base, kind: 'control_held' } satisfies BehaviorComputationProposal };
@@ -604,6 +613,8 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
604
613
  await Promise.all(runners.map((runner) => runner.stop(runnerReason)));
605
614
  await this.applyTransitions(this.manager.clearScope(reason, this.now()));
606
615
  this.runtimes.clear();
616
+ this.delegatedShorts.clear();
617
+ this.finishSummaries.clear();
607
618
  for (const handle of this.controls.values()) handle.release(reason);
608
619
  this.controls.clear();
609
620
  this.observationMemory.clear();
@@ -675,8 +686,13 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
675
686
  this.refreshBackendStrategyReport(input, context);
676
687
 
677
688
  await this.applyTransitions(this.manager.advance(now));
678
- const frame = this.manager.current()
679
- ? createBehaviorInput(input, this.manager.current()!.input)
689
+ const currentForFrame = this.manager.current();
690
+ const frame = currentForFrame
691
+ ? createBehaviorInput(
692
+ input,
693
+ currentForFrame.input,
694
+ this.runtimes.get(currentForFrame.activationId)?.pendingContinuation,
695
+ )
680
696
  : frameForClock;
681
697
  if (frame?.gameState.phase === 'game_over' || computed.kind === 'game_over') {
682
698
  await this.applyTransitions(this.manager.clearScope('game_over', now));
@@ -800,10 +816,25 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
800
816
  if (decision.finish && (decision.actions?.length ?? 0) > 0) {
801
817
  throw new Error('behavior_finish_with_actions_invalid');
802
818
  }
819
+ if (decision.delegate && (decision.actions?.length ?? 0) > 0) {
820
+ throw new Error('behavior_delegate_with_actions_invalid');
821
+ }
822
+ if (decision.delegate && decision.finish) {
823
+ throw new Error('behavior_delegate_with_finish_invalid');
824
+ }
825
+ if (decision.delegate && activation.layer !== 'long') {
826
+ throw new Error('behavior_delegate_layer_invalid');
827
+ }
828
+ const delegated = decision.delegate === undefined
829
+ ? undefined
830
+ : await this.prepareDelegatedShort(decision.delegate);
803
831
  const declaredEvents = new Set(runtime.prepared.manifest.produces ?? []);
804
832
  for (const event of decision.events ?? []) {
805
833
  if (!declaredEvents.has(event.type)) throw new Error('behavior_event_output_invalid');
806
834
  }
835
+ // A continuation belongs to the first Decision that actually reaches the
836
+ // ordered effect queue. Stale proposals and cadence skips never consume it.
837
+ runtime.pendingContinuation = undefined;
807
838
  const state = input.epoch.state;
808
839
  const safetyGeneration = isClawclawRuntimeState(state)
809
840
  ? state.action_safety_generation
@@ -855,21 +886,79 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
855
886
  payload: { ...event.payload },
856
887
  ...(event.occurredAt === undefined ? {} : { occurredAt: event.occurredAt }),
857
888
  }));
858
- if (decision.finish) {
889
+ if (delegated) {
890
+ // Keep the status on the suspended parent. Publishing it as the current
891
+ // semantic status would incorrectly attach it to the newly started child.
892
+ runtime.lastStatus = decision.status ?? runtime.lastStatus;
893
+ await this.startDelegatedShort(activation, delegated, frame.nowMs);
894
+ } else if (decision.finish) {
859
895
  await this.finishCurrent(activation, decision.finish, frame.nowMs);
860
896
  }
861
897
  return {
862
- ...(decision.status === undefined ? {} : { status: decision.status }),
898
+ ...(decision.status === undefined || delegated ? {} : { status: decision.status }),
863
899
  events,
864
900
  };
865
901
  }
866
902
 
903
+ private async prepareDelegatedShort(
904
+ delegation: Readonly<BehaviorDelegation>,
905
+ ): Promise<Readonly<{
906
+ behaviorId: string;
907
+ rawInput: Readonly<Record<string, unknown>>;
908
+ prepared: PreparedClawclawBehavior;
909
+ }>> {
910
+ const rawInput = delegation.input ?? Object.freeze({});
911
+ const prepared = await this.catalog.prepare(delegation.behavior, rawInput);
912
+ return Object.freeze({
913
+ behaviorId: delegation.behavior,
914
+ rawInput: Object.freeze(structuredClone(rawInput)),
915
+ prepared,
916
+ });
917
+ }
918
+
919
+ private async startDelegatedShort(
920
+ parent: Readonly<BehaviorActivationSnapshot>,
921
+ delegated: Readonly<{
922
+ behaviorId: string;
923
+ rawInput: Readonly<Record<string, unknown>>;
924
+ prepared: PreparedClawclawBehavior;
925
+ }>,
926
+ now: number,
927
+ ): Promise<void> {
928
+ if (!this.manager.isCurrent(parent.activationId, parent.instanceGeneration)) return;
929
+ const activationId = this.createActivationId();
930
+ const maxRuntimeMs = runtimeMs(delegated.prepared, delegated.rawInput)
931
+ ?? DEFAULT_SHORT_MAX_RUNTIME_MS;
932
+ const transitions = this.manager.startShort({
933
+ activationId,
934
+ behaviorId: delegated.behaviorId,
935
+ source: 'behavior',
936
+ input: delegated.prepared.input,
937
+ requestedAt: now,
938
+ maxRuntimeMs,
939
+ deadlineOutcome: deadlineOutcome(delegated.prepared, delegated.rawInput) ?? 'failed',
940
+ }, now);
941
+ this.runtimes.set(activationId, {
942
+ activationId,
943
+ behaviorId: delegated.behaviorId,
944
+ prepared: delegated.prepared,
945
+ committedActionDedupeKeys: new Map(),
946
+ });
947
+ this.delegatedShorts.set(activationId, Object.freeze({
948
+ parentActivationId: parent.activationId,
949
+ }));
950
+ await this.applyTransitions(transitions);
951
+ }
952
+
867
953
  private async finishCurrent(
868
954
  activation: Readonly<BehaviorActivationSnapshot>,
869
955
  finish: Readonly<BehaviorFinish>,
870
956
  now: number,
871
957
  ): Promise<void> {
872
958
  if (!this.manager.isCurrent(activation.activationId, activation.instanceGeneration)) return;
959
+ if (finish.summary !== undefined) {
960
+ this.finishSummaries.set(activation.activationId, finish.summary);
961
+ }
873
962
  await this.applyTransitions(this.manager.finish(
874
963
  activation.activationId,
875
964
  finish.outcome,
@@ -890,6 +979,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
890
979
  private async applyTransitions(
891
980
  transitions: readonly BehaviorActivationTransition[],
892
981
  ): Promise<void> {
982
+ this.captureDelegationResults(transitions);
893
983
  for (const transition of transitions) {
894
984
  const event = lifecycleEvent(transition);
895
985
  if (event) this.pendingLifecycleEvents.push(event);
@@ -950,6 +1040,45 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
950
1040
  if (failures.length > 0) await this.applyTransitions(failures);
951
1041
  }
952
1042
 
1043
+ private captureDelegationResults(
1044
+ transitions: readonly BehaviorActivationTransition[],
1045
+ ): void {
1046
+ for (const transition of transitions) {
1047
+ if (
1048
+ transition.type !== 'completed'
1049
+ && transition.type !== 'failed'
1050
+ && transition.type !== 'cancelled'
1051
+ && transition.type !== 'replaced'
1052
+ ) continue;
1053
+ const delegated = this.delegatedShorts.get(transition.activationId);
1054
+ const summary = this.finishSummaries.get(transition.activationId);
1055
+ if (delegated) {
1056
+ const parent = currentRuntimeSnapshot(this.manager, delegated.parentActivationId);
1057
+ const parentRuntime = this.runtimes.get(delegated.parentActivationId);
1058
+ if (parent?.layer === 'long' && parentRuntime) {
1059
+ parentRuntime.pendingContinuation = Object.freeze({
1060
+ delegatedBehavior: Object.freeze({
1061
+ activationId: transition.activationId,
1062
+ behavior: transition.behaviorId,
1063
+ outcome: transition.type,
1064
+ reason: transition.reason,
1065
+ ...(summary === undefined ? {} : { summary }),
1066
+ }),
1067
+ });
1068
+ }
1069
+ this.delegatedShorts.delete(transition.activationId);
1070
+ }
1071
+ this.finishSummaries.delete(transition.activationId);
1072
+ if (transition.layer === 'long') {
1073
+ for (const [childActivationId, relation] of this.delegatedShorts) {
1074
+ if (relation.parentActivationId === transition.activationId) {
1075
+ this.delegatedShorts.delete(childActivationId);
1076
+ }
1077
+ }
1078
+ }
1079
+ }
1080
+ }
1081
+
953
1082
  private async ensureRuntime(
954
1083
  activation: Readonly<BehaviorActivationSnapshot>,
955
1084
  ): Promise<ActivationRuntime> {