@myclaw163/clawclaw-cli 0.8.19 → 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.
- package/docs/configuration.md +71 -2
- package/package.json +1 -1
- package/skills/clawclaw/SKILL.md +3 -1
- package/skills/clawclaw/references/COMMANDS.md +2 -0
- package/src/commands/behavior.ts +1 -0
- package/src/commands/capability.ts +1 -0
- package/src/commands/data.ts +1 -0
- package/src/commands/load.ts +31 -2
- package/src/lib/agent-workspace-client.ts +1 -0
- package/src/lib/agent-workspace-runtime.ts +6 -0
- package/src/lib/agent-workspace-sync.ts +117 -6
- package/src/lib/capability-cloud-refresh.ts +7 -0
- package/src/lib/capability-cloud-sync.ts +11 -3
- package/src/lib/capability-workspace.ts +3 -0
- package/src/lib/diagnostics-config.ts +26 -1
- package/src/lib/hub-client.ts +6 -0
- package/src/lib/persona.ts +2 -0
- package/src/runtime/clawclaw/owner.ts +2 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +21 -0
- package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +8 -1
- package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +19 -1
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +36 -0
- package/src/runtime/clawclaw/plugins/perception/perception-reducer-thread-pool.ts +13 -0
- package/src/runtime/clawclaw/runtime-data-export.ts +9 -0
- package/src/runtime/clawclaw/runtime.ts +8 -0
- package/src/runtime/framework/events/memory-event-repository.ts +24 -1
- package/src/runtime/framework/events/runtime-resume.ts +20 -0
- package/src/runtime/framework/events/sqlite-event-repository.ts +32 -8
- package/src/runtime/framework/participation-manager.ts +10 -1
- package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +20 -1
- package/src/runtime/framework/persistence/memory-first-persistence.ts +116 -13
- package/src/runtime/framework/plugins/runtime-input-journal.ts +13 -8
- package/src/runtime/framework/runtime.ts +19 -7
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +11 -8
- package/src/runtime/observability/detail-capture.ts +123 -0
- package/src/runtime/observability/factory.ts +13 -0
- package/src/runtime/observability/recorder.ts +34 -5
|
@@ -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
|
-
|
|
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
|
|
package/src/lib/hub-client.ts
CHANGED
|
@@ -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 ?? '',
|
package/src/lib/persona.ts
CHANGED
|
@@ -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 };
|
|
@@ -861,6 +861,8 @@ export async function runClawclawOwner(
|
|
|
861
861
|
},
|
|
862
862
|
scheduler: runtime?.runtimeEpochDiagnosticSnapshot(),
|
|
863
863
|
retained_records: runtime?.runtimeRetainedRecordCounts(),
|
|
864
|
+
persistence: runtime?.runtimePersistenceDiagnostics(),
|
|
865
|
+
detail_capture: telemetry?.detailStats(),
|
|
864
866
|
behavior: {
|
|
865
867
|
...assembly.behavior.diagnosticSnapshot(),
|
|
866
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;
|
|
@@ -117,6 +117,14 @@ export function createClawclawRuntime(
|
|
|
117
117
|
eventLedgerPath: getProfileEventLedgerPath(profile),
|
|
118
118
|
stateHistoryPath: getProfileStateHistoryPath(profile),
|
|
119
119
|
inputJournalPath: getProfileInputJournalPath(profile),
|
|
120
|
+
recovery: {
|
|
121
|
+
account: { adapterId: CLAWCLAW_ADAPTER_ID, accountId: getRuntimeAccountId(profile) },
|
|
122
|
+
resume: runtimeOptions.resume, resumeKey: runtimeOptions.resumeKey,
|
|
123
|
+
initialSegment: runtimeOptions.initialSegment,
|
|
124
|
+
},
|
|
125
|
+
onDiagnostic: runtimeOptions.observability
|
|
126
|
+
? (name, attributes) => runtimeOptions.observability?.log('info', name, { ...attributes }, { component: 'runtime.persistence' })
|
|
127
|
+
: undefined,
|
|
120
128
|
onDegraded: (error, health) => runtimeOptions.observability?.error(
|
|
121
129
|
'runtime.persistence.async_degraded',
|
|
122
130
|
error,
|
|
@@ -107,7 +107,12 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
107
107
|
}
|
|
108
108
|
private nextCommitSeq = 1;
|
|
109
109
|
|
|
110
|
-
constructor(
|
|
110
|
+
constructor(
|
|
111
|
+
snapshot?: EventRepositorySnapshot,
|
|
112
|
+
private readonly archivedIdentities?: (event: CommitEventRequest['event']) => Array<{
|
|
113
|
+
event: CanonicalEvent; deliveries: EventDeliveryRecord[];
|
|
114
|
+
}>,
|
|
115
|
+
) {
|
|
111
116
|
if (snapshot) this.restore(snapshot);
|
|
112
117
|
}
|
|
113
118
|
|
|
@@ -297,6 +302,24 @@ export class MemoryEventRepository implements EventRepository, MailboxRepository
|
|
|
297
302
|
throw new Error(`Unknown event segment ${draft.segmentId} in session ${draft.sessionId}`);
|
|
298
303
|
}
|
|
299
304
|
|
|
305
|
+
// Source event IDs are global to their source, unlike epoch recovery scope.
|
|
306
|
+
// A replay of an archived fact must not consume a new in-memory sequence
|
|
307
|
+
// while the SQLite mirror deduplicates it against an older record.
|
|
308
|
+
for (const { event: archived, deliveries } of this.archivedIdentities?.(draft) ?? []) {
|
|
309
|
+
if (this.events.has(archived.eventId)) continue;
|
|
310
|
+
this.events.set(archived.eventId, archived);
|
|
311
|
+
this.eventOrder.push(archived.eventId);
|
|
312
|
+
this.eventOrder.sort((a, b) => this.events.get(a)!.commitSeq - this.events.get(b)!.commitSeq);
|
|
313
|
+
if (archived.sourceEventId) {
|
|
314
|
+
this.remoteEventIds.set(sourceEventKey(archived.sourceId, archived.sourceEventId), archived.eventId);
|
|
315
|
+
}
|
|
316
|
+
if (archived.sourceSequence) {
|
|
317
|
+
this.remoteSequences.set(sourceSequenceKey(archived.sourceId, archived.sessionId,
|
|
318
|
+
archived.segmentId, archived.sourceSequence), archived.eventId);
|
|
319
|
+
}
|
|
320
|
+
for (const delivery of deliveries) this.deliveries.set(deliveryKey(delivery.eventId, delivery.consumerId), delivery);
|
|
321
|
+
}
|
|
322
|
+
|
|
300
323
|
const duplicateId = draft.sourceEventId
|
|
301
324
|
? this.remoteEventIds.get(sourceEventKey(draft.sourceId, draft.sourceEventId))
|
|
302
325
|
: undefined;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { CurrentEventScope } from './types.js';
|
|
2
|
+
|
|
3
|
+
export interface RuntimeResumeSelection {
|
|
4
|
+
resume?: boolean;
|
|
5
|
+
resumeKey?: string;
|
|
6
|
+
initialSegment: { kind: string; identity?: string };
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Shared by startup hydration and Runtime; never hydrate a scope Runtime will reject. */
|
|
10
|
+
export function canResumeRuntimeScope(
|
|
11
|
+
current: CurrentEventScope | null,
|
|
12
|
+
options: RuntimeResumeSelection,
|
|
13
|
+
): boolean {
|
|
14
|
+
return !!options.resume && !!current && current.session.status === 'open' && (
|
|
15
|
+
(options.resumeKey !== undefined && current.session.resumeKey === options.resumeKey)
|
|
16
|
+
|| (options.initialSegment.identity !== undefined
|
|
17
|
+
&& current.segment.kind === options.initialSegment.kind
|
|
18
|
+
&& current.segment.scopeRef === options.initialSegment.identity)
|
|
19
|
+
);
|
|
20
|
+
}
|
|
@@ -296,14 +296,18 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
296
296
|
}
|
|
297
297
|
|
|
298
298
|
/** Full startup image for the memory-primary runtime. This is never used on a hot tick. */
|
|
299
|
-
snapshot(): EventRepositorySnapshot {
|
|
300
|
-
|
|
301
|
-
|
|
299
|
+
snapshot(sessionId?: string | null): EventRepositorySnapshot {
|
|
300
|
+
// undefined retains the explicit full-export API; null loads no historical payloads.
|
|
301
|
+
const where = sessionId === undefined ? '' : sessionId === null ? ' WHERE 0' : ' WHERE session_id = ?';
|
|
302
|
+
const params = typeof sessionId === 'string' ? [sessionId] : [];
|
|
303
|
+
const events = this.db.prepare(`SELECT * FROM events${where} ORDER BY commit_seq ASC`)
|
|
304
|
+
.all(...params).map(eventFromRow);
|
|
302
305
|
return {
|
|
303
|
-
sessions: this.db.prepare(
|
|
304
|
-
segments: this.db.prepare(
|
|
306
|
+
sessions: this.db.prepare(`SELECT * FROM play_sessions${where}`).all(...params).map(sessionFromRow),
|
|
307
|
+
segments: this.db.prepare(`SELECT * FROM event_segments${where}`).all(...params).map(segmentFromRow),
|
|
305
308
|
events,
|
|
306
|
-
deliveries: this.db.prepare(
|
|
309
|
+
deliveries: this.db.prepare(`SELECT * FROM event_deliveries WHERE event_id IN (SELECT event_id FROM events${where})`)
|
|
310
|
+
.all(...params).map(deliveryFromRow),
|
|
307
311
|
checkpoints: this.db.prepare('SELECT * FROM source_checkpoints').all().map(checkpointFromRow),
|
|
308
312
|
leases: this.db.prepare('SELECT * FROM consumer_leases').all().map((row) => ({
|
|
309
313
|
consumerId: String(row.consumer_id),
|
|
@@ -311,8 +315,9 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
311
315
|
ownerId: String(row.owner_id),
|
|
312
316
|
expiresAt: numberValue(row.expires_at),
|
|
313
317
|
})),
|
|
314
|
-
mailboxItems: this.db.prepare(
|
|
315
|
-
|
|
318
|
+
mailboxItems: this.db.prepare(`SELECT * FROM mailbox_items${where}`).all(...params).map(mailboxItemFromRow),
|
|
319
|
+
// The mirror uses SQLite's global sequence, not the selected session's last row.
|
|
320
|
+
nextCommitSeq: numberValue(this.db.prepare('SELECT MAX(commit_seq) AS seq FROM events').get()?.seq) + 1,
|
|
316
321
|
};
|
|
317
322
|
}
|
|
318
323
|
|
|
@@ -600,6 +605,25 @@ export class SqliteEventRepository implements EventRepository, MailboxRepository
|
|
|
600
605
|
});
|
|
601
606
|
}
|
|
602
607
|
|
|
608
|
+
/** Indexed cold-archive identity check; never materializes the historical ledger. */
|
|
609
|
+
archivedEventIdentities(
|
|
610
|
+
event: CommitEventRequest['event'],
|
|
611
|
+
loadedSessionId: string | null,
|
|
612
|
+
throughCommitSeq: number,
|
|
613
|
+
): Array<{ event: CanonicalEvent; deliveries: EventDeliveryRecord[] }> {
|
|
614
|
+
if (throughCommitSeq === 0) return [];
|
|
615
|
+
const rows = this.db.prepare(`SELECT * FROM events
|
|
616
|
+
WHERE (event_id = ? OR (source_id = ? AND source_event_id = ?))
|
|
617
|
+
AND commit_seq <= ? AND (? IS NULL OR session_id <> ?)
|
|
618
|
+
LIMIT 2`).all(event.eventId, event.sourceId, event.sourceEventId ?? null,
|
|
619
|
+
throughCommitSeq, loadedSessionId, loadedSessionId);
|
|
620
|
+
return rows.map((row) => {
|
|
621
|
+
const event = eventFromRow(row);
|
|
622
|
+
return { event, deliveries: this.db.prepare('SELECT * FROM event_deliveries WHERE event_id = ?')
|
|
623
|
+
.all(event.eventId).map(deliveryFromRow) };
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
|
|
603
627
|
eventById(eventId: string): CanonicalEvent | null {
|
|
604
628
|
const row = this.db.prepare('SELECT * FROM events WHERE event_id = ?').get(eventId);
|
|
605
629
|
return row ? eventFromRow(row) : null;
|
|
@@ -21,6 +21,15 @@ export interface ParticipationSegment {
|
|
|
21
21
|
endedAt?: string;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
export function canReuseParticipationSegment(
|
|
25
|
+
current: Pick<ParticipationSegment, 'kind' | 'identity' | 'endedAt'>,
|
|
26
|
+
kind: string,
|
|
27
|
+
identity?: string,
|
|
28
|
+
): boolean {
|
|
29
|
+
return !current.endedAt && current.kind === kind
|
|
30
|
+
&& (identity === undefined || current.identity === undefined || current.identity === identity);
|
|
31
|
+
}
|
|
32
|
+
|
|
24
33
|
export interface ParticipationSnapshot {
|
|
25
34
|
session: ParticipationSession;
|
|
26
35
|
segment: ParticipationSegment;
|
|
@@ -146,7 +155,7 @@ export class ParticipationManager {
|
|
|
146
155
|
throw new Error('Cannot activate a segment without an active session.');
|
|
147
156
|
}
|
|
148
157
|
const current = this.currentValue.segment;
|
|
149
|
-
if (
|
|
158
|
+
if (canReuseParticipationSegment(current, kind, identity)) {
|
|
150
159
|
// An omitted identity means "keep the currently known identity". This
|
|
151
160
|
// matters for room reconnect loops, where a caller may only know that it
|
|
152
161
|
// is returning to the lobby while the durable room code is already set.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { parentPort, workerData } from 'worker_threads';
|
|
1
|
+
import { parentPort, workerData, threadId } from 'worker_threads';
|
|
2
|
+
import { getHeapStatistics } from 'v8';
|
|
2
3
|
import { SqliteEventRepository } from '../events/sqlite-event-repository.js';
|
|
3
4
|
import { SqliteRuntimeInputJournal } from '../plugins/runtime-input-journal.js';
|
|
4
5
|
import { SqliteStateHistoryRepository } from '../state/history/sqlite-state-history-repository.js';
|
|
@@ -7,6 +8,7 @@ interface WorkerPaths {
|
|
|
7
8
|
eventLedgerPath: string;
|
|
8
9
|
stateHistoryPath: string;
|
|
9
10
|
inputJournalPath: string;
|
|
11
|
+
diagnostics?: boolean;
|
|
10
12
|
}
|
|
11
13
|
|
|
12
14
|
interface PersistenceOperation {
|
|
@@ -24,6 +26,21 @@ const stores = {
|
|
|
24
26
|
input: new SqliteRuntimeInputJournal(paths.inputJournalPath),
|
|
25
27
|
};
|
|
26
28
|
|
|
29
|
+
function reportMemory(): void {
|
|
30
|
+
if (!paths.diagnostics) return;
|
|
31
|
+
const memory = process.memoryUsage();
|
|
32
|
+
parentPort?.postMessage({ type: 'diagnostics', memory: {
|
|
33
|
+
sampled_at_ms: Date.now(), thread_id: threadId,
|
|
34
|
+
heap_used_bytes: memory.heapUsed, heap_total_bytes: memory.heapTotal,
|
|
35
|
+
external_bytes: memory.external, array_buffers_bytes: memory.arrayBuffers,
|
|
36
|
+
heap_size_limit_bytes: getHeapStatistics().heap_size_limit,
|
|
37
|
+
// RSS is process-wide; never present it as this Worker's private memory.
|
|
38
|
+
} });
|
|
39
|
+
}
|
|
40
|
+
reportMemory();
|
|
41
|
+
const memoryTimer = paths.diagnostics ? setInterval(reportMemory, 5_000) : undefined;
|
|
42
|
+
memoryTimer?.unref();
|
|
43
|
+
|
|
27
44
|
parentPort?.on('message', (message: {
|
|
28
45
|
type: 'batch' | 'barrier' | 'close';
|
|
29
46
|
id: number;
|
|
@@ -44,6 +61,8 @@ parentPort?.on('message', (message: {
|
|
|
44
61
|
parentPort?.postMessage({ type: 'barrier', id: message.id });
|
|
45
62
|
return;
|
|
46
63
|
}
|
|
64
|
+
if (memoryTimer) clearInterval(memoryTimer);
|
|
65
|
+
reportMemory();
|
|
47
66
|
stores.history.close();
|
|
48
67
|
stores.input.close();
|
|
49
68
|
stores.events.close();
|