@myclaw163/clawclaw-cli 0.8.20 → 0.8.21

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.
@@ -11,9 +11,17 @@ export type DiagnosticsLevel = typeof DIAGNOSTICS_LEVELS[number];
11
11
  export interface DiagnosticsConfig {
12
12
  level: DiagnosticsLevel;
13
13
  allow_upload: boolean;
14
+ capture?: DiagnosticsCaptureConfig;
14
15
  }
15
16
 
16
- const TOP_LEVEL_KEYS = new Set(['level', 'allow_upload']);
17
+ export interface DiagnosticsCaptureConfig {
18
+ actions?: boolean;
19
+ behavior_io?: boolean;
20
+ perception_io?: boolean;
21
+ max_record_bytes?: number;
22
+ }
23
+
24
+ const TOP_LEVEL_KEYS = new Set(['level', 'allow_upload', 'capture']);
17
25
 
18
26
  export function defaultDiagnosticsConfig(): DiagnosticsConfig {
19
27
  return {
@@ -41,9 +49,26 @@ export function parseDiagnosticsConfig(value: unknown): DiagnosticsConfig {
41
49
  if (typeof root.allow_upload !== 'boolean') {
42
50
  throw new Error('user-data/diagnostics.json allow_upload must be a boolean.');
43
51
  }
52
+ let capture: DiagnosticsCaptureConfig | undefined;
53
+ if (root.capture !== undefined) {
54
+ const value = record(root.capture);
55
+ if (!value) throw new Error('diagnostics.capture must be an object.');
56
+ if (Object.keys(value).some(key => !['actions', 'behavior_io', 'perception_io', 'max_record_bytes'].includes(key))) {
57
+ throw new Error('Unknown diagnostics.capture field.');
58
+ }
59
+ for (const key of ['actions', 'behavior_io', 'perception_io']) {
60
+ if (value[key] !== undefined && typeof value[key] !== 'boolean') throw new Error(`diagnostics.capture.${key} must be boolean.`);
61
+ }
62
+ if (value.max_record_bytes !== undefined && (!Number.isInteger(value.max_record_bytes)
63
+ || Number(value.max_record_bytes) < 4096 || Number(value.max_record_bytes) > 4 * 1024 * 1024)) {
64
+ throw new Error('diagnostics.capture.max_record_bytes must be 4096..4194304.');
65
+ }
66
+ capture = value as DiagnosticsCaptureConfig;
67
+ }
44
68
  return {
45
69
  level: root.level as DiagnosticsLevel,
46
70
  allow_upload: root.allow_upload,
71
+ ...(capture ? { capture } : {}),
47
72
  };
48
73
  }
49
74
 
@@ -13,6 +13,7 @@ export interface ResourceStats {
13
13
 
14
14
  export interface ResourceSummary {
15
15
  id: string;
16
+ forkedFromResourceId?: string;
16
17
  type: ResourceType;
17
18
  title: string;
18
19
  description: string;
@@ -61,6 +62,7 @@ export interface ListOptions {
61
62
 
62
63
  export interface WorkspaceResourceSummary {
63
64
  workspaceItemId: string;
65
+ forkedFromResourceId?: string;
64
66
  resourceId: string;
65
67
  resourceType: ResourceType;
66
68
  title: string;
@@ -126,6 +128,7 @@ interface RawVersion {
126
128
 
127
129
  interface RawResource {
128
130
  id?: string;
131
+ forked_from_resource_id?: string | null;
129
132
  resource_id: string;
130
133
  resource_type: ResourceType;
131
134
  owner?: { id?: string; name?: string | null; avatar_url?: string | null; is_official?: boolean };
@@ -142,6 +145,7 @@ interface RawResource {
142
145
 
143
146
  interface RawWorkspaceItem {
144
147
  workspace_item_id: string;
148
+ forked_from_resource_id?: string | null;
145
149
  resource_id: string;
146
150
  resource_type: ResourceType;
147
151
  title?: string;
@@ -182,6 +186,7 @@ function toSummary(resource: RawResource): ResourceSummary {
182
186
  const owner = resource.owner ?? {};
183
187
  return {
184
188
  id: resource.resource_id ?? resource.id ?? '',
189
+ forkedFromResourceId: resource.forked_from_resource_id ?? undefined,
185
190
  type: resource.resource_type,
186
191
  title: version.title,
187
192
  description: version.description,
@@ -313,6 +318,7 @@ export class HubClient {
313
318
  return {
314
319
  items: response.data.items.map((item) => ({
315
320
  workspaceItemId: item.workspace_item_id,
321
+ forkedFromResourceId: item.forked_from_resource_id ?? undefined,
316
322
  resourceId: item.resource_id,
317
323
  resourceType: item.resource_type,
318
324
  title: item.title ?? '',
@@ -139,6 +139,8 @@ function hubPersona(
139
139
  const entry = registerDiscoveredCapability(workspaceDir, profile, {
140
140
  type: 'persona', path: working, runtimeId: basename(working, '.md'), selectedByHub: true,
141
141
  hub: { resourceId: item.resourceId, versionId: item.versionId, workspaceItemId: item.workspaceItemId,
142
+ pendingForkConflict: item.forkReconciliation?.status === 'linked' && item.resolution === 'concurrent_difference' || undefined,
143
+ ...(item.forkReconciliation?.status === 'unresolved' ? { forkRelationshipUnresolved: true } : {}),
142
144
  publisher: item.hub?.publisher ?? 'community', baseSha256: item.sourceFiles[0]?.sha256 },
143
145
  });
144
146
  return { path: working, source: 'hub', resourceId: item.resourceId, id: entry.runtimeId };
@@ -862,6 +862,7 @@ export async function runClawclawOwner(
862
862
  scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
863
863
  retained_records: runtime?.runtimeRetainedRecordCounts(),
864
864
  persistence: runtime?.runtimePersistenceDiagnostics(),
865
+ detail_capture: telemetry?.detailStats(),
865
866
  behavior: {
866
867
  ...assembly.behavior.diagnosticSnapshot(),
867
868
  effective_source: effectiveBehavior
@@ -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 type { GameClient } from '../../../../lib/game-client.js';
4
5
  import { ApiError } from '../../../../lib/http-transport.js';
@@ -31,6 +32,8 @@ export interface ClawclawActionRequest {
31
32
  audioFile?: { path: string; contentType: string };
32
33
  /** Host-only preconditions for one unified Behavior activation instance. */
33
34
  behaviorOriginEpochSeq?: number;
35
+ /** Runtime-owned operation name, for diagnostic attribution; not sent to the backend. */
36
+ behaviorOriginId?: string;
34
37
  behaviorOriginTick?: number;
35
38
  behaviorActionSafetyGeneration?: number;
36
39
  behaviorActivationGeneration?: number;
@@ -185,6 +188,7 @@ function automatedDiagnosticAttributes(
185
188
  : 'unknown',
186
189
  route: admitted.route,
187
190
  caller_kind: caller.kind,
191
+ behavior_id: request.behaviorOriginId,
188
192
  behavior_activation_id: caller.activationId,
189
193
  behavior_activation_generation: caller.activationGeneration,
190
194
  behavior_layer: caller.layer,
@@ -278,6 +282,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
278
282
  private readonly automatedProviderQueueDepths = new Map<string, number>();
279
283
 
280
284
  constructor(private readonly client: GameClient) {}
285
+ private detailCapture?: DetailCapture;
281
286
 
282
287
  attachAgentActivity(listener: () => void): void {
283
288
  this.noteAgentActivity = listener;
@@ -287,6 +292,7 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
287
292
  if (this.unregister) throw new Error('Clawclaw Action Plugin is already started.');
288
293
  this.stage = context.currentSegment().kind === 'room_lobby' ? 'room' : 'matching';
289
294
  this.diagnostic = context.diagnostic;
295
+ this.detailCapture = new DetailCapture('actions', context.diagnostic);
290
296
  this.unregister = context.capabilities.provideAction({
291
297
  capability: CLAWCLAW_ACTION_CAPABILITY,
292
298
  describeControl: describeClawclawActionControl,
@@ -347,6 +353,10 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
347
353
  queuePositionReleased = true;
348
354
  const releasedAtMs = performance.now();
349
355
  if (endpointStarted) timing.startedAtMs = releasedAtMs;
356
+ this.detailCapture?.emit(endpointStarted ? 'queue_released' : 'provider_skipped', () => ({
357
+ ...automatedDiagnosticAttributes(request, admitted, caller), action: admitted.action,
358
+ queue_wait_ms: elapsedMs(timing.queuedAtMs, releasedAtMs),
359
+ }));
350
360
  const remainingQueueDepth = Math.max(
351
361
  0,
352
362
  (this.automatedProviderQueueDepths.get(queueKey) ?? 1) - 1,
@@ -533,6 +543,8 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
533
543
  queue_depth: queued.timing.queueDepthAtAdmission,
534
544
  in_flight: queued.timing.inFlightAtAdmission,
535
545
  });
546
+ this.detailCapture?.emit('queued', () => ({ ...automatedDiagnosticAttributes(request, admitted, caller),
547
+ action: admitted.action, queue_depth: queued.timing.queueDepthAtAdmission }));
536
548
  const ownedSettlement = this.ownSettlement(
537
549
  scope,
538
550
  caller,
@@ -589,6 +601,8 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
589
601
  );
590
602
  if (rejected) return rejected;
591
603
  const pending = this.client.chatRoomConfirmed(action.text);
604
+ this.detailCapture?.emit('provider_started', () => ({ action_id: admitted.actionId,
605
+ action, caller, behavior_id: request.behaviorOriginId, route: admitted.route }));
592
606
  actionEndpointStarted = true;
593
607
  markProviderStartedOrSkipped(true);
594
608
  return acknowledgedActionResult(
@@ -604,6 +618,9 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
604
618
  );
605
619
  if (rejected) return rejected;
606
620
  const pending = this.client.submitPreparedActionConfirmed(preparedAction, context.signal);
621
+ this.detailCapture?.emit('provider_started', () => ({ action_id: admitted.actionId,
622
+ action: preparedAction, caller, behavior_id: request.behaviorOriginId,
623
+ origin_epoch_seq: request.behaviorOriginEpochSeq, origin_tick: request.behaviorOriginTick, route: admitted.route }));
607
624
  actionEndpointStarted = true;
608
625
  markProviderStartedOrSkipped(true);
609
626
  const response = await untilAborted(pending, context.signal);
@@ -650,9 +667,13 @@ export class ClawclawActionPlugin implements RuntimeEpochPlugin<Record<string, a
650
667
  // may be stopped after the Runtime starts draining, but the final provider
651
668
  // result still belongs to this Action dispatch and must remain observable.
652
669
  const diagnostic = this.diagnostic;
670
+ const detailCapture = this.detailCapture;
653
671
  const report = (result: ActionResult): ActionResult => {
654
672
  const settledAtMs = performance.now();
655
673
  const errorCode = actionResultErrorCode(result);
674
+ detailCapture?.emit('provider_settled', () => ({ action_id: actionId, action, caller,
675
+ behavior_id: request.behaviorOriginId, origin_epoch_seq: request.behaviorOriginEpochSeq,
676
+ origin_tick: request.behaviorOriginTick, result, total_duration_ms: elapsedMs(timing.queuedAtMs, settledAtMs) }));
656
677
  this.emitDiagnostic('runtime.action.provider_settled', {
657
678
  ...automatedDiagnosticAttributes(request, {
658
679
  actionId,
@@ -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', {
@@ -996,7 +1003,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
996
1003
  try {
997
1004
  const result = await context.capabilities.performAction(
998
1005
  CLAWCLAW_ACTION_CAPABILITY,
999
- request,
1006
+ { ...request, behaviorOriginId: activation.behaviorId },
1000
1007
  asActionCaller(control.caller),
1001
1008
  );
1002
1009
  context.diagnostic('behavior.action.receipt', {
@@ -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> {
@@ -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) {
@@ -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
  }
@@ -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;
@@ -1,4 +1,5 @@
1
1
  import { canResumeRuntimeScope } from './events/runtime-resume.js';
2
+ import { randomUUID as captureId } from 'node:crypto';
2
3
  import {
3
4
  ActionRegistry,
4
5
  ObservationRegistry,
@@ -962,11 +963,19 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
962
963
  ): Promise<ActionResult<R>> {
963
964
  const scope = this.assertExpectedScope(expectedScope);
964
965
  const startedAt = Date.now();
966
+ const detailId = this.observability?.captureEnabled('actions') ? captureId() : undefined;
967
+ if (detailId) this.observability?.log('debug', 'runtime.detail.actions.requested', {
968
+ request_id: detailId, capability, caller, request: action,
969
+ }, { component: 'runtime.actions', scope });
965
970
  try {
966
971
  const result = await this.actions.perform<A, R>(capability, action, scope, caller, {
967
972
  ...admission,
968
973
  latestAcceptedState: () => this.latestAcceptedActionState(scope),
969
974
  });
975
+ if (detailId) this.observability?.log('debug', 'runtime.detail.actions.receipt', {
976
+ request_id: detailId, capability, caller, action_id: result.actionId, result,
977
+ duration_ms: Date.now() - startedAt,
978
+ }, { component: 'runtime.actions', scope });
970
979
  const attributes = {
971
980
  capability,
972
981
  caller_kind: caller.kind,
@@ -1026,6 +1035,9 @@ implements RuntimeSourceContext<Record<string, any>, Record<string, unknown>> {
1026
1035
  return result;
1027
1036
  } catch (error) {
1028
1037
  const summary = summarizeActionError(error);
1038
+ if (detailId) this.observability?.log('debug', 'runtime.detail.actions.failed', {
1039
+ request_id: detailId, capability, caller, error, duration_ms: Date.now() - startedAt,
1040
+ }, { component: 'runtime.actions', scope });
1029
1041
  this.observability?.error('runtime.action.failed', {
1030
1042
  name: error instanceof Error ? error.name : 'ActionFailure',
1031
1043
  ...(summary.code ? { code: summary.code } : {}),
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readDiagnosticsConfig, type DiagnosticsConfig } from '../../lib/diagnostics-config.js';
3
+
4
+ export type CaptureCategory = 'actions' | 'behavior_io' | 'perception_io';
5
+ export interface DetailCaptureConfig {
6
+ actions: boolean;
7
+ behavior_io: boolean;
8
+ perception_io: boolean;
9
+ max_record_bytes: number;
10
+ }
11
+ export function resolveDetailCapture(config?: DiagnosticsConfig, env = process.env): DetailCaptureConfig {
12
+ let selected = config;
13
+ if (!selected) { try { selected = readDiagnosticsConfig(); } catch { /* fail closed */ } }
14
+ const requestedLevel = env.CLAWCLAW_OBSERVABILITY_LEVEL?.trim().toLowerCase();
15
+ const full = (requestedLevel && ['errors', 'telemetry', 'full'].includes(requestedLevel)
16
+ ? requestedLevel : selected?.level) === 'full';
17
+ const enabled = (key: CaptureCategory): boolean => {
18
+ const value = env[`CLAWCLAW_CAPTURE_${key.toUpperCase()}`];
19
+ return value === undefined ? selected?.capture?.[key] ?? full : value.trim() === '1';
20
+ };
21
+ return { actions: enabled('actions'), behavior_io: enabled('behavior_io'), perception_io: enabled('perception_io'),
22
+ max_record_bytes: selected?.capture?.max_record_bytes ?? 256 * 1024 };
23
+ }
24
+ export function detailCategory(name: string): CaptureCategory | undefined {
25
+ return /^runtime\.detail\.(actions|behavior_io|perception_io)\./.exec(name)?.[1] as CaptureCategory | undefined;
26
+ }
27
+ type Diagnostic = (name: string, attributes: Readonly<Record<string, unknown>>, severity?: 'debug' | 'info' | 'warn' | 'error') => void;
28
+
29
+ /** Opt-in, lazy, Owner-side observer. No module API, gameplay Event or cross-Worker payload is added. */
30
+ export class DetailCapture {
31
+ readonly enabled: boolean;
32
+ constructor(readonly category: CaptureCategory, private readonly diagnostic?: Diagnostic,
33
+ config?: DetailCaptureConfig) { this.enabled = !!diagnostic && (config ?? resolveDetailCapture())[category]; }
34
+ emit(phase: string, attributes: () => Record<string, unknown>): void {
35
+ if (!this.enabled) return;
36
+ try { this.diagnostic?.(`runtime.detail.${this.category}.${phase}`, attributes(), 'debug'); } catch { /* observational */ }
37
+ }
38
+ run<T>(operation: string, metadata: Record<string, unknown>, input: unknown, invoke: () => Promise<T>, signal?: AbortSignal): Promise<T> {
39
+ if (!this.enabled) return invoke();
40
+ const invocation_id = randomUUID(), started = performance.now();
41
+ const base = { ...metadata, invocation_id, operation };
42
+ this.emit('input', () => ({ ...base, input, stage: 'requested' }));
43
+ let aborted = false;
44
+ const onAbort = () => {
45
+ aborted = true;
46
+ this.emit('cancelled', () => ({ ...base, duration_ms: performance.now() - started,
47
+ error: signal?.reason instanceof Error ? signal.reason.message : 'aborted' }));
48
+ };
49
+ signal?.addEventListener('abort', onAbort, { once: true });
50
+ return (async () => {
51
+ try {
52
+ const output = await invoke();
53
+ this.emit('output', () => ({ ...base, output: output ?? null,
54
+ stage: aborted ? 'late_result' : 'computed_not_yet_runtime_committed', duration_ms: performance.now() - started }));
55
+ return output;
56
+ } catch (error) {
57
+ this.emit('failed', () => ({ ...base, error: error instanceof Error ? { name: error.name, message: error.message } : String(error),
58
+ duration_ms: performance.now() - started }));
59
+ throw error;
60
+ } finally { signal?.removeEventListener('abort', onAbort); }
61
+ })();
62
+ }
63
+ }
64
+
65
+ /** Bounded JSON snapshot: preserves gameplay payloads and IDs, always removes credentials. */
66
+ export function captureSnapshot(value: unknown, maxBytes: number): { value: unknown; truncated: boolean } {
67
+ let remaining = maxBytes, nodes = 0, truncated = false;
68
+ const seen = new WeakSet<object>();
69
+ const marker = (): string => { truncated = true; return '[TRUNCATED]'; };
70
+ const secret = /(?:^|_)(?:api_key|claw_key|token|access_token|refresh_token|authorization|cookie|password|passwd|secret|private_key|credential|env|environment)(?:_value)?$/i;
71
+ const visit = (item: unknown, key = '', depth = 0): unknown => {
72
+ if (++nodes > 20000 || remaining <= 0 || depth > 32) return marker();
73
+ remaining -= Buffer.byteLength(key) * 6 + 16;
74
+ if (secret.test(key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').replace(/[^A-Za-z0-9]+/g, '_'))) return '[REDACTED]';
75
+ if (item === null || item === undefined) return item ?? null;
76
+ if (typeof item === 'boolean' || typeof item === 'number') return item;
77
+ if (typeof item === 'string') {
78
+ const limit = Math.max(0, Math.floor(remaining / 6));
79
+ const cut = item.length > limit;
80
+ const text = item.slice(0, limit)
81
+ .replace(/\bBearer\s+[^\s"']+/gi, 'Bearer [REDACTED]')
82
+ .replace(/\b(?:sk-|claw_|ghp_|github_pat_)[A-Za-z0-9_-]+/g, '[REDACTED]')
83
+ .replace(/([?&](?:token|key|code|api_key|access_token)=)[^&\s"']+/gi, '$1[REDACTED]');
84
+ remaining -= text.length * 6;
85
+ return cut ? text + marker() : text;
86
+ }
87
+ if (typeof item !== 'object') return `[${typeof item}_OMITTED]`;
88
+ if (item instanceof Error) {
89
+ const field = (name: string, fallback: string) => {
90
+ const descriptor = Object.getOwnPropertyDescriptor(item, name);
91
+ return descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : fallback;
92
+ };
93
+ return visit({ name: field('name', 'Error'), message: field('message', '') }, key, depth + 1);
94
+ }
95
+ if (seen.has(item)) return '[CIRCULAR]';
96
+ if (ArrayBuffer.isView(item) || item instanceof ArrayBuffer) return '[BINARY_OMITTED]';
97
+ seen.add(item);
98
+ const out: any = Array.isArray(item) ? [] : {};
99
+ if (Array.isArray(item)) {
100
+ // JSON serializes holes as nulls. Charge them too; copying an isolated
101
+ // high index would create an enormous sparse output despite the budget.
102
+ for (let index = 0; index < item.length; index += 1) {
103
+ if (remaining <= 0 || nodes > 20000) { out.push(marker()); break; }
104
+ const descriptor = Object.getOwnPropertyDescriptor(item, String(index));
105
+ out.push(visit(descriptor ? 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]' : null, String(index), depth + 1));
106
+ }
107
+ seen.delete(item);
108
+ return out;
109
+ }
110
+ // Do not enumerate getters or run user-defined toJSON methods while logging.
111
+ for (const name in item) {
112
+ if (!Object.prototype.hasOwnProperty.call(item, name)) continue;
113
+ if (name.length > 1024) { if (Array.isArray(out)) out.push(marker()); else out.__capture_truncated = marker(); break; }
114
+ if (remaining <= 0 || nodes > 20000) { if (Array.isArray(out)) out.push(marker()); else out.__capture_truncated = marker(); break; }
115
+ const descriptor = Object.getOwnPropertyDescriptor(item, name);
116
+ const next = visit(descriptor && 'value' in descriptor ? descriptor.value : '[ACCESSOR_OMITTED]', name, depth + 1);
117
+ Object.defineProperty(out, name, { value: next, enumerable: true, configurable: true, writable: true });
118
+ }
119
+ seen.delete(item);
120
+ return out;
121
+ };
122
+ return { value: visit(value), truncated };
123
+ }
@@ -10,6 +10,7 @@ import { getProfileRuntimeStateDir, getRuntimeAccountId } from '../../lib/init-c
10
10
  import { ObservabilityRedactor } from './redaction.js';
11
11
  import { BufferedObservabilityReporter } from './reporter.js';
12
12
  import { TelemetryRecorder } from './recorder.js';
13
+ import { resolveDetailCapture } from './detail-capture.js';
13
14
  import { JsonlObservabilitySink } from './sinks.js';
14
15
  import type { RecordTelemetryInput } from './types.js';
15
16
 
@@ -159,6 +160,9 @@ export function createOwnerTelemetryRecorder(
159
160
  config = defaultDiagnosticsConfig();
160
161
  }
161
162
  const level = observabilityLevel(config, env);
163
+ const capture = resolveDetailCapture(config, env);
164
+ // A two-record batch must fit the configured file rotation budget.
165
+ capture.max_record_bytes = Math.min(capture.max_record_bytes, Math.floor(observabilityRetention(env).maxFileBytes / 2));
162
166
  const runtimeAccountId = getRuntimeAccountId(profile);
163
167
  const redactor = new ObservabilityRedactor({ hashSalt: runtimeAccountId });
164
168
  const sink = new JsonlObservabilitySink(
@@ -168,12 +172,21 @@ export function createOwnerTelemetryRecorder(
168
172
  const reporter = new BufferedObservabilityReporter(sink, {
169
173
  flushIntervalMs: options.flushIntervalMs,
170
174
  });
175
+ const detailReporter = capture.actions || capture.behavior_io || capture.perception_io
176
+ ? new BufferedObservabilityReporter(new JsonlObservabilitySink(
177
+ join(options.runtimeStateDir ?? getProfileRuntimeStateDir(profile), 'observability', 'owner-detail.jsonl'),
178
+ observabilityRetention(env),
179
+ ), { maxQueueRecords: Math.max(2, Math.floor(8 * 1024 * 1024 / capture.max_record_bytes)),
180
+ batchSize: 2, flushIntervalMs: 100 })
181
+ : undefined;
171
182
  const recorder = new TelemetryRecorder({
172
183
  enabled: true,
173
184
  process: { role: 'owner', pid: process.pid },
174
185
  reporter,
175
186
  redactor,
176
187
  sampler: (input) => observabilityInputEnabled(level, input),
188
+ capture,
189
+ detailReporter,
177
190
  });
178
191
  if (configError) {
179
192
  recorder.error('observability.config.invalid', configError, {