@myclaw163/clawclaw-cli 0.9.1 → 0.10.1

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 (216) hide show
  1. package/QUICKSTART_OTHER.md +5 -5
  2. package/README.md +7 -8
  3. package/bin/clawclaw-channel.mjs +2 -2
  4. package/bin/clawclaw-cli.mjs +2 -2
  5. package/docs/configuration.md +25 -99
  6. package/docs/custom-modules/README.md +27 -40
  7. package/docs/custom-modules/api-reference.md +132 -273
  8. package/docs/custom-modules/behavior.md +185 -75
  9. package/docs/custom-modules/examples/auto-escape.ts +41 -0
  10. package/docs/custom-modules/examples/go-to-point.ts +11 -11
  11. package/docs/custom-modules/examples/nearby-reflex.ts +22 -0
  12. package/docs/custom-modules/examples/task-reminder.ts +4 -5
  13. package/docs/custom-modules/perception.md +46 -806
  14. package/docs/custom-modules/skill.md +1 -1
  15. package/docs/desktop-event-push.md +3 -3
  16. package/docs/runtime/README.md +18 -19
  17. package/docs/runtime/agent-notifications.md +31 -12
  18. package/docs/runtime/behavior-runtime.md +54 -48
  19. package/docs/runtime/components-and-boundaries.md +87 -137
  20. package/docs/runtime/events-and-state.md +52 -17
  21. package/docs/runtime/framework-package.md +73 -0
  22. package/docs/runtime/official-perception-modules.md +5 -5
  23. package/docs/runtime/owner-lifecycle-and-observability.md +6 -6
  24. package/docs/runtime/short-commands-and-capabilities.md +8 -9
  25. package/docs/user-guide/README.md +12 -9
  26. package/docs/user-guide/api-reference.md +132 -180
  27. package/docs/user-guide/behavior.md +175 -65
  28. package/docs/user-guide/installation.md +7 -7
  29. package/docs/user-guide/perception.md +46 -789
  30. package/docs/user-guide/skill.md +1 -1
  31. package/package.json +24 -9
  32. package/scripts/check-framework-boundaries.mjs +27 -0
  33. package/scripts/check-skill-command-surface.mjs +9 -14
  34. package/scripts/install-local-runtime.mjs +35 -0
  35. package/scripts/qa-install.mjs +105 -0
  36. package/skills/clawclaw/SKILL.md +50 -48
  37. package/skills/clawclaw/references/BEHAVIORS.md +45 -65
  38. package/skills/clawclaw/references/CHANNELS.md +2 -2
  39. package/skills/clawclaw/references/COMMANDS.md +65 -87
  40. package/skills/clawclaw/references/CUSTOM-BEHAVIOR-DEVELOPMENT.md +185 -75
  41. package/skills/clawclaw/references/CUSTOM-MODULE-API.md +145 -198
  42. package/skills/clawclaw/references/CUSTOM-MODULES.md +28 -29
  43. package/skills/clawclaw/references/CUSTOM-PERCEPTION-DEVELOPMENT.md +46 -811
  44. package/skills/clawclaw/references/CUSTOM-SKILL-DEVELOPMENT.md +1 -1
  45. package/skills/clawclaw/references/HUB.md +1 -1
  46. package/skills/clawclaw/references/STREAM.md +8 -8
  47. package/skills/clawclaw/references/TACTICS.md +1 -1
  48. package/src/channel/claude-channel-ipc-server.ts +1 -0
  49. package/src/cli.ts +4 -2
  50. package/src/commands/behavior.ts +49 -104
  51. package/src/commands/capability.ts +3 -3
  52. package/src/commands/load.ts +18 -25
  53. package/src/commands/module-runtime-control.ts +113 -0
  54. package/src/commands/perception.ts +23 -4
  55. package/src/commands/strategy.ts +2 -0
  56. package/src/commands/trigger.ts +1 -1
  57. package/src/lib/capability-load-diagnostics.ts +3 -3
  58. package/src/lib/perception-config.ts +18 -6
  59. package/src/lib/runtime-cadence-config.ts +16 -0
  60. package/src/lib/workspace-runtime-lock.ts +3 -46
  61. package/src/pipeline/canonical-event-presentation.ts +23 -124
  62. package/src/pipeline/event-format.ts +12 -21
  63. package/src/pipeline/event-hints.ts +6 -6
  64. package/src/pipeline/game-sync-event-normalization.ts +57 -63
  65. package/src/runtime/clawclaw/behavior-decision.ts +7 -3
  66. package/src/runtime/clawclaw/behavior-input.ts +8 -4
  67. package/src/runtime/clawclaw/behavior-observation-memory.ts +3 -2
  68. package/src/runtime/clawclaw/behavior-read-api.ts +4 -0
  69. package/src/runtime/clawclaw/behavior-reflex-control.ts +74 -0
  70. package/src/runtime/clawclaw/notification-policy.ts +42 -0
  71. package/src/runtime/clawclaw/notification-turn.ts +19 -0
  72. package/src/runtime/clawclaw/observation-frame-projector.ts +3 -3
  73. package/src/runtime/clawclaw/owner.ts +67 -8
  74. package/src/runtime/clawclaw/perception-module-manifest.ts +22 -8
  75. package/src/runtime/clawclaw/perception-strategy-names.ts +17 -0
  76. package/src/runtime/clawclaw/persistence-compatibility.ts +36 -0
  77. package/src/runtime/clawclaw/plugins/action/action-plugin.ts +3 -3
  78. package/src/runtime/clawclaw/plugins/assembly.ts +29 -41
  79. package/src/runtime/clawclaw/plugins/behavior/activation-manager.ts +1 -482
  80. package/src/runtime/clawclaw/plugins/behavior/behavior-analysis-thread-host.ts +17 -186
  81. package/src/runtime/clawclaw/plugins/behavior/behavior-catalog.ts +2 -0
  82. package/src/runtime/clawclaw/plugins/behavior/behavior-instance-snapshot.ts +1 -123
  83. package/src/runtime/clawclaw/plugins/behavior/behavior-normalization.ts +3 -0
  84. package/src/runtime/clawclaw/plugins/behavior/behavior-plugin.ts +126 -1707
  85. package/src/runtime/clawclaw/plugins/behavior/behavior-runner.ts +13 -271
  86. package/src/runtime/clawclaw/plugins/behavior/behavior-source.ts +2 -2
  87. package/src/runtime/clawclaw/plugins/behavior/behavior-worker-bridge.ts +8 -0
  88. package/src/runtime/clawclaw/plugins/behavior/control-driver.ts +3 -180
  89. package/src/runtime/clawclaw/plugins/behavior/thread-behavior-executor.ts +13 -960
  90. package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +9 -107
  91. package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +5 -4
  92. package/src/runtime/clawclaw/plugins/derived-event/reminder-plugin.ts +27 -17
  93. package/src/runtime/clawclaw/plugins/derived-event/reminder-runner.ts +1 -0
  94. package/src/runtime/clawclaw/plugins/derived-event/state-change-rules.ts +84 -0
  95. package/src/runtime/clawclaw/plugins/derived-event/task-change-tracker.ts +1 -0
  96. package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +4 -4
  97. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-adapter.ts +9 -97
  98. package/src/runtime/clawclaw/plugins/mailbox/adapters/claude-channel-socket.ts +8 -343
  99. package/src/runtime/clawclaw/plugins/mailbox/agent-mailbox-coordinator.ts +60 -572
  100. package/src/runtime/clawclaw/plugins/mailbox/desktop-event-socket.ts +6 -434
  101. package/src/runtime/clawclaw/plugins/mailbox/mailbox-event-batch-delivery.ts +1 -266
  102. package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +6 -161
  103. package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +4 -23
  104. package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +49 -752
  105. package/src/runtime/clawclaw/plugins/perception/map-concurrent.ts +1 -0
  106. package/src/runtime/clawclaw/plugins/perception/notification-content.ts +60 -0
  107. package/src/runtime/clawclaw/plugins/perception/perception-module-plugin.ts +136 -0
  108. package/src/runtime/clawclaw/plugins/perception/perception-module-runner.ts +13 -0
  109. package/src/runtime/clawclaw/plugins/perception/perception-module-worker.ts +13 -24
  110. package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +19 -8
  111. package/src/runtime/clawclaw/plugins/perception/perception-source.ts +23 -15
  112. package/src/runtime/clawclaw/plugins/perception/task-baseline.ts +29 -0
  113. package/src/runtime/clawclaw/plugins/source/source-plugin.ts +8 -103
  114. package/src/runtime/clawclaw/plugins/system-perception/rule-runner.ts +107 -0
  115. package/src/runtime/clawclaw/plugins/system-perception/system-perceptions.ts +107 -0
  116. package/src/runtime/clawclaw/plugins/trigger/contracts.ts +3 -1
  117. package/src/runtime/clawclaw/plugins/trigger/trigger-module-loader.ts +5 -2
  118. package/src/runtime/clawclaw/plugins/trigger/trigger-plugin.ts +69 -13
  119. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-pool.ts +13 -1
  120. package/src/runtime/clawclaw/plugins/trigger/trigger-thread-worker.ts +4 -0
  121. package/src/runtime/clawclaw/reaction-behavior-resolution.ts +1 -23
  122. package/src/runtime/clawclaw/reaction-manifest.ts +18 -12
  123. package/src/runtime/clawclaw/reminder-manifest.ts +5 -2
  124. package/src/runtime/clawclaw/runtime-cadence.ts +24 -0
  125. package/src/runtime/clawclaw/runtime-state.ts +12 -1
  126. package/src/runtime/clawclaw/runtime.ts +11 -3
  127. package/src/runtime/clawclaw/strategy-memory-rpc.ts +1 -0
  128. package/src/runtime/clawclaw/strategy-memory.ts +1 -0
  129. package/src/runtime/clawclaw-event-catalog.ts +17 -17
  130. package/src/runtime/framework/action-diagnostics.ts +3 -83
  131. package/src/runtime/framework/capability-registry.ts +2 -395
  132. package/src/runtime/framework/contracts.ts +2 -144
  133. package/src/runtime/framework/control/control-scheduler.ts +2 -1268
  134. package/src/runtime/framework/control/domain-set.ts +2 -81
  135. package/src/runtime/framework/control/index.ts +1 -3
  136. package/src/runtime/framework/control/types.ts +2 -191
  137. package/src/runtime/framework/control-coordinator.ts +2 -11
  138. package/src/runtime/framework/events/event-catalog.ts +2 -74
  139. package/src/runtime/framework/events/event-delivery-service.ts +2 -200
  140. package/src/runtime/framework/events/event-ingress.ts +2 -99
  141. package/src/runtime/framework/events/event-repository.ts +2 -82
  142. package/src/runtime/framework/events/index.ts +2 -7
  143. package/src/runtime/framework/events/memory-event-repository.ts +2 -1100
  144. package/src/runtime/framework/events/runtime-resume.ts +2 -20
  145. package/src/runtime/framework/events/sqlite-event-repository.ts +5 -2280
  146. package/src/runtime/framework/events/test-helpers.ts +1 -1
  147. package/src/runtime/framework/events/types.ts +2 -312
  148. package/src/runtime/framework/index.ts +3 -7
  149. package/src/runtime/framework/load-node-sqlite.ts +2 -17
  150. package/src/runtime/framework/mailbox/coalescer.ts +2 -83
  151. package/src/runtime/framework/mailbox/host-notification-sink.ts +2 -44
  152. package/src/runtime/framework/mailbox/identity.ts +2 -38
  153. package/src/runtime/framework/mailbox/index.ts +1 -7
  154. package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +2 -282
  155. package/src/runtime/framework/mailbox/mailbox-repository.ts +2 -44
  156. package/src/runtime/framework/mailbox/notification-projector.ts +2 -65
  157. package/src/runtime/framework/mailbox/types.ts +2 -145
  158. package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +2 -154
  159. package/src/runtime/framework/modules/runtime-module-loader.ts +7 -51
  160. package/src/runtime/framework/modules/runtime-module-output.ts +2 -24
  161. package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +3 -23
  162. package/src/runtime/framework/participation-manager.ts +2 -253
  163. package/src/runtime/framework/persistence/async-sqlite-persistence-worker.ts +2 -77
  164. package/src/runtime/framework/persistence/memory-first-persistence.ts +4 -489
  165. package/src/runtime/framework/plugins/contracts.ts +2 -388
  166. package/src/runtime/framework/plugins/index.ts +1 -4
  167. package/src/runtime/framework/plugins/runtime-event-identity.ts +2 -17
  168. package/src/runtime/framework/plugins/runtime-input-journal.ts +2 -866
  169. package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +2 -2060
  170. package/src/runtime/framework/runtime.ts +5 -1843
  171. package/src/runtime/framework/serial-task-queue.ts +2 -14
  172. package/src/runtime/framework/state/contracts.ts +2 -49
  173. package/src/runtime/framework/state/current-state-store.ts +2 -184
  174. package/src/runtime/framework/state/durable-agent-state-snapshot.ts +2 -209
  175. package/src/runtime/framework/state/freshness.ts +2 -72
  176. package/src/runtime/framework/state/history/contracts.ts +2 -158
  177. package/src/runtime/framework/state/history/history-writer.ts +2 -194
  178. package/src/runtime/framework/state/history/memory-state-history-repository.ts +2 -230
  179. package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +2 -648
  180. package/src/runtime/framework/state/history/trajectory-projector.ts +2 -209
  181. package/src/runtime/framework/state/index.ts +1 -13
  182. package/src/runtime/framework/state/state-ingress.ts +2 -95
  183. package/src/runtime/framework/state/state-provider.ts +2 -62
  184. package/src/runtime/framework/state/types.ts +2 -155
  185. package/src/runtime/host-monitor-rate-gate.ts +1 -123
  186. package/src/runtime/mailbox-host-relay.ts +1 -326
  187. package/src/runtime/observability/detail-capture.ts +4 -108
  188. package/src/runtime/observability/process-timing.ts +2 -59
  189. package/src/runtime/observability/recorder.ts +2 -238
  190. package/src/runtime/observability/redaction.ts +2 -181
  191. package/src/runtime/observability/reporter.ts +2 -154
  192. package/src/runtime/observability/sinks.ts +2 -135
  193. package/src/runtime/observability/types.ts +2 -92
  194. package/src/runtime/owner-control.ts +45 -315
  195. package/src/runtime/parent-process-watch.ts +1 -51
  196. package/src/runtime/process-identity.ts +1 -72
  197. package/src/sdk/behavior-plugin/index.ts +13 -4
  198. package/src/sdk/index.ts +44 -3
  199. package/src/sdk/module-input/index.ts +5 -0
  200. package/src/sdk/perception-plugin/index.ts +9 -5
  201. package/src/sdk/perception-plugin/module.ts +25 -6
  202. package/src/sdk/perception-plugin/reaction.ts +1 -1
  203. package/src/sdk/perception-plugin/reminder-rules.ts +8 -42
  204. package/src/sdk/perception-plugin/reminder.ts +2 -1
  205. package/src/{runtime/clawclaw/plugins/source → sdk/perception-plugin}/task-change-tracker.ts +1 -2
  206. package/src/sdk/strategy-memory.ts +1 -0
  207. package/src/sdk/strategy-plugin/index.ts +36 -0
  208. package/src/sdk/trigger-plugin/index.ts +4 -3
  209. package/docs/custom-modules/examples/nearby-escape.ts +0 -56
  210. package/docs/custom-modules/examples/nearby-notice.ts +0 -36
  211. package/docs/custom-modules/trigger.md +0 -295
  212. package/src/runtime/clawclaw/behavior-activation-capability.ts +0 -21
  213. package/src/runtime/clawclaw/plugins/perception/reaction-plugin.ts +0 -233
  214. package/src/runtime/clawclaw/plugins/perception/reaction-runner.ts +0 -49
  215. package/src/runtime/clawclaw/plugins/perception/reaction-worker.ts +0 -26
  216. /package/src/runtime/clawclaw/plugins/{source → derived-event}/player-change-tracker.ts +0 -0
@@ -1,1268 +1,2 @@
1
- import type { ScopeRef } from '../contracts.js';
2
- import {
3
- cloneSymbolicDomains,
4
- containsAllDomains,
5
- containsDomain,
6
- domainsOverlap,
7
- emptySymbolicDomains,
8
- normalizeDomains,
9
- normalizeNames,
10
- requestDomains,
11
- symbolicHasAny,
12
- symbolicList,
13
- WILDCARD_DOMAIN,
14
- type SymbolicDomains,
15
- } from './domain-set.js';
16
- import {
17
- DEFAULT_CONTROLLER_PRIORITY,
18
- type AwaitControlOptions,
19
- type AwaitControlResult,
20
- type ControlClock,
21
- type ControlDeferred,
22
- type ControlExecutionContext,
23
- type ControllerBlockerSnapshot,
24
- type ControllerHandoff,
25
- type ControllerLifecycle,
26
- type ControllerSnapshot,
27
- type ControllerSpec,
28
- type ControlRunResult,
29
- type ControlSnapshot,
30
- type ReleaseControllerOptions,
31
- type RunControlledAction,
32
- type TouchControllerOptions,
33
- } from './types.js';
34
-
35
- const DEFAULT_ACTIVITY_LEASE_MS = 15_000;
36
- const DEFAULT_HANDOFF_WAIT_MS = 250;
37
- const MAX_RELEASED_TOMBSTONES = 32;
38
-
39
- const realClock: ControlClock = {
40
- now: () => Date.now(),
41
- sleep: (milliseconds) => new Promise((resolve) => {
42
- const timer = setTimeout(resolve, milliseconds);
43
- // An abandoned wait after a controller change must not keep the owner
44
- // process alive until an old lease/deadline timer elapses.
45
- timer.unref?.();
46
- }),
47
- };
48
-
49
- export interface ControlSchedulerOptions {
50
- clock?: ControlClock;
51
- defaultActivityLeaseMs?: number;
52
- defaultHandoffWaitMs?: number;
53
- }
54
-
55
- interface DomainClaim {
56
- expiresAtMs?: number;
57
- }
58
-
59
- interface ControllerRecord {
60
- spec: Omit<ControllerSpec, 'domains' | 'mutexGroups' | 'priority' | 'holdMode' | 'lifecycle'> & {
61
- domains: string[];
62
- mutexGroups: string[];
63
- priority: number;
64
- holdMode: 'all_or_nothing' | 'per_resource';
65
- lifecycle: ControllerLifecycle;
66
- };
67
- sequence: number;
68
- epoch: number;
69
- /** Changes only when an admitted permit must become stale. */
70
- authorityEpoch: number;
71
- registeredAtMs: number;
72
- lastTouchedAtMs: number;
73
- claims: Map<string, DomainClaim>;
74
- excludedDomains: Set<string>;
75
- ready: boolean;
76
- releasedAtMs?: number;
77
- releaseReason?: string;
78
- }
79
-
80
- interface EffectiveController {
81
- record: ControllerRecord;
82
- claim: SymbolicDomains;
83
- grant: SymbolicDomains;
84
- held: SymbolicDomains;
85
- blockers: Map<string, ControllerBlockerSnapshot>;
86
- }
87
-
88
- interface InFlightOperation {
89
- operationId: number;
90
- controllerId: string;
91
- controllerEpoch: number;
92
- scope: ScopeRef;
93
- scopeKey: string;
94
- domains: string[];
95
- domainSet: SymbolicDomains;
96
- mutexGroups: string[];
97
- priority: number;
98
- sequence: number;
99
- submittedAtMs: number;
100
- settled: Promise<unknown>;
101
- }
102
-
103
- type OperationWaitResult = 'settled' | 'timeout' | 'interrupted';
104
-
105
- function scopeKey(scope: ScopeRef): string {
106
- return JSON.stringify([scope.adapterId, scope.accountId, scope.sessionId, scope.segmentId]);
107
- }
108
-
109
- function sameScope(left: ScopeRef, right: ScopeRef): boolean {
110
- return scopeKey(left) === scopeKey(right);
111
- }
112
-
113
- function cloneScope(scope: ScopeRef): ScopeRef {
114
- return { ...scope };
115
- }
116
-
117
- function validateDuration(name: string, value: number): number {
118
- if (!Number.isFinite(value) || value <= 0) {
119
- throw new TypeError(`${name} must be a positive finite number.`);
120
- }
121
- return value;
122
- }
123
-
124
- function validateBoundedWait(name: string, value: number): number {
125
- if (!Number.isFinite(value) || value < 0) {
126
- throw new TypeError(`${name} must be a non-negative finite number.`);
127
- }
128
- return value;
129
- }
130
-
131
- function lifecycleFor(spec: ControllerSpec): ControllerLifecycle {
132
- if (spec.lifecycle) return spec.lifecycle;
133
- if (spec.kind === 'agent' || spec.kind === 'user') return 'activity_lease';
134
- return 'persistent';
135
- }
136
-
137
- function priorityFor(spec: ControllerSpec): number {
138
- if (spec.priority !== undefined) {
139
- if (!Number.isFinite(spec.priority)) throw new TypeError('Controller priority must be finite.');
140
- return spec.priority;
141
- }
142
- if (spec.kind === 'behavior') {
143
- throw new TypeError('Behavior controller priority must be supplied by the Behavior Host.');
144
- }
145
- return DEFAULT_CONTROLLER_PRIORITY[spec.kind];
146
- }
147
-
148
- function comparePrecedence(left: ControllerRecord, right: ControllerRecord): number {
149
- return right.spec.priority - left.spec.priority || left.sequence - right.sequence;
150
- }
151
-
152
- function hasSharedMutex(left: ControllerRecord, right: ControllerRecord): boolean {
153
- return left.spec.mutexGroups.some((group) => right.spec.mutexGroups.includes(group));
154
- }
155
-
156
- function blockerSnapshot(
157
- blocker: EffectiveController,
158
- domains: string[],
159
- mutexGroups: string[] = [],
160
- ): ControllerBlockerSnapshot {
161
- return {
162
- controllerId: blocker.record.spec.controllerId,
163
- domains: [...domains],
164
- mutexGroups: [...mutexGroups],
165
- };
166
- }
167
-
168
- /**
169
- * Controller-oriented control arbitration.
170
- *
171
- * Actions are never queued while their controller is held. A high-priority
172
- * takeover may only wait briefly for a conflicting provider call that was
173
- * already submitted before the takeover became effective.
174
- */
175
- export class ControlScheduler {
176
- private readonly clock: ControlClock;
177
- private readonly defaultActivityLeaseMs: number;
178
- private readonly defaultHandoffWaitMs: number;
179
- private readonly controllers = new Map<string, ControllerRecord>();
180
- private readonly inFlight = new Map<number, InFlightOperation>();
181
- private readonly changeWaiters = new Set<() => boolean | void>();
182
- private activeScope?: ScopeRef;
183
- private activeScopeKey?: string;
184
- private scopeEpoch = 0;
185
- private version = 0;
186
- private controllerSequence = 0;
187
- private operationSequence = 0;
188
- private stopping = false;
189
-
190
- constructor(options: ControlSchedulerOptions = {}) {
191
- this.clock = options.clock ?? realClock;
192
- this.defaultActivityLeaseMs = validateDuration(
193
- 'defaultActivityLeaseMs',
194
- options.defaultActivityLeaseMs ?? DEFAULT_ACTIVITY_LEASE_MS,
195
- );
196
- this.defaultHandoffWaitMs = validateBoundedWait(
197
- 'defaultHandoffWaitMs',
198
- options.defaultHandoffWaitMs ?? DEFAULT_HANDOFF_WAIT_MS,
199
- );
200
- }
201
-
202
- activateScope(scope: ScopeRef): void {
203
- if (this.stopping) return;
204
- const nextKey = scopeKey(scope);
205
- if (nextKey === this.activeScopeKey) return;
206
- this.activeScope = cloneScope(scope);
207
- this.activeScopeKey = nextKey;
208
- this.scopeEpoch += 1;
209
- const now = this.clock.now();
210
- for (const [controllerId, controller] of this.controllers) {
211
- if (scopeKey(controller.spec.scope) === nextKey) continue;
212
- if (controller.releasedAtMs === undefined) {
213
- controller.releasedAtMs = now;
214
- controller.releaseReason = 'scope_changed';
215
- controller.ready = false;
216
- controller.epoch += 1;
217
- controller.authorityEpoch += 1;
218
- }
219
- // The scheduler is live ownership state, not the audit log. In-flight
220
- // operations retain their own immutable fence data and old waiters are
221
- // invalidated by object identity, so old-scope registrations can go now.
222
- this.controllers.delete(controllerId);
223
- }
224
- this.pruneReleasedControllers();
225
- this.changed();
226
- }
227
-
228
- registerController(spec: ControllerSpec): ControllerSnapshot {
229
- const now = this.clock.now();
230
- this.sweepExpired(now);
231
- const previous = this.controllers.get(spec.controllerId);
232
- if (previous && previous.releasedAtMs === undefined) {
233
- throw new Error(`Control controller already exists: ${spec.controllerId}`);
234
- }
235
- const domains = normalizeDomains(spec.domains);
236
- const lifecycle = lifecycleFor(spec);
237
- const activityLeaseMs = spec.activityLeaseMs === undefined
238
- ? this.defaultActivityLeaseMs
239
- : validateDuration('activityLeaseMs', spec.activityLeaseMs);
240
- const priority = priorityFor(spec);
241
- let deadlineAtMs = spec.deadlineAtMs;
242
- if (spec.maxRuntimeMs !== undefined) {
243
- validateDuration('maxRuntimeMs', spec.maxRuntimeMs);
244
- if (deadlineAtMs !== undefined) {
245
- throw new TypeError('Use deadlineAtMs or maxRuntimeMs, not both.');
246
- }
247
- deadlineAtMs = now + spec.maxRuntimeMs;
248
- }
249
- if (lifecycle === 'finite') {
250
- if (deadlineAtMs === undefined || !Number.isFinite(deadlineAtMs) || deadlineAtMs <= now) {
251
- throw new TypeError('A finite controller requires a future deadlineAtMs or maxRuntimeMs.');
252
- }
253
- }
254
- const record: ControllerRecord = {
255
- spec: {
256
- ...spec,
257
- scope: cloneScope(spec.scope),
258
- domains,
259
- mutexGroups: normalizeNames(spec.mutexGroups),
260
- priority,
261
- holdMode: spec.holdMode ?? 'all_or_nothing',
262
- lifecycle,
263
- activityLeaseMs,
264
- deadlineAtMs,
265
- },
266
- sequence: this.controllerSequence++,
267
- epoch: 1,
268
- authorityEpoch: 1,
269
- registeredAtMs: now,
270
- lastTouchedAtMs: now,
271
- claims: new Map(),
272
- excludedDomains: new Set(),
273
- ready: spec.ready ?? false,
274
- };
275
- if (this.activeScopeKey && scopeKey(spec.scope) !== this.activeScopeKey) {
276
- record.releasedAtMs = now;
277
- record.releaseReason = 'scope_changed';
278
- record.ready = false;
279
- record.epoch += 1;
280
- }
281
- if (lifecycle !== 'activity_lease') {
282
- for (const domain of domains) {
283
- record.claims.set(domain, lifecycle === 'finite' ? { expiresAtMs: deadlineAtMs } : {});
284
- }
285
- }
286
- this.controllers.set(spec.controllerId, record);
287
- if (!this.activeScopeKey) this.activateScope(spec.scope);
288
- this.changed();
289
- return this.controllerSnapshot(record, this.allocate());
290
- }
291
-
292
- ensureController(spec: ControllerSpec): ControllerSnapshot {
293
- this.sweepExpired(this.clock.now());
294
- const existing = this.controllers.get(spec.controllerId);
295
- if (!existing) return this.registerController(spec);
296
- if (existing.releasedAtMs !== undefined) return this.registerController(spec);
297
- if (!sameScope(existing.spec.scope, spec.scope)) {
298
- throw new Error(`Controller ${spec.controllerId} belongs to another scope.`);
299
- }
300
- return this.controllerSnapshot(existing, this.allocate());
301
- }
302
-
303
- setReady(controllerId: string, ready = true): ControllerSnapshot | undefined {
304
- const record = this.controllers.get(controllerId);
305
- if (!record || record.releasedAtMs !== undefined) return undefined;
306
- if (record.ready !== ready) {
307
- record.ready = ready;
308
- record.epoch += 1;
309
- if (!ready) record.authorityEpoch += 1;
310
- record.lastTouchedAtMs = this.clock.now();
311
- this.changed();
312
- }
313
- return this.controllerSnapshot(record, this.allocate());
314
- }
315
-
316
- touch(controllerId: string, options: TouchControllerOptions = {}): ControllerSnapshot | undefined {
317
- const record = this.controllers.get(controllerId);
318
- if (!record || record.releasedAtMs !== undefined) return undefined;
319
- const now = this.clock.now();
320
- this.sweepExpired(now);
321
- if (record.releasedAtMs !== undefined) return this.controllerSnapshot(record, this.allocate());
322
- const domains = normalizeDomains(options.domains ?? record.spec.domains);
323
- const leaseMs = options.activityLeaseMs === undefined
324
- ? record.spec.activityLeaseMs ?? this.defaultActivityLeaseMs
325
- : validateDuration('activityLeaseMs', options.activityLeaseMs);
326
- this.applyTouch(record, domains, now, leaseMs);
327
- record.lastTouchedAtMs = now;
328
- record.epoch += 1;
329
- this.changed();
330
- return this.controllerSnapshot(record, this.allocate());
331
- }
332
-
333
- release(controllerId: string, options: ReleaseControllerOptions = {}): ControllerSnapshot | undefined {
334
- const record = this.controllers.get(controllerId);
335
- if (!record) return undefined;
336
- const now = this.clock.now();
337
- if (!options.domains) {
338
- if (record.releasedAtMs === undefined) {
339
- record.releasedAtMs = now;
340
- record.releaseReason = options.reason ?? 'released';
341
- record.ready = false;
342
- record.epoch += 1;
343
- record.authorityEpoch += 1;
344
- this.changed();
345
- }
346
- const snapshot = this.controllerSnapshot(record, this.allocate());
347
- this.pruneReleasedControllers();
348
- return snapshot;
349
- }
350
- if (record.releasedAtMs !== undefined) return this.controllerSnapshot(record, this.allocate());
351
- const domains = normalizeDomains(options.domains);
352
- for (const domain of domains) this.releaseDomain(record, domain);
353
- record.lastTouchedAtMs = now;
354
- record.epoch += 1;
355
- record.authorityEpoch += 1;
356
- this.changed();
357
- return this.controllerSnapshot(record, this.allocate());
358
- }
359
-
360
- handoff(request: ControllerHandoff): {
361
- from: ControllerSnapshot;
362
- to: ControllerSnapshot;
363
- } {
364
- const source = this.controllers.get(request.fromControllerId);
365
- const target = this.controllers.get(request.toControllerId);
366
- if (!source || !target) throw new Error('Both handoff controllers must be registered.');
367
- const now = this.clock.now();
368
- this.sweepExpired(now);
369
- if (!sameScope(source.spec.scope, target.spec.scope)) {
370
- throw new Error('Control handoff cannot cross scopes.');
371
- }
372
- if (source.releasedAtMs !== undefined || target.releasedAtMs !== undefined) {
373
- throw new Error('A released controller cannot participate in a handoff.');
374
- }
375
- const domains = normalizeDomains(request.domains);
376
- const sourceBefore = {
377
- claims: new Map([...source.claims].map(([domain, claim]) => [domain, { ...claim }])),
378
- excludedDomains: new Set(source.excludedDomains),
379
- ready: source.ready,
380
- lastTouchedAtMs: source.lastTouchedAtMs,
381
- };
382
- const targetBefore = {
383
- claims: new Map([...target.claims].map(([domain, claim]) => [domain, { ...claim }])),
384
- excludedDomains: new Set(target.excludedDomains),
385
- ready: target.ready,
386
- lastTouchedAtMs: target.lastTouchedAtMs,
387
- };
388
- for (const domain of domains) {
389
- if (!this.isDeclaredDomain(source, domain) || !this.isDeclaredDomain(target, domain)) {
390
- throw new Error(`Both controllers must declare handoff domain: ${domain}`);
391
- }
392
- }
393
- for (const domain of domains) {
394
- this.releaseDomain(source, domain);
395
- }
396
- this.applyTouch(
397
- target,
398
- domains,
399
- now,
400
- target.spec.activityLeaseMs ?? this.defaultActivityLeaseMs,
401
- );
402
- // Handoff is the atomic READY boundary. A not-ready reservation would
403
- // release the source without leaving an eligible controller.
404
- target.ready = true;
405
- source.lastTouchedAtMs = now;
406
- target.lastTouchedAtMs = now;
407
- const provisional = this.allocate(domains);
408
- const targetControl = provisional.get(target.spec.controllerId);
409
- if (!targetControl || !containsAllDomains(targetControl.grant, domains)) {
410
- source.claims = sourceBefore.claims;
411
- source.excludedDomains = sourceBefore.excludedDomains;
412
- source.ready = sourceBefore.ready;
413
- source.lastTouchedAtMs = sourceBefore.lastTouchedAtMs;
414
- target.claims = targetBefore.claims;
415
- target.excludedDomains = targetBefore.excludedDomains;
416
- target.ready = targetBefore.ready;
417
- target.lastTouchedAtMs = targetBefore.lastTouchedAtMs;
418
- throw new Error('control_handoff_target_held');
419
- }
420
- source.epoch += 1;
421
- source.authorityEpoch += 1;
422
- target.epoch += 1;
423
- this.changed();
424
- const allocation = this.allocate();
425
- return {
426
- from: this.controllerSnapshot(source, allocation),
427
- to: this.controllerSnapshot(target, allocation),
428
- };
429
- }
430
-
431
- async runAction<T>(request: RunControlledAction<T>): Promise<ControlRunResult<T>> {
432
- const domains = request.domains.length === 0 ? [] : normalizeDomains(request.domains);
433
- if (domains.length === 0) return this.runUncontrolledAction(request, domains);
434
- let admission = this.admit(request.controllerId, request.scope, domains, {
435
- touchActivityLease: request.touchActivityLease ?? true,
436
- });
437
- if (admission.status === 'deferred') return admission;
438
-
439
- const capturedScopeEpoch = this.scopeEpoch;
440
- const capturedController = admission.controller;
441
- const capturedControllerEpoch = capturedController.authorityEpoch;
442
- const conflicts = this.conflictingInFlight(admission.controller, request.scope, domains);
443
- const waitable: InFlightOperation[] = [];
444
- const notWaitable: InFlightOperation[] = [];
445
- for (const conflict of conflicts) {
446
- if (conflict.scopeKey !== this.activeScopeKey
447
- || this.precedes(admission.controller, conflict)) {
448
- waitable.push(conflict);
449
- } else {
450
- notWaitable.push(conflict);
451
- }
452
- }
453
- if (notWaitable.length > 0) {
454
- return this.deferred('CONTROL_BUSY', request.controllerId, domains, 'provider_in_flight', true,
455
- notWaitable.map((operation) => operation.controllerId));
456
- }
457
- if (waitable.length > 0) {
458
- const waitMs = request.handoffWaitMs === undefined
459
- ? this.defaultHandoffWaitMs
460
- : validateBoundedWait('handoffWaitMs', request.handoffWaitMs);
461
- const waitResult = await this.waitForOperations(waitable, waitMs, () => (
462
- this.stopping
463
- || capturedScopeEpoch !== this.scopeEpoch
464
- || this.controllers.get(request.controllerId) !== capturedController
465
- || capturedController.authorityEpoch !== capturedControllerEpoch
466
- ));
467
- if (this.stopping) {
468
- return this.deferred('CONTROL_STOPPING', request.controllerId, domains, 'scheduler_stopping', false);
469
- }
470
- if (capturedScopeEpoch !== this.scopeEpoch || scopeKey(request.scope) !== this.activeScopeKey) {
471
- return this.deferred('CONTROL_SCOPE_CHANGED', request.controllerId, domains, 'scope_changed', false);
472
- }
473
- this.sweepExpired(this.clock.now());
474
- const current = this.controllers.get(request.controllerId);
475
- if (current !== capturedController) {
476
- return this.deferred(
477
- 'CONTROL_RELEASED', request.controllerId, domains, 'controller_changed', false,
478
- );
479
- }
480
- if (current.releasedAtMs !== undefined) {
481
- return this.deferred(
482
- current.releaseReason === 'scope_changed'
483
- ? 'CONTROL_SCOPE_CHANGED'
484
- : 'CONTROL_RELEASED',
485
- request.controllerId,
486
- domains,
487
- current.releaseReason ?? 'released',
488
- false,
489
- );
490
- }
491
- if (current.authorityEpoch !== capturedControllerEpoch) {
492
- return this.deferred(
493
- 'CONTROL_RELEASED', request.controllerId, domains, 'authority_changed', false,
494
- );
495
- }
496
- if (waitResult !== 'settled') {
497
- return this.deferred('CONTROL_BUSY', request.controllerId, domains, 'handoff_timeout', true,
498
- waitable.map((operation) => operation.controllerId));
499
- }
500
- admission = this.admit(request.controllerId, request.scope, domains, {
501
- touchActivityLease: false,
502
- });
503
- if (admission.status === 'deferred') return admission;
504
- if (this.conflictingInFlight(admission.controller, request.scope, domains).length > 0) {
505
- return this.deferred('CONTROL_BUSY', request.controllerId, domains, 'provider_race', true);
506
- }
507
- }
508
-
509
- // Install the submission fence before invoking user/provider code. This
510
- // prevents a synchronous re-entrant Action from bypassing arbitration.
511
- const operationId = this.operationSequence++;
512
- let markSettled!: () => void;
513
- const settled = new Promise<void>((resolve) => { markSettled = resolve; });
514
- const operation: InFlightOperation = {
515
- operationId,
516
- controllerId: request.controllerId,
517
- controllerEpoch: admission.controller.authorityEpoch,
518
- scope: cloneScope(request.scope),
519
- scopeKey: scopeKey(request.scope),
520
- domains,
521
- domainSet: requestDomains(domains),
522
- mutexGroups: [...admission.controller.spec.mutexGroups],
523
- priority: admission.controller.spec.priority,
524
- sequence: admission.controller.sequence,
525
- submittedAtMs: this.clock.now(),
526
- settled,
527
- };
528
- this.inFlight.set(operationId, operation);
529
- this.changed();
530
- let providerPromise: Promise<T>;
531
- try {
532
- providerPromise = Promise.resolve(request.execute(
533
- this.executionContext(admission.controller, request.scope, domains),
534
- ));
535
- } catch (error) {
536
- providerPromise = Promise.reject(error);
537
- }
538
- try {
539
- const value = await providerPromise;
540
- return { status: 'executed', controllerId: request.controllerId, domains, value };
541
- } finally {
542
- markSettled();
543
- this.inFlight.delete(operationId);
544
- this.changed();
545
- }
546
- }
547
-
548
- submit<T>(request: RunControlledAction<T>): Promise<ControlRunResult<T>> {
549
- return this.runAction(request);
550
- }
551
-
552
- async awaitControl(
553
- controllerId: string,
554
- scope: ScopeRef,
555
- domainsInput: string[],
556
- options: AwaitControlOptions = {},
557
- ): Promise<AwaitControlResult> {
558
- const domains = normalizeDomains(domainsInput);
559
- const lifecycle = this.controllers.get(controllerId);
560
- const startedAt = this.clock.now();
561
- const timeoutMs = options.timeoutMs ?? Number.POSITIVE_INFINITY;
562
- if (timeoutMs < 0 || Number.isNaN(timeoutMs)) throw new TypeError('timeoutMs must not be negative.');
563
- while (true) {
564
- if (options.signal?.aborted) {
565
- return this.deferred(
566
- 'CONTROL_CANCELLED', controllerId, domains, 'await_aborted', false,
567
- );
568
- }
569
- if (this.stopping) {
570
- return this.deferred(
571
- 'CONTROL_STOPPING', controllerId, domains, 'scheduler_stopping', false,
572
- );
573
- }
574
- if (scopeKey(scope) !== this.activeScopeKey) {
575
- return this.deferred(
576
- 'CONTROL_SCOPE_CHANGED', controllerId, domains, 'scope_changed', false,
577
- );
578
- }
579
- if (this.controllers.get(controllerId) !== lifecycle) {
580
- return this.deferred(
581
- 'CONTROL_RELEASED', controllerId, domains, 'controller_changed', false,
582
- );
583
- }
584
- const admission = this.admit(controllerId, scope, domains, { touchActivityLease: false });
585
- const conflicts = admission.status === 'deferred'
586
- ? []
587
- : this.conflictingInFlight(admission.controller, scope, domains);
588
- if (admission.status !== 'deferred' && conflicts.length === 0) {
589
- return { status: 'granted', controllerId, domains };
590
- }
591
- const unavailable = admission.status === 'deferred'
592
- ? admission
593
- : this.deferred(
594
- 'CONTROL_BUSY', controllerId, domains, 'provider_in_flight', true,
595
- conflicts.map((operation) => operation.controllerId),
596
- );
597
- if (!unavailable.retryable) return unavailable;
598
- const elapsed = this.clock.now() - startedAt;
599
- if (elapsed >= timeoutMs) {
600
- return this.deferred('CONTROL_BUSY', controllerId, domains, 'await_timeout', true,
601
- unavailable.blockedBy);
602
- }
603
- const remaining = timeoutMs - elapsed;
604
- const untilTransition = this.nextTransitionDelay();
605
- const sleepMs = Math.max(0, Math.min(remaining, untilTransition ?? remaining));
606
- await this.waitForChange(Number.isFinite(sleepMs) ? sleepMs : undefined, options.signal);
607
- }
608
- }
609
-
610
- snapshot(): ControlSnapshot {
611
- this.sweepExpired(this.clock.now());
612
- const allocation = this.allocate();
613
- return {
614
- activeScope: this.activeScope ? cloneScope(this.activeScope) : undefined,
615
- scopeEpoch: this.scopeEpoch,
616
- version: this.version,
617
- stopping: this.stopping,
618
- nowMs: this.clock.now(),
619
- controllers: [...this.controllers.values()]
620
- .sort((left, right) => left.sequence - right.sequence)
621
- .map((record) => this.controllerSnapshot(record, allocation)),
622
- inFlight: [...this.inFlight.values()].map((operation) => ({
623
- operationId: operation.operationId,
624
- controllerId: operation.controllerId,
625
- scope: cloneScope(operation.scope),
626
- domains: [...operation.domains],
627
- submittedAtMs: operation.submittedAtMs,
628
- })),
629
- };
630
- }
631
-
632
- beginStopping(): void {
633
- if (this.stopping) return;
634
- this.stopping = true;
635
- this.changed();
636
- }
637
-
638
- async waitForIdle(): Promise<void> {
639
- while (this.inFlight.size > 0) {
640
- await Promise.all([...this.inFlight.values()].map((operation) => operation.settled));
641
- }
642
- }
643
-
644
- private admit(
645
- controllerId: string,
646
- scope: ScopeRef,
647
- domains: string[],
648
- options: { touchActivityLease: boolean },
649
- ): { status: 'admitted'; controller: ControllerRecord } | ControlDeferred {
650
- if (this.stopping) {
651
- return this.deferred('CONTROL_STOPPING', controllerId, domains, 'scheduler_stopping', false);
652
- }
653
- if (scopeKey(scope) !== this.activeScopeKey) {
654
- return this.deferred('CONTROL_SCOPE_CHANGED', controllerId, domains, 'scope_changed', false);
655
- }
656
- const record = this.controllers.get(controllerId);
657
- if (!record) {
658
- return this.deferred('CONTROL_UNKNOWN_CONTROLLER', controllerId, domains, 'unknown_controller', false);
659
- }
660
- this.sweepExpired(this.clock.now());
661
- if (record.releasedAtMs !== undefined) {
662
- const code = record.releaseReason === 'scope_changed'
663
- ? 'CONTROL_SCOPE_CHANGED' as const
664
- : 'CONTROL_RELEASED' as const;
665
- return this.deferred(code, controllerId, domains, record.releaseReason ?? 'released', false);
666
- }
667
- if (!record.ready) {
668
- return this.deferred('CONTROL_NOT_READY', controllerId, domains, 'controller_not_ready', true);
669
- }
670
- for (const domain of domains) {
671
- if (!this.isDeclaredDomain(record, domain)) {
672
- return this.deferred('CONTROL_HELD', controllerId, domains, 'domain_not_declared', false);
673
- }
674
- }
675
- let previousClaims: Map<string, DomainClaim> | undefined;
676
- let previousExcluded: Set<string> | undefined;
677
- let previousTouchedAt: number | undefined;
678
- if (options.touchActivityLease && record.spec.lifecycle === 'activity_lease') {
679
- previousClaims = new Map(
680
- [...record.claims].map(([domain, claim]) => [domain, { ...claim }]),
681
- );
682
- previousExcluded = new Set(record.excludedDomains);
683
- previousTouchedAt = record.lastTouchedAtMs;
684
- this.applyTouch(
685
- record,
686
- domains,
687
- this.clock.now(),
688
- record.spec.activityLeaseMs ?? this.defaultActivityLeaseMs,
689
- );
690
- }
691
- const allocation = this.allocate(domains);
692
- const effective = allocation.get(controllerId);
693
- if (!effective || !containsAllDomains(effective.grant, domains)) {
694
- if (previousClaims && previousExcluded && previousTouchedAt !== undefined) {
695
- record.claims = previousClaims;
696
- record.excludedDomains = previousExcluded;
697
- record.lastTouchedAtMs = previousTouchedAt;
698
- }
699
- return this.deferred(
700
- 'CONTROL_HELD',
701
- controllerId,
702
- domains,
703
- 'controller_held',
704
- true,
705
- effective ? [...effective.blockers.keys()] : undefined,
706
- );
707
- }
708
- if (previousClaims) {
709
- record.lastTouchedAtMs = this.clock.now();
710
- record.epoch += 1;
711
- this.changed();
712
- }
713
- return { status: 'admitted', controller: record };
714
- }
715
-
716
- private async runUncontrolledAction<T>(
717
- request: RunControlledAction<T>,
718
- domains: string[],
719
- ): Promise<ControlRunResult<T>> {
720
- if (this.stopping) {
721
- return this.deferred(
722
- 'CONTROL_STOPPING', request.controllerId, domains, 'scheduler_stopping', false,
723
- );
724
- }
725
- if (scopeKey(request.scope) !== this.activeScopeKey) {
726
- return this.deferred(
727
- 'CONTROL_SCOPE_CHANGED', request.controllerId, domains, 'scope_changed', false,
728
- );
729
- }
730
- this.sweepExpired(this.clock.now());
731
- const record = this.controllers.get(request.controllerId);
732
- if (!record) {
733
- return this.deferred(
734
- 'CONTROL_UNKNOWN_CONTROLLER', request.controllerId, domains, 'unknown_controller', false,
735
- );
736
- }
737
- if (record.releasedAtMs !== undefined) {
738
- return this.deferred(
739
- record.releaseReason === 'scope_changed' ? 'CONTROL_SCOPE_CHANGED' : 'CONTROL_RELEASED',
740
- request.controllerId,
741
- domains,
742
- record.releaseReason ?? 'released',
743
- false,
744
- );
745
- }
746
- if (!record.ready) {
747
- return this.deferred(
748
- 'CONTROL_NOT_READY', request.controllerId, domains, 'controller_not_ready', true,
749
- );
750
- }
751
- const capturedScopeEpoch = this.scopeEpoch;
752
- const capturedController = record;
753
- const capturedControllerEpoch = record.authorityEpoch;
754
- const oldScopeOperations = [...this.inFlight.values()].filter(
755
- (operation) => operation.scopeKey !== this.activeScopeKey,
756
- );
757
- if (oldScopeOperations.length > 0) {
758
- const waitMs = request.handoffWaitMs === undefined
759
- ? this.defaultHandoffWaitMs
760
- : validateBoundedWait('handoffWaitMs', request.handoffWaitMs);
761
- const waitResult = await this.waitForOperations(oldScopeOperations, waitMs, () => (
762
- this.stopping
763
- || capturedScopeEpoch !== this.scopeEpoch
764
- || this.controllers.get(request.controllerId) !== capturedController
765
- || capturedController.authorityEpoch !== capturedControllerEpoch
766
- ));
767
- if (this.stopping) {
768
- return this.deferred(
769
- 'CONTROL_STOPPING', request.controllerId, domains, 'scheduler_stopping', false,
770
- );
771
- }
772
- if (capturedScopeEpoch !== this.scopeEpoch || scopeKey(request.scope) !== this.activeScopeKey) {
773
- return this.deferred(
774
- 'CONTROL_SCOPE_CHANGED', request.controllerId, domains, 'scope_changed', false,
775
- );
776
- }
777
- this.sweepExpired(this.clock.now());
778
- const current = this.controllers.get(request.controllerId);
779
- if (current !== capturedController) {
780
- return this.deferred(
781
- 'CONTROL_RELEASED', request.controllerId, domains, 'controller_changed', false,
782
- );
783
- }
784
- if (current.releasedAtMs !== undefined) {
785
- return this.deferred(
786
- current.releaseReason === 'scope_changed'
787
- ? 'CONTROL_SCOPE_CHANGED'
788
- : 'CONTROL_RELEASED',
789
- request.controllerId,
790
- domains,
791
- current.releaseReason ?? 'released',
792
- false,
793
- );
794
- }
795
- if (!current.ready) {
796
- return this.deferred(
797
- 'CONTROL_NOT_READY', request.controllerId, domains, 'controller_not_ready', true,
798
- );
799
- }
800
- if (current.authorityEpoch !== capturedControllerEpoch) {
801
- return this.deferred(
802
- 'CONTROL_RELEASED', request.controllerId, domains, 'authority_changed', false,
803
- );
804
- }
805
- if (waitResult !== 'settled') {
806
- return this.deferred(
807
- 'CONTROL_BUSY',
808
- request.controllerId,
809
- domains,
810
- 'handoff_timeout',
811
- true,
812
- oldScopeOperations.map((operation) => operation.controllerId),
813
- );
814
- }
815
- }
816
-
817
- const operationId = this.operationSequence++;
818
- let markSettled!: () => void;
819
- const settled = new Promise<void>((resolve) => { markSettled = resolve; });
820
- this.inFlight.set(operationId, {
821
- operationId,
822
- controllerId: request.controllerId,
823
- controllerEpoch: record.authorityEpoch,
824
- scope: cloneScope(request.scope),
825
- scopeKey: scopeKey(request.scope),
826
- domains,
827
- domainSet: requestDomains(domains),
828
- mutexGroups: [],
829
- priority: record.spec.priority,
830
- sequence: record.sequence,
831
- submittedAtMs: this.clock.now(),
832
- settled,
833
- });
834
- this.changed();
835
- let providerPromise: Promise<T>;
836
- try {
837
- providerPromise = Promise.resolve(request.execute(
838
- this.executionContext(record, request.scope, domains),
839
- ));
840
- } catch (error) {
841
- providerPromise = Promise.reject(error);
842
- }
843
- try {
844
- const value = await providerPromise;
845
- return { status: 'executed', controllerId: request.controllerId, domains, value };
846
- } finally {
847
- markSettled();
848
- this.inFlight.delete(operationId);
849
- this.changed();
850
- }
851
- }
852
-
853
- private allocate(extraDomains: string[] = []): Map<string, EffectiveController> {
854
- const now = this.clock.now();
855
- this.sweepExpired(now);
856
- const knownDomains = new Set(extraDomains.filter((domain) => domain !== WILDCARD_DOMAIN));
857
- for (const record of this.controllers.values()) {
858
- for (const domain of record.claims.keys()) if (domain !== WILDCARD_DOMAIN) knownDomains.add(domain);
859
- for (const domain of record.excludedDomains) knownDomains.add(domain);
860
- }
861
- const active = [...this.controllers.values()]
862
- .filter((record) => record.ready
863
- && record.releasedAtMs === undefined
864
- && scopeKey(record.spec.scope) === this.activeScopeKey)
865
- .sort(comparePrecedence);
866
- const result = new Map<string, EffectiveController>();
867
- const granted: EffectiveController[] = [];
868
- for (const record of active) {
869
- const claim = this.claimsFor(record);
870
- const grant = emptySymbolicDomains();
871
- const held = emptySymbolicDomains();
872
- const blockers = new Map<string, ControllerBlockerSnapshot>();
873
- const mutexBlockers = granted.filter((higher) => hasSharedMutex(record, higher.record));
874
- if (mutexBlockers.length > 0) {
875
- Object.assign(held, cloneSymbolicDomains(claim));
876
- for (const higher of mutexBlockers) {
877
- blockers.set(higher.record.spec.controllerId, blockerSnapshot(
878
- higher,
879
- [],
880
- record.spec.mutexGroups.filter((group) => higher.record.spec.mutexGroups.includes(group)),
881
- ));
882
- }
883
- } else if (record.spec.holdMode === 'all_or_nothing') {
884
- const domainBlockers = granted.filter((higher) => domainsOverlap(claim, higher.grant));
885
- if (domainBlockers.length > 0) {
886
- Object.assign(held, cloneSymbolicDomains(claim));
887
- for (const higher of domainBlockers) {
888
- blockers.set(higher.record.spec.controllerId, blockerSnapshot(higher, symbolicList(higher.grant)));
889
- }
890
- } else {
891
- Object.assign(grant, cloneSymbolicDomains(claim));
892
- }
893
- } else {
894
- for (const domain of claim.exact) {
895
- const higher = granted.find((candidate) => containsDomain(candidate.grant, domain));
896
- if (higher) {
897
- held.exact.add(domain);
898
- blockers.set(higher.record.spec.controllerId, blockerSnapshot(higher, [domain]));
899
- } else {
900
- grant.exact.add(domain);
901
- }
902
- }
903
- if (claim.wildcard) {
904
- const higherWildcard = granted.find((candidate) => candidate.grant.wildcard);
905
- if (!higherWildcard) {
906
- grant.wildcard = true;
907
- grant.excluded = new Set(claim.excluded);
908
- for (const domain of knownDomains) {
909
- const higher = granted.find((candidate) => containsDomain(candidate.grant, domain));
910
- if (!higher) continue;
911
- grant.excluded.add(domain);
912
- held.exact.add(domain);
913
- blockers.set(higher.record.spec.controllerId, blockerSnapshot(higher, [domain]));
914
- }
915
- } else {
916
- held.wildcard = true;
917
- blockers.set(higherWildcard.record.spec.controllerId,
918
- blockerSnapshot(higherWildcard, [WILDCARD_DOMAIN]));
919
- // A higher wildcard may have explicit holes that this wildcard can own.
920
- for (const domain of knownDomains) {
921
- if (containsDomain(claim, domain)
922
- && !granted.some((candidate) => containsDomain(candidate.grant, domain))) {
923
- grant.exact.add(domain);
924
- }
925
- }
926
- }
927
- }
928
- }
929
- const effective = { record, claim, grant, held, blockers };
930
- result.set(record.spec.controllerId, effective);
931
- if (symbolicHasAny(grant)) granted.push(effective);
932
- }
933
- return result;
934
- }
935
-
936
- /**
937
- * Build a revalidation guard tied to the exact controller record admitted
938
- * for this attempt. Object identity closes the release/re-register (ABA)
939
- * hole without treating an ordinary lease touch as authority revocation.
940
- */
941
- private executionContext(
942
- capturedController: ControllerRecord,
943
- scope: ScopeRef,
944
- domains: string[],
945
- ): ControlExecutionContext {
946
- const capturedScopeEpoch = this.scopeEpoch;
947
- const capturedAuthorityEpoch = capturedController.authorityEpoch;
948
- const controllerId = capturedController.spec.controllerId;
949
- return {
950
- revalidate: () => {
951
- if (this.stopping) {
952
- return this.deferred(
953
- 'CONTROL_STOPPING', controllerId, domains, 'scheduler_stopping', false,
954
- );
955
- }
956
- if (capturedScopeEpoch !== this.scopeEpoch || scopeKey(scope) !== this.activeScopeKey) {
957
- return this.deferred(
958
- 'CONTROL_SCOPE_CHANGED', controllerId, domains, 'scope_changed', false,
959
- );
960
- }
961
- this.sweepExpired(this.clock.now());
962
- const current = this.controllers.get(controllerId);
963
- if (current !== capturedController) {
964
- return this.deferred(
965
- 'CONTROL_RELEASED', controllerId, domains, 'controller_changed', false,
966
- );
967
- }
968
- if (current.authorityEpoch !== capturedAuthorityEpoch) {
969
- return this.deferred(
970
- 'CONTROL_RELEASED', controllerId, domains, 'authority_changed', false,
971
- );
972
- }
973
- if (current.releasedAtMs !== undefined) {
974
- return this.deferred(
975
- current.releaseReason === 'scope_changed'
976
- ? 'CONTROL_SCOPE_CHANGED'
977
- : 'CONTROL_RELEASED',
978
- controllerId,
979
- domains,
980
- current.releaseReason ?? 'released',
981
- false,
982
- );
983
- }
984
- if (!current.ready) {
985
- return this.deferred(
986
- 'CONTROL_NOT_READY', controllerId, domains, 'controller_not_ready', true,
987
- );
988
- }
989
- // A no-control Action still needs lifecycle and scope validation, but
990
- // intentionally participates in no domain or mutex arbitration.
991
- if (domains.length === 0) return undefined;
992
- const effective = this.allocate(domains).get(controllerId);
993
- if (!effective || !containsAllDomains(effective.grant, domains)) {
994
- return this.deferred(
995
- 'CONTROL_HELD',
996
- controllerId,
997
- domains,
998
- 'controller_held',
999
- true,
1000
- effective ? [...effective.blockers.keys()] : undefined,
1001
- );
1002
- }
1003
- return undefined;
1004
- },
1005
- };
1006
- }
1007
-
1008
- private claimsFor(record: ControllerRecord): SymbolicDomains {
1009
- const claims = emptySymbolicDomains();
1010
- for (const domain of record.claims.keys()) {
1011
- if (domain === WILDCARD_DOMAIN) claims.wildcard = true;
1012
- else claims.exact.add(domain);
1013
- }
1014
- claims.excluded = new Set(record.excludedDomains);
1015
- return claims;
1016
- }
1017
-
1018
- private controllerSnapshot(
1019
- record: ControllerRecord,
1020
- allocation: Map<string, EffectiveController>,
1021
- ): ControllerSnapshot {
1022
- const effective = allocation.get(record.spec.controllerId);
1023
- const claim = effective?.claim ?? this.claimsFor(record);
1024
- const grant = effective?.grant ?? emptySymbolicDomains();
1025
- const held = effective?.held ?? emptySymbolicDomains();
1026
- let state: ControllerSnapshot['state'];
1027
- if (record.releasedAtMs !== undefined) {
1028
- state = record.releaseReason === 'deadline_expired' ? 'expired' : 'released';
1029
- } else if (!record.ready) {
1030
- state = 'registered';
1031
- } else if (!symbolicHasAny(claim)) {
1032
- state = 'idle';
1033
- } else if (!symbolicHasAny(grant)) {
1034
- state = 'held';
1035
- } else if (symbolicHasAny(held)) {
1036
- state = 'partially_active';
1037
- } else {
1038
- state = 'active';
1039
- }
1040
- const expiries = [...record.claims.values()]
1041
- .map((entry) => entry.expiresAtMs)
1042
- .filter((value): value is number => value !== undefined);
1043
- return {
1044
- controllerId: record.spec.controllerId,
1045
- kind: record.spec.kind,
1046
- scope: cloneScope(record.spec.scope),
1047
- priority: record.spec.priority,
1048
- sequence: record.sequence,
1049
- epoch: record.epoch,
1050
- lifecycle: record.spec.lifecycle,
1051
- state,
1052
- ready: record.ready,
1053
- holdMode: record.spec.holdMode,
1054
- declaredDomains: [...record.spec.domains],
1055
- claimedDomains: symbolicList(claim),
1056
- grantedDomains: symbolicList(grant),
1057
- heldDomains: symbolicList(held),
1058
- excludedDomains: [...record.excludedDomains].sort(),
1059
- mutexGroups: [...record.spec.mutexGroups],
1060
- blockers: effective ? [...effective.blockers.values()] : [],
1061
- registeredAtMs: record.registeredAtMs,
1062
- lastTouchedAtMs: record.lastTouchedAtMs,
1063
- nextExpiryAtMs: expiries.length > 0 ? Math.min(...expiries) : undefined,
1064
- deadlineAtMs: record.spec.deadlineAtMs,
1065
- releasedAtMs: record.releasedAtMs,
1066
- releaseReason: record.releaseReason,
1067
- metadata: record.spec.metadata,
1068
- };
1069
- }
1070
-
1071
- private sweepExpired(now: number): void {
1072
- let changed = false;
1073
- for (const record of this.controllers.values()) {
1074
- if (record.releasedAtMs !== undefined) continue;
1075
- if (record.spec.lifecycle === 'finite'
1076
- && record.spec.deadlineAtMs !== undefined
1077
- && now >= record.spec.deadlineAtMs) {
1078
- record.releasedAtMs = record.spec.deadlineAtMs;
1079
- record.releaseReason = 'deadline_expired';
1080
- record.ready = false;
1081
- record.epoch += 1;
1082
- record.authorityEpoch += 1;
1083
- changed = true;
1084
- continue;
1085
- }
1086
- for (const [domain, claim] of record.claims) {
1087
- if (claim.expiresAtMs !== undefined && now >= claim.expiresAtMs) {
1088
- record.claims.delete(domain);
1089
- record.epoch += 1;
1090
- record.authorityEpoch += 1;
1091
- changed = true;
1092
- }
1093
- }
1094
- }
1095
- if (changed) {
1096
- this.pruneReleasedControllers();
1097
- this.changed();
1098
- }
1099
- }
1100
-
1101
- private pruneReleasedControllers(): void {
1102
- const released = [...this.controllers.entries()]
1103
- .filter(([, record]) => record.releasedAtMs !== undefined)
1104
- .sort(([, left], [, right]) => (
1105
- (left.releasedAtMs ?? 0) - (right.releasedAtMs ?? 0)
1106
- || left.sequence - right.sequence
1107
- ));
1108
- for (const [controllerId] of released.slice(
1109
- 0,
1110
- Math.max(0, released.length - MAX_RELEASED_TOMBSTONES),
1111
- )) {
1112
- this.controllers.delete(controllerId);
1113
- }
1114
- }
1115
-
1116
- private isDeclaredDomain(record: ControllerRecord, domain: string): boolean {
1117
- return domain === WILDCARD_DOMAIN
1118
- ? record.spec.domains.includes(WILDCARD_DOMAIN)
1119
- : record.spec.domains.includes(domain) || record.spec.domains.includes(WILDCARD_DOMAIN);
1120
- }
1121
-
1122
- private releaseDomain(record: ControllerRecord, domain: string): void {
1123
- if (domain === WILDCARD_DOMAIN) {
1124
- record.claims.clear();
1125
- record.excludedDomains.clear();
1126
- return;
1127
- }
1128
- record.claims.delete(domain);
1129
- if (record.claims.has(WILDCARD_DOMAIN)) record.excludedDomains.add(domain);
1130
- }
1131
-
1132
- private applyTouch(
1133
- record: ControllerRecord,
1134
- domains: string[],
1135
- now: number,
1136
- activityLeaseMs: number,
1137
- ): void {
1138
- for (const domain of domains) {
1139
- if (!this.isDeclaredDomain(record, domain)) {
1140
- throw new Error(
1141
- `Controller ${record.spec.controllerId} did not declare control domain: ${domain}`,
1142
- );
1143
- }
1144
- if (domain === WILDCARD_DOMAIN) record.excludedDomains.clear();
1145
- else record.excludedDomains.delete(domain);
1146
- record.claims.set(domain, record.spec.lifecycle === 'activity_lease'
1147
- ? { expiresAtMs: now + activityLeaseMs }
1148
- : record.spec.lifecycle === 'finite'
1149
- ? { expiresAtMs: record.spec.deadlineAtMs }
1150
- : {});
1151
- }
1152
- }
1153
-
1154
- private conflictingInFlight(
1155
- controller: ControllerRecord,
1156
- scope: ScopeRef,
1157
- domains: string[],
1158
- ): InFlightOperation[] {
1159
- const requested = requestDomains(domains);
1160
- return [...this.inFlight.values()].filter((operation) => {
1161
- // Scope transition is a global barrier: no provider from two logical
1162
- // segments may overlap, even when their named domains differ.
1163
- if (operation.scopeKey !== scopeKey(scope)) return true;
1164
- return domainsOverlap(requested, operation.domainSet)
1165
- || (operation.sequence !== controller.sequence
1166
- && controller.spec.mutexGroups.some((group) => operation.mutexGroups.includes(group)));
1167
- });
1168
- }
1169
-
1170
- private precedes(controller: ControllerRecord, operation: InFlightOperation): boolean {
1171
- return controller.spec.priority > operation.priority
1172
- || (controller.spec.priority === operation.priority
1173
- && controller.sequence < operation.sequence);
1174
- }
1175
-
1176
- private async waitForOperations(
1177
- operations: InFlightOperation[],
1178
- timeoutMs: number,
1179
- shouldInterrupt: () => boolean,
1180
- ): Promise<OperationWaitResult> {
1181
- if (operations.length === 0) return 'settled';
1182
- if (shouldInterrupt()) return 'interrupted';
1183
- if (timeoutMs <= 0) return 'timeout';
1184
-
1185
- let resolveInterrupt!: () => void;
1186
- const interrupted = new Promise<void>((resolve) => { resolveInterrupt = resolve; });
1187
- const waiter = (): boolean => {
1188
- if (!shouldInterrupt()) return false;
1189
- resolveInterrupt();
1190
- return true;
1191
- };
1192
- this.changeWaiters.add(waiter);
1193
- try {
1194
- return await Promise.race([
1195
- Promise.all(operations.map((operation) => operation.settled)).then(() => 'settled' as const),
1196
- this.clock.sleep(timeoutMs).then(() => 'timeout' as const),
1197
- interrupted.then(() => 'interrupted' as const),
1198
- ]);
1199
- } finally {
1200
- this.changeWaiters.delete(waiter);
1201
- }
1202
- }
1203
-
1204
- private nextTransitionDelay(): number | undefined {
1205
- const now = this.clock.now();
1206
- let next: number | undefined;
1207
- for (const record of this.controllers.values()) {
1208
- if (record.releasedAtMs !== undefined) continue;
1209
- if (record.spec.deadlineAtMs !== undefined && record.spec.deadlineAtMs > now) {
1210
- next = Math.min(next ?? Number.POSITIVE_INFINITY, record.spec.deadlineAtMs);
1211
- }
1212
- for (const claim of record.claims.values()) {
1213
- if (claim.expiresAtMs !== undefined && claim.expiresAtMs > now) {
1214
- next = Math.min(next ?? Number.POSITIVE_INFINITY, claim.expiresAtMs);
1215
- }
1216
- }
1217
- }
1218
- return next === undefined ? undefined : next - now;
1219
- }
1220
-
1221
- private async waitForChange(milliseconds?: number, signal?: AbortSignal): Promise<void> {
1222
- if (signal?.aborted) return;
1223
- let resolveChange!: () => void;
1224
- const changed = new Promise<void>((resolve) => { resolveChange = resolve; });
1225
- this.changeWaiters.add(resolveChange);
1226
- let abortHandler: (() => void) | undefined;
1227
- const aborted = new Promise<void>((resolve) => {
1228
- abortHandler = resolve;
1229
- signal?.addEventListener('abort', abortHandler, { once: true });
1230
- });
1231
- const waits: Promise<void>[] = [changed, aborted];
1232
- if (milliseconds !== undefined) waits.push(this.clock.sleep(milliseconds));
1233
- try {
1234
- await Promise.race(waits);
1235
- } finally {
1236
- this.changeWaiters.delete(resolveChange);
1237
- if (abortHandler) signal?.removeEventListener('abort', abortHandler);
1238
- }
1239
- }
1240
-
1241
- private changed(): void {
1242
- this.version += 1;
1243
- for (const waiter of [...this.changeWaiters]) {
1244
- if (waiter() !== false) this.changeWaiters.delete(waiter);
1245
- }
1246
- }
1247
-
1248
- private deferred(
1249
- code: ControlDeferred['code'],
1250
- controllerId: string,
1251
- domains: string[],
1252
- reason: string,
1253
- retryable: boolean,
1254
- blockedBy?: string[],
1255
- ): ControlDeferred {
1256
- return {
1257
- status: 'deferred',
1258
- code,
1259
- controllerId,
1260
- domains: [...domains],
1261
- retryable,
1262
- reason,
1263
- ...(blockedBy && blockedBy.length > 0
1264
- ? { blockedBy: [...new Set(blockedBy)].sort() }
1265
- : {}),
1266
- };
1267
- }
1268
- }
1
+ // Compatibility facade; implementation lives in the game-neutral runtime package.
2
+ export * from '@myclaw163/game-agent-runtime/framework/control/control-scheduler.js';