@myclaw163/clawclaw-cli 0.8.20 → 0.8.22

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 (50) hide show
  1. package/docs/configuration.md +57 -2
  2. package/docs/custom-modules/api-reference.md +2 -0
  3. package/docs/custom-modules/perception.md +25 -0
  4. package/docs/runtime/official-perception-modules.md +23 -0
  5. package/package.json +1 -1
  6. package/skills/clawclaw/SKILL.md +3 -1
  7. package/skills/clawclaw/references/COMMANDS.md +2 -0
  8. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +2 -0
  9. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +25 -0
  10. package/src/commands/behavior.ts +1 -0
  11. package/src/commands/capability.ts +1 -0
  12. package/src/commands/data.ts +1 -0
  13. package/src/commands/load.ts +31 -2
  14. package/src/lib/agent-workspace-client.ts +1 -0
  15. package/src/lib/agent-workspace-runtime.ts +6 -0
  16. package/src/lib/agent-workspace-sync.ts +117 -6
  17. package/src/lib/capability-cloud-refresh.ts +7 -0
  18. package/src/lib/capability-cloud-sync.ts +11 -3
  19. package/src/lib/capability-workspace.ts +3 -0
  20. package/src/lib/diagnostics-config.ts +26 -1
  21. package/src/lib/hub-client.ts +6 -0
  22. package/src/lib/persona.ts +2 -0
  23. package/src/runtime/clawclaw/agent-event-policy.ts +7 -0
  24. package/src/runtime/clawclaw/owner.ts +17 -10
  25. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +21 -0
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +26 -12
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +19 -1
  28. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +2 -0
  29. package/src/runtime/clawclaw/plugins/mailbox/adapters/game-sync-perception-report-adapter.ts +10 -1
  30. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +17 -1
  31. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +5 -2
  32. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +46 -15
  33. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +36 -0
  34. package/src/runtime/clawclaw/plugins/perception/perception-module-output.ts +2 -1
  35. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1 -0
  36. package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +13 -0
  37. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +4 -0
  38. package/src/runtime/clawclaw/runtime-data-export.ts +9 -0
  39. package/src/runtime/framework/events/event-ingress.ts +1 -0
  40. package/src/runtime/framework/events/memory-event-repository.ts +5 -4
  41. package/src/runtime/framework/events/sqlite-event-repository.ts +36 -9
  42. package/src/runtime/framework/events/types.ts +4 -0
  43. package/src/runtime/framework/mailbox/types.ts +4 -0
  44. package/src/runtime/framework/plugins/contracts.ts +2 -0
  45. package/src/runtime/framework/runtime.ts +13 -0
  46. package/src/runtime/mailbox-host-relay.ts +13 -12
  47. package/src/runtime/observability/detail-capture.ts +123 -0
  48. package/src/runtime/observability/factory.ts +13 -0
  49. package/src/runtime/observability/recorder.ts +34 -5
  50. package/src/sdk/perception-plugin/index.ts +4 -0
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { resolveDetailCapture } from '../../../observability/detail-capture.js';
2
3
  import { performance } from 'node:perf_hooks';
3
4
  import type {
4
5
  BehaviorContinuation,
@@ -289,6 +290,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
289
290
  private readonly now: () => number;
290
291
  private readonly createActivationId: () => string;
291
292
  private readonly decisionTimeoutMs: number;
293
+ private readonly captureActions = resolveDetailCapture().actions;
292
294
  private readonly diagnosticsEnabled: boolean;
293
295
  private readonly observationMemory = new ClawclawBehaviorObservationMemory();
294
296
  private readonly runtimes = new Map<string, ActivationRuntime>();
@@ -639,6 +641,11 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
639
641
  current.activationId,
640
642
  );
641
643
  const resolved = runtime.decisionHistory.complete(frame.epochId, decision.actions);
644
+ if (this.captureActions) context.diagnostic('runtime.detail.actions.decision', {
645
+ behavior_id: current.behaviorId, activation_id: current.activationId,
646
+ instance_generation: current.instanceGeneration, epoch_id: frame.epochId,
647
+ tick: frame.gameState.tick, stage: 'computed_not_yet_committed', actions: decision.actions ?? [],
648
+ }, 'debug');
642
649
  if (resolved) {
643
650
  const history = runtime.decisionHistory.snapshot();
644
651
  context.diagnostic('behavior.decision_history.frame_resolved', {
@@ -698,7 +705,13 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
698
705
  computation: Readonly<RuntimeEpochPluginResult>,
699
706
  context: RuntimeEpochPluginContext<Record<string, any>>,
700
707
  ): Promise<RuntimeEpochPluginResult> {
701
- return this.enqueueControl(() => this.commitOrdered(input, proposal(computation.proposal), context));
708
+ return this.enqueueControl(async () => {
709
+ const result = await this.commitOrdered(input, proposal(computation.proposal), context);
710
+ // Report the final activation after this epoch's advances, finishes and
711
+ // boundary transitions, rather than the activation it started with.
712
+ this.refreshBackendStrategyReport(input, context);
713
+ return result;
714
+ });
702
715
  }
703
716
 
704
717
  async stop(reason: 'segment_ending' | 'shutdown'): Promise<void> {
@@ -790,7 +803,6 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
790
803
  const runtimeState = input.epoch.state;
791
804
 
792
805
  await this.syncRoleFallback(frameForClock, now);
793
- this.refreshBackendStrategyReport(input, context);
794
806
 
795
807
  await this.applyTransitions(this.manager.advance(now));
796
808
  const currentForFrame = this.manager.current();
@@ -996,7 +1008,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
996
1008
  try {
997
1009
  const result = await context.capabilities.performAction(
998
1010
  CLAWCLAW_ACTION_CAPABILITY,
999
- request,
1011
+ { ...request, behaviorOriginId: activation.behaviorId },
1000
1012
  asActionCaller(control.caller),
1001
1013
  );
1002
1014
  context.diagnostic('behavior.action.receipt', {
@@ -1337,17 +1349,19 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1337
1349
 
1338
1350
  /**
1339
1351
  * The backend still calls this display-only field a Strategy. Report the
1340
- * persistent long/fallback Behavior, never a short or reflex overlay.
1352
+ * current activation, including short/reflex overrides. A configured fallback
1353
+ * or suspended long is not active until the manager gives it control.
1341
1354
  */
1342
1355
  private backendStrategyDescriptor(): ClawclawResolvedResourceMetadata | undefined {
1343
- const stack = this.manager.snapshot();
1344
- const long = stack.long;
1345
- const behaviorId = long?.behaviorId ?? stack.fallback?.behaviorId;
1346
- if (!behaviorId) return undefined;
1347
- const prepared = long
1348
- ? this.runtimes.get(long.activationId)?.prepared
1349
- : this.fallbackPrepared;
1350
- if (!prepared || prepared.manifest.id !== behaviorId) return undefined;
1356
+ const current = this.manager.current();
1357
+ if (!current) return {
1358
+ // The backend requires non-empty display text and has no clear action.
1359
+ id: 'clawclaw:no-active-behavior',
1360
+ name: '无策略在运行',
1361
+ description: '当前没有活跃的策略。',
1362
+ };
1363
+ const prepared = this.runtimes.get(current.activationId)?.prepared;
1364
+ if (!prepared || prepared.manifest.id !== current.behaviorId) return undefined;
1351
1365
  return resolveClawclawResourceMetadata({
1352
1366
  id: prepared.manifest.id,
1353
1367
  name: prepared.manifest.name,
@@ -10,6 +10,7 @@ import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observa
10
10
  import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contracts.js';
11
11
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
12
12
  import { ThreadBehaviorExecutor } from './thread-behavior-executor.js';
13
+ import { DetailCapture } from '../../../observability/detail-capture.js';
13
14
 
14
15
  export interface ClawclawBehaviorRunnerOptions {
15
16
  readonly behaviorId: string;
@@ -55,6 +56,7 @@ export class ClawclawBehaviorRunner {
55
56
  private parallelReady?: Promise<void>;
56
57
  private parallelStop?: Promise<void>;
57
58
  private stopped = false;
59
+ private readonly capture: DetailCapture;
58
60
 
59
61
  constructor(private readonly options: ClawclawBehaviorRunnerOptions) {
60
62
  this.behaviorId = options.behaviorId;
@@ -62,6 +64,7 @@ export class ClawclawBehaviorRunner {
62
64
  this.instanceGeneration = options.instanceGeneration;
63
65
  this.prepared = options.prepared;
64
66
  this.serialModule = options.prepared.module;
67
+ this.capture = new DetailCapture('behavior_io', options.diagnostic);
65
68
  }
66
69
 
67
70
  get execution(): 'parallel' | 'serial' {
@@ -100,6 +103,11 @@ export class ClawclawBehaviorRunner {
100
103
  signal: AbortSignal,
101
104
  observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
102
105
  ): Promise<BehaviorDecision> {
106
+ return this.traceDecision(input, observationSnapshot, signal, () => this.decideSerialInternal(input, signal, observationSnapshot));
107
+ }
108
+
109
+ private decideSerialInternal(input: Readonly<BehaviorInput>, signal: AbortSignal,
110
+ observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>): Promise<BehaviorDecision> {
103
111
  if (this.prepared.source) {
104
112
  return this.enqueue(() => this.invokeThread(input, signal, observationSnapshot));
105
113
  }
@@ -113,7 +121,17 @@ export class ClawclawBehaviorRunner {
113
121
  signal: AbortSignal,
114
122
  observationSnapshot?: Readonly<ClawclawBehaviorObservationSnapshot>,
115
123
  ): Promise<BehaviorDecision> {
116
- return this.invokeThread(input, signal, observationSnapshot);
124
+ return this.traceDecision(input, observationSnapshot, signal, () => this.invokeThread(input, signal, observationSnapshot));
125
+ }
126
+
127
+ private traceDecision(input: Readonly<BehaviorInput>, observationSnapshot: Readonly<ClawclawBehaviorObservationSnapshot> | undefined,
128
+ signal: AbortSignal, invoke: () => Promise<BehaviorDecision>): Promise<BehaviorDecision> {
129
+ if (!this.capture.enabled) return invoke();
130
+ return this.capture.run('decide', {
131
+ behavior_id: this.behaviorId, activation_id: this.activationId, instance_generation: this.instanceGeneration,
132
+ epoch_id: input.epochId, tick: input.gameState.tick, game_id: input.gameState.game_id,
133
+ session_id: input.scope.sessionId, segment_id: input.scope.segmentId, execution: this.execution,
134
+ }, { frame: input, observation: observationSnapshot }, invoke, signal);
117
135
  }
118
136
 
119
137
  stop(reason: 'switched' | 'scope_ended' | 'shutdown' = 'switched'): Promise<void> {
@@ -15,6 +15,7 @@ export const CLAUDE_CHANNEL_CONSUMER_ID = CLAUDE_CHANNEL_MAILBOX_CONSUMER_ID;
15
15
  export const CLAUDE_CHANNEL_COALESCE_MS = 220;
16
16
 
17
17
  export interface ClaudeChannelMailboxAdapterOptions {
18
+ onDelivered?: (events: readonly CanonicalEvent[]) => void;
18
19
  repository: EventRepository;
19
20
  readyView: () => RuntimeReadyView;
20
21
  consumerId?: string;
@@ -39,6 +40,7 @@ export class ClaudeChannelMailboxAdapter implements ClawclawMailboxDriver {
39
40
  consumerId: this.consumerId,
40
41
  };
41
42
  this.coordinator = new AgentMailboxCoordinator({
43
+ onDelivered: options.onDelivered,
42
44
  repository: options.repository,
43
45
  readyView: options.readyView,
44
46
  presentEvent: presentCanonicalEventForChannel,
@@ -56,14 +56,22 @@ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
56
56
  };
57
57
 
58
58
  private stopped = false;
59
+ private sessionId?: string;
60
+ private readonly reported = new Set<string>();
59
61
 
60
62
  constructor(private readonly options: GameSyncPerceptionReportAdapterOptions) {}
61
63
 
62
- observeEvents(events: readonly CanonicalEvent[]): void {
64
+ /** Called only at Agent delivery, including Monitor backlog notification. */
65
+ reportDelivered(events: readonly CanonicalEvent[]): void {
63
66
  if (this.stopped) return;
64
67
  let skipped = 0;
65
68
  const reports: GameSyncPerceptionReport[] = [];
66
69
  for (const event of events) {
70
+ if (this.sessionId !== event.sessionId) {
71
+ this.sessionId = event.sessionId;
72
+ this.reported.clear();
73
+ }
74
+ if (this.reported.has(event.eventId)) continue;
67
75
  if (
68
76
  event.producerPluginId !== this.options.producerPluginId
69
77
  || event.deliveryClass === 'internal_only'
@@ -75,6 +83,7 @@ export class GameSyncPerceptionReportAdapter implements ClawclawMailboxDriver {
75
83
  skipped += 1;
76
84
  continue;
77
85
  }
86
+ this.reported.add(event.eventId);
78
87
  reports.push({
79
88
  id: uuidForEvent(event),
80
89
  name: descriptor.name.trim(),
@@ -51,6 +51,8 @@ export interface AgentMailboxCoordinatorOptions {
51
51
  state: Record<string, any> | null | undefined,
52
52
  events?: Array<Record<string, any>>,
53
53
  ) => Record<string, any> | null;
54
+ /** Best-effort observer after this consumer accepts a batch. */
55
+ onDelivered?: (events: readonly CanonicalEvent[]) => void;
54
56
  /** Adapter-specific selection; omitted adapters receive every Agent-visible Event. */
55
57
  eventFilter?: (
56
58
  event: CanonicalEvent,
@@ -164,6 +166,7 @@ function compactBehaviorStateForAgent(
164
166
  */
165
167
  export class AgentMailboxCoordinator {
166
168
  readonly adapter?: ClawclawMailboxAdapterDescriptor;
169
+ private readonly onDelivered?: AgentMailboxCoordinatorOptions['onDelivered'];
167
170
  private readonly repository: EventRepository;
168
171
  private readonly readyView: () => RuntimeReadyView;
169
172
  private readonly presentEvent: AgentMailboxCoordinatorOptions['presentEvent'];
@@ -183,6 +186,7 @@ export class AgentMailboxCoordinator {
183
186
  private stopped = false;
184
187
 
185
188
  constructor(options: AgentMailboxCoordinatorOptions) {
189
+ this.onDelivered = options.onDelivered;
186
190
  this.repository = options.repository;
187
191
  this.readyView = options.readyView;
188
192
  this.presentEvent = options.presentEvent;
@@ -255,6 +259,11 @@ export class AgentMailboxCoordinator {
255
259
  return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
256
260
  }
257
261
 
262
+ if (!options.bypassDelay && !pending.some(({ event }) => event.wakeAgent !== false)) {
263
+ this.delayWindow = undefined;
264
+ return { batch: emptyBatch(state), readyEpochSeq: ready.epochSeq };
265
+ }
266
+
258
267
  if (this.delayWindow?.sessionId !== ready.scope.sessionId) {
259
268
  this.delayWindow = {
260
269
  sessionId: ready.scope.sessionId,
@@ -375,6 +384,12 @@ export class AgentMailboxCoordinator {
375
384
  } as Parameters<EventRepository['transitionDetails']>[0];
376
385
  const changed = this.repository.transitionDetails(transition);
377
386
  if (changed !== prepared.eventIds.length) return false;
387
+ try {
388
+ this.onDelivered?.(prepared.eventIds.flatMap((id) => {
389
+ const event = this.repository.eventById(id);
390
+ return event ? [event] : [];
391
+ }));
392
+ } catch { /* Display reporting must not affect delivery ACK. */ }
378
393
  this.prepared.delete(deliveryToken);
379
394
  this.repository.releaseLease(prepared.lease);
380
395
  this.notifyPreparedSlotAvailable();
@@ -452,7 +467,7 @@ export class AgentMailboxCoordinator {
452
467
  }, this.consumerId, ['details']).filter((row) => (
453
468
  this.selectsEvent(row.event, ready.state.state)
454
469
  ));
455
- if (pending.length === 0 && this.prepared.size === 0) return true;
470
+ if (!pending.some(({ event }) => event.wakeAgent !== false) && this.prepared.size === 0) return true;
456
471
  await new Promise<void>((resolve) => {
457
472
  const timer = setTimeout(resolve, READY_VIEW_RETRY_MS);
458
473
  timer.unref?.();
@@ -471,6 +486,7 @@ export class AgentMailboxCoordinator {
471
486
  event: CanonicalEvent,
472
487
  state: Record<string, any> | null | undefined,
473
488
  ): boolean {
489
+ if (this.delegatedMonitorConsumerId && event.deliveryClass !== 'internal_only' && event.wakeAgent === false) return true;
474
490
  if (this.eventFilter(event, state)) return true;
475
491
  if (!this.delegatedMonitorConsumerId) return false;
476
492
  return this.repository.delivery(event.eventId, this.delegatedMonitorConsumerId)
@@ -7,6 +7,7 @@ import type { CanonicalEvent } from '../../../framework/events/index.js';
7
7
  import type { RuntimeReadyView } from '../../../framework/runtime.js';
8
8
  import {
9
9
  clawclawMonitorPriority,
10
+ clawclawMonitorEventPriority,
10
11
  } from '../../agent-event-policy.js';
11
12
  import { isRoomMode } from '../../../../lib/room.js';
12
13
 
@@ -31,6 +32,7 @@ export const CLAWCLAW_DETAIL_EVENT_TYPES = new Set<string>([
31
32
  export interface ClawclawMonitorItemPayload extends Record<string, unknown> {
32
33
  schema: 'clawclaw.monitor-item.v1';
33
34
  event_id: string;
35
+ monitor_priority?: number;
34
36
  ready: {
35
37
  epoch_seq: number;
36
38
  frame_seq: number;
@@ -92,6 +94,7 @@ export function monitorItemPayload(
92
94
  const fullMessage = fullMonitorMessage(presented, ready.state.state);
93
95
  return {
94
96
  schema: 'clawclaw.monitor-item.v1',
97
+ monitor_priority: clawclawMonitorEventPriority(event),
95
98
  event_id: event.eventId,
96
99
  ready: {
97
100
  epoch_seq: ready.epochSeq,
@@ -111,8 +114,8 @@ function orderedItems(items: readonly ClawclawMonitorItemPayload[]): ClawclawMon
111
114
  return items
112
115
  .map((item, index) => ({ item, index }))
113
116
  .sort((left, right) => (
114
- clawclawMonitorPriority(String(right.item.event.type ?? ''))
115
- - clawclawMonitorPriority(String(left.item.event.type ?? ''))
117
+ (right.item.monitor_priority ?? clawclawMonitorPriority(String(right.item.event.type ?? '')))
118
+ - (left.item.monitor_priority ?? clawclawMonitorPriority(String(left.item.event.type ?? '')))
116
119
  || left.index - right.index
117
120
  ))
118
121
  .map(({ item }) => item);
@@ -13,7 +13,7 @@ import {
13
13
  } from '../../../framework/mailbox/index.js';
14
14
  import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contracts.js';
15
15
  import type { RuntimeReadyView } from '../../../framework/runtime.js';
16
- import { clawclawMonitorPriority } from '../../agent-event-policy.js';
16
+ import { clawclawMonitorEventPriority } from '../../agent-event-policy.js';
17
17
  import { AgentMailboxCoordinator } from './agent-mailbox-coordinator.js';
18
18
  import type {
19
19
  ClawclawMailboxAdapterDescriptor,
@@ -59,15 +59,15 @@ const MONITOR_NOISY_VISUAL_EVENT_TYPES = new Set([
59
59
  'visual.players_moving_together',
60
60
  ]);
61
61
 
62
- function monitorEventMustRemainDirect(event: Pick<CanonicalEvent, 'type'>): boolean {
62
+ function monitorEventMustRemainDirect(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): boolean {
63
63
  return MONITOR_TERMINAL_EVENT_TYPES.has(event.type)
64
- || clawclawMonitorPriority(event.type) >= MONITOR_PROTECTED_PRIORITY;
64
+ || clawclawMonitorEventPriority(event) >= MONITOR_PROTECTED_PRIORITY;
65
65
  }
66
66
 
67
- function monitorDirectAdmissionPriority(event: Pick<CanonicalEvent, 'type'>): number {
67
+ function monitorDirectAdmissionPriority(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): number {
68
68
  return MONITOR_TERMINAL_EVENT_TYPES.has(event.type)
69
69
  ? Number.MAX_SAFE_INTEGER
70
- : clawclawMonitorPriority(event.type);
70
+ : clawclawMonitorEventPriority(event);
71
71
  }
72
72
 
73
73
  function ordinaryMonitorRetentionRank(event: Pick<CanonicalEvent, 'type' | 'commitSeq'>): number {
@@ -77,7 +77,7 @@ function ordinaryMonitorRetentionRank(event: Pick<CanonicalEvent, 'type' | 'comm
77
77
  return event.type.startsWith('visual.') ? 1 : 0;
78
78
  }
79
79
 
80
- function monitorEventIsNoisyVisual(event: Pick<CanonicalEvent, 'type'>): boolean {
80
+ function monitorEventIsNoisyVisual(event: Pick<CanonicalEvent, 'type' | 'wakeAgent'>): boolean {
81
81
  return MONITOR_NOISY_VISUAL_EVENT_TYPES.has(event.type);
82
82
  }
83
83
 
@@ -340,7 +340,7 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
340
340
  row.event.eventId,
341
341
  'short',
342
342
  ));
343
- if (unprojected.length === 0) return 0;
343
+ if (unprojected.length === 0 || !unprojected.some(({ event }) => event.wakeAgent !== false)) return 0;
344
344
 
345
345
  const nowMs = this.now();
346
346
  this.pruneMonitorAdmissionWindows(nowMs);
@@ -414,15 +414,19 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
414
414
  const noisyVisualEvents = allOrdinaryEvents
415
415
  .filter((row) => monitorEventIsNoisyVisual(row.event))
416
416
  .sort((left, right) => left.event.commitSeq - right.event.commitSeq);
417
- const directVisualCandidate = visualAdmissionAvailable ? noisyVisualEvents.at(-1) : undefined;
417
+ const directVisualCandidate = visualAdmissionAvailable ? [...noisyVisualEvents].sort((left, right) => (
418
+ clawclawMonitorEventPriority(right.event) - clawclawMonitorEventPriority(left.event)
419
+ || right.event.commitSeq - left.event.commitSeq
420
+ ))[0] : undefined;
418
421
  const coalescedVisualOverflow = directVisualCandidate
419
- ? noisyVisualEvents.slice(0, -1)
422
+ ? noisyVisualEvents.filter((row) => row !== directVisualCandidate)
420
423
  : noisyVisualEvents;
421
424
  const ordinaryEvents = allOrdinaryEvents
422
425
  .filter((row) => !monitorEventIsNoisyVisual(row.event))
423
426
  .concat(directVisualCandidate ? [directVisualCandidate] : [])
424
427
  .sort((left, right) => (
425
- ordinaryMonitorRetentionRank(left.event) - ordinaryMonitorRetentionRank(right.event)
428
+ clawclawMonitorEventPriority(right.event) - clawclawMonitorEventPriority(left.event)
429
+ || ordinaryMonitorRetentionRank(left.event) - ordinaryMonitorRetentionRank(right.event)
426
430
  || left.event.commitSeq - right.event.commitSeq
427
431
  ));
428
432
  const ordinaryDirectAdmissionCount = Math.min(
@@ -438,7 +442,10 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
438
442
  ...coalescedVisualOverflow,
439
443
  ].sort((left, right) => left.event.commitSeq - right.event.commitSeq);
440
444
  let direct = [...directProtected, ...directOrdinary]
441
- .sort((left, right) => left.event.commitSeq - right.event.commitSeq);
445
+ .sort((left, right) => (
446
+ monitorDirectAdmissionPriority(right.event) - monitorDirectAdmissionPriority(left.event)
447
+ || left.event.commitSeq - right.event.commitSeq
448
+ ));
442
449
  let dedicatedBacklogHintEventId: string | undefined;
443
450
  // A full ordinary queue still needs one durable signal. Use the first new
444
451
  // Event as that signal's factual anchor and allow one separately-budgeted
@@ -454,16 +461,18 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
454
461
  )
455
462
  && (overflow.length > 1 || (overflow.length > 0 && delegatedUnreadBefore > 0))
456
463
  ) {
457
- const firstNonVisualIndex = overflow.findIndex((row) => (
464
+ const highestPriority = Math.max(...overflow.map(({ event }) => clawclawMonitorEventPriority(event)));
465
+ const preferred = overflow.filter(({ event }) => clawclawMonitorEventPriority(event) === highestPriority);
466
+ const firstNonVisualIndex = preferred.findIndex((row) => (
458
467
  !row.event.type.startsWith('visual.')
459
468
  ));
460
469
  const hintAnchorIndex = firstNonVisualIndex >= 0
461
470
  ? firstNonVisualIndex
462
- : overflow.length - 1;
463
- const hintAnchor = overflow[hintAnchorIndex]!;
471
+ : preferred.length - 1;
472
+ const hintAnchor = preferred[hintAnchorIndex]!;
464
473
  direct = [hintAnchor];
465
474
  dedicatedBacklogHintEventId = hintAnchor.event.eventId;
466
- overflow = overflow.filter((_, index) => index !== hintAnchorIndex);
475
+ overflow = overflow.filter((row) => row !== hintAnchor);
467
476
  }
468
477
  if (direct.length === 0 && overflow.length === 0) return 0;
469
478
  // With only one newly blocked Event there is no factual anchor plus
@@ -511,6 +520,9 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
511
520
  return { coalesceKey, payload, row };
512
521
  });
513
522
  });
523
+ // Reassign only delivery slots within this batch; canonical sequence is unchanged.
524
+ const slots = entries.map(({ row }) => row.event.commitSeq).sort((a, b) => a - b);
525
+ const deliveryOrder = new Map(entries.map((entry, index) => [entry.row.event.eventId, slots[index]!]));
514
526
  const enqueue = (entry: typeof entries[number]) => {
515
527
  const event = entry.row.event;
516
528
  return this.repository.enqueueMailboxItem<Record<string, unknown>>({
@@ -527,6 +539,7 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
527
539
  segmentId: event.segmentId,
528
540
  eventId: event.eventId,
529
541
  eventCommitSeq: event.commitSeq,
542
+ deliveryOrder: deliveryOrder.get(event.eventId),
530
543
  mode: 'short',
531
544
  coalesceKey: entry.coalesceKey,
532
545
  payload: entry.payload,
@@ -623,6 +636,24 @@ export class ClawclawMailboxService implements ClawclawMailboxDriver {
623
636
  return inserted;
624
637
  }
625
638
 
639
+ /** Monitor delivery reports every perception covered by the accepted Ready batch.
640
+ * A backlog hint counts as delivery for display; detail ACK is independent.
641
+ */
642
+ monitorDeliveredEvents(eventIds: readonly string[]): CanonicalEvent[] {
643
+ const bounds = new Map<string, number>();
644
+ for (const id of eventIds) {
645
+ const item = this.repository.mailboxItemForEvent<Record<string, any>>(this.consumerId, id, 'short');
646
+ if (!item || item.state !== 'accepted') continue;
647
+ const through = Number(item.payload.ready?.event_commit_seq ?? item.eventCommitSeq);
648
+ bounds.set(item.sessionId, Math.max(bounds.get(item.sessionId) ?? 0, through));
649
+ }
650
+ const events: CanonicalEvent[] = [];
651
+ for (const [sessionId, through] of bounds) {
652
+ events.push(...this.repository.listCommittedEvents({ sessionId, maxCommitSeq: through, order: 'asc' }));
653
+ }
654
+ return events;
655
+ }
656
+
626
657
  composeMonitor(values: readonly Record<string, unknown>[]): Record<string, unknown> {
627
658
  const hasBacklog = values.some((value) => (
628
659
  !!value.backlog && typeof value.backlog === 'object'
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { DetailCapture } from '../../../observability/detail-capture.js';
2
3
  import { performance } from 'node:perf_hooks';
3
4
  import { Worker } from 'node:worker_threads';
4
5
  import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/index.js';
@@ -87,6 +88,7 @@ export interface PerceptionAnalysisThreadPoolOptions {
87
88
  }
88
89
 
89
90
  interface PendingBatch {
91
+ readonly captureRequestId?: string;
90
92
  readonly requestId: string;
91
93
  readonly jobs: readonly PerceptionAnalysisJob[];
92
94
  readonly signal: AbortSignal;
@@ -254,6 +256,26 @@ export class PerceptionAnalysisThreadPool {
254
256
  jobs: readonly PerceptionAnalysisJob[],
255
257
  signal: AbortSignal,
256
258
  ): Promise<PerceptionAnalysisBatch> {
259
+ const capture = this.detailCapture ??= new DetailCapture('perception_io',
260
+ (name, attributes, severity) => this.emitDiagnostic(name, attributes, severity));
261
+ if (!capture.enabled) return this.analyzeInternal(jobs, signal);
262
+ const requestId = randomUUID();
263
+ for (const job of jobs) capture.emit('input', () => ({ invocation_id: `${requestId}:${job.moduleId}`,
264
+ module_id: job.moduleId, operation: 'analyze', tick: job.input.frame.tick,
265
+ frame_seq: job.input.frame.frameSeq, game_id: job.input.frame.gameState.game_id, input: job.input, stage: 'requested' }));
266
+ try {
267
+ return await this.analyzeInternal(jobs, signal, requestId);
268
+ } catch (error) {
269
+ for (const job of jobs) capture.emit(signal.aborted ? 'cancelled' : 'failed', () => ({ invocation_id: `${requestId}:${job.moduleId}`,
270
+ module_id: job.moduleId, operation: 'analyze', cancelled: signal.aborted,
271
+ tick: job.input.frame.tick, frame_seq: job.input.frame.frameSeq, stage: 'batch_discarded',
272
+ error: error instanceof Error ? error.message : String(error) }));
273
+ throw error;
274
+ }
275
+ }
276
+
277
+ private detailCapture?: DetailCapture;
278
+ private async analyzeInternal(jobs: readonly PerceptionAnalysisJob[], signal: AbortSignal, captureRequestId?: string): Promise<PerceptionAnalysisBatch> {
257
279
  signal.throwIfAborted();
258
280
  await this.start();
259
281
  signal.throwIfAborted();
@@ -278,6 +300,7 @@ export class PerceptionAnalysisThreadPool {
278
300
  }
279
301
  return new Promise<PerceptionAnalysisBatch>((resolve, reject) => {
280
302
  const pending: PendingBatch = {
303
+ captureRequestId,
281
304
  requestId: randomUUID(),
282
305
  jobs,
283
306
  signal,
@@ -567,6 +590,7 @@ export class PerceptionAnalysisThreadPool {
567
590
  this.currentWorkerHeapUsedBytes(),
568
591
  );
569
592
  moduleJob.slot = undefined;
593
+ this.captureModuleResult(moduleJob, result);
570
594
  if (!batch.settled) {
571
595
  batch.results[moduleJob.index] = result;
572
596
  batch.remaining -= 1;
@@ -635,10 +659,22 @@ export class PerceptionAnalysisThreadPool {
635
659
  outcome: 'rejected',
636
660
  failure: moduleFailure(error),
637
661
  };
662
+ this.captureModuleResult(moduleJob, batch.results[moduleJob.index]!);
638
663
  batch.remaining -= 1;
639
664
  if (batch.remaining === 0) this.resolveBatch(batch);
640
665
  }
641
666
 
667
+ private captureModuleResult(job: PendingModuleJob, result: PerceptionAnalysisResult): void {
668
+ if (!job.batch.captureRequestId) return;
669
+ this.detailCapture?.emit('output', () => ({
670
+ invocation_id: `${job.batch.captureRequestId}:${job.job.moduleId}`,
671
+ worker_request_id: job.requestId, module_id: job.job.moduleId, operation: 'analyze',
672
+ tick: job.job.input.frame.tick, frame_seq: job.job.input.frame.frameSeq,
673
+ game_id: job.job.input.frame.gameState.game_id, outcome: result.outcome,
674
+ stage: job.batch.settled ? 'late_result' : 'analysis_only_not_committed', output: result,
675
+ }));
676
+ }
677
+
642
678
  private failSlot(slot: WorkerSlot, error: Error): void {
643
679
  slot.readyReject?.(error);
644
680
  if (slot.current) {
@@ -17,13 +17,14 @@ export function normalizePerceptionEvents(
17
17
  !event
18
18
  || typeof event !== 'object'
19
19
  || !declared.has(event.type)
20
+ || (event.wakeAgent !== undefined && typeof event.wakeAgent !== 'boolean')
20
21
  || typeof event.dedupeKey !== 'string'
21
22
  || !event.dedupeKey
22
23
  || !event.payload
23
24
  || typeof event.payload !== 'object'
24
25
  || Array.isArray(event.payload)
25
26
  ) throw new Error(`perception_event_invalid:${index}`);
26
- return structuredClone(event);
27
+ return structuredClone({ ...event, wakeAgent: event.wakeAgent ?? manifest.wakeAgent ?? true });
27
28
  });
28
29
  assertRuntimeModuleOutputSize(events, 'perception_event_output');
29
30
  return events;
@@ -232,6 +232,7 @@ function perceptionLifecycle(frame: Readonly<PerceptionFrame>): string {
232
232
  }
233
233
 
234
234
  function hasValidPerceptionEventMetadata(manifest: ClawclawPerceptionManifest): boolean {
235
+ if (manifest.wakeAgent !== undefined && typeof manifest.wakeAgent !== 'boolean') return false;
235
236
  const metadata = manifest.eventMetadata;
236
237
  if (metadata === undefined) return true;
237
238
  if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return false;
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { DetailCapture } from '../../../observability/detail-capture.js';
2
3
  import { Worker } from 'node:worker_threads';
3
4
  import type {
4
5
  PerceptionBoundary,
@@ -241,6 +242,18 @@ export class PerceptionReducerThreadPool {
241
242
  input: PerceptionReducerOperationInput,
242
243
  signal: AbortSignal,
243
244
  ): Promise<readonly PerceptionEventProposal[]> {
245
+ const capture = this.detailCapture ??= new DetailCapture('perception_io',
246
+ (name, attributes, severity) => this.diagnostic(name, attributes, severity));
247
+ if (!capture.enabled) return this.operateInternal(moduleId, operation, input, signal);
248
+ const frame = input.frame ?? input.boundary?.through;
249
+ return capture.run(operation, { module_id: moduleId, tick: frame?.tick,
250
+ frame_seq: frame?.frameSeq, game_id: frame?.gameState.game_id }, input,
251
+ () => this.operateInternal(moduleId, operation, input, signal), signal);
252
+ }
253
+
254
+ private detailCapture?: DetailCapture;
255
+ private operateInternal(moduleId: string, operation: PerceptionReducerOperation,
256
+ input: PerceptionReducerOperationInput, signal: AbortSignal): Promise<readonly PerceptionEventProposal[]> {
244
257
  if (this.state !== 'running') {
245
258
  return Promise.reject(new Error('perception_reducer_pool_not_running'));
246
259
  }
@@ -352,6 +352,9 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
352
352
  const boundaryBaseline = literalProperty(manifestBlock, 'boundaryBaseline')?.trim();
353
353
  const localizations = literalLocalizations(manifestBlock);
354
354
  const eventMetadata = literalEventMetadata(manifestBlock);
355
+ const hasWakePolicy = /\bwakeAgent\s*:/.test(manifestBlock);
356
+ const wakeValue = /\bwakeAgent\s*:\s*(true|false)\b\s*(?=,|}|\n|\/\/|\/\*)/.exec(manifestBlock)?.[1];
357
+ if (hasWakePolicy && wakeValue === undefined) return null;
355
358
  const parallelClass = classMatch[1] === 'ClawclawParallelPerception';
356
359
  if (
357
360
  !id
@@ -388,6 +391,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
388
391
  name,
389
392
  description,
390
393
  ...(localizations === undefined ? {} : { localizations }),
394
+ ...(wakeValue === undefined ? {} : { wakeAgent: wakeValue === 'true' }),
391
395
  subjectScope: subjectScope as ClawclawPerceptionManifest['subjectScope'],
392
396
  produces,
393
397
  ...(eventMetadata === undefined ? {} : { eventMetadata }),
@@ -34,6 +34,7 @@ export interface RuntimeDataExportPaths {
34
34
  readonly inputJournal: string;
35
35
  readonly observability: string;
36
36
  readonly rawWs?: string;
37
+ readonly detailCapture?: string;
37
38
  }
38
39
 
39
40
  export type RuntimeDataExportSelection =
@@ -55,6 +56,7 @@ export interface RuntimeDataExportResult {
55
56
  readonly rowCounts: Readonly<Record<string, number>>;
56
57
  readonly diagnosticCount: number;
57
58
  readonly rawWsFrameCount: number;
59
+ readonly detailCaptureCount?: number;
58
60
  }
59
61
 
60
62
  interface GameScopeSelection {
@@ -370,6 +372,11 @@ export async function exportRuntimeData(options: RuntimeDataExportOptions): Prom
370
372
  join(diagnosticsDirectory, 'game-sync.raw-ws.jsonl'),
371
373
  options.selection.kind === 'game' ? options.selection.gameId : null,
372
374
  );
375
+ const detailCaptureCount = await exportDiagnostics(
376
+ options.paths.detailCapture ?? join(dirname(options.paths.observability), 'owner-detail.jsonl'),
377
+ join(diagnosticsDirectory, 'owner-detail.jsonl'),
378
+ scope ? new Set(scope.segmentIds) : null,
379
+ );
373
380
  const now = (options.now ?? (() => new Date()))().toISOString();
374
381
  const manifest = {
375
382
  schema: 'clawclaw.runtime-data-export.v1',
@@ -379,6 +386,7 @@ export async function exportRuntimeData(options: RuntimeDataExportOptions): Prom
379
386
  segments: scope?.segments ?? [],
380
387
  row_counts: rowCounts,
381
388
  diagnostic_count: diagnosticCount,
389
+ detail_capture_count: detailCaptureCount,
382
390
  raw_ws_frame_count: rawWsFrameCount,
383
391
  skipped_game_scoped_tables: skippedTables,
384
392
  format: 'One JSON object per line; schema.sql preserves the source table definitions.',
@@ -391,6 +399,7 @@ export async function exportRuntimeData(options: RuntimeDataExportOptions): Prom
391
399
  segmentIds: scope?.segmentIds ?? [],
392
400
  rowCounts,
393
401
  diagnosticCount,
402
+ detailCaptureCount,
394
403
  rawWsFrameCount,
395
404
  };
396
405
  completed = true;
@@ -73,6 +73,7 @@ export class EventIngress {
73
73
  ...(input.producerOutputIndex === undefined
74
74
  ? {}
75
75
  : { producerOutputIndex: input.producerOutputIndex }),
76
+ ...(input.wakeAgent === undefined ? {} : { wakeAgent: input.wakeAgent }),
76
77
  deliveryClass: policy.deliveryClass,
77
78
  occurredAt: input.occurredAt ?? receivedAt,
78
79
  receivedAt,