@myclaw163/clawclaw-cli 0.10.6 → 0.10.7

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 (55) hide show
  1. package/dist/strategy-worker/assets/clawclaw-spatial-facts.json +1383 -0
  2. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-3VLVCU6P.js +71 -0
  3. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ATQQZA4X.js +44 -0
  4. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-CF6IEQ4V.js +12 -0
  5. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-QEPKDSLE.js +278 -0
  6. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/chunk-ZQILO6OM.js +0 -0
  7. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/clawclaw-walkable.bin +0 -0
  8. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/host.js +1388 -0
  9. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-behavior-plugin.js +22 -0
  10. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-module-input.js +0 -0
  11. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-perception-plugin.js +72 -0
  12. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-sdk.js +3034 -0
  13. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-strategy-plugin.js +25 -0
  14. package/dist/strategy-worker/runtime/clawclaw/plugins/behavior/sdk-trigger-plugin.js +16 -0
  15. package/docs/custom-modules/api-reference.md +10 -8
  16. package/docs/custom-modules/perception.md +26 -3
  17. package/docs/runtime/behavior-runtime.md +3 -1
  18. package/docs/runtime/official-perception-modules.md +2 -2
  19. package/docs/user-guide/behavior.md +3 -1
  20. package/package.json +5 -3
  21. package/scripts/build-strategy-worker.mjs +28 -0
  22. package/scripts/migrate-official-perceptions.mjs +157 -0
  23. package/skills/clawclaw/SKILL.md +1 -1
  24. package/skills/clawclaw/references/BEHAVIORS.md +2 -0
  25. package/skills/clawclaw/references/TACTICS.md +4 -0
  26. package/skills/clawclaw-creator/SKILL.md +3 -1
  27. package/skills/clawclaw-creator/references/CUSTOM-MODULE-API.md +10 -8
  28. package/skills/clawclaw-creator/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +26 -3
  29. package/skills/clawclaw-creator/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  30. package/src/commands/capability.ts +4 -2
  31. package/src/commands/load.ts +5 -2
  32. package/src/lib/agent-workspace-skills.ts +12 -7
  33. package/src/lib/capability-cloud-sync.ts +13 -7
  34. package/src/lib/capability-discovery.ts +10 -3
  35. package/src/lib/capability-selection.ts +7 -0
  36. package/src/lib/package-skills.ts +11 -1
  37. package/src/runtime/clawclaw/behavior-start-control.ts +114 -0
  38. package/src/runtime/clawclaw/owner.ts +19 -4
  39. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +1 -0
  40. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +11 -6
  41. package/src/runtime/clawclaw/plugins/behavior/behavior-module-loader.ts +48 -1
  42. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +2 -0
  43. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +28 -6
  44. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +25 -3
  45. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +1 -1
  46. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +9 -0
  47. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +3 -0
  48. package/src/runtime/clawclaw/plugins/perception/module-input-boundary.ts +64 -0
  49. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +37 -49
  50. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +3 -1
  51. package/src/runtime/clawclaw/plugins/system-perception/sabotage-availability-rule.ts +2 -0
  52. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +122 -61
  53. package/src/sdk/perception-plugin/index.ts +1 -0
  54. package/src/sdk/perception-plugin/lifecycle.ts +15 -0
  55. package/src/sdk/perception-plugin/module.ts +15 -0
@@ -7,7 +7,7 @@ export { PARALLEL_STRATEGY_THREAD_POOL_SIZE as PARALLEL_BEHAVIOR_THREAD_POOL_SIZ
7
7
  export type { ThreadStrategyExecutorSnapshot as ThreadBehaviorExecutorSnapshot } from '@myclaw163/game-agent-runtime/strategy/thread-strategy-executor.js';
8
8
  export type ThreadBehaviorExecutorOptions = Omit<ThreadStrategyExecutorOptions<ResolvedClawclawBehaviorSource, BehaviorInput, ClawclawBehaviorObservationSnapshot>, 'bridge' | 'inputMetadata'>;
9
9
  export type BehaviorThreadPreparation = StrategyThreadPreparation<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>;
10
- export const prepareBehaviorInWorker = (source: ResolvedClawclawBehaviorSource, input: Readonly<Record<string,unknown>>, options: {maxOldGenerationSizeMb?: number; diagnosticsEnabled?: boolean} = {}): Promise<BehaviorThreadPreparation> =>
10
+ export const prepareBehaviorInWorker = (source: ResolvedClawclawBehaviorSource, input: Readonly<Record<string,unknown>>, options: {maxOldGenerationSizeMb?: number; diagnosticsEnabled?: boolean; retainWorker?: boolean} = {}): Promise<BehaviorThreadPreparation> =>
11
11
  prepareStrategyInWorker<ResolvedClawclawBehaviorSource, ClawclawBehaviorManifest>(source, input, {...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE});
12
12
  export class ThreadBehaviorExecutor extends ThreadStrategyExecutor<ResolvedClawclawBehaviorSource, BehaviorInput, BehaviorDecision, ClawclawBehaviorObservationSnapshot> {
13
13
  constructor(options: ThreadBehaviorExecutorOptions) { super({...options, bridge: CLAWCLAW_STRATEGY_WORKER_BRIDGE,
@@ -14,6 +14,8 @@ export interface ClawclawDerivedEventRule {
14
14
  readonly eventTypes: readonly string[];
15
15
  readonly consumes?: readonly string[];
16
16
  reset(): void;
17
+ save?(): unknown;
18
+ restore?(state: any): void;
17
19
  inspect(frame: StoredStateFrame<Record<string, any>>, events?: readonly RuntimeSourceEvent[]): RuntimeEventProposal[];
18
20
  }
19
21
 
@@ -66,6 +68,8 @@ function roomReadyPayload(room: UnknownRecord): UnknownRecord {
66
68
  }
67
69
 
68
70
  export class RoomReadyDerivedEventRule implements ClawclawDerivedEventRule {
71
+ save() { return { ready: this.ready }; }
72
+ restore(state: any) { this.ready = state?.ready === true; }
69
73
  readonly id = 'room-ready';
70
74
  readonly eventTypes = ['room_ready_to_start'] as const;
71
75
  private ready = false;
@@ -123,6 +127,9 @@ function freshGameSnapshot(
123
127
  const EMERGENCY_WARNING_THRESHOLDS = [30, 20] as const;
124
128
 
125
129
  export class EmergencyCountdownDerivedEventRule implements ClawclawDerivedEventRule {
130
+ save() { return { emergencyKey: this.emergencyKey, remainingSecs: this.remainingSecs, emittedThresholds: [...this.emittedThresholds] }; }
131
+ restore(state: any) { if (!state) return; this.emergencyKey = state.emergencyKey; this.remainingSecs = state.remainingSecs;
132
+ this.emittedThresholds.clear(); for (const value of state.emittedThresholds ?? []) this.emittedThresholds.add(value); }
126
133
  readonly id = 'emergency-countdown';
127
134
  readonly eventTypes = ['emergency_countdown_warning'] as const;
128
135
  private emergencyKey = '';
@@ -198,6 +205,8 @@ export class EmergencyCountdownDerivedEventRule implements ClawclawDerivedEventR
198
205
  }
199
206
 
200
207
  export class AbilityStateDerivedEventRule implements ClawclawDerivedEventRule {
208
+ save() { return { initialized: this.initialized, abilities: structuredClone(this.abilities) }; }
209
+ restore(state: any) { if (!state) return; this.initialized = state.initialized; this.abilities = structuredClone(state.abilities); }
201
210
  readonly id = 'ability-state';
202
211
  readonly eventTypes = [
203
212
  'ability.ready',
@@ -45,6 +45,9 @@ function proposal(type: string, frame: StoredStateFrame<Record<string, any>>, pa
45
45
  }
46
46
 
47
47
  export class PlayerChangesDerivedEventRule implements ClawclawDerivedEventRule {
48
+ save() { return { initialized: this.initialized, projection: structuredClone(this.projection), snapshots: structuredClone(this.snapshots) }; }
49
+ restore(state: any) { if (!state) return; this.initialized = state.initialized;
50
+ this.projection = structuredClone(state.projection); this.snapshots = structuredClone(state.snapshots); }
48
51
  readonly id = 'player-changes';
49
52
  readonly eventTypes = ['players_changed'] as const;
50
53
  readonly consumes = [...CLAWCLAW_GAME_STREAM_BACKEND_EVENT_TYPES, 'players_changed'];
@@ -0,0 +1,64 @@
1
+ import type { PerceptionLifecycleChange, PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
2
+ import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
3
+ import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
4
+ import { createCanonicalGameState } from '../../behavior-input.js';
5
+ import { ObservationFrameProjector } from '../../observation-frame-projector.js';
6
+
7
+ export interface PerceptionInputBaseline {
8
+ scope?: string;
9
+ gameId?: string;
10
+ phase?: string;
11
+ connectionId?: string;
12
+ connected?: boolean;
13
+ tick?: number;
14
+ alive?: boolean;
15
+ ended?: boolean;
16
+ }
17
+
18
+ /** Shared, game-owned input projection for mandatory and installed perceptions. */
19
+ export function perceptionInputBoundary(
20
+ input: RuntimeEpochPluginInput<Record<string, any>>,
21
+ previous: PerceptionInputBaseline = {},
22
+ ) {
23
+ const rawState = input.epoch.state;
24
+ const runtime = isClawclawRuntimeState(rawState) ? rawState : undefined;
25
+ const raw = clawclawComputationGameState(input.frame.state) ?? (rawState.cycle ? null : input.currentState.state);
26
+ const connected = !runtime || runtime.connection === 'connected';
27
+ const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
28
+ const frame = new ObservationFrameProjector().project(input.frame);
29
+ const scope = `${input.epoch.scope.sessionId}:${input.epoch.scope.segmentId}`;
30
+ const initial = previous.scope !== scope || !!game && previous.gameId !== game.game_id;
31
+ const recovery = !initial && connected && (previous.connected === false || previous.connectionId !== input.epoch.connectionId);
32
+ const lifecycle: PerceptionLifecycleChange[] = [];
33
+ if (initial) lifecycle.push({ kind: 'initial' });
34
+ else if (recovery) lifecycle.push({ kind: 'recovery' });
35
+ else {
36
+ if (game?.phase && previous.phase && previous.phase !== game.phase) {
37
+ lifecycle.push({ kind: 'phase_changed', from: previous.phase, to: game.phase });
38
+ }
39
+ if (previous.alive === true && game?.you?.is_alive === false) lifecycle.push({ kind: 'observer_died' });
40
+ if (!connected && previous.connected !== false) lifecycle.push({ kind: 'observation_gap' });
41
+ }
42
+ const delta = frame && previous.tick !== undefined && !initial && !recovery ? frame.tick - previous.tick : null;
43
+ // Repeated local cycles and same-tick revisions are valid; missing visual samples are explicit.
44
+ const continuous = connected && lifecycle.length === 0 && delta !== null && delta >= 0 && delta <= 3;
45
+ if (frame && !continuous && !initial && !recovery && lifecycle.length === 0) lifecycle.push({ kind: 'observation_gap' });
46
+ if (frame) Object.assign(frame, { tickDelta: delta, continuousFromPrevious: continuous });
47
+ const ended = runtime?.stage === 'ended' || game?.phase === 'game_over';
48
+ const state: PerceptionInputBaseline = { scope, connectionId: input.epoch.connectionId, connected, ended,
49
+ gameId: game?.game_id ?? previous.gameId, phase: game?.phase ?? previous.phase,
50
+ tick: frame?.tick ?? previous.tick, alive: game?.you?.is_alive ?? previous.alive };
51
+ if (runtime?.cause === 'agent_events_query') lifecycle.push({ kind: 'snapshot_requested' });
52
+ if (ended && !previous.ended) lifecycle.push({ kind: 'segment_ending' });
53
+ const common: Pick<PerceptionModuleInput, 'source' | 'scope' | 'gameState' | 'frame' | 'cycle' | 'boundary' | 'lifecycle' | 'roomState' | 'queueState' | 'nowMs'> = {
54
+ source: { epochId: input.epoch.epochSeq, frameSeq: input.frame.frameSeq, connectionId: input.epoch.connectionId,
55
+ backendTick: input.frame.backendTick, receivedAtMs: input.frame.receivedAtMs, observedAtMs: input.frame.observedAtMs },
56
+ scope: { sessionId: input.epoch.scope.sessionId, segmentId: input.epoch.scope.segmentId },
57
+ gameState: game, frame: connected ? frame : null,
58
+ ...(runtime?.cycle ? { cycle: runtime.cycle } : {}),
59
+ boundary: initial ? 'initial' : recovery ? 'recovery' : null, lifecycle,
60
+ roomState: runtime?.room ?? null, queueState: runtime?.queue ?? null,
61
+ nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs,
62
+ };
63
+ return { state, common, initial, recovery };
64
+ }
@@ -1,13 +1,11 @@
1
1
  import { normalizePerceptionStrategyNames } from '../../perception-strategy-names.js';
2
- import { prepareNotificationContent } from './notification-content.js';
2
+ import { prepareNotificationContent, notificationStateAt } from './notification-content.js';
3
3
  import { preparePerceptionNotification } from './report-content.js';
4
4
  import { isNotificationTurn } from '../../notification-turn.js';
5
- import type { RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
5
+ import type { RuntimeEpochPluginInput, RuntimeEpochPluginContext } from '../../../framework/plugins/index.js';
6
6
  import { normalizeBehaviorInput } from '../../behavior-input-fields.js';
7
7
  import { type ReactionBehaviorCandidate } from '../../reaction-behavior-resolution.js';
8
- import { ObservationFrameProjector } from '../../observation-frame-projector.js';
9
8
  import { clawclawComputationGameState, isClawclawRuntimeState } from '../../runtime-state.js';
10
- import { createCanonicalGameState } from '../../behavior-input.js';
11
9
  import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
12
10
  import type { ResolvedClawclawPerceptionSource } from './perception-source.js';
13
11
  import { PerceptionModuleRunner } from './perception-module-runner.js';
@@ -17,6 +15,7 @@ import { comparePerceptionTasks, type PerceptionTaskBaseline } from './task-base
17
15
  import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
18
16
  import type { PerceptionAdapter, PerceptionSource } from '@myclaw163/game-agent-runtime/perception/contracts.js';
19
17
  import type { ClawclawResolvedResourceMetadata } from '../../../../sdk/resource-metadata.js';
18
+ import { perceptionInputBoundary, type PerceptionInputBaseline } from './module-input-boundary.js';
20
19
  export const CLAWCLAW_PERCEPTION_MODULE_PLUGIN_ID = 'clawclaw.perception.modules';
21
20
  export { REACTION_HOST_EVENT_TYPES } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
22
21
  export interface PerceptionModulePluginOptions {
@@ -27,6 +26,7 @@ export interface PerceptionModulePluginOptions {
27
26
  runnerFactory?: (source: ResolvedClawclawPerceptionSource) => Pick<PerceptionModuleRunner, 'start' | 'evaluate' | 'stop'>;
28
27
  }
29
28
  interface GameCheckpoint {
29
+ inputBoundary?: PerceptionInputBaseline;
30
30
  gameId?: string;
31
31
  phase?: string;
32
32
  connectionId?: string;
@@ -42,55 +42,41 @@ interface GameCheckpoint {
42
42
  }
43
43
  function sourceValue(source: PerceptionSource): ResolvedClawclawPerceptionSource { return source.value as ResolvedClawclawPerceptionSource; }
44
44
  function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapter {
45
- const projector = new ObservationFrameProjector();
46
- function prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown) {
47
- let checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint;
48
- checkpoint.modules = {};
45
+ function prepare(input: RuntimeEpochPluginInput<Record<string, any>>, previous: unknown, context?: RuntimeEpochPluginContext<Record<string, any>>) {
46
+ const checkpoint = structuredClone(previous ?? { modules: {} }) as GameCheckpoint;
47
+ // The shipped host checkpoint already has this baseline under flat names.
48
+ // Recover it without pretending a running game has just been initialized.
49
+ const oldBoundary = checkpoint.gameId ? { scope: `${input.epoch.scope.sessionId}:${input.epoch.scope.segmentId}`,
50
+ gameId: checkpoint.gameId, phase: checkpoint.phase, connectionId: checkpoint.connectionId,
51
+ tick: checkpoint.previousTick, connected: true } : undefined;
52
+ const shared = perceptionInputBoundary(input, checkpoint.inputBoundary ?? oldBoundary);
49
53
  const oldGame = checkpoint.gameId, oldPhase = checkpoint.phase;
50
- const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
51
- const connected = !isClawclawRuntimeState(input.frame.state) || input.frame.state.connection === 'connected';
52
- const game = connected && raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
53
- const initial = !!game && checkpoint.gameId !== game.game_id;
54
- const boundary = initial ? 'initial' as const : checkpoint.connectionId !== undefined
55
- && checkpoint.connectionId !== input.epoch.connectionId ? 'recovery' as const : null;
56
- if (game && checkpoint.gameId !== game.game_id)
57
- checkpoint = { gameId: game.game_id, modules: {} };
58
- if ((!game && checkpoint.phase !== undefined)
59
- || (game && checkpoint.phase !== game.phase)) {
60
- checkpoint.previousTick = undefined;
61
- for (const state of Object.values(checkpoint.modules)) {
62
- state.value = undefined;
63
- for (const binding of Object.values(state.bindings)) {
64
- binding.armed = true;
65
- binding.lastAcceptedAt = undefined;
66
- binding.failedAttempt = undefined;
67
- }
68
- }
69
- checkpoint.phase = game?.phase;
70
- }
71
- const frame = projector.project(input.frame);
72
- if (frame) {
73
- const delta = checkpoint.previousTick === undefined ? null : frame.tick - checkpoint.previousTick;
74
- Object.assign(frame, { tickDelta: delta, continuousFromPrevious: delta === 1
75
- && checkpoint.connectionId === input.epoch.connectionId });
76
- checkpoint.previousTick = frame.tick;
77
- }
78
- const nowMs = input.frame.observedAtMs ?? input.frame.receivedAtMs;
79
- const facts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined).map(event => ({
54
+ const game = shared.common.gameState;
55
+ const connected = shared.state.connected === true;
56
+ const boundary = shared.common.boundary;
57
+ const frame = shared.common.frame;
58
+ const nowMs = shared.common.nowMs;
59
+ const originalFacts = input.pendingEvents.filter(event => !event.replayed && !event.notificationOf && event.producerPluginId === undefined);
60
+ const eventStates = Object.fromEntries(originalFacts.map(event => [event.eventId,
61
+ context ? notificationStateAt(context, event.epochSeq) : null]));
62
+ const facts = originalFacts.map(event => ({
80
63
  eventId: event.eventId, epochId: event.epochSeq, producer: event.producer,
81
64
  type: event.type, occurredAt: event.occurredAt, receivedAt: event.receivedAt,
82
- payload: projectTaskChoiceEventPayload(raw, event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
65
+ payload: projectTaskChoiceEventPayload(eventStates[event.eventId], event.type, event.payload), wakeAgent: event.wakeAgent, replayed: false,
83
66
  }));
84
67
  const resetScope = !!game && oldGame !== game.game_id;
85
- const resetModules = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase);
68
+ const resetBindings = (!game && oldPhase !== undefined) || (!!game && (resetScope ? undefined : oldPhase) !== game.phase);
86
69
  checkpoint.connectionId = input.epoch.connectionId;
87
- return { state: checkpoint, identity: game?.game_id, resetScope, resetModules, notificationOnly: false, nowMs,
70
+ checkpoint.inputBoundary = shared.state;
71
+ checkpoint.gameId = game?.game_id ?? oldGame;
72
+ checkpoint.phase = game?.phase;
73
+ return { state: checkpoint, identity: game?.game_id, resetScope, resetModules: false, resetBindings, notificationOnly: false, nowMs,
88
74
  reflexAllowed: !!game && game.phase === 'wandering' && game.you?.is_alive === true && connected,
89
- value: { input, game, frame, facts, boundary } };
75
+ value: { input, game, frame, facts, eventStates, boundary, common: shared.common } };
90
76
  }
91
77
  type Prepared = ReturnType<typeof prepare>['value'];
92
78
  return {
93
- reset: () => projector.reset(),
79
+ reset: () => {},
94
80
  recover: saved => {
95
81
  const value = saved as {
96
82
  adapterState?: unknown;
@@ -103,9 +89,9 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
103
89
  }
104
90
  return value.adapterState ?? { gameId: value.gameId, phase: value.phase, connectionId: value.connectionId, previousTick: value.previousTick, modules: {} };
105
91
  },
106
- prepare: (input, previous) => isNotificationTurn(input.epoch.state)
92
+ prepare: (input, previous, context) => isNotificationTurn(input.epoch.state)
107
93
  ? { state: previous, resetScope: false, resetModules: false, notificationOnly: true, nowMs: 0, reflexAllowed: false, value: null }
108
- : prepare(input, previous),
94
+ : prepare(input, previous, context),
109
95
  configure: (source, value) => normalizeBehaviorInput(value, sourceValue(source).module!.inputs ?? []),
110
96
  describe: (source, locale) => { const value = sourceValue(source); return resolveClawclawResourceMetadata({ ...value.manifest, display: value.display }, locale); },
111
97
  createRunner: (source, bindMemory) => {
@@ -114,14 +100,16 @@ function createAdapter(options: PerceptionModulePluginOptions): PerceptionAdapte
114
100
  return { start: () => runner.start(), stop: () => runner.stop(), evaluate: async (input) => normalizePerceptionStrategyNames(await runner.evaluate(input.value as PerceptionModuleInput)) };
115
101
  },
116
102
  input: (source, prepared, baseline, state, config, bindings) => {
117
- const { input, game, frame, facts, boundary } = prepared.value as Prepared;
103
+ const { input, game, frame, facts, eventStates, boundary, common } = prepared.value as Prepared;
104
+ const events = facts.filter(event => source.module.consumes?.includes(event.type));
118
105
  const comparison = comparePerceptionTasks(baseline as PerceptionTaskBaseline | undefined, input, boundary);
119
- const moduleInput: PerceptionModuleInput = { moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
106
+ const moduleInput: PerceptionModuleInput = { ...common, moduleId: source.id, scope: input.epoch.scope, gameState: game, frame,
120
107
  ...(isClawclawRuntimeState(input.epoch.state) && input.epoch.state.cycle ? { cycle: input.epoch.state.cycle } : {}),
121
- events: facts.filter(event => source.module.consumes?.includes(event.type)), nowMs: prepared.nowMs,
108
+ events, eventStates: Object.fromEntries(events.map(event => [event.eventId, eventStates[event.eventId]])), nowMs: prepared.nowMs,
122
109
  state, config, ...bindings, availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes, boundary };
123
110
  return { invocation: { scope: moduleInput.scope, value: moduleInput }, inputState: comparison.baseline,
124
- evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || moduleInput.events.length > 0 };
111
+ evaluate: !!frame || !!clawclawComputationGameState(input.frame.state) || !!common.roomState || !!common.queueState
112
+ || moduleInput.events.length > 0 || !!moduleInput.lifecycle?.length };
125
113
  },
126
114
  notification: (event, prepared, source) => {
127
115
  const { game, input } = prepared.value as Prepared;
@@ -4,6 +4,7 @@ import { ClawclawPerception, ClawclawReaction } from '../../../../sdk/perception
4
4
  import type { PerceptionModuleInput } from '../../../../sdk/perception-plugin/module.js';
5
5
  import { normalizePerceptionModuleManifest } from '../../perception-module-manifest.js';
6
6
  import { normalizeReactionManifest } from '../../reaction-manifest.js';
7
+ import { CLAWCLAW_PERCEPTION_SPATIAL_API } from './spatial-facts.js';
7
8
 
8
9
  await runPerceptionWorker<PerceptionModuleInput>(async data => {
9
10
  const Module = (await import(pathToFileURL(data.modulePath).href)).default;
@@ -13,5 +14,6 @@ await runPerceptionWorker<PerceptionModuleInput>(async data => {
13
14
  const {kind: _kind, ...common} = legacy ?? {} as any;
14
15
  const manifest = legacy ? {...common,apiVersion:3} : normalizePerceptionModuleManifest(Module.manifest);
15
16
  if (JSON.stringify(manifest) !== JSON.stringify(data.expectedManifest)) throw Error('PERCEPTION_MODULE_MANIFEST_CHANGED');
16
- return { create: () => new Module(), prepareInput: input => ({...input,events:input.events.filter(event=>manifest.consumes?.includes(event.type))}) };
17
+ return { create: () => ({ evaluate: (input, api) => new Module().evaluate(input, { ...api, spatial: CLAWCLAW_PERCEPTION_SPATIAL_API }) }),
18
+ prepareInput: input => ({...input,events:input.events.filter(event=>manifest.consumes?.includes(event.type))}) };
17
19
  });
@@ -7,6 +7,8 @@ type SabotageStatus = 'ready' | 'cooldown_charged' | 'emergency_active';
7
7
 
8
8
  /** Shared sabotage availability belongs to the game, not to a strategy instance. */
9
9
  export class SabotageAvailabilityRule implements ClawclawDerivedEventRule {
10
+ save() { return { boundary: this.boundary, status: this.status }; }
11
+ restore(state: any) { this.boundary = state?.boundary; this.status = state?.status; }
10
12
  readonly id = 'sabotage-availability';
11
13
  readonly eventTypes = ['ability.ready', 'ability.unavailable'] as const;
12
14
  private boundary?: string;
@@ -1,83 +1,144 @@
1
1
  import { prepareNotificationContent, notificationStateAt } from '../perception/notification-content.js';
2
- import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput, RuntimeEpochPluginResult, RuntimeEventProposal } from '../../../framework/plugins/index.js';
2
+ import type { RuntimeEpochPluginContext, RuntimeEpochPluginInput } from '../../../framework/plugins/index.js';
3
3
  import { CLAWCLAW_BACKEND_AGENT_EVENT_TYPES, CLAWCLAW_LOCAL_AGENT_EVENT_TYPES } from '../../../clawclaw-event-catalog.js';
4
4
  import { BUILTIN_PERCEPTION_PREFIX, CLAWCLAW_SYSTEM_CONTROL_EVENTS } from '../../notification-policy.js';
5
5
  import { AbilityStateDerivedEventRule, EmergencyCountdownDerivedEventRule, RoomReadyDerivedEventRule,
6
6
  type ClawclawDerivedEventRule } from '../derived-event/derived-event-rules.js';
7
7
  import { PlayerChangesDerivedEventRule } from '../derived-event/state-change-rules.js';
8
- import { PerceptionRuleRunner } from './rule-runner.js';
9
8
  import { defaultReminder, TASK_LIFECYCLE_FACT_TYPES } from '../../../../sdk/perception-plugin/reminder-rules.js';
10
- import { clawclawComputationGameState } from '../../runtime-state.js';
11
- import { createCanonicalGameState } from '../../behavior-input.js';
12
- import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
9
+ import { ClawclawPerception, type PerceptionModuleInput, type PerceptionModuleResult } from '../../../../sdk/perception-plugin/index.js';
10
+ import type { StoredStateFrame } from '../../../framework/state/index.js';
11
+ import type { CanonicalEvent } from '../../../framework/events/index.js';
13
12
  import { SabotageAvailabilityRule } from './sabotage-availability-rule.js';
13
+ import { PerceptionHost } from '@myclaw163/game-agent-runtime/perception/perception-host.js';
14
+ import type { PerceptionAdapter, PerceptionBoundary } from '@myclaw163/game-agent-runtime/perception/contracts.js';
15
+ import { perceptionInputBoundary, type PerceptionInputBaseline } from '../perception/module-input-boundary.js';
16
+ import { comparePerceptionTasks, type PerceptionTaskBaseline } from '../perception/task-baseline.js';
17
+ import { projectTaskChoiceEventPayload } from '../../task-choice-projection.js';
14
18
 
15
19
  export const BUILTIN_PERCEPTION_NAMES = {
16
20
  players: '玩家变化', tasks: '任务提醒', abilities: '能力变化', emergency: '紧急任务',
17
21
  flow: '房间与游戏流程', meeting: '会议', behavior: '策略消息',
18
22
  } as const;
19
23
  type Domain = keyof typeof BUILTIN_PERCEPTION_NAMES;
20
- interface TaskCheckpoint { gameId?: string; connectionId?: string }
24
+ interface NativeState { rules: Record<string, unknown> }
21
25
 
22
- /** Native mandatory perception. Public resource loadouts cannot replace or disable it. */
23
- export class SystemPerceptionPlugin extends PerceptionRuleRunner {
24
- readonly agentNotificationProducer = true;
25
- override readonly consumes: { events: readonly string[] };
26
- override readonly produces: { events: readonly string[] };
27
- readonly notificationRelay: { sourceEvents?: boolean; producerPluginIds?: readonly string[]; previousEpochOnly?: boolean };
28
- private taskState: TaskCheckpoint = {};
29
- constructor(readonly domain: Domain, private readonly forwardedTypes: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) {
30
- super(`${BUILTIN_PERCEPTION_PREFIX}${domain}`, rules);
31
- this.notificationRelay = domain === 'behavior'
32
- ? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true };
33
- this.consumes = { events: [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwardedTypes,
34
- ...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])] };
35
- this.produces = { events: [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwardedTypes,
36
- ...(domain === 'tasks' ? ['reminder.task'] : [])])] };
37
- }
38
- override start(): void { super.start(); this.taskState = {}; }
39
- override recover(context: RuntimeEpochPluginContext<Record<string, any>>): void {
40
- super.recover(context);
41
- if (this.domain === 'tasks') this.taskState = structuredClone(context.checkpoint() as TaskCheckpoint ?? {});
42
- }
43
- override update(input: RuntimeEpochPluginInput<Record<string, any>>, context: RuntimeEpochPluginContext<Record<string, any>>): RuntimeEpochPluginResult {
44
- const ruleResult = super.update(input, context);
45
- const events: RuntimeEventProposal[] = [...(ruleResult.events ?? [])];
46
- let cursor: number | undefined;
47
- for (const event of input.pendingEvents) {
48
- // A same-round Behavior output is deliberately held for the next round.
49
- // Do not move the cursor past it, even if commit order overlaps epochs.
50
- if (this.domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior'
51
- && (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break;
52
- cursor = event.commitSeq;
53
- if (event.notificationOf || !this.forwardedTypes.includes(event.type)) continue;
54
- if (this.domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
55
- events.push({ type: event.type, forwardEventId: event.eventId, dedupeKey: event.eventId, payload: {},
56
- notificationContent: prepareNotificationContent(event.type, event.payload, notificationStateAt(context, event.epochSeq), 'builtin', event) });
26
+ /** Native modules use the same evaluate/input/result contract as installed scripts. */
27
+ class NativePerceptionModule extends ClawclawPerception {
28
+ constructor(private readonly domain: Domain, private readonly forwarded: readonly string[],
29
+ private readonly rules: readonly ClawclawDerivedEventRule[]) { super(); }
30
+ override evaluate(input: Readonly<PerceptionModuleInput>): PerceptionModuleResult {
31
+ const prior = input.state as NativeState | undefined;
32
+ const source = input.source!;
33
+ const frame: StoredStateFrame<Record<string, any>> = {
34
+ frameSeq: source.frameSeq, epochSeq: source.epochId,
35
+ scope: { ...input.scope, adapterId: 'clawclaw', accountId: '' },
36
+ sourceId: 'clawclaw.perception-input', sourceKey: input.frame?.frameKey ?? `epoch:${source.epochId}`,
37
+ connectionId: source.connectionId, backendTick: source.backendTick,
38
+ receivedAtMs: source.receivedAtMs, observedAtMs: source.observedAtMs,
39
+ state: { schema: 'clawclaw.runtime-state.v1', stage: input.roomState ? 'room' : input.gameState?.phase === 'meeting' ? 'meeting' : 'game',
40
+ connection: 'connected', transport: 'none', cause: 'processing_cycle', room: input.roomState,
41
+ game_snapshot: input.gameState ? { status: 'cached', state: input.gameState } : { status: 'not_updated' } },
42
+ };
43
+ const facts = input.events.map(event => ({ type: event.type, payload: { ...event.payload }, producer: event.producer,
44
+ sourceEventId: event.eventId, observedAt: event.occurredAt, replayed: event.replayed }));
45
+ const events: NonNullable<PerceptionModuleResult['events']>[number][] = [];
46
+ const state: NativeState = { rules: {} };
47
+ for (const rule of this.rules) {
48
+ rule.reset();
49
+ if (input.boundary !== 'recovery') rule.restore?.(prior?.rules[rule.id]);
50
+ const proposals = rule.inspect(frame, facts);
51
+ state.rules[rule.id] = rule.save?.();
52
+ if (input.boundary !== 'recovery') for (const event of proposals) events.push({
53
+ type: event.type, key: event.dedupeKey ?? `${source.epochId}:${event.type}`,
54
+ payload: event.payload ?? {}, wakeAgent: event.wakeAgent, occurredAt: event.occurredAt,
55
+ });
57
56
  }
58
57
  if (this.domain === 'tasks') {
59
- const raw = clawclawComputationGameState(input.frame.state) ?? (input.epoch.state.cycle ? null : input.currentState.state);
60
- const game = raw?.game_id ? createCanonicalGameState(raw, input.frame.backendTick) : null;
61
- const boundary = game && this.taskState.gameId !== game.game_id ? 'initial'
62
- : this.taskState.connectionId !== undefined && this.taskState.connectionId !== input.epoch.connectionId ? 'recovery' : null;
63
- this.taskState = { gameId: game?.game_id ?? this.taskState.gameId, connectionId: input.epoch.connectionId };
64
- // Task facts have one notification owner. Do not recreate them from State differences.
65
- const result = defaultReminder('tasks', { scope: input.epoch.scope, gameState: game, frame: null,
66
- facts: input.pendingEvents.filter(event => !event.notificationOf && event.producerPluginId === undefined).map(event => ({
67
- eventId: event.eventId, epochId: event.epochSeq, type: event.type, occurredAt: event.occurredAt,
68
- producer: event.producer, replayed: event.replayed, payload: projectTaskChoiceEventPayload(game, event.type, event.payload),
69
- })), taskChanges: [], boundary, config: {}, state: undefined,
70
- nowMs: input.frame.observedAtMs ?? input.frame.receivedAtMs });
71
- for (const event of result.events ?? []) events.push({ type: event.type, dedupeKey: event.key,
72
- wakeAgent: event.wakeAgent, payload: { ...event.payload }, occurredAt: new Date(input.frame.receivedAtMs).toISOString() });
58
+ const result = defaultReminder('tasks', { ...input, facts: input.events, taskChanges: [], config: {} });
59
+ events.push(...result.events ?? []);
73
60
  }
74
- const notifications = events.map(event => event.notificationContent ? event : { ...event,
75
- notificationContent: prepareNotificationContent(event.type, event.payload,
76
- notificationStateAt(context, input.epoch.epochSeq), 'builtin', { producer: 'local_synth', producerPluginId: this.id }),
61
+ return { state, events, forwards: input.events.filter(event => this.forwarded.includes(event.type))
62
+ .map(event => ({ eventId: event.eventId })) };
63
+ }
64
+ }
65
+
66
+ interface PreparedNative {
67
+ input: RuntimeEpochPluginInput<Record<string, any>>;
68
+ common: ReturnType<typeof perceptionInputBoundary>['common'];
69
+ facts: CanonicalEvent[];
70
+ context: RuntimeEpochPluginContext<Record<string, any>>;
71
+ }
72
+ function nativeAdapter(domain: Domain, forwarded: readonly string[], rules: readonly ClawclawDerivedEventRule[]): PerceptionAdapter {
73
+ const module = new NativePerceptionModule(domain, forwarded, rules);
74
+ const prepared = (boundary: PerceptionBoundary) => boundary.value as PreparedNative;
75
+ return {
76
+ reset: () => {}, recover: checkpoint => (checkpoint as { adapterState?: unknown })?.adapterState,
77
+ prepare(input, previous, context) {
78
+ if (!context) throw Error('NATIVE_PERCEPTION_CONTEXT_MISSING');
79
+ const shared = perceptionInputBoundary(input, previous as PerceptionInputBaseline | undefined);
80
+ const eligible = [] as CanonicalEvent[];
81
+ let cursor = context.progress().eventCursor;
82
+ for (const event of input.pendingEvents) {
83
+ if (domain === 'behavior' && event.producerPluginId === 'clawclaw.behavior'
84
+ && (event.epochSeq ?? input.epoch.epochSeq) >= input.epoch.epochSeq) break;
85
+ cursor = event.commitSeq;
86
+ if (event.notificationOf) continue;
87
+ if (domain === 'behavior' ? event.producerPluginId !== 'clawclaw.behavior' : event.producerPluginId !== undefined) continue;
88
+ eligible.push(event);
89
+ }
90
+ return { state: shared.state, identity: shared.state.scope, resetScope: shared.initial, resetModules: false,
91
+ notificationOnly: false, nowMs: shared.common.nowMs, reflexAllowed: false, consumeEventsThroughCommitSeq: cursor,
92
+ value: { input, common: shared.common, facts: eligible, context } satisfies PreparedNative };
93
+ },
94
+ configure: (_source, config) => config, describe: source => ({ id: source.id, name: source.name }),
95
+ createRunner: () => ({ start: async () => {}, stop: async () => {},
96
+ evaluate: async invocation => module.evaluate(invocation.value as PerceptionModuleInput) }),
97
+ input(source, boundary, inputState, state, config, bindings) {
98
+ const p = prepared(boundary);
99
+ const facts = p.facts.filter(e => source.module.consumes?.includes(e.type));
100
+ const eventStates = Object.fromEntries(facts.map(e => [e.eventId, notificationStateAt(p.context, e.epochSeq)]));
101
+ const comparison = comparePerceptionTasks(inputState as PerceptionTaskBaseline | undefined, p.input, p.common.boundary);
102
+ const value: PerceptionModuleInput = { ...p.common, moduleId: source.id, config, state, ...bindings,
103
+ availableStrategies: bindings.availableBehaviors, taskChanges: comparison.changes,
104
+ events: facts.map(e => ({ eventId: e.eventId, epochId: e.epochSeq, type: e.type, occurredAt: e.occurredAt,
105
+ producer: e.producer, replayed: e.replayed, receivedAt: e.receivedAt, wakeAgent: e.wakeAgent,
106
+ payload: projectTaskChoiceEventPayload(eventStates[e.eventId], e.type, e.payload) })),
107
+ eventStates,
108
+ };
109
+ return { invocation: { scope: value.scope, value }, inputState: comparison.baseline, evaluate: true };
110
+ },
111
+ forward(eventId, boundary) {
112
+ const event = prepared(boundary).facts.find(e => e.eventId === eventId && forwarded.includes(e.type));
113
+ if (!event) throw Error('PERCEPTION_FORWARD_NOT_AUTHORIZED');
114
+ return { type: event.type, forwardEventId: eventId, dedupeKey: eventId, payload: {} };
115
+ },
116
+ notification(proposal, boundary) {
117
+ const p = prepared(boundary);
118
+ const original = proposal.forwardEventId ? p.facts.find(e => e.eventId === proposal.forwardEventId) : undefined;
119
+ return prepareNotificationContent(proposal.type, original?.payload ?? proposal.payload ?? {},
120
+ original ? notificationStateAt(p.context, original.epochSeq) : p.common.gameState,
121
+ 'builtin', original ?? { producer: 'local_synth', producerPluginId: `${BUILTIN_PERCEPTION_PREFIX}${domain}` });
122
+ },
123
+ };
124
+ }
125
+
126
+ /** Host registration, not module text, grants mandatory status and forwarding authority. */
127
+ export class SystemPerceptionPlugin extends PerceptionHost {
128
+ constructor(readonly domain: Domain, forwarded: readonly string[], rules: readonly ClawclawDerivedEventRule[] = []) {
129
+ const consumes = [...new Set([...rules.flatMap(rule => rule.consumes ?? []), ...forwarded,
130
+ ...(domain === 'tasks' ? TASK_LIFECYCLE_FACT_TYPES : [])])];
131
+ const produces = [...new Set([...rules.flatMap(rule => rule.eventTypes), ...forwarded,
132
+ ...(domain === 'tasks' ? ['reminder.task'] : [])])];
133
+ super({ id: `${BUILTIN_PERCEPTION_PREFIX}${domain}`, after: [],
134
+ sources: [{ id: domain, name: BUILTIN_PERCEPTION_NAMES[domain], module: { consumes, produces }, value: null }],
135
+ adapter: nativeAdapter(domain, forwarded, rules),
136
+ // Mandatory native rules must account for every accepted fact in a source batch.
137
+ // Custom workers retain the host's default per-result budgets.
138
+ resultLimits: { events: Infinity, bytes: Infinity },
139
+ notificationRelay: domain === 'behavior'
140
+ ? { producerPluginIds: ['clawclaw.behavior'], previousEpochOnly: true } : { sourceEvents: true },
77
141
  });
78
- return { outcome: events.length ? 'processed' : 'noop', events: notifications,
79
- ...(this.domain === 'tasks' ? { checkpoint: structuredClone(this.taskState) } : {}),
80
- ...(cursor === undefined ? {} : { consumeEventsThroughCommitSeq: cursor }) };
81
142
  }
82
143
  }
83
144
 
@@ -1,6 +1,7 @@
1
1
  /** Frozen API v2 compatibility version; new modules use PERCEPTION_MODULE_API_VERSION (3). */
2
2
  export const PERCEPTION_PLUGIN_API_VERSION = 2 as const;
3
3
  export * from './module.js';
4
+ export * from './lifecycle.js';
4
5
  import { Perception } from '@myclaw163/game-agent-runtime/sdk/perception.js';
5
6
  import type { PerceptionModuleManifest, PerceptionModuleInput, PerceptionModuleResult, PerceptionModuleApi } from './module.js';
6
7
  export { ClawclawReaction } from './reaction.js';
@@ -0,0 +1,15 @@
1
+ import type { PerceptionModuleInput, PerceptionLifecycleChange } from './module.js';
2
+
3
+ export function hasPerceptionBoundary(input: Pick<PerceptionModuleInput, 'lifecycle'>, kind: PerceptionLifecycleChange['kind']): boolean {
4
+ return input.lifecycle?.some(change => change.kind === kind) ?? false;
5
+ }
6
+ export function enteredPhase(input: Pick<PerceptionModuleInput, 'lifecycle'>, phase: string): boolean {
7
+ return input.lifecycle?.some(change => change.kind === 'phase_changed' && change.to === phase) ?? false;
8
+ }
9
+ export function leftPhase(input: Pick<PerceptionModuleInput, 'lifecycle'>, phase: string): boolean {
10
+ return input.lifecycle?.some(change => change.kind === 'phase_changed' && change.from === phase) ?? false;
11
+ }
12
+ /** Return a new module state; never mutates the read-only input or another module. */
13
+ export function resetPerceptionState<T extends object>(state: Readonly<T>, replacement: Partial<T>): T {
14
+ return { ...state, ...replacement };
15
+ }
@@ -27,6 +27,13 @@ export interface PerceptionModuleManifest {
27
27
  readonly behaviors?: Readonly<Record<string, ReactionBehaviorBinding>>;
28
28
  }
29
29
  export interface PerceptionModuleInput {
30
+ readonly source?: Readonly<{ epochId: number; frameSeq: number; connectionId: string; backendTick?: number; receivedAtMs: number; observedAtMs?: number }>;
31
+ /** Explicit boundaries; the host does not erase module state on a phase change. */
32
+ readonly lifecycle?: readonly PerceptionLifecycleChange[];
33
+ readonly roomState?: Readonly<Record<string, unknown>> | null;
34
+ readonly queueState?: Readonly<Record<string, unknown>> | null;
35
+ /** Source facts keep their own accepted State boundary, distinct from gameState. */
36
+ readonly eventStates?: Readonly<Record<string, Readonly<Record<string, unknown>> | null>>;
30
37
  readonly cycle?: import('../module-input/index.js').ProcessingCycleInfo;
31
38
  readonly moduleId: string;
32
39
  readonly scope: Readonly<{ sessionId: string; segmentId: string }>;
@@ -47,6 +54,7 @@ export interface PerceptionModuleInput {
47
54
  readonly enabledBindings?: readonly string[];
48
55
  }
49
56
  export interface PerceptionModuleApi {
57
+ readonly spatial?: import('../behavior-plugin/index.js').SpatialApi;
50
58
  /** Shared with a unique explicitly bound strategy; otherwise module-private. */
51
59
  readonly memory: StrategyMemory;
52
60
  }
@@ -56,10 +64,17 @@ export interface PerceptionModuleEvent {
56
64
  /** false retains the event for a later wake; omit the event to produce no notification. */
57
65
  readonly wakeAgent?: boolean;
58
66
  readonly payload: Readonly<Record<string, unknown>>;
67
+ readonly occurredAt?: string;
59
68
  }
60
69
  export interface PerceptionModuleResult {
61
70
  readonly state?: unknown;
62
71
  readonly events?: readonly PerceptionModuleEvent[];
72
+ /** Requires host registration authority; user manifests cannot grant it. */
73
+ readonly forwards?: readonly { readonly eventId: string }[];
63
74
  /** Keys in manifest.behaviors; never arbitrary strategy names or executable Actions. */
64
75
  readonly activations?: readonly (PerceptionStrategyActivation | ReactionActivation)[];
65
76
  }
77
+
78
+ export type PerceptionLifecycleChange =
79
+ | Readonly<{ kind: 'initial' | 'recovery' | 'observation_gap' | 'observer_died' | 'segment_ending' | 'snapshot_requested' }>
80
+ | Readonly<{ kind: 'phase_changed'; from: string; to: string }>;