@myclaw163/clawclaw-cli 0.8.23 → 0.8.25

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 (40) hide show
  1. package/docs/custom-modules/api-reference.md +9 -4
  2. package/docs/custom-modules/behavior.md +3 -2
  3. package/docs/custom-modules/perception.md +3 -3
  4. package/package.json +1 -1
  5. package/skills/clawclaw/SKILL.md +13 -12
  6. package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +3 -1
  7. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +22 -2
  8. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +9 -4
  9. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +3 -3
  10. package/skills/clawclaw/references/STREAM.md +1 -1
  11. package/src/commands/behavior.ts +1 -0
  12. package/src/commands/load.ts +6 -5
  13. package/src/lib/agent-workspace-client.ts +3 -0
  14. package/src/lib/agent-workspace-runtime.ts +5 -3
  15. package/src/lib/agent-workspace-skills.ts +3 -2
  16. package/src/lib/agent-workspace-sync.ts +7 -1
  17. package/src/lib/capability-cloud-refresh.ts +3 -0
  18. package/src/lib/capability-cloud-sync.ts +3 -0
  19. package/src/lib/capability-discovery.ts +2 -2
  20. package/src/lib/capability-operation-name.ts +2 -0
  21. package/src/lib/capability-workspace.ts +22 -2
  22. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +8 -0
  23. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +3 -0
  24. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +123 -0
  25. package/src/runtime/clawclaw/plugins/behavior/behavior-manifest.ts +10 -2
  26. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +3 -0
  27. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
  28. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +10 -1
  29. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +11 -0
  30. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +11 -1
  31. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +23 -3
  32. package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +11 -2
  33. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +12 -4
  34. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +2 -1
  35. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +4 -1
  36. package/src/runtime/framework/plugins/contracts.ts +2 -0
  37. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +19 -0
  38. package/src/sdk/behavior-plugin/index.ts +5 -1
  39. package/src/sdk/perception-plugin/index.ts +2 -1
  40. package/src/sdk/resource-metadata.ts +5 -2
@@ -15,6 +15,7 @@ import { prepareClawclawBehavior } from './behavior-normalization.js';
15
15
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
16
16
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
17
17
  import { assertRuntimeModuleOutputSize } from '../../../framework/modules/runtime-module-output.js';
18
+ import { captureBehaviorInstance, restoreBehaviorInstance, type BehaviorInstanceSnapshot } from './behavior-instance-snapshot.js';
18
19
 
19
20
  interface BehaviorThreadWorkerData {
20
21
  readonly poolId: string;
@@ -26,6 +27,7 @@ interface BehaviorThreadWorkerData {
26
27
  }
27
28
 
28
29
  interface BehaviorThreadRunRequest {
30
+ readonly instanceSnapshot?: BehaviorInstanceSnapshot;
29
31
  readonly type: 'run';
30
32
  readonly poolId: string;
31
33
  readonly requestId: string;
@@ -137,6 +139,9 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
137
139
  if (!instance || typeof instance.decide !== 'function') {
138
140
  throw new Error('behavior_thread_instance_invalid');
139
141
  }
142
+ if (loaded.manifest.stateMode === 'snapshot' && request.instanceSnapshot) {
143
+ restoreBehaviorInstance(instance, request.instanceSnapshot);
144
+ }
140
145
  const api = createBehaviorReadApi(input, {
141
146
  onQuery: () => { queryCount += 1; },
142
147
  isActive: () => invocationActive,
@@ -146,10 +151,13 @@ async function run(request: BehaviorThreadRunRequest | BehaviorThreadStopRequest
146
151
  });
147
152
  try {
148
153
  const result = normalizeBehaviorDecision(await instance.decide(input, api), { finite: false });
154
+ const instanceSnapshot = loaded.manifest.stateMode === 'snapshot' ? captureBehaviorInstance(instance) : undefined;
155
+ if (instanceSnapshot) assertRuntimeModuleOutputSize({ result, instanceSnapshot }, 'behavior_snapshot_output');
149
156
  send({
150
157
  type: 'result',
151
158
  requestId: request.requestId,
152
159
  result,
160
+ ...(instanceSnapshot === undefined ? {} : { instanceSnapshot }),
153
161
  queryCount,
154
162
  durationMs: Math.round((performance.now() - startedAt) * 1_000) / 1_000,
155
163
  ...diagnosticMemory(),
@@ -23,6 +23,7 @@ export interface ClawclawBehaviorCatalogEntry {
23
23
  readonly localizations?: ResolvedClawclawBehaviorSource['localizations'];
24
24
  readonly inputs: ResolvedClawclawBehaviorSource['inputs'];
25
25
  readonly execution: ResolvedClawclawBehaviorSource['execution'];
26
+ readonly stateMode?: ResolvedClawclawBehaviorSource['stateMode'];
26
27
  readonly everyTicks: number;
27
28
  readonly produces?: readonly string[];
28
29
  readonly runtime?: ResolvedClawclawBehaviorSource['runtime'];
@@ -49,6 +50,7 @@ function catalogEntry(source: ResolvedClawclawBehaviorSource): ClawclawBehaviorC
49
50
  ...(source.localizations === undefined ? {} : { localizations: source.localizations }),
50
51
  inputs: source.inputs,
51
52
  execution: source.execution,
53
+ ...(source.stateMode === undefined ? {} : { stateMode: source.stateMode }),
52
54
  everyTicks: source.everyTicks,
53
55
  ...(source.produces === undefined ? {} : { produces: source.produces }),
54
56
  ...(source.runtime === undefined ? {} : { runtime: source.runtime }),
@@ -102,6 +104,7 @@ export class ClawclawBehaviorCatalog {
102
104
  manifest: deepFreezeBehaviorValue(structuredClone(prepared.manifest)),
103
105
  input: deepFreezeBehaviorValue(structuredClone(prepared.input)),
104
106
  source: prepared.source,
107
+ display: source.display,
105
108
  ...(prepared.timing === undefined ? {} : { timing: prepared.timing }),
106
109
  });
107
110
  }
@@ -0,0 +1,123 @@
1
+ import { serialize } from 'node:v8';
2
+
3
+ type Value = null | undefined | boolean | number | string | bigint | { ref: number };
4
+ interface Node {
5
+ kind: 'object' | 'array' | 'map' | 'set' | 'date';
6
+ className?: string;
7
+ nullPrototype?: boolean;
8
+ entries?: Array<[string, Value]>;
9
+ items?: Value[];
10
+ pairs?: Array<[Value, Value]>;
11
+ time?: number;
12
+ }
13
+ export interface BehaviorInstanceSnapshot { readonly nodes: readonly Node[]; }
14
+ export const MAX_BEHAVIOR_SNAPSHOT_BYTES = 1024 * 1024;
15
+
16
+ /** One activation's completed computation state; never an Action receipt or commit checkpoint. */
17
+ export class BehaviorSnapshotStore {
18
+ generation = 0;
19
+ latest?: { epochId: number; value: BehaviorInstanceSnapshot };
20
+ publish(epochId: number, value: BehaviorInstanceSnapshot, generation: number): boolean {
21
+ if (generation !== this.generation || (this.latest && epochId <= this.latest.epochId)) return false;
22
+ this.latest = { epochId, value: structuredClone(value) };
23
+ return true;
24
+ }
25
+ reset(): void { this.generation++; this.latest = undefined; }
26
+ }
27
+
28
+ function unsupported(reason: string): never { throw new Error(`behavior_snapshot_unsupported:${reason}`); }
29
+ function className(value: object): string | undefined {
30
+ const proto = Object.getPrototypeOf(value);
31
+ if (proto === null || proto === Object.prototype) return undefined;
32
+ const constructor = Object.getOwnPropertyDescriptor(proto, 'constructor')?.value;
33
+ return typeof constructor === 'function' ? constructor.name : unsupported('prototype');
34
+ }
35
+
36
+ /** Capture data only. Methods stay on fresh constructor-created instances in each Worker. */
37
+ export function captureBehaviorInstance(instance: object): BehaviorInstanceSnapshot {
38
+ const nodes: Node[] = [];
39
+ const seen = new Map<object, number>();
40
+ let stringBytes = 0;
41
+ function encode(value: unknown, depth: number): Value {
42
+ if (depth > 128) unsupported('depth');
43
+ if (typeof value === 'string') {
44
+ stringBytes += Buffer.byteLength(value);
45
+ if (stringBytes > MAX_BEHAVIOR_SNAPSHOT_BYTES) throw new Error('behavior_snapshot_too_large');
46
+ }
47
+ if (value === null || value === undefined || ['boolean', 'number', 'string', 'bigint'].includes(typeof value)) return value as Value;
48
+ if (typeof value !== 'object') unsupported(typeof value);
49
+ const object = value as object;
50
+ const prior = seen.get(object);
51
+ if (prior !== undefined) return { ref: prior };
52
+ if (nodes.length >= 10_000) throw new Error('behavior_snapshot_too_large');
53
+ const ref = nodes.length;
54
+ const node: Node = { kind: 'object' };
55
+ seen.set(object, ref); nodes.push(node);
56
+ if (Array.isArray(object)) {
57
+ node.kind = 'array'; node.items = object.map(v => encode(v, depth + 1));
58
+ } else if (object instanceof Map) {
59
+ node.kind = 'map'; node.pairs = [...object].map(([k, v]) => [encode(k, depth + 1), encode(v, depth + 1)]);
60
+ } else if (object instanceof Set) {
61
+ node.kind = 'set'; node.items = [...object].map(v => encode(v, depth + 1));
62
+ } else if (object instanceof Date) {
63
+ node.kind = 'date'; node.time = object.getTime();
64
+ } else {
65
+ node.className = className(object);
66
+ node.nullPrototype = Object.getPrototypeOf(object) === null;
67
+ node.entries = [];
68
+ for (const key of Reflect.ownKeys(object)) {
69
+ if (typeof key !== 'string') unsupported('symbol_key');
70
+ const descriptor = Object.getOwnPropertyDescriptor(object, key)!;
71
+ if (!('value' in descriptor)) unsupported('accessor');
72
+ node.entries.push([key, encode(descriptor.value, depth + 1)]);
73
+ }
74
+ }
75
+ return { ref };
76
+ }
77
+ encode(instance, 0);
78
+ const snapshot = { nodes };
79
+ if (serialize(snapshot).byteLength > MAX_BEHAVIOR_SNAPSHOT_BYTES) throw new Error('behavior_snapshot_too_large');
80
+ return snapshot;
81
+ }
82
+
83
+ /** Custom helper classes must be created by the constructor so their methods are retained. */
84
+ export function restoreBehaviorInstance(instance: object, snapshot: BehaviorInstanceSnapshot): void {
85
+ if (!Array.isArray(snapshot.nodes) || snapshot.nodes.length === 0
86
+ || snapshot.nodes.length > 10_000 || serialize(snapshot).byteLength > MAX_BEHAVIOR_SNAPSHOT_BYTES) {
87
+ throw new Error('behavior_snapshot_invalid');
88
+ }
89
+ const restored = new Map<number, any>();
90
+ function decode(value: Value, seed?: any): any {
91
+ if (value === null || typeof value !== 'object') return value;
92
+ if (restored.has(value.ref)) return restored.get(value.ref);
93
+ const node = snapshot.nodes[value.ref];
94
+ if (!node) throw new Error('behavior_snapshot_reference_invalid');
95
+ let result: any;
96
+ if (node.kind === 'array') result = [];
97
+ else if (node.kind === 'map') result = new Map();
98
+ else if (node.kind === 'set') result = new Set();
99
+ else if (node.kind === 'date') result = new Date(node.time!);
100
+ else if (node.className) {
101
+ if (!seed || typeof seed !== 'object' || className(seed) !== node.className) unsupported(`class_template:${node.className}`);
102
+ result = seed;
103
+ } else result = node.nullPrototype ? Object.create(null) : {};
104
+ restored.set(value.ref, result);
105
+ if (node.kind === 'object') {
106
+ const keys = new Set(node.entries!.map(([key]) => key));
107
+ for (const key of Object.getOwnPropertyNames(result)) if (!keys.has(key)) {
108
+ if (!Reflect.deleteProperty(result, key)) unsupported('nonconfigurable_field');
109
+ }
110
+ for (const [key, entry] of node.entries!) {
111
+ const initial = Object.getOwnPropertyDescriptor(result, key);
112
+ const decoded = decode(entry, initial && 'value' in initial ? initial.value : undefined);
113
+ Object.defineProperty(result, key, { value: decoded, enumerable: true, writable: true, configurable: true });
114
+ }
115
+ } else if (node.kind === 'array') node.items!.forEach((v, i) => { result[i] = decode(v, seed?.[i]); });
116
+ else if (node.kind === 'set') for (const v of node.items!) result.add(decode(v));
117
+ else if (node.kind === 'map') for (const [k, v] of node.pairs!) {
118
+ const key = decode(k); result.set(key, decode(v, seed instanceof Map ? seed.get(key) : undefined));
119
+ }
120
+ return result;
121
+ }
122
+ decode({ ref: 0 }, instance);
123
+ }
@@ -18,6 +18,7 @@ const MANIFEST_FIELDS = new Set([
18
18
  'localizations',
19
19
  'inputs',
20
20
  'execution',
21
+ 'stateMode',
21
22
  'everyTicks',
22
23
  'produces',
23
24
  'runtime',
@@ -118,7 +119,7 @@ export function normalizeClawclawBehaviorManifest(
118
119
  );
119
120
  const id = nonEmpty(manifest.id) ? manifest.id.trim() : '';
120
121
  if (!BEHAVIOR_ID.test(id)) throw new Error('behavior_id_invalid');
121
- if (!nonEmpty(manifest.name)) throw new Error('behavior_name_invalid');
122
+ if (manifest.name !== undefined && !nonEmpty(manifest.name)) throw new Error('behavior_name_invalid');
122
123
  if (!nonEmpty(manifest.description)) throw new Error('behavior_description_invalid');
123
124
  if (!hasValidClawclawResourceLocalizations(
124
125
  manifest.localizations as ClawclawBehaviorManifest['localizations'],
@@ -135,6 +136,12 @@ export function normalizeClawclawBehaviorManifest(
135
136
  && manifest.execution !== 'serial'
136
137
  ) throw new Error('behavior_execution_invalid');
137
138
  const everyTicks = manifest.everyTicks ?? 1;
139
+ if (manifest.stateMode !== undefined && manifest.stateMode !== 'isolated' && manifest.stateMode !== 'snapshot') {
140
+ throw new Error('behavior_state_mode_invalid');
141
+ }
142
+ if (manifest.stateMode === 'snapshot' && manifest.execution === 'serial') {
143
+ throw new Error('behavior_snapshot_requires_parallel');
144
+ }
138
145
  if (!Number.isSafeInteger(everyTicks) || (everyTicks as number) <= 0) {
139
146
  throw new Error('behavior_every_ticks_invalid');
140
147
  }
@@ -157,10 +164,11 @@ export function normalizeClawclawBehaviorManifest(
157
164
  return deepFreezeBehaviorValue({
158
165
  apiVersion: BEHAVIOR_PLUGIN_API_VERSION,
159
166
  id,
160
- name: (manifest.name as string).trim(),
167
+ name: ((manifest.name ?? manifest.id) as string).trim(),
161
168
  description: (manifest.description as string).trim(),
162
169
  ...(localizations === undefined ? {} : { localizations }),
163
170
  inputs,
171
+ ...(manifest.stateMode === undefined ? {} : { stateMode: manifest.stateMode as 'isolated' | 'snapshot' }),
164
172
  ...(manifest.execution === undefined
165
173
  ? {}
166
174
  : { execution: manifest.execution as 'parallel' | 'serial' }),
@@ -95,6 +95,9 @@ function assertSourceParity(
95
95
  manifest: Readonly<ClawclawBehaviorManifest>,
96
96
  source: ResolvedClawclawBehaviorSource,
97
97
  ): void {
98
+ if ((manifest.stateMode ?? 'isolated') !== (source.stateMode ?? 'isolated')) {
99
+ throw new Error('behavior_state_mode_source_mismatch');
100
+ }
98
101
  if (manifest.id !== (source.declaredId ?? source.id)) throw new Error('behavior_id_source_mismatch');
99
102
  if (manifest.name !== source.name) throw new Error('behavior_name_source_mismatch');
100
103
  if (manifest.description !== source.description) {
@@ -13,6 +13,8 @@ const MIN_RUNTIME_MS = 1_000;
13
13
  const MAX_RUNTIME_MS = 120_000;
14
14
 
15
15
  export interface PreparedClawclawBehavior {
16
+ /** Host-owned display text, separate from the executable manifest. */
17
+ readonly display?: Readonly<{ name: string; description: string }>;
16
18
  /** Owner-local instance exists only for explicitly serial trusted execution. */
17
19
  readonly module?: ClawclawBehavior;
18
20
  readonly createModule?: () => ClawclawBehavior;
@@ -46,6 +46,7 @@ import type { ClawclawBehaviorCatalog } from './behavior-catalog.js';
46
46
  import { BehaviorDecisionHistory } from './behavior-decision-history.js';
47
47
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
48
48
  import { ClawclawBehaviorRunner } from './behavior-runner.js';
49
+ import { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
49
50
  import type {
50
51
  ClawclawBehaviorControlDriver,
51
52
  ClawclawBehaviorControlHandle,
@@ -134,6 +135,7 @@ export interface ClawclawBehaviorHostStatus {
134
135
  }
135
136
 
136
137
  interface ActivationRuntime {
138
+ snapshotStore?: BehaviorSnapshotStore;
137
139
  readonly activationId: string;
138
140
  readonly behaviorId: string;
139
141
  prepared: PreparedClawclawBehavior;
@@ -280,7 +282,11 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
280
282
  readonly produces: RuntimeEpochPlugin<Record<string, any>>['produces'];
281
283
  readonly capabilities = { uses: [CLAWCLAW_ACTION_CAPABILITY] } as const;
282
284
  readonly catchUp: RuntimeEpochCatchUp;
283
- readonly maxInFlight = 10;
285
+ readonly backlogPolicy = 'finish_started' as const;
286
+ get maxInFlight(): number {
287
+ const current = this.manager.current();
288
+ return current && this.runtimes.get(current.activationId)?.prepared.manifest.execution === 'serial' ? 1 : 10;
289
+ }
284
290
  readonly maxPendingEpochs = 10;
285
291
  readonly timeoutMs: number;
286
292
  readonly failurePolicy = 'failed_completion' as const;
@@ -1292,6 +1298,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1292
1298
  : {}),
1293
1299
  });
1294
1300
  runtime.runner = new ClawclawBehaviorRunner({
1301
+ snapshotStore: runtime.snapshotStore ??= new BehaviorSnapshotStore(),
1295
1302
  behaviorId: activation.behaviorId,
1296
1303
  activationId: activation.activationId,
1297
1304
  instanceGeneration: activation.instanceGeneration,
@@ -1304,6 +1311,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1304
1311
  ),
1305
1312
  });
1306
1313
  runtime.instanceGeneration = activation.instanceGeneration;
1314
+ await runtime.runner.prepare();
1307
1315
  runtime.lastCommittedBackendTick = undefined;
1308
1316
  runtime.lastStatus = undefined;
1309
1317
  runtime.committedActionDedupeKeys.clear();
@@ -1366,6 +1374,7 @@ implements RuntimeEpochPlugin<Record<string, any>>, BehaviorReflexActivationDriv
1366
1374
  id: prepared.manifest.id,
1367
1375
  name: prepared.manifest.name,
1368
1376
  description: prepared.manifest.description,
1377
+ display: prepared.display,
1369
1378
  ...(prepared.manifest.localizations === undefined
1370
1379
  ? {}
1371
1380
  : { localizations: prepared.manifest.localizations }),
@@ -11,8 +11,10 @@ import type { RuntimeDiagnosticSeverity } from '../../../framework/plugins/contr
11
11
  import type { PreparedClawclawBehavior } from './behavior-normalization.js';
12
12
  import { ThreadBehaviorExecutor } from './thread-behavior-executor.js';
13
13
  import { DetailCapture } from '../../../observability/detail-capture.js';
14
+ import type { BehaviorSnapshotStore } from './behavior-instance-snapshot.js';
14
15
 
15
16
  export interface ClawclawBehaviorRunnerOptions {
17
+ readonly snapshotStore?: BehaviorSnapshotStore;
16
18
  readonly behaviorId: string;
17
19
  readonly activationId: string;
18
20
  readonly instanceGeneration: number;
@@ -71,6 +73,13 @@ export class ClawclawBehaviorRunner {
71
73
  return this.prepared.manifest.execution ?? 'parallel';
72
74
  }
73
75
 
76
+ /** Start/import Workers at activation, outside per-decision computation deadlines. */
77
+ async prepare(): Promise<void> {
78
+ if (!this.prepared.source) return;
79
+ this.ensureThreadExecutor();
80
+ await this.parallelReady;
81
+ }
82
+
74
83
  get everyTicks(): number {
75
84
  return this.prepared.manifest.everyTicks ?? 1;
76
85
  }
@@ -172,6 +181,8 @@ export class ClawclawBehaviorRunner {
172
181
  throw new Error('behavior_thread_source_invalid');
173
182
  }
174
183
  const executor = new ThreadBehaviorExecutor({
184
+ fixedWorkers: true,
185
+ snapshotStore: this.options.snapshotStore,
175
186
  source,
176
187
  diagnostic: this.options.diagnostic,
177
188
  diagnosticsEnabled: this.options.diagnosticsEnabled,
@@ -39,6 +39,7 @@ const MANIFEST_FIELDS = new Set([
39
39
  'localizations',
40
40
  'inputs',
41
41
  'execution',
42
+ 'stateMode',
42
43
  'everyTicks',
43
44
  'produces',
44
45
  'runtime',
@@ -64,10 +65,12 @@ export interface ResolvedClawclawBehaviorSource {
64
65
  readonly declaredId?: string;
65
66
  readonly workingCopyPath?: string;
66
67
  readonly name: string;
68
+ readonly display?: Readonly<{ name: string; description: string }>;
67
69
  readonly description: string;
68
70
  readonly localizations?: ClawclawResourceLocalizations;
69
71
  readonly inputs: readonly Readonly<BehaviorInputFieldSpec>[];
70
72
  readonly execution: 'parallel' | 'serial';
73
+ readonly stateMode?: 'isolated' | 'snapshot';
71
74
  readonly everyTicks: number;
72
75
  readonly produces?: readonly string[];
73
76
  readonly runtime?: Readonly<BehaviorRuntimeDefaults>;
@@ -428,7 +431,7 @@ function sourceCompatibility(
428
431
  const descriptionProperty = literalProperty(manifest, 'description');
429
432
  const name = nameProperty.status === 'valid' && typeof nameProperty.value === 'string'
430
433
  ? nameProperty.value.trim()
431
- : '';
434
+ : nameProperty.status === 'missing' ? id : '';
432
435
  const description = descriptionProperty.status === 'valid'
433
436
  && typeof descriptionProperty.value === 'string'
434
437
  ? descriptionProperty.value.trim()
@@ -438,6 +441,9 @@ function sourceCompatibility(
438
441
  ? localizationsProperty.value as ClawclawResourceLocalizations
439
442
  : undefined;
440
443
  const executionProperty = literalProperty(manifest, 'execution');
444
+ const stateModeProperty = literalProperty(manifest, 'stateMode');
445
+ const stateMode = stateModeProperty.status === 'valid'
446
+ ? stateModeProperty.value as 'isolated' | 'snapshot' : undefined;
441
447
  const execution = executionProperty.status === 'valid' && executionProperty.value === 'serial'
442
448
  ? 'serial'
443
449
  : 'parallel';
@@ -502,6 +508,9 @@ function sourceCompatibility(
502
508
  && (!Number.isSafeInteger(everyTicksProperty.value) || (everyTicksProperty.value as number) <= 0)
503
509
  )
504
510
  ) compatibilityError = 'behavior_every_ticks_invalid';
511
+ else if (stateModeProperty.status === 'invalid'
512
+ || (stateMode !== undefined && stateMode !== 'isolated' && stateMode !== 'snapshot')) compatibilityError = 'behavior_state_mode_invalid';
513
+ else if (stateMode === 'snapshot' && execution === 'serial') compatibilityError = 'behavior_snapshot_requires_parallel';
505
514
  else if (runtimeError) compatibilityError = runtimeError;
506
515
  else if (producesProperty.status === 'invalid') compatibilityError = 'behavior_produces_invalid';
507
516
  else if (produces !== undefined) compatibilityError = behaviorProducesDiagnostic(produces);
@@ -513,6 +522,7 @@ function sourceCompatibility(
513
522
  ...(localizations === undefined ? {} : { localizations: structuredClone(localizations) }),
514
523
  inputs,
515
524
  execution,
525
+ ...(stateMode === undefined ? {} : { stateMode }),
516
526
  everyTicks,
517
527
  ...(produces === undefined ? {} : { produces: [...produces] }),
518
528
  ...(runtime === undefined ? {} : { runtime }),
@@ -18,6 +18,7 @@ import {
18
18
  } from './behavior-module-loader.js';
19
19
  import type { ResolvedClawclawBehaviorSource } from './behavior-source.js';
20
20
  import type { ClawclawBehaviorObservationSnapshot } from '../../behavior-observation-memory.js';
21
+ import { BehaviorSnapshotStore, type BehaviorInstanceSnapshot } from './behavior-instance-snapshot.js';
21
22
 
22
23
  export const PARALLEL_BEHAVIOR_THREAD_POOL_SIZE = 10;
23
24
  const INITIAL_WORKER_COUNT = 2;
@@ -33,6 +34,8 @@ const WORKER_BOOTSTRAP = realpathSync(fileURLToPath(
33
34
  const WORKER_HOST_URL = new URL('./behavior-analysis-thread-host.ts', import.meta.url).href;
34
35
 
35
36
  export interface ThreadBehaviorExecutorOptions {
37
+ readonly fixedWorkers?: boolean;
38
+ readonly snapshotStore?: BehaviorSnapshotStore;
36
39
  readonly source: ResolvedClawclawBehaviorSource;
37
40
  /** Maximum Worker count and in-flight request window. Tests may reduce it. */
38
41
  readonly poolSize?: number;
@@ -62,6 +65,8 @@ export interface ThreadBehaviorExecutorSnapshot {
62
65
  }
63
66
 
64
67
  interface PendingRequest {
68
+ snapshotEpoch?: number;
69
+ snapshotGeneration?: number;
65
70
  readonly requestId: string;
66
71
  readonly operation: 'decide';
67
72
  readonly frame: BehaviorInput;
@@ -106,6 +111,7 @@ interface WorkerReadyMessage extends WorkerMessageBase {
106
111
  }
107
112
 
108
113
  interface WorkerResultMessage extends WorkerMessageBase {
114
+ readonly instanceSnapshot?: BehaviorInstanceSnapshot;
109
115
  readonly type: 'result';
110
116
  readonly requestId: string;
111
117
  readonly result: BehaviorDecision;
@@ -238,6 +244,7 @@ export async function prepareBehaviorInWorker(
238
244
 
239
245
  /** Adaptive Worker Thread pool for cross-tick computations. */
240
246
  export class ThreadBehaviorExecutor {
247
+ private readonly snapshotStore: BehaviorSnapshotStore;
241
248
  readonly runtimeInstanceId = randomUUID();
242
249
 
243
250
  private readonly maxWorkerCount: number;
@@ -265,6 +272,7 @@ export class ThreadBehaviorExecutor {
265
272
  private readonly options: ThreadBehaviorExecutorOptions;
266
273
 
267
274
  constructor(options: ThreadBehaviorExecutorOptions) {
275
+ this.snapshotStore = options.snapshotStore ?? new BehaviorSnapshotStore();
268
276
  this.options = Object.freeze({
269
277
  ...options,
270
278
  source: pinBehaviorSource(options.source),
@@ -284,7 +292,7 @@ export class ThreadBehaviorExecutor {
284
292
  this.maxPendingRequestCount = execution === 'serial'
285
293
  ? PARALLEL_BEHAVIOR_THREAD_POOL_SIZE
286
294
  : maxWorkerCount;
287
- this.minWorkerCount = Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
295
+ this.minWorkerCount = options.fixedWorkers ? maxWorkerCount : Math.min(INITIAL_WORKER_COUNT, maxWorkerCount);
288
296
  this.desiredWorkerCount = this.minWorkerCount;
289
297
  this.idleWorkerTimeoutMs = idleWorkerTimeoutMs;
290
298
  this.maxOldGenerationSizeMb = Math.max(16, Math.min(
@@ -349,8 +357,7 @@ export class ThreadBehaviorExecutor {
349
357
  }
350
358
 
351
359
  async reset(_signal: AbortSignal): Promise<void> {
352
- // Parallel Behavior instances are already fresh per input. Only the
353
- // module/Class is cached by each slot.
360
+ this.snapshotStore.reset();
354
361
  }
355
362
 
356
363
  stop(reason: 'switched' | 'scope_ended' | 'shutdown'): Promise<void> {
@@ -555,6 +562,9 @@ export class ThreadBehaviorExecutor {
555
562
  slot.current = request;
556
563
  request.slot = slot;
557
564
  request.assignedAt = performance.now();
565
+ const inherited = this.options.source.stateMode === 'snapshot' ? this.snapshotStore.latest : undefined;
566
+ request.snapshotEpoch = inherited?.epochId;
567
+ request.snapshotGeneration = this.snapshotStore.generation;
558
568
  try {
559
569
  slot.worker.postMessage({
560
570
  type: 'run',
@@ -562,6 +572,7 @@ export class ThreadBehaviorExecutor {
562
572
  requestId: request.requestId,
563
573
  operation: request.operation,
564
574
  frame: request.frame,
575
+ ...(inherited ? { instanceSnapshot: inherited.value } : {}),
565
576
  ...(request.observationSnapshot === undefined
566
577
  ? {}
567
578
  : { observationSnapshot: request.observationSnapshot }),
@@ -654,6 +665,15 @@ export class ThreadBehaviorExecutor {
654
665
  message: WorkerResultMessage,
655
666
  ): void {
656
667
  if (request.settled) return;
668
+ const published = this.options.source.stateMode === 'snapshot' && message.instanceSnapshot
669
+ && !request.signal.aborted && this.state === 'running'
670
+ ? this.snapshotStore.publish(request.frame.epochId, message.instanceSnapshot, request.snapshotGeneration!)
671
+ : false;
672
+ if (this.options.source.stateMode === 'snapshot') this.diagnostic('behavior.snapshot.completed', {
673
+ behavior_id: this.options.source.id, epoch_id: request.frame.epochId,
674
+ inherited_epoch_id: request.snapshotEpoch ?? null, published,
675
+ latest_completed_epoch_id: this.snapshotStore.latest?.epochId ?? null,
676
+ }, 'debug');
657
677
  request.settled = true;
658
678
  request.signal.removeEventListener('abort', request.onAbort);
659
679
  this.inFlight.delete(request);
@@ -73,6 +73,10 @@ export interface PerceptionAnalysisThreadPoolSnapshot {
73
73
  }
74
74
 
75
75
  export interface PerceptionAnalysisThreadPoolOptions {
76
+ /** Accepted frame batches, independent of the number of module-analysis Workers. */
77
+ readonly maxPendingBatches?: number;
78
+ /** Prewarm and retain the configured pool instead of importing Workers during overload. */
79
+ readonly fixedWorkers?: boolean;
76
80
  readonly modules: readonly PerceptionThreadModuleSpec[];
77
81
  readonly loader: PerceptionThreadLoaderConfig;
78
82
  readonly spatialFacts: PerceptionSpatialFacts;
@@ -189,6 +193,7 @@ export class PerceptionAnalysisThreadPool {
189
193
  private readonly poolId = randomUUID();
190
194
  private readonly minWorkers: number;
191
195
  private readonly maxWorkers: number;
196
+ private readonly maxPendingBatches: number;
192
197
  private readonly maxOldGenerationSizeMb: number;
193
198
  private state: PerceptionAnalysisThreadPoolSnapshot['state'] = 'new';
194
199
  private readonly slots = new Set<WorkerSlot>();
@@ -212,7 +217,11 @@ export class PerceptionAnalysisThreadPool {
212
217
  throw new TypeError(`maxWorkers must be between 1 and ${MAX_WORKERS}.`);
213
218
  }
214
219
  this.maxWorkers = maxWorkers;
215
- this.minWorkers = Math.min(DEFAULT_WARM_WORKERS, maxWorkers);
220
+ this.maxPendingBatches = options.maxPendingBatches ?? maxWorkers;
221
+ if (!Number.isInteger(this.maxPendingBatches) || this.maxPendingBatches < 1 || this.maxPendingBatches > MAX_WORKERS) {
222
+ throw new Error('perception_pending_batch_limit_invalid');
223
+ }
224
+ this.minWorkers = options.fixedWorkers ? maxWorkers : Math.min(DEFAULT_WARM_WORKERS, maxWorkers);
216
225
  this.maxOldGenerationSizeMb = Math.max(16, Math.min(
217
226
  256,
218
227
  Math.floor(options.maxOldGenerationSizeMb ?? 64),
@@ -290,7 +299,7 @@ export class PerceptionAnalysisThreadPool {
290
299
  workerPoolHeapUsedBytes: this.currentWorkerHeapUsedBytes(),
291
300
  };
292
301
  }
293
- if (this.inFlight.size >= this.maxWorkers) {
302
+ if (this.inFlight.size >= this.maxPendingBatches) {
294
303
  throw new Error('perception_analysis_window_full');
295
304
  }
296
305
  const configured = new Set(this.options.modules.map(({ moduleId }) => moduleId));
@@ -288,7 +288,7 @@ export function validatePerceptionManifest(
288
288
  !manifest
289
289
  || manifest.apiVersion !== PERCEPTION_PLUGIN_API_VERSION
290
290
  || !/^[a-z0-9][a-z0-9._-]*$/.test(manifest.id)
291
- || !nonEmpty(manifest.name)
291
+ || (manifest.name !== undefined && !nonEmpty(manifest.name))
292
292
  || !nonEmpty(manifest.description)
293
293
  || !hasValidClawclawResourceLocalizations(manifest.localizations)
294
294
  || !['others', 'self_and_others', 'visible_pairs', 'corpses'].includes(manifest.subjectScope)
@@ -373,6 +373,10 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
373
373
  }
374
374
  readonly maxInFlight: number;
375
375
  readonly maxPendingEpochs = 10;
376
+ readonly backlogPolicy = 'finish_started' as const;
377
+ // Includes bounded analysis queueing and ordered reducer roundtrips. A 1s
378
+ // framework default killed healthy Workers during CPU contention/recovery.
379
+ readonly timeoutMs = 5_000;
376
380
  readonly recoveryTimeoutMs = DEFAULT_PERCEPTION_RECOVERY_TIMEOUT_MS;
377
381
  readonly produces: { readonly events: readonly string[] };
378
382
 
@@ -819,7 +823,9 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
819
823
  }
820
824
 
821
825
  localizedModuleDescriptors(locale: string): ClawclawResolvedResourceMetadata[] {
822
- return this.modules.map(({ manifest }) => resolveClawclawResourceMetadata(manifest, locale));
826
+ return this.modules.map(({ manifest, source }) => resolveClawclawResourceMetadata({
827
+ ...manifest, display: source.display,
828
+ }, locale));
823
829
  }
824
830
 
825
831
  localizedModuleDescriptorForEvent(
@@ -829,7 +835,7 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
829
835
  const module = this.modules.find(({ manifest }) => manifest.produces.includes(type));
830
836
  if (!module) return undefined;
831
837
  return {
832
- ...resolveClawclawResourceMetadata(module.manifest, locale),
838
+ ...resolveClawclawResourceMetadata({ ...module.manifest, display: module.source.display }, locale),
833
839
  perceptionId: module.manifest.id,
834
840
  };
835
841
  }
@@ -1720,7 +1726,9 @@ export class ClawclawPerceptionPlugin implements RuntimeEpochPlugin<Record<strin
1720
1726
  modules: parallelCandidates.map(({ threadModule }) => threadModule),
1721
1727
  loader: this.moduleLoader.threadConfig(),
1722
1728
  spatialFacts: CLAWCLAW_PERCEPTION_SPATIAL_FACTS satisfies PerceptionSpatialFacts,
1723
- maxWorkers: this.maxInFlight,
1729
+ maxWorkers: Math.min(this.maxInFlight, Math.max(2, parallelCandidates.length)),
1730
+ maxPendingBatches: this.maxInFlight,
1731
+ fixedWorkers: true,
1724
1732
  diagnosticsEnabled: this.diagnosticsEnabled,
1725
1733
  diagnostic,
1726
1734
  });
@@ -36,6 +36,7 @@ export interface ResolvedClawclawPerceptionSource {
36
36
  readonly declaredId?: string;
37
37
  readonly workingCopyPath?: string;
38
38
  readonly name: string;
39
+ readonly display?: Readonly<{ name: string; description: string }>;
39
40
  readonly description: string;
40
41
  readonly manifest: ClawclawPerceptionManifest;
41
42
  readonly sourcePath: string;
@@ -344,7 +345,7 @@ function parseSource(sourcePath: string, sourceRoot: string): ResolvedClawclawPe
344
345
 
345
346
  const apiVersion = literalPluginApiVersion(manifestBlock) ?? null;
346
347
  const id = literalProperty(manifestBlock, 'id')?.trim();
347
- const name = literalProperty(manifestBlock, 'name')?.trim();
348
+ const name = literalProperty(manifestBlock, 'name')?.trim() ?? id;
348
349
  const description = literalProperty(manifestBlock, 'description')?.trim();
349
350
  const subjectScope = literalProperty(manifestBlock, 'subjectScope')?.trim();
350
351
  const produces = literalStringArray(manifestBlock, 'produces');
@@ -245,6 +245,7 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
245
245
  return this.threaded ? 10 : 1;
246
246
  }
247
247
  readonly maxPendingEpochs = 10;
248
+ readonly backlogPolicy = 'finish_started' as const;
248
249
  readonly timeoutMs = DEFAULT_TRIGGER_PLUGIN_TIMEOUT_MS;
249
250
  readonly failurePolicy = 'failed_completion' as const;
250
251
 
@@ -736,7 +737,9 @@ export class ClawclawTriggerPlugin implements RuntimeEpochPlugin<Record<string,
736
737
  ? 'trigger_activation_accepted'
737
738
  : selected ? `trigger_activation_rejected:${activationResult?.reason ?? 'unknown'}` : 'trigger_no_eligible_match',
738
739
  checkpoint: this.checkpoint(),
739
- ...(computed.eventCursor === undefined ? {} : {
740
+ // Earlier ordered commits may have consumed a newer watermark while this
741
+ // computation was in flight. Never move the consumption cursor backwards.
742
+ ...(computed.eventCursor === undefined || computed.eventCursor <= context.progress().eventCursor ? {} : {
740
743
  consumeEventsThroughCommitSeq: computed.eventCursor,
741
744
  }),
742
745
  };
@@ -195,6 +195,8 @@ extends RuntimePluginIdentity<'epoch'> {
195
195
  readonly after?: readonly string[];
196
196
  readonly capabilities?: RuntimePluginCapabilityDeclaration;
197
197
  readonly catchUp?: RuntimeEpochCatchUp;
198
+ /** Preserve started computations under ordinary overload, then catch up to the latest boundary. */
199
+ readonly backlogPolicy?: 'finish_started';
198
200
  /**
199
201
  * Maximum overlapping update calls, from 1 through 10. Defaults to 1.
200
202
  * Values above 1 are an explicit promise that update is re-entrant and