@avantics/node-red-home-automation 0.0.0-stage → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +292 -2
- package/contract-examples/README.md +28 -0
- package/contract-examples/_shared.mjs +11 -0
- package/contract-examples/motion-lighting.mjs +42 -0
- package/contract-examples/occupancy-fusion.mjs +35 -0
- package/contract-examples/room-lighting.mjs +58 -0
- package/contract-examples/run.mjs +16 -0
- package/contract-examples/source-readiness.mjs +64 -0
- package/contract-examples/switch-gestures.mjs +34 -0
- package/contract-examples/theatre-activity.mjs +62 -0
- package/contract-examples/volume-ownership.mjs +59 -0
- package/dist/lib/activity-lighting-controller.d.ts +129 -0
- package/dist/lib/activity-lighting-controller.js +372 -0
- package/dist/lib/avr-controller.d.ts +169 -0
- package/dist/lib/avr-controller.js +948 -0
- package/dist/lib/backlighting-controller.d.ts +108 -0
- package/dist/lib/backlighting-controller.js +269 -0
- package/dist/lib/bounded-trace.d.ts +30 -0
- package/dist/lib/bounded-trace.js +36 -0
- package/dist/lib/circadian-refresh.d.ts +7 -0
- package/dist/lib/circadian-refresh.js +11 -0
- package/dist/lib/circadian-schedule.d.ts +11 -0
- package/dist/lib/circadian-schedule.js +63 -0
- package/dist/lib/circadian.d.ts +6 -0
- package/dist/lib/circadian.js +15 -0
- package/dist/lib/cover-controller.d.ts +130 -0
- package/dist/lib/cover-controller.js +336 -0
- package/dist/lib/display-mode-controller.d.ts +148 -0
- package/dist/lib/display-mode-controller.js +587 -0
- package/dist/lib/display-transport.d.ts +41 -0
- package/dist/lib/display-transport.js +177 -0
- package/dist/lib/light-styling.d.ts +11 -0
- package/dist/lib/light-styling.js +15 -0
- package/dist/lib/motion-policy.d.ts +72 -0
- package/dist/lib/motion-policy.js +251 -0
- package/dist/lib/observation-time.d.ts +10 -0
- package/dist/lib/observation-time.js +40 -0
- package/dist/lib/occupancy-fusion.d.ts +53 -0
- package/dist/lib/occupancy-fusion.js +131 -0
- package/dist/lib/room-controller.d.ts +113 -0
- package/dist/lib/room-controller.js +431 -0
- package/dist/lib/source-capability-controller.d.ts +144 -0
- package/dist/lib/source-capability-controller.js +494 -0
- package/dist/lib/switch-policy.d.ts +53 -0
- package/dist/lib/switch-policy.js +110 -0
- package/dist/lib/theatre-activity-controller.d.ts +165 -0
- package/dist/lib/theatre-activity-controller.js +846 -0
- package/dist/lib/theatre-slo.d.ts +49 -0
- package/dist/lib/theatre-slo.js +156 -0
- package/dist/lib/theatre-state-contract.d.ts +77 -0
- package/dist/lib/theatre-state-contract.js +391 -0
- package/dist/lib/wall-input.d.ts +62 -0
- package/dist/lib/wall-input.js +198 -0
- package/dist/nodes/activity-lighting-controller.d.ts +3 -0
- package/dist/nodes/activity-lighting-controller.html +38 -0
- package/dist/nodes/activity-lighting-controller.js +116 -0
- package/dist/nodes/avr-controller.d.ts +3 -0
- package/dist/nodes/avr-controller.html +47 -0
- package/dist/nodes/avr-controller.js +130 -0
- package/dist/nodes/backlighting-controller.d.ts +3 -0
- package/dist/nodes/backlighting-controller.html +31 -0
- package/dist/nodes/backlighting-controller.js +103 -0
- package/dist/nodes/display-mode-controller.d.ts +3 -0
- package/dist/nodes/display-mode-controller.html +66 -0
- package/dist/nodes/display-mode-controller.js +132 -0
- package/dist/nodes/motion-policy.d.ts +3 -0
- package/dist/nodes/motion-policy.html +35 -0
- package/dist/nodes/motion-policy.js +194 -0
- package/dist/nodes/occupancy-fusion.d.ts +3 -0
- package/dist/nodes/occupancy-fusion.html +32 -0
- package/dist/nodes/occupancy-fusion.js +53 -0
- package/dist/nodes/room-controller.d.ts +3 -0
- package/dist/nodes/room-controller.html +82 -0
- package/dist/nodes/room-controller.js +123 -0
- package/dist/nodes/source-capability-controller.d.ts +3 -0
- package/dist/nodes/source-capability-controller.html +46 -0
- package/dist/nodes/source-capability-controller.js +114 -0
- package/dist/nodes/switch-policy.d.ts +3 -0
- package/dist/nodes/switch-policy.html +29 -0
- package/dist/nodes/switch-policy.js +129 -0
- package/dist/nodes/theatre-activity-controller.d.ts +3 -0
- package/dist/nodes/theatre-activity-controller.html +32 -0
- package/dist/nodes/theatre-activity-controller.js +105 -0
- package/dist/nodes/theatre-state-contract.d.ts +3 -0
- package/dist/nodes/theatre-state-contract.html +41 -0
- package/dist/nodes/theatre-state-contract.js +83 -0
- package/examples/Home theatre activity.json +477 -0
- package/examples/Home theatre equipment.json +329 -0
- package/examples/Room lighting.json +212 -0
- package/package.json +62 -4
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TARGETS = void 0;
|
|
4
|
+
exports.normaliseActivityProfiles = normaliseActivityProfiles;
|
|
5
|
+
exports.createTheatreState = createTheatreState;
|
|
6
|
+
exports.normaliseConfig = normaliseConfig;
|
|
7
|
+
exports.transitionTheatre = transitionTheatre;
|
|
8
|
+
const observation_time_1 = require("./observation-time");
|
|
9
|
+
const PROFILE_NAME = /^[a-z][a-z0-9_-]*$/;
|
|
10
|
+
exports.TARGETS = ["display", "avr", "source", "lighting", "backlighting"];
|
|
11
|
+
const REQUIRED_TARGETS = ["display", "avr", "backlighting"];
|
|
12
|
+
const OPTIONAL_TARGETS = ["lighting"];
|
|
13
|
+
const TARGET_STATUSES = {
|
|
14
|
+
discovering: true,
|
|
15
|
+
transitioning: true,
|
|
16
|
+
confirming: true,
|
|
17
|
+
ready: true,
|
|
18
|
+
waiting_for_source: true,
|
|
19
|
+
failed: true,
|
|
20
|
+
unavailable: true
|
|
21
|
+
};
|
|
22
|
+
const TARGET_CLASSIFICATIONS = {
|
|
23
|
+
drift: true,
|
|
24
|
+
manual_override: true
|
|
25
|
+
};
|
|
26
|
+
const AVAILABILITIES = {
|
|
27
|
+
unknown: true,
|
|
28
|
+
available: true,
|
|
29
|
+
degraded: true,
|
|
30
|
+
unavailable: true
|
|
31
|
+
};
|
|
32
|
+
const SOURCE_ACTIONS = { activate: true, deactivate: true };
|
|
33
|
+
const SOURCE_READINESS = { required: true, optional: true };
|
|
34
|
+
const BACKLIGHTING_POWER = {
|
|
35
|
+
on: true,
|
|
36
|
+
off: true
|
|
37
|
+
};
|
|
38
|
+
function normaliseActivityProfiles(value) {
|
|
39
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
40
|
+
throw new Error("activityProfiles must be an object");
|
|
41
|
+
}
|
|
42
|
+
const entries = Object.entries(value);
|
|
43
|
+
if (entries.length === 0)
|
|
44
|
+
throw new Error("activityProfiles must not be empty");
|
|
45
|
+
const profiles = {};
|
|
46
|
+
for (const [name, profileValue] of entries) {
|
|
47
|
+
if (!PROFILE_NAME.test(name))
|
|
48
|
+
throw new Error(`invalid activity profile name: ${name}`);
|
|
49
|
+
if (!profileValue || typeof profileValue !== "object" || Array.isArray(profileValue)) {
|
|
50
|
+
throw new Error(`activity profile ${name} must be an object`);
|
|
51
|
+
}
|
|
52
|
+
const profile = profileValue;
|
|
53
|
+
const targets = {};
|
|
54
|
+
for (const target of exports.TARGETS) {
|
|
55
|
+
const desired = profile[target];
|
|
56
|
+
if (!desired || typeof desired !== "object" || Array.isArray(desired)) {
|
|
57
|
+
throw new Error(`activity profile ${name} must define ${target}`);
|
|
58
|
+
}
|
|
59
|
+
targets[target] = { ...desired };
|
|
60
|
+
}
|
|
61
|
+
const source = targets.source;
|
|
62
|
+
if (!Object.hasOwn(SOURCE_ACTIONS, source.action)) {
|
|
63
|
+
throw new Error(`activity profile ${name} has an invalid source action`);
|
|
64
|
+
}
|
|
65
|
+
if (!Object.hasOwn(SOURCE_READINESS, source.readiness)) {
|
|
66
|
+
throw new Error(`activity profile ${name} has invalid source readiness`);
|
|
67
|
+
}
|
|
68
|
+
if (source.action === "activate" &&
|
|
69
|
+
(typeof source.sourceId !== "string" || !source.sourceId)) {
|
|
70
|
+
throw new Error(`activity profile ${name} must define sourceId`);
|
|
71
|
+
}
|
|
72
|
+
const lighting = targets.lighting;
|
|
73
|
+
if (typeof lighting.profile !== "string" || !PROFILE_NAME.test(lighting.profile)) {
|
|
74
|
+
throw new Error(`activity profile ${name} has invalid lighting profile`);
|
|
75
|
+
}
|
|
76
|
+
const backlighting = targets.backlighting;
|
|
77
|
+
if (!Object.hasOwn(BACKLIGHTING_POWER, backlighting.power)) {
|
|
78
|
+
throw new Error(`activity profile ${name} has invalid backlighting power`);
|
|
79
|
+
}
|
|
80
|
+
profiles[name] = targets;
|
|
81
|
+
}
|
|
82
|
+
return profiles;
|
|
83
|
+
}
|
|
84
|
+
function emptyTargets(saved = {}) {
|
|
85
|
+
return Object.fromEntries(exports.TARGETS.map((target) => [
|
|
86
|
+
target,
|
|
87
|
+
saved[target] && typeof saved[target] === "object" ? { ...saved[target] } : null
|
|
88
|
+
]));
|
|
89
|
+
}
|
|
90
|
+
// A refresh is re-sent at this many attempts at most before the target is
|
|
91
|
+
// reported as not responding.
|
|
92
|
+
const REFRESH_ATTEMPTS = 3;
|
|
93
|
+
function emptyRefreshPending(saved = {}) {
|
|
94
|
+
return Object.fromEntries(exports.TARGETS.map((target) => {
|
|
95
|
+
const entry = saved[target];
|
|
96
|
+
// Saved before retries existed: pending with no send time, so it retries.
|
|
97
|
+
if (entry === true)
|
|
98
|
+
return [target, { sentAt: 0, attempts: 1, exhausted: false }];
|
|
99
|
+
if (entry && typeof entry === "object" && Number.isFinite(entry.sentAt) && Number.isInteger(entry.attempts)) {
|
|
100
|
+
return [target, { sentAt: entry.sentAt, attempts: entry.attempts, exhausted: entry.exhausted === true }];
|
|
101
|
+
}
|
|
102
|
+
return [target, null];
|
|
103
|
+
}));
|
|
104
|
+
}
|
|
105
|
+
function count(value) {
|
|
106
|
+
const parsed = Number(value);
|
|
107
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
|
|
108
|
+
}
|
|
109
|
+
function nullableDuration(value) {
|
|
110
|
+
const parsed = Number(value);
|
|
111
|
+
return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
|
|
112
|
+
}
|
|
113
|
+
function targetMetrics(saved = {}) {
|
|
114
|
+
return Object.fromEntries(exports.TARGETS.map((target) => {
|
|
115
|
+
const metric = saved[target] || {};
|
|
116
|
+
const availability = typeof metric.availability === "string" &&
|
|
117
|
+
Object.hasOwn(AVAILABILITIES, metric.availability)
|
|
118
|
+
? metric.availability
|
|
119
|
+
: "unknown";
|
|
120
|
+
return [target, {
|
|
121
|
+
attempts: count(metric.attempts),
|
|
122
|
+
retries: count(metric.retries),
|
|
123
|
+
failures: count(metric.failures),
|
|
124
|
+
manualOverrides: count(metric.manualOverrides),
|
|
125
|
+
fallbackUses: count(metric.fallbackUses),
|
|
126
|
+
fallbackUsed: metric.fallbackUsed === true,
|
|
127
|
+
lastConfirmationMs: nullableDuration(metric.lastConfirmationMs),
|
|
128
|
+
observationAgeMs: nullableDuration(metric.observationAgeMs),
|
|
129
|
+
availability
|
|
130
|
+
}];
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
function createMetrics(saved = {}) {
|
|
134
|
+
return {
|
|
135
|
+
requests: count(saved.requests),
|
|
136
|
+
ready: count(saved.ready),
|
|
137
|
+
failed: count(saved.failed),
|
|
138
|
+
superseded: count(saved.superseded),
|
|
139
|
+
manualOverrides: count(saved.manualOverrides),
|
|
140
|
+
driftEvents: count(saved.driftEvents),
|
|
141
|
+
recoveriesAdopted: count(saved.recoveriesAdopted),
|
|
142
|
+
recoveriesSafeOff: count(saved.recoveriesSafeOff),
|
|
143
|
+
lastTransitionMs: nullableDuration(saved.lastTransitionMs),
|
|
144
|
+
maxTransitionMs: nullableDuration(saved.maxTransitionMs),
|
|
145
|
+
lastOutcome: typeof saved.lastOutcome === "string" ? saved.lastOutcome : null,
|
|
146
|
+
targets: targetMetrics(saved.targets)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function createTheatreState(saved = {}, activityProfiles = {}) {
|
|
150
|
+
const savedDesired = saved.desired && typeof saved.desired === "object" ? saved.desired : null;
|
|
151
|
+
const desired = savedDesired && Object.hasOwn(activityProfiles, savedDesired.activity)
|
|
152
|
+
? { ...savedDesired }
|
|
153
|
+
: null;
|
|
154
|
+
return {
|
|
155
|
+
desired,
|
|
156
|
+
currentActivity: typeof saved.currentActivity === "string" &&
|
|
157
|
+
Object.hasOwn(activityProfiles, saved.currentActivity)
|
|
158
|
+
? saved.currentActivity
|
|
159
|
+
: "unknown",
|
|
160
|
+
generation: Number.isInteger(saved.generation) && (saved.generation ?? -1) >= 0 ? saved.generation : 0,
|
|
161
|
+
lastProposedGeneration: Number.isInteger(saved.lastProposedGeneration)
|
|
162
|
+
? saved.lastProposedGeneration
|
|
163
|
+
: savedDesired && !savedDesired.requestId.startsWith("recovery-") && Number.isInteger(savedDesired.generation)
|
|
164
|
+
? savedDesired.generation
|
|
165
|
+
: 0,
|
|
166
|
+
phase: typeof saved.phase === "string" ? saved.phase : "idle",
|
|
167
|
+
targets: emptyTargets(saved.targets),
|
|
168
|
+
refreshPending: emptyRefreshPending(saved.refreshPending),
|
|
169
|
+
failure: saved.failure && typeof saved.failure === "object" ? { ...saved.failure } : null,
|
|
170
|
+
blockedGeneration: Number.isInteger(saved.blockedGeneration) ? saved.blockedGeneration : null,
|
|
171
|
+
degraded: Array.isArray(saved.degraded) ? saved.degraded.map((entry) => ({ ...entry })) : [],
|
|
172
|
+
availability: saved.availability && Object.hasOwn(AVAILABILITIES, saved.availability)
|
|
173
|
+
? saved.availability
|
|
174
|
+
: "unknown",
|
|
175
|
+
transitionStartedAt: typeof saved.transitionStartedAt === "string"
|
|
176
|
+
? saved.transitionStartedAt
|
|
177
|
+
: null,
|
|
178
|
+
transitionCompletedAt: typeof saved.transitionCompletedAt === "string"
|
|
179
|
+
? saved.transitionCompletedAt
|
|
180
|
+
: null,
|
|
181
|
+
metrics: createMetrics(saved.metrics)
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function normaliseConfig(config = {}) {
|
|
185
|
+
const activityProfiles = normaliseActivityProfiles(config.activityProfiles);
|
|
186
|
+
const recoveryOffActivity = typeof config.recoveryOffActivity === "string" &&
|
|
187
|
+
config.recoveryOffActivity
|
|
188
|
+
? config.recoveryOffActivity
|
|
189
|
+
: "off";
|
|
190
|
+
return {
|
|
191
|
+
area: typeof config.area === "string" && config.area ? config.area : "room",
|
|
192
|
+
freshnessMs: Math.max(1000, Number(config.freshnessMs) || 30000),
|
|
193
|
+
activityProfiles,
|
|
194
|
+
recoveryOffActivity
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
function targetCommand(target, kind, desired, values = {}) {
|
|
198
|
+
return {
|
|
199
|
+
target,
|
|
200
|
+
kind,
|
|
201
|
+
requestId: desired?.requestId || null,
|
|
202
|
+
generation: desired?.generation || 0,
|
|
203
|
+
...values
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function targetIntentCommands(desired, config, previousDesired) {
|
|
207
|
+
const profile = config.activityProfiles[desired.activity];
|
|
208
|
+
if (!profile)
|
|
209
|
+
throw new Error("desired activity profile is missing");
|
|
210
|
+
const previousSource = previousDesired
|
|
211
|
+
? config.activityProfiles[previousDesired.activity]?.source
|
|
212
|
+
: null;
|
|
213
|
+
return exports.TARGETS.map((target) => {
|
|
214
|
+
let values = profile[target];
|
|
215
|
+
if (target === "source" && values.action === "deactivate" && !values.sourceId) {
|
|
216
|
+
values = { ...values, sourceId: previousSource?.sourceId || null };
|
|
217
|
+
}
|
|
218
|
+
return targetCommand(target, "intent", desired, values);
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
function targetRefreshCommands(desired) {
|
|
222
|
+
return exports.TARGETS.map((target) => targetCommand(target, "refresh", desired));
|
|
223
|
+
}
|
|
224
|
+
function targetProbeCommands() {
|
|
225
|
+
return exports.TARGETS.map((target) => targetCommand(target, "refresh", null));
|
|
226
|
+
}
|
|
227
|
+
function observationTime(targetState) {
|
|
228
|
+
return typeof targetState?.observedAt === "string" ? (0, observation_time_1.parseObservedAt)(targetState.observedAt) : null;
|
|
229
|
+
}
|
|
230
|
+
function isFresh(targetState, nowMs, freshnessMs) {
|
|
231
|
+
return (0, observation_time_1.isFresh)(observationTime(targetState), nowMs, freshnessMs);
|
|
232
|
+
}
|
|
233
|
+
function statusFor(state) {
|
|
234
|
+
const activity = state.desired?.activity || "none";
|
|
235
|
+
if (state.phase === "failed") {
|
|
236
|
+
return { phase: "failed", text: `${activity}: ${state.failure?.reason || "failed"}` };
|
|
237
|
+
}
|
|
238
|
+
return { phase: state.phase, text: `${activity}: ${state.phase}` };
|
|
239
|
+
}
|
|
240
|
+
function stateEvent(state, area) {
|
|
241
|
+
return {
|
|
242
|
+
theatre: {
|
|
243
|
+
kind: "state",
|
|
244
|
+
area,
|
|
245
|
+
requestId: state.desired?.requestId || null,
|
|
246
|
+
generation: state.generation,
|
|
247
|
+
desiredActivity: state.desired?.activity || null,
|
|
248
|
+
requestedAt: state.desired?.requestedAt || null,
|
|
249
|
+
currentActivity: state.currentActivity,
|
|
250
|
+
phase: state.phase,
|
|
251
|
+
availability: state.availability,
|
|
252
|
+
transitionStartedAt: state.transitionStartedAt,
|
|
253
|
+
transitionCompletedAt: state.transitionCompletedAt,
|
|
254
|
+
targets: emptyTargets(state.targets),
|
|
255
|
+
failure: state.failure ? { ...state.failure } : null,
|
|
256
|
+
degraded: state.degraded.map((entry) => ({ ...entry })),
|
|
257
|
+
metrics: createMetrics(state.metrics)
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
const RECOVERY_TARGETS = ["display", "avr", "source", "backlighting"];
|
|
262
|
+
function matchesExpected(expected, observed) {
|
|
263
|
+
if (!expected || typeof expected !== "object" || Array.isArray(expected)) {
|
|
264
|
+
return Object.is(expected, observed);
|
|
265
|
+
}
|
|
266
|
+
if (!observed || typeof observed !== "object" || Array.isArray(observed))
|
|
267
|
+
return false;
|
|
268
|
+
return Object.entries(expected).every(([key, value]) => matchesExpected(value, observed[key]));
|
|
269
|
+
}
|
|
270
|
+
function recoveryMatches(profile, observations, nowMs, freshnessMs) {
|
|
271
|
+
return RECOVERY_TARGETS.every((target) => {
|
|
272
|
+
const observation = observations[target];
|
|
273
|
+
if (!observation || !isFresh(observation, nowMs, freshnessMs))
|
|
274
|
+
return false;
|
|
275
|
+
const expected = { ...profile[target] };
|
|
276
|
+
if (target === "source")
|
|
277
|
+
delete expected.readiness;
|
|
278
|
+
return matchesExpected(expected, observation.values);
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
function transitionTheatre(saved, msg, suppliedConfig = {}, nowValue = new Date()) {
|
|
282
|
+
const config = normaliseConfig(suppliedConfig);
|
|
283
|
+
const now = nowValue instanceof Date ? nowValue : new Date(nowValue);
|
|
284
|
+
const nowMs = now.getTime();
|
|
285
|
+
if (!Number.isFinite(nowMs))
|
|
286
|
+
throw new Error("now must be a valid date");
|
|
287
|
+
const state = createTheatreState(saved, config.activityProfiles);
|
|
288
|
+
const event = msg?.theatre;
|
|
289
|
+
const commands = [];
|
|
290
|
+
const events = [];
|
|
291
|
+
const traces = [];
|
|
292
|
+
if (!event || typeof event.kind !== "string")
|
|
293
|
+
throw new Error("msg.theatre.kind is required");
|
|
294
|
+
function trace(name, outcome, reason = null, details = {}) {
|
|
295
|
+
traces.push({ event: name, outcome, reason, details });
|
|
296
|
+
}
|
|
297
|
+
function emit(kind, details = {}) {
|
|
298
|
+
events.push({
|
|
299
|
+
theatre: {
|
|
300
|
+
kind,
|
|
301
|
+
area: config.area,
|
|
302
|
+
requestId: state.desired?.requestId || null,
|
|
303
|
+
generation: state.generation,
|
|
304
|
+
activity: state.desired?.activity || null,
|
|
305
|
+
...details
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
function completeTransition(outcome) {
|
|
310
|
+
const startedAt = Date.parse(state.transitionStartedAt || "");
|
|
311
|
+
if (Number.isFinite(startedAt)) {
|
|
312
|
+
const duration = Math.max(0, nowMs - startedAt);
|
|
313
|
+
state.metrics.lastTransitionMs = duration;
|
|
314
|
+
state.metrics.maxTransitionMs = Math.max(state.metrics.maxTransitionMs || 0, duration);
|
|
315
|
+
}
|
|
316
|
+
state.metrics.lastOutcome = outcome;
|
|
317
|
+
if (outcome === "ready")
|
|
318
|
+
state.metrics.ready += 1;
|
|
319
|
+
if (outcome === "failed")
|
|
320
|
+
state.metrics.failed += 1;
|
|
321
|
+
}
|
|
322
|
+
function resetTransitionMetrics() {
|
|
323
|
+
for (const target of exports.TARGETS) {
|
|
324
|
+
const metric = state.metrics.targets[target];
|
|
325
|
+
metric.attempts = 0;
|
|
326
|
+
metric.retries = 0;
|
|
327
|
+
metric.fallbackUsed = false;
|
|
328
|
+
metric.lastConfirmationMs = null;
|
|
329
|
+
metric.observationAgeMs = null;
|
|
330
|
+
metric.availability = "unknown";
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
function updateTargetMetrics(target, targetState, previous) {
|
|
334
|
+
const metric = state.metrics.targets[target];
|
|
335
|
+
const details = targetState.details && typeof targetState.details === "object"
|
|
336
|
+
? targetState.details
|
|
337
|
+
: {};
|
|
338
|
+
const detailMetrics = details.metrics && typeof details.metrics === "object" &&
|
|
339
|
+
!Array.isArray(details.metrics)
|
|
340
|
+
? details.metrics
|
|
341
|
+
: {};
|
|
342
|
+
const attempts = count(detailMetrics.attempts ?? details.attempt);
|
|
343
|
+
metric.attempts = Math.max(metric.attempts, attempts);
|
|
344
|
+
metric.retries = Math.max(metric.retries, Math.max(0, attempts - 1));
|
|
345
|
+
const fallbackUsed = detailMetrics.fallbackUsed === true;
|
|
346
|
+
if (fallbackUsed && !metric.fallbackUsed)
|
|
347
|
+
metric.fallbackUses += 1;
|
|
348
|
+
metric.fallbackUsed ||= fallbackUsed;
|
|
349
|
+
const observedAt = observationTime(targetState);
|
|
350
|
+
metric.observationAgeMs = observedAt === null ? null : Math.max(0, nowMs - observedAt);
|
|
351
|
+
if (targetState.status === "ready") {
|
|
352
|
+
const startedAt = Date.parse(state.transitionStartedAt || "");
|
|
353
|
+
metric.lastConfirmationMs = Number.isFinite(startedAt) && observedAt !== null
|
|
354
|
+
? Math.max(0, observedAt - startedAt)
|
|
355
|
+
: null;
|
|
356
|
+
metric.availability = "available";
|
|
357
|
+
}
|
|
358
|
+
else if (targetState.status === "failed" || targetState.status === "unavailable") {
|
|
359
|
+
metric.availability = "unavailable";
|
|
360
|
+
if (previous?.status !== targetState.status)
|
|
361
|
+
metric.failures += 1;
|
|
362
|
+
}
|
|
363
|
+
else {
|
|
364
|
+
metric.availability = "degraded";
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function fail(target, targetState) {
|
|
368
|
+
const firstFailure = state.phase !== "failed";
|
|
369
|
+
const failure = targetState.failure && typeof targetState.failure === "object"
|
|
370
|
+
? targetState.failure
|
|
371
|
+
: {};
|
|
372
|
+
state.failure = {
|
|
373
|
+
target,
|
|
374
|
+
operation: failure.operation || null,
|
|
375
|
+
reason: failure.reason || (targetState.status === "unavailable" ? "unavailable" : "target-failed"),
|
|
376
|
+
occurredAt: failure.occurredAt || targetState.observedAt || now.toISOString()
|
|
377
|
+
};
|
|
378
|
+
state.blockedGeneration = state.generation;
|
|
379
|
+
state.currentActivity = "unknown";
|
|
380
|
+
state.phase = "failed";
|
|
381
|
+
state.availability = "unavailable";
|
|
382
|
+
state.transitionCompletedAt = state.transitionCompletedAt || now.toISOString();
|
|
383
|
+
if (firstFailure)
|
|
384
|
+
completeTransition("failed");
|
|
385
|
+
}
|
|
386
|
+
function reconcile() {
|
|
387
|
+
const previousPhase = state.phase;
|
|
388
|
+
const previousCurrent = state.currentActivity;
|
|
389
|
+
state.degraded = [];
|
|
390
|
+
if (!state.desired) {
|
|
391
|
+
if (state.phase !== "recovering")
|
|
392
|
+
state.phase = "idle";
|
|
393
|
+
state.currentActivity = "unknown";
|
|
394
|
+
state.availability = "unknown";
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (state.blockedGeneration === state.generation) {
|
|
398
|
+
state.phase = "failed";
|
|
399
|
+
state.currentActivity = "unknown";
|
|
400
|
+
state.availability = "unavailable";
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const profile = config.activityProfiles[state.desired.activity];
|
|
404
|
+
if (!profile)
|
|
405
|
+
throw new Error("desired activity profile is missing");
|
|
406
|
+
const sourceProfile = profile.source;
|
|
407
|
+
for (const target of exports.TARGETS) {
|
|
408
|
+
const optional = OPTIONAL_TARGETS.includes(target) ||
|
|
409
|
+
(target === "source" && sourceProfile.readiness === "optional");
|
|
410
|
+
if (!optional)
|
|
411
|
+
continue;
|
|
412
|
+
const targetState = state.targets[target];
|
|
413
|
+
if (!targetState) {
|
|
414
|
+
state.degraded.push({ target, reason: "unconfirmed" });
|
|
415
|
+
}
|
|
416
|
+
else if (!isFresh(targetState, nowMs, config.freshnessMs)) {
|
|
417
|
+
state.degraded.push({ target, reason: "stale" });
|
|
418
|
+
}
|
|
419
|
+
else if (targetState.status !== "ready") {
|
|
420
|
+
state.degraded.push({ target, reason: targetState.failure?.reason || targetState.status });
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const manualTarget = exports.TARGETS.find((target) => {
|
|
424
|
+
const targetState = state.targets[target];
|
|
425
|
+
return targetState?.classification === "manual_override" &&
|
|
426
|
+
isFresh(targetState, nowMs, config.freshnessMs);
|
|
427
|
+
});
|
|
428
|
+
if (manualTarget) {
|
|
429
|
+
state.phase = "manual_override";
|
|
430
|
+
state.currentActivity = "unknown";
|
|
431
|
+
state.availability = "degraded";
|
|
432
|
+
if (previousPhase !== "manual_override") {
|
|
433
|
+
completeTransition("manual_override");
|
|
434
|
+
emit("manual_override", { target: manualTarget });
|
|
435
|
+
trace("activity", "manual_override", null, { target: manualTarget });
|
|
436
|
+
}
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
for (const target of REQUIRED_TARGETS) {
|
|
440
|
+
const targetState = state.targets[target];
|
|
441
|
+
if (targetState && isFresh(targetState, nowMs, config.freshnessMs) &&
|
|
442
|
+
(targetState.status === "failed" || targetState.status === "unavailable")) {
|
|
443
|
+
fail(target, targetState);
|
|
444
|
+
break;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
if (state.phase === "failed") {
|
|
448
|
+
const failure = state.failure;
|
|
449
|
+
if (!failure)
|
|
450
|
+
throw new Error("failed theatre state is missing failure details");
|
|
451
|
+
if (previousPhase !== "failed") {
|
|
452
|
+
emit("failed", { failure });
|
|
453
|
+
trace("activity", "failed", failure.reason, { target: failure.target });
|
|
454
|
+
}
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
// Once this activity is ready, a confirmed target that is only due for
|
|
458
|
+
// re-confirmation keeps it ready; the staleness shows in degraded.
|
|
459
|
+
const holdReady = previousPhase === "ready" && previousCurrent === state.desired.activity;
|
|
460
|
+
const unverified = (target) => {
|
|
461
|
+
state.degraded.push({ target, reason: state.refreshPending[target]?.exhausted ? "no-response" : "stale" });
|
|
462
|
+
};
|
|
463
|
+
for (const target of REQUIRED_TARGETS) {
|
|
464
|
+
const targetState = state.targets[target];
|
|
465
|
+
if (targetState && holdReady && targetState.status === "ready" &&
|
|
466
|
+
!isFresh(targetState, nowMs, config.freshnessMs)) {
|
|
467
|
+
unverified(target);
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
if (!targetState || !isFresh(targetState, nowMs, config.freshnessMs)) {
|
|
471
|
+
state.phase = "confirming";
|
|
472
|
+
state.currentActivity = "unknown";
|
|
473
|
+
state.availability = "unknown";
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
if (targetState.status !== "ready") {
|
|
477
|
+
state.phase = targetState.status === "discovering" || targetState.status === "confirming"
|
|
478
|
+
? "confirming"
|
|
479
|
+
: "transitioning";
|
|
480
|
+
state.currentActivity = "unknown";
|
|
481
|
+
state.availability = state.degraded.length ? "degraded" : "available";
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
if (sourceProfile.readiness === "required") {
|
|
486
|
+
const source = state.targets.source;
|
|
487
|
+
const staleButHeld = source && holdReady && source.status === "ready" &&
|
|
488
|
+
!isFresh(source, nowMs, config.freshnessMs);
|
|
489
|
+
if (staleButHeld)
|
|
490
|
+
unverified("source");
|
|
491
|
+
else if (!source || !isFresh(source, nowMs, config.freshnessMs) || source.status !== "ready") {
|
|
492
|
+
state.phase = "waiting_for_source";
|
|
493
|
+
state.currentActivity = "unknown";
|
|
494
|
+
state.availability = "degraded";
|
|
495
|
+
if (previousPhase !== "waiting_for_source") {
|
|
496
|
+
emit("waiting_for_source", {
|
|
497
|
+
sourceId: sourceProfile.sourceId,
|
|
498
|
+
reason: source?.failure?.reason || source?.status || "unconfirmed"
|
|
499
|
+
});
|
|
500
|
+
trace("activity", "waiting", "source-unconfirmed");
|
|
501
|
+
}
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
state.failure = null;
|
|
506
|
+
state.phase = "ready";
|
|
507
|
+
state.currentActivity = state.desired.activity;
|
|
508
|
+
state.availability = state.degraded.length ? "degraded" : "available";
|
|
509
|
+
if (previousPhase !== "ready" || previousCurrent !== state.currentActivity) {
|
|
510
|
+
// Only the first ready of a generation completes its transition.
|
|
511
|
+
if (state.transitionCompletedAt === null) {
|
|
512
|
+
state.transitionCompletedAt = now.toISOString();
|
|
513
|
+
completeTransition("ready");
|
|
514
|
+
}
|
|
515
|
+
emit("ready");
|
|
516
|
+
trace("activity", "ready", null, { activity: state.currentActivity });
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
// Refresh each confirmed target at half its freshness window, so a settled
|
|
520
|
+
// activity stays fresh, and re-send an unanswered refresh a bounded number
|
|
521
|
+
// of times before reporting the target as not responding.
|
|
522
|
+
function tickRefreshes() {
|
|
523
|
+
const intervalMs = config.freshnessMs / 2;
|
|
524
|
+
for (const target of exports.TARGETS) {
|
|
525
|
+
const pending = state.refreshPending[target];
|
|
526
|
+
if (pending) {
|
|
527
|
+
if (pending.exhausted || nowMs - pending.sentAt < intervalMs)
|
|
528
|
+
continue;
|
|
529
|
+
if (pending.attempts < REFRESH_ATTEMPTS) {
|
|
530
|
+
commands.push(targetCommand(target, "refresh", state.desired));
|
|
531
|
+
state.refreshPending[target] = { sentAt: nowMs, attempts: pending.attempts + 1, exhausted: false };
|
|
532
|
+
trace("refresh", "retried", null, { target, attempt: pending.attempts + 1 });
|
|
533
|
+
}
|
|
534
|
+
else {
|
|
535
|
+
pending.exhausted = true;
|
|
536
|
+
noResponse(target);
|
|
537
|
+
}
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const targetState = state.targets[target];
|
|
541
|
+
const observedAt = observationTime(targetState);
|
|
542
|
+
if (state.desired && targetState && observedAt !== null && nowMs - observedAt >= intervalMs) {
|
|
543
|
+
commands.push(targetCommand(target, "refresh", state.desired));
|
|
544
|
+
state.refreshPending[target] = { sentAt: nowMs, attempts: 1, exhausted: false };
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
function noResponse(target) {
|
|
549
|
+
state.metrics.targets[target].availability = "unavailable";
|
|
550
|
+
trace("refresh", "no-response", null, { target, attempts: REFRESH_ATTEMPTS });
|
|
551
|
+
// Before the activity first completes, an owner that never answers is
|
|
552
|
+
// unavailable; afterwards it shows as degraded and does not undo ready.
|
|
553
|
+
if (state.desired && state.transitionCompletedAt === null) {
|
|
554
|
+
state.targets[target] = {
|
|
555
|
+
status: "unavailable",
|
|
556
|
+
observedAt: now.toISOString(),
|
|
557
|
+
classification: null,
|
|
558
|
+
failure: { operation: "refresh", reason: "no-response", occurredAt: now.toISOString() },
|
|
559
|
+
details: null
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
function acceptIntent(event, internal = false) {
|
|
564
|
+
if (typeof event.requestId !== "string" || !event.requestId) {
|
|
565
|
+
throw new Error("theatre requestId is required");
|
|
566
|
+
}
|
|
567
|
+
if (!Number.isInteger(event.generation) || event.generation < 1) {
|
|
568
|
+
throw new Error("theatre generation must be a positive integer");
|
|
569
|
+
}
|
|
570
|
+
if (!Object.hasOwn(config.activityProfiles, event.activity)) {
|
|
571
|
+
throw new Error("unknown theatre activity");
|
|
572
|
+
}
|
|
573
|
+
if (event.requestedAt && observationTime({ observedAt: event.requestedAt }) === null) {
|
|
574
|
+
throw new Error("theatre requestedAt must be an ISO timestamp");
|
|
575
|
+
}
|
|
576
|
+
// The controller owns generations: a new request whose proposed number is
|
|
577
|
+
// already taken (for example by a recovery) gets the next free one.
|
|
578
|
+
let generation = event.generation;
|
|
579
|
+
const taken = generation < state.generation || (generation === state.generation && state.desired !== null);
|
|
580
|
+
if (taken && !internal && state.desired?.requestId !== event.requestId &&
|
|
581
|
+
event.generation > state.lastProposedGeneration) {
|
|
582
|
+
generation = state.generation + 1;
|
|
583
|
+
trace("intent", "reassigned", "generation-taken", { requestId: event.requestId, proposed: event.generation, assigned: generation });
|
|
584
|
+
}
|
|
585
|
+
else if (event.generation < state.generation) {
|
|
586
|
+
emit("rejected", { reason: "stale-generation", rejectedRequestId: event.requestId });
|
|
587
|
+
trace("intent", "rejected", "stale-generation");
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (generation === state.generation && state.desired) {
|
|
591
|
+
const duplicate = state.desired.requestId === event.requestId &&
|
|
592
|
+
state.desired.activity === event.activity;
|
|
593
|
+
if (duplicate) {
|
|
594
|
+
trace("intent", "duplicate", null, { requestId: event.requestId });
|
|
595
|
+
reconcile();
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
emit("rejected", {
|
|
599
|
+
reason: state.desired.requestId === event.requestId ? "request-conflict" : "generation-conflict",
|
|
600
|
+
rejectedRequestId: event.requestId
|
|
601
|
+
});
|
|
602
|
+
trace("intent", "rejected", "generation-conflict");
|
|
603
|
+
return;
|
|
604
|
+
}
|
|
605
|
+
const previousDesired = state.desired;
|
|
606
|
+
if (state.desired) {
|
|
607
|
+
emit("superseded", {
|
|
608
|
+
supersededRequestId: state.desired.requestId,
|
|
609
|
+
supersededGeneration: state.desired.generation,
|
|
610
|
+
supersededBy: event.requestId
|
|
611
|
+
});
|
|
612
|
+
state.metrics.superseded += 1;
|
|
613
|
+
}
|
|
614
|
+
const requestedAt = event.requestedAt || now.toISOString();
|
|
615
|
+
state.desired = {
|
|
616
|
+
requestId: event.requestId,
|
|
617
|
+
generation,
|
|
618
|
+
activity: event.activity,
|
|
619
|
+
requestedAt
|
|
620
|
+
};
|
|
621
|
+
state.generation = generation;
|
|
622
|
+
if (!internal)
|
|
623
|
+
state.lastProposedGeneration = Math.max(state.lastProposedGeneration, event.generation);
|
|
624
|
+
state.phase = "preparing";
|
|
625
|
+
state.currentActivity = "unknown";
|
|
626
|
+
state.targets = emptyTargets();
|
|
627
|
+
state.refreshPending = emptyRefreshPending();
|
|
628
|
+
state.failure = null;
|
|
629
|
+
state.blockedGeneration = null;
|
|
630
|
+
state.availability = "unknown";
|
|
631
|
+
state.transitionStartedAt = requestedAt;
|
|
632
|
+
state.transitionCompletedAt = null;
|
|
633
|
+
state.metrics.requests += 1;
|
|
634
|
+
resetTransitionMetrics();
|
|
635
|
+
commands.push(...targetIntentCommands(state.desired, config, previousDesired));
|
|
636
|
+
trace("intent", "accepted", null, { activity: event.activity, generation });
|
|
637
|
+
}
|
|
638
|
+
function acceptTargetState(event) {
|
|
639
|
+
if (!exports.TARGETS.includes(event.target))
|
|
640
|
+
throw new Error("unknown theatre target");
|
|
641
|
+
if (!Number.isInteger(event.generation) || event.generation < 1) {
|
|
642
|
+
throw new Error("target generation must be a positive integer");
|
|
643
|
+
}
|
|
644
|
+
if (!Object.hasOwn(TARGET_STATUSES, event.status))
|
|
645
|
+
throw new Error("unknown theatre target status");
|
|
646
|
+
if (observationTime(event) === null)
|
|
647
|
+
throw new Error("target observedAt must be an ISO timestamp");
|
|
648
|
+
if (event.classification && !Object.hasOwn(TARGET_CLASSIFICATIONS, event.classification)) {
|
|
649
|
+
throw new Error("unknown theatre target classification");
|
|
650
|
+
}
|
|
651
|
+
if (!state.desired || event.generation !== state.generation) {
|
|
652
|
+
trace("target-state", "ignored", "stale-generation", {
|
|
653
|
+
target: event.target,
|
|
654
|
+
generation: event.generation
|
|
655
|
+
});
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const previous = state.targets[event.target];
|
|
659
|
+
const bounded = (0, observation_time_1.boundObservedAt)(event.observedAt, observationTime(event), nowMs);
|
|
660
|
+
if (bounded.skewed) {
|
|
661
|
+
trace("target-state", "adjusted", "clock-skew", { target: event.target, reported: event.observedAt, usedAt: bounded.observedAt });
|
|
662
|
+
}
|
|
663
|
+
if (previous && (0, observation_time_1.isOutOfOrder)(bounded.ms, previous.observedAt, nowMs)) {
|
|
664
|
+
trace("target-state", "ignored", "out-of-order", { target: event.target });
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const drifted = state.phase === "ready" &&
|
|
668
|
+
event.status !== "ready" && event.status !== "failed" && event.status !== "unavailable";
|
|
669
|
+
const classification = event.classification || (drifted ? "drift" : null);
|
|
670
|
+
state.targets[event.target] = {
|
|
671
|
+
status: event.status,
|
|
672
|
+
observedAt: bounded.observedAt,
|
|
673
|
+
classification,
|
|
674
|
+
failure: event.failure && typeof event.failure === "object" ? { ...event.failure } : null,
|
|
675
|
+
details: event.details && typeof event.details === "object" ? { ...event.details } : null
|
|
676
|
+
};
|
|
677
|
+
updateTargetMetrics(event.target, state.targets[event.target], previous);
|
|
678
|
+
if (classification === "manual_override" && previous?.classification !== classification) {
|
|
679
|
+
state.metrics.manualOverrides += 1;
|
|
680
|
+
state.metrics.targets[event.target].manualOverrides += 1;
|
|
681
|
+
}
|
|
682
|
+
else if (classification === "drift" && previous?.classification !== classification) {
|
|
683
|
+
state.metrics.driftEvents += 1;
|
|
684
|
+
}
|
|
685
|
+
state.refreshPending[event.target] = null;
|
|
686
|
+
if (classification) {
|
|
687
|
+
emit(classification, { target: event.target });
|
|
688
|
+
trace("target-state", "classified", classification, { target: event.target });
|
|
689
|
+
}
|
|
690
|
+
else {
|
|
691
|
+
trace("target-state", "accepted", null, { target: event.target, status: event.status });
|
|
692
|
+
}
|
|
693
|
+
reconcile();
|
|
694
|
+
}
|
|
695
|
+
function acceptRecovery(event) {
|
|
696
|
+
if (!event.observations || typeof event.observations !== "object" ||
|
|
697
|
+
Array.isArray(event.observations)) {
|
|
698
|
+
throw new Error("recovery observations must be an object");
|
|
699
|
+
}
|
|
700
|
+
if (event.reason === "startup" && state.desired) {
|
|
701
|
+
trace("recovery", "ignored", "active-desired-state");
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (event.reason === "manual_override" && state.phase !== "manual_override") {
|
|
705
|
+
trace("recovery", "ignored", "manual-override-cleared");
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
const matches = Object.entries(config.activityProfiles)
|
|
709
|
+
.filter(([, profile]) => recoveryMatches(profile, event.observations, nowMs, config.freshnessMs))
|
|
710
|
+
.map(([activity]) => activity);
|
|
711
|
+
if (matches.length === 1) {
|
|
712
|
+
const activity = matches[0];
|
|
713
|
+
const generation = state.generation + 1;
|
|
714
|
+
const requestedAt = now.toISOString();
|
|
715
|
+
state.desired = {
|
|
716
|
+
requestId: `recovery-${event.reason}-${nowMs}`,
|
|
717
|
+
generation,
|
|
718
|
+
activity,
|
|
719
|
+
requestedAt
|
|
720
|
+
};
|
|
721
|
+
state.generation = generation;
|
|
722
|
+
state.targets = emptyTargets();
|
|
723
|
+
state.refreshPending = emptyRefreshPending();
|
|
724
|
+
state.failure = null;
|
|
725
|
+
state.blockedGeneration = null;
|
|
726
|
+
state.degraded = [];
|
|
727
|
+
state.transitionStartedAt = requestedAt;
|
|
728
|
+
state.transitionCompletedAt = requestedAt;
|
|
729
|
+
resetTransitionMetrics();
|
|
730
|
+
for (const target of exports.TARGETS) {
|
|
731
|
+
const observation = event.observations[target];
|
|
732
|
+
state.targets[target] = {
|
|
733
|
+
status: "ready",
|
|
734
|
+
observedAt: observation?.observedAt || requestedAt,
|
|
735
|
+
classification: null,
|
|
736
|
+
failure: null,
|
|
737
|
+
details: {
|
|
738
|
+
recovery: observation?.values || {},
|
|
739
|
+
ownership: target === "lighting" && !observation ? "preserved" : "observed"
|
|
740
|
+
}
|
|
741
|
+
};
|
|
742
|
+
updateTargetMetrics(target, state.targets[target], null);
|
|
743
|
+
}
|
|
744
|
+
state.phase = "ready";
|
|
745
|
+
state.currentActivity = activity;
|
|
746
|
+
state.availability = "available";
|
|
747
|
+
state.metrics.recoveriesAdopted += 1;
|
|
748
|
+
completeTransition("ready");
|
|
749
|
+
state.metrics.lastOutcome = "recovery_adopted";
|
|
750
|
+
emit("recovery_adopted", { reason: event.reason, matchedActivity: activity });
|
|
751
|
+
trace("recovery", "adopted", null, { reason: event.reason, activity });
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
if (event.reason === "startup") {
|
|
755
|
+
if (!Object.hasOwn(config.activityProfiles, config.recoveryOffActivity)) {
|
|
756
|
+
throw new Error(`recovery off activity does not exist: ${config.recoveryOffActivity}`);
|
|
757
|
+
}
|
|
758
|
+
state.metrics.recoveriesSafeOff += 1;
|
|
759
|
+
acceptIntent({
|
|
760
|
+
kind: "intent",
|
|
761
|
+
requestId: `recovery-safe-off-${nowMs}`,
|
|
762
|
+
generation: state.generation + 1,
|
|
763
|
+
activity: config.recoveryOffActivity,
|
|
764
|
+
requestedAt: now.toISOString()
|
|
765
|
+
}, true);
|
|
766
|
+
emit("recovery_safe_off", {
|
|
767
|
+
matchCount: matches.length,
|
|
768
|
+
matchedActivities: matches
|
|
769
|
+
});
|
|
770
|
+
trace("recovery", "safe_off", matches.length ? "ambiguous" : "no-clean-match", {
|
|
771
|
+
matchedActivities: matches
|
|
772
|
+
});
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
state.phase = "manual_override";
|
|
776
|
+
state.currentActivity = "unknown";
|
|
777
|
+
state.availability = "degraded";
|
|
778
|
+
state.metrics.lastOutcome = "manual_override";
|
|
779
|
+
emit("recovery_ambiguous", {
|
|
780
|
+
matchCount: matches.length,
|
|
781
|
+
matchedActivities: matches
|
|
782
|
+
});
|
|
783
|
+
trace("recovery", "held", matches.length ? "ambiguous" : "no-clean-match", {
|
|
784
|
+
matchedActivities: matches
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
if (event.kind === "intent") {
|
|
788
|
+
acceptIntent(event);
|
|
789
|
+
}
|
|
790
|
+
else if (event.kind === "target_state") {
|
|
791
|
+
acceptTargetState(event);
|
|
792
|
+
}
|
|
793
|
+
else if (event.kind === "recover") {
|
|
794
|
+
acceptRecovery(event);
|
|
795
|
+
}
|
|
796
|
+
else if (event.kind === "startup" || event.kind === "refresh") {
|
|
797
|
+
state.targets = emptyTargets();
|
|
798
|
+
state.refreshPending = emptyRefreshPending();
|
|
799
|
+
if (state.desired) {
|
|
800
|
+
commands.push(...targetRefreshCommands(state.desired));
|
|
801
|
+
for (const target of exports.TARGETS)
|
|
802
|
+
state.refreshPending[target] = { sentAt: nowMs, attempts: 1, exhausted: false };
|
|
803
|
+
state.phase = state.blockedGeneration === state.generation ? "failed" : "confirming";
|
|
804
|
+
state.currentActivity = "unknown";
|
|
805
|
+
state.availability = state.blockedGeneration === state.generation
|
|
806
|
+
? "unavailable"
|
|
807
|
+
: "unknown";
|
|
808
|
+
if (state.blockedGeneration !== state.generation) {
|
|
809
|
+
state.transitionStartedAt = now.toISOString();
|
|
810
|
+
state.transitionCompletedAt = null;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
else {
|
|
814
|
+
commands.push(...targetProbeCommands());
|
|
815
|
+
for (const target of exports.TARGETS)
|
|
816
|
+
state.refreshPending[target] = { sentAt: nowMs, attempts: 1, exhausted: false };
|
|
817
|
+
state.phase = "recovering";
|
|
818
|
+
state.availability = "unknown";
|
|
819
|
+
emit("recovery_required", { reason: "startup" });
|
|
820
|
+
}
|
|
821
|
+
trace(event.kind, state.desired ? "refreshing" : "recovering");
|
|
822
|
+
}
|
|
823
|
+
else if (event.kind === "tick") {
|
|
824
|
+
if (Number.isInteger(event.generation) && state.desired && event.generation !== state.generation) {
|
|
825
|
+
trace("tick", "ignored", "stale-generation", { generation: event.generation });
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
tickRefreshes();
|
|
829
|
+
if (!state.desired && state.phase === "recovering" &&
|
|
830
|
+
exports.TARGETS.every((target) => state.refreshPending[target]?.exhausted === true)) {
|
|
831
|
+
// Nobody supplied recovery observations: fall back as for no evidence.
|
|
832
|
+
trace("recovery", "timed-out", "no-observations");
|
|
833
|
+
acceptRecovery({ kind: "recover", reason: "startup", observations: {} });
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
reconcile();
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
else {
|
|
841
|
+
throw new Error("unknown theatre event kind");
|
|
842
|
+
}
|
|
843
|
+
events.unshift(stateEvent(state, config.area));
|
|
844
|
+
return { state, commands, events, traces, status: statusFor(state) };
|
|
845
|
+
}
|
|
846
|
+
//# sourceMappingURL=theatre-activity-controller.js.map
|