@dsh-ray/assistant-health 0.0.0-stage → 0.2.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/lib/service.js ADDED
@@ -0,0 +1,803 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { Context, Service } from '@deepseek-ai/cordis';
3
+ import Schema from '@deepseek-ai/schemastery';
4
+ import { registerAssistantHealthTool } from './tools.js';
5
+ export const providerIds = [
6
+ 'assistantPolicy',
7
+ 'personalMemory',
8
+ 'personalWiki',
9
+ 'assistantAutomations',
10
+ 'assistantEvaluation',
11
+ 'preferenceLearning',
12
+ 'assistantEvolution',
13
+ 'assistantDelivery',
14
+ 'credentialsKeychain',
15
+ 'eventTriggers',
16
+ 'assistantRecovery',
17
+ 'assistantGrowthExperiments',
18
+ 'pluginControlPlane',
19
+ 'assistantHeartbeat',
20
+ 'larkChannel',
21
+ 'assistantVerifier',
22
+ 'assistantGoals',
23
+ 'assistantDreaming',
24
+ 'assistantProactive',
25
+ 'assistantGrowthDriver',
26
+ 'assistantMemoryLearning',
27
+ 'assistantWorkItems',
28
+ ];
29
+ /**
30
+ * Public health ids are stable configuration/report vocabulary. They do not
31
+ * necessarily equal the Cordis service registration name exposed by a
32
+ * provider. Keep that runtime seam explicit so a renamed/public-facing id
33
+ * cannot silently turn an installed provider into `missing`.
34
+ */
35
+ const providerServiceNames = Object.freeze({
36
+ assistantPolicy: 'assistantPolicy',
37
+ personalMemory: 'personalMemory',
38
+ personalWiki: 'personalWiki',
39
+ assistantAutomations: 'assistantAutomations',
40
+ assistantEvaluation: 'assistantEvaluation',
41
+ preferenceLearning: 'assistantPreferenceLearning',
42
+ assistantEvolution: 'assistantEvolution',
43
+ assistantDelivery: 'assistantDelivery',
44
+ credentialsKeychain: 'credentialsKeychain',
45
+ eventTriggers: 'eventTriggers',
46
+ assistantRecovery: 'assistantRecovery',
47
+ assistantGrowthExperiments: 'assistantGrowthExperiments',
48
+ pluginControlPlane: 'pluginControlPlane',
49
+ assistantHeartbeat: 'assistantHeartbeat',
50
+ larkChannel: 'larkChannel',
51
+ assistantVerifier: 'assistantVerifier',
52
+ assistantGoals: 'assistantGoals',
53
+ assistantDreaming: 'assistantDreaming',
54
+ assistantProactive: 'assistantProactive',
55
+ assistantGrowthDriver: 'assistantGrowthDriver',
56
+ assistantMemoryLearning: 'assistantMemoryLearning',
57
+ assistantWorkItems: 'assistantWorkItems',
58
+ });
59
+ export class AssistantHealthError extends Error {
60
+ code;
61
+ constructor(code, message) {
62
+ super(message);
63
+ this.code = code;
64
+ this.name = 'AssistantHealthError';
65
+ }
66
+ }
67
+ const configSchema = Schema.object({
68
+ requiredProviders: Schema.array(Schema.union(providerIds)).default([
69
+ 'assistantPolicy', 'personalMemory', 'personalWiki', 'assistantAutomations',
70
+ ]),
71
+ });
72
+ /** Fixed Policy subject used by the non-model supervised-growth runbook. */
73
+ export const HOST_RECOVERY_BACKGROUND_ID = 'dsh-ray-assistant-recovery';
74
+ function hostText(value, label, maxBytes, code = 'invalid-input') {
75
+ if (typeof value !== 'string') {
76
+ throw new AssistantHealthError(code, `${label} must be a string`);
77
+ }
78
+ const normalized = value.normalize('NFC').trim();
79
+ if (normalized === '' || Buffer.byteLength(normalized, 'utf8') > maxBytes
80
+ || hasControl(normalized)) {
81
+ throw new AssistantHealthError(code, `${label} is invalid`);
82
+ }
83
+ return normalized;
84
+ }
85
+ function hasControl(value) {
86
+ for (const character of value) {
87
+ const codePoint = character.codePointAt(0);
88
+ if (codePoint <= 0x1f || codePoint === 0x7f)
89
+ return true;
90
+ }
91
+ return false;
92
+ }
93
+ const keys = {
94
+ assistantPolicy: { emergencyStop: 'boolean', lastAuditSequence: 'number' },
95
+ personalMemory: { activeRecords: 'number', removedRecords: 'number', expiredRecords: 'number', pendingProposals: 'number' },
96
+ personalWiki: { pages: 'number', lintErrors: 'number', lintWarnings: 'number', pendingProposals: 'number' },
97
+ assistantAutomations: { activeAutomations: 'number', pausedAutomations: 'number', pendingTasks: 'number',
98
+ runningTasks: 'number', failedRuns: 'number', unknownRuns: 'number', pendingEvaluations: 'number',
99
+ retryingEvaluations: 'number', failedEvaluationAttempts: 'number', deadLetterEvaluations: 'number',
100
+ oldestPendingEvaluationAt: 'number', openCircuits: 'optional-number',
101
+ openIncidents: 'optional-number', pendingIncidentAlerts: 'optional-number' },
102
+ assistantEvaluation: { ready: 'boolean', schemaVersion: 'number', outcomes: 'number',
103
+ trustedOutcomes: 'number', selfReportedOutcomes: 'number', externalOutcomes: 'number',
104
+ selfAssessments: 'number', latestOccurredAt: 'optional-number',
105
+ taskProjections: 'optional-number', conflictedTaskProjections: 'optional-number',
106
+ pendingProjections: 'optional-number', retryingProjections: 'optional-number',
107
+ projectionAttempts: 'optional-number', oldestPendingProjectionAt: 'optional-number' },
108
+ preferenceLearning: { ready: 'boolean', enabled: 'boolean', schemaVersion: 'number', signals: 'number',
109
+ hypotheses: 'number', active: 'number', shadow: 'number', proposed: 'number',
110
+ rolledBack: 'number', expired: 'number', lastRecordedAt: 'optional-number' },
111
+ assistantEvolution: { activeRules: 'number', retiredRules: 'number', pendingProposals: 'number',
112
+ conflictedProposals: 'number', trustedEpisodes: 'number', unattributedTrustedEpisodes: 'number',
113
+ lastTrustedEpisodeAt: 'number', lastReconciledAt: 'number', autonomousRollbacks: 'number',
114
+ qualityEligibleEpisodes: 'optional-number', operationalEpisodes: 'optional-number',
115
+ legacyQuarantinedEpisodes: 'optional-number', unattributedQualityEligibleEpisodes: 'optional-number',
116
+ lastQualityEligibleEpisodeAt: 'optional-number',
117
+ // Evolution v8 adds this independently optional counter. Older producers
118
+ // did not expose task-learning projection integrity at all.
119
+ taskLearningProjectionIntegrityErrors: 'optional-number' },
120
+ assistantDelivery: { pendingInbox: 'number', deadLetterInbox: 'number', pendingOutbox: 'number',
121
+ deadLetterOutbox: 'number', unknownOutbox: 'number', adapters: 'number',
122
+ actionableDeadLetterInbox: 'optional-number', resolvedDeadLetterInbox: 'optional-number',
123
+ actionableDeadLetterOutbox: 'optional-number', resolvedDeadLetterOutbox: 'optional-number',
124
+ actionableUnknownOutbox: 'optional-number', resolvedUnknownOutbox: 'optional-number',
125
+ pendingPresentations: 'optional-number', deadPresentations: 'optional-number' },
126
+ credentialsKeychain: { handles: 'number', activeLeases: 'number', failedLeases: 'number' },
127
+ eventTriggers: { pendingEvents: 'number', deliveredEvents: 'number', triggersObserved: 'number' },
128
+ assistantRecovery: { runningRuns: 'number', failedRuns: 'number', unknownRuns: 'number',
129
+ incompleteSteps: 'number', staleRuns: 'number', staleSteps: 'number',
130
+ lastSucceededAt: 'number', lastFailedAt: 'number',
131
+ latestProductionStatus: 'optional-production-status',
132
+ consecutiveProductionFailures: 'optional-number', lastProductionRunAt: 'optional-number',
133
+ bootstrapStatus: 'optional-bootstrap-status', bootstrapFailureCode: 'optional-code',
134
+ bootstrapGeneration: 'optional-number', bootstrapAttestationValid: 'optional-boolean',
135
+ bootstrapAttestationSetDigest: 'optional-digest',
136
+ bootstrapUpdatedAt: 'optional-number' },
137
+ assistantGrowthExperiments: { candidates: 'number', readyCandidates: 'number',
138
+ activeExperiments: 'number', rollbackPending: 'number', proposedPaused: 'number',
139
+ promoted: 'number',
140
+ traceRevisions: 'number', currentTraces: 'number', exhaustedRollbacks: 'number',
141
+ lastErrorCode: 'optional-code' },
142
+ pluginControlPlane: { gaps: 'number', readyPlans: 'number', activeActivations: 'number',
143
+ failed: 'number', rollbackPending: 'number',
144
+ // Post-activation deployment cohort counters (control-plane schema v12).
145
+ // Optional while independently-installable control planes roll forward.
146
+ watchingActivations: 'optional-number', closedRegressed: 'optional-number',
147
+ closedRetracted: 'optional-number' },
148
+ assistantHeartbeat: { active: 'number', paused: 'number', empty: 'number' },
149
+ larkChannel: { state: ['connected', 'connected-with-gap', 'connecting', 'disabled', 'disconnected', 'reconnecting'],
150
+ gapGeneration: 'number' },
151
+ // A dynamic seam keeps assistant-verifier independently installable. Only
152
+ // its fixed Host producer ids are public health vocabulary.
153
+ assistantVerifier: { ready: 'boolean', profiles: 'number', requireAcceptance: 'boolean',
154
+ hostProducers: 'host-producers', evaluationConnected: 'boolean', awaitingExecution: 'number',
155
+ pendingVerification: 'number', pendingReceipts: 'number', expiredReceipts: 'number',
156
+ needsAttention: 'number' },
157
+ // Goals is independently installable. Keep this flattened vocabulary to
158
+ // bounded current-state capability signals; nested provider payloads can
159
+ // otherwise grow into route, owner, or durable-store disclosures.
160
+ assistantGoals: { ready: 'boolean', contextReady: 'boolean', executionEnabled: 'boolean',
161
+ verifierConnected: 'boolean', outcomeEnabled: 'boolean', outcomeConnected: 'boolean',
162
+ budgetEnabled: 'boolean', registeredBudgetMeters: 'number', activeBudgetCalls: 'number',
163
+ wakeEnabled: 'boolean', wakeConnected: 'boolean', wakeReconciliationFailures: 'number',
164
+ observationFailures: 'number' },
165
+ assistantDreaming: { enabled: 'boolean', scheduler: ['active', 'dormant', 'unavailable'],
166
+ runs: 'number', ideas: 'number', recorded: 'number', lastRunAt: 'optional-number' },
167
+ assistantProactive: { enabled: 'boolean', registered: 'boolean',
168
+ readiness: ['disabled', 'unavailable', 'registered', 'degraded'],
169
+ consecutiveFailures: 'number', callsInWindow: 'number', budgetExhausted: 'boolean',
170
+ hasError: 'boolean' },
171
+ assistantGrowthDriver: { outcome: ['never-run', 'ran', 'skipped', 'failed'],
172
+ usageEnabled: 'boolean', usageConnected: 'boolean', usageError: 'optional-boolean',
173
+ usagePending: 'optional-number', usageRunning: 'optional-number',
174
+ usageFailed: 'optional-number', usageUnknown: 'optional-number',
175
+ ownerAnchoredAbstained: 'optional-number' },
176
+ assistantMemoryLearning: { enabled: 'boolean', connected: 'boolean', available: 'boolean',
177
+ hasError: 'boolean', remainingExtractions: 'number', pending: 'number',
178
+ queued: 'number', running: 'number', unknown: 'number', adopted: 'number', failed: 'number' },
179
+ assistantWorkItems: { enabled: 'boolean', mode: ['observe', 'active'],
180
+ openItems: 'number', dispatchUnknown: 'number', workerConnected: 'boolean',
181
+ ownerRouteValid: 'boolean', followsUnresolved: 'number', followsDegraded: 'boolean',
182
+ authorityParked: 'number', settlementEnabled: 'boolean', settlementUnverified: 'number',
183
+ settlementDegraded: 'boolean', evaluationEnabled: 'boolean', evaluationConnected: 'boolean',
184
+ evaluationDegraded: 'boolean', schedulerWakeSubscribed: 'boolean', schedulerWakeError: 'boolean',
185
+ interventionRequired: 'boolean', intakeEvaluationRegistered: 'optional-boolean',
186
+ intakeEvaluationUnpersisted: 'optional-number' },
187
+ };
188
+ function operationalAssessments(provider, required) {
189
+ if (provider.status !== 'ready')
190
+ return [];
191
+ const metric = (key) => provider.metrics[key];
192
+ const output = [];
193
+ const add = (condition, severity, code, blocksReadiness = false) => {
194
+ if (condition)
195
+ output.push({ severity, code, ...(blocksReadiness ? { blocksReadiness: true } : {}) });
196
+ };
197
+ // Assess only current, actionable state. Lifetime ledger counters such as
198
+ // Automations failedRuns/unknownRuns, failedEvaluationAttempts, conflictedProposals,
199
+ // and failedLeases remain observable metrics but cannot prove that the
200
+ // provider is unhealthy now.
201
+ switch (provider.id) {
202
+ case 'assistantPolicy':
203
+ add(metric('emergencyStop') === true, 'unhealthy', 'emergency-stop', true);
204
+ break;
205
+ case 'personalWiki':
206
+ add(metric('lintErrors') > 0, 'degraded', 'lint-errors');
207
+ break;
208
+ case 'assistantAutomations':
209
+ add(metric('deadLetterEvaluations') > 0, 'degraded', 'evaluation-dead-letter-backlog');
210
+ add(metric('openCircuits') !== undefined
211
+ && metric('openCircuits') > 0, 'degraded', 'open-circuit-backlog');
212
+ add(metric('openIncidents') !== undefined
213
+ && metric('openIncidents') > 0, 'degraded', 'open-incident-backlog');
214
+ add(metric('pendingIncidentAlerts') !== undefined
215
+ && metric('pendingIncidentAlerts') > 0, 'degraded', 'pending-incident-alerts');
216
+ break;
217
+ case 'assistantEvaluation':
218
+ add(metric('retryingProjections') !== undefined
219
+ && metric('retryingProjections') > 0, 'degraded', 'projection-retry-backlog');
220
+ add(metric('conflictedTaskProjections') !== undefined
221
+ && metric('conflictedTaskProjections') > 0, 'degraded', 'evaluation-task-conflicts');
222
+ break;
223
+ case 'assistantEvolution':
224
+ add(metric('taskLearningProjectionIntegrityErrors') !== undefined
225
+ && metric('taskLearningProjectionIntegrityErrors') > 0, 'degraded', 'task-learning-projection-integrity-errors');
226
+ break;
227
+ case 'assistantRecovery':
228
+ add(metric('latestProductionStatus') === 'failed'
229
+ || metric('latestProductionStatus') === 'unknown', 'degraded', 'incomplete-recovery');
230
+ // A currently running step is not itself unhealthy. Recovery owns the
231
+ // durable deadline/lease and will surface a terminal unknown/failed run;
232
+ // treating every started step as degraded makes final verification
233
+ // self-referential and permanently masks other provider failures.
234
+ add(metric('staleRuns') > 0 || metric('staleSteps') > 0, 'degraded', 'stale-recovery-intent');
235
+ add(metric('bootstrapStatus') === 'running', 'degraded', 'bootstrap-in-progress');
236
+ add(metric('bootstrapStatus') === 'failed', 'unhealthy', 'bootstrap-failed', true);
237
+ add(metric('bootstrapStatus') === 'succeeded'
238
+ && metric('bootstrapAttestationValid') === false, 'unhealthy', 'bootstrap-attestation-invalid', required);
239
+ break;
240
+ case 'assistantGrowthExperiments':
241
+ add(metric('rollbackPending') > 0, 'degraded', 'growth-rollback-pending');
242
+ add(metric('exhaustedRollbacks') > 0, 'unhealthy', 'growth-rollback-exhausted', required);
243
+ add(metric('lastErrorCode') !== undefined, 'degraded', 'growth-runtime-error');
244
+ break;
245
+ case 'pluginControlPlane':
246
+ add(metric('rollbackPending') > 0, 'unhealthy', 'capability-rollback-pending', required);
247
+ // A closed-regressed deployment cohort needs owner attention even
248
+ // though the exact version is already ledger-closed.
249
+ add((metric('closedRegressed') ?? 0) > 0, 'degraded', 'capability-cohort-regressed');
250
+ // A retraction closes the watch and reopens its gap for the next
251
+ // evolution cycle; it is a rollback signal, not a stuck deployment.
252
+ add((metric('closedRetracted') ?? 0) > 0, 'degraded', 'capability-cohort-retracted');
253
+ break;
254
+ case 'preferenceLearning':
255
+ add(metric('enabled') === false && required, 'unhealthy', 'disabled', true);
256
+ break;
257
+ case 'assistantDelivery': {
258
+ // Delivery v9 distinguishes unresolved work from immutable terminal
259
+ // history. Fall back to v8 raw counters during rolling upgrades.
260
+ const actionableUnknown = metric('actionableUnknownOutbox') ?? metric('unknownOutbox');
261
+ const actionableInbox = metric('actionableDeadLetterInbox') ?? metric('deadLetterInbox');
262
+ const actionableOutbox = metric('actionableDeadLetterOutbox') ?? metric('deadLetterOutbox');
263
+ add(actionableUnknown > 0, 'unhealthy', 'unknown-outbox-backlog');
264
+ add(actionableInbox > 0 || actionableOutbox > 0, 'degraded', 'dead-letter-backlog');
265
+ add(metric('pendingPresentations') !== undefined
266
+ && metric('pendingPresentations') > 0, 'degraded', 'presentation-backlog');
267
+ add(metric('deadPresentations') !== undefined
268
+ && metric('deadPresentations') > 0, 'unhealthy', 'presentation-dead-letter');
269
+ break;
270
+ }
271
+ case 'larkChannel': {
272
+ const state = metric('state');
273
+ add(state === 'connected-with-gap', 'degraded', 'connected-with-gap');
274
+ add(state === 'connecting' || state === 'reconnecting', 'degraded', 'connection-in-progress', required);
275
+ add(state === 'disconnected', required ? 'unhealthy' : 'degraded', 'disconnected', required);
276
+ add(state === 'disabled' && required, 'unhealthy', 'disabled', true);
277
+ break;
278
+ }
279
+ case 'assistantVerifier':
280
+ // No approved profile is the default disabled state. Surface it without
281
+ // claiming that the installed service supplies acceptance capability.
282
+ add(metric('profiles') === 0, 'degraded', 'acceptance-disabled');
283
+ // An unconnected optional verifier is actionable only when it has a
284
+ // receipt that cannot reach Evaluation.
285
+ add(metric('pendingReceipts') > 0 && metric('evaluationConnected') === false, 'degraded', 'evaluation-disconnected-with-pending-receipts');
286
+ add(metric('expiredReceipts') > 0, 'degraded', 'expired-receipt-backlog');
287
+ // This queue holds durable unknown/expired continuations, rather than
288
+ // a lifetime count of historical verification failures.
289
+ add(metric('needsAttention') > 0, 'degraded', 'verification-needs-attention');
290
+ break;
291
+ case 'assistantGoals':
292
+ // A context-only Goals installation is useful, but it cannot be
293
+ // advertised as autonomous execution. Disabled optional extensions are
294
+ // normal; only enabled-but-disconnected extensions are actionable.
295
+ add(metric('contextReady') === false, 'degraded', 'context-unavailable');
296
+ add(metric('executionEnabled') === false, 'degraded', 'execution-disabled');
297
+ add(metric('executionEnabled') === true && metric('verifierConnected') === false, 'degraded', 'verified-execution-verifier-disconnected');
298
+ add(metric('outcomeEnabled') === true && metric('outcomeConnected') === false, 'degraded', 'outcome-verifier-disconnected');
299
+ add(metric('budgetEnabled') === true && metric('registeredBudgetMeters') === 0, 'degraded', 'budget-meter-missing');
300
+ add(metric('wakeEnabled') === true && metric('wakeConnected') === false, 'degraded', 'wake-automations-disconnected');
301
+ add(metric('wakeReconciliationFailures') > 0, 'degraded', 'wake-reconciliation-failures');
302
+ add(metric('observationFailures') > 0, 'degraded', 'observation-failures');
303
+ break;
304
+ case 'assistantDreaming':
305
+ add(metric('enabled') === true && metric('scheduler') === 'unavailable', 'unhealthy', 'scheduler-unavailable', required);
306
+ add(metric('enabled') === true && metric('scheduler') === 'dormant', 'degraded', 'scheduler-dormant');
307
+ break;
308
+ case 'assistantProactive':
309
+ add(metric('enabled') === true && metric('readiness') === 'unavailable', 'unhealthy', 'intake-evaluation-unavailable', required);
310
+ add(metric('enabled') === true && metric('readiness') === 'degraded', 'degraded', 'intake-evaluation-degraded');
311
+ add(metric('budgetExhausted') === true, 'degraded', 'intake-evaluation-budget-exhausted');
312
+ add(metric('hasError') === true, 'degraded', 'intake-evaluation-error');
313
+ break;
314
+ case 'assistantGrowthDriver':
315
+ add(metric('outcome') === 'failed', 'degraded', 'wake-failed');
316
+ add(metric('usageEnabled') === true && metric('usageConnected') === false, 'degraded', 'usage-learning-disconnected');
317
+ add(metric('usageError') === true, 'degraded', 'usage-learning-error');
318
+ add(typeof metric('usageUnknown') === 'number' && metric('usageUnknown') > 0, 'degraded', 'usage-jobs-unknown');
319
+ add(typeof metric('usageFailed') === 'number' && metric('usageFailed') > 0, 'degraded', 'usage-jobs-failed');
320
+ break;
321
+ case 'assistantMemoryLearning':
322
+ add(metric('enabled') === true && metric('connected') === false, 'unhealthy', 'memory-learning-disconnected', required);
323
+ add(metric('enabled') === true && metric('available') === false, 'degraded', 'memory-learning-unavailable');
324
+ add(metric('hasError') === true, 'degraded', 'memory-learning-error');
325
+ add(metric('unknown') > 0, 'degraded', 'memory-learning-jobs-unknown');
326
+ add(metric('failed') > 0, 'degraded', 'memory-learning-jobs-failed');
327
+ break;
328
+ case 'assistantWorkItems':
329
+ add(metric('enabled') === true && metric('workerConnected') === false, 'unhealthy', 'automations-disconnected', required);
330
+ add(metric('enabled') === true && metric('ownerRouteValid') === false, 'degraded', 'owner-route-invalid');
331
+ add(metric('dispatchUnknown') > 0, 'degraded', 'dispatch-unknown');
332
+ add(metric('followsUnresolved') > 0 || metric('followsDegraded') === true, 'degraded', 'follows-degraded');
333
+ add(metric('settlementUnverified') > 0 || metric('settlementDegraded') === true, 'degraded', 'settlement-degraded');
334
+ add(metric('evaluationEnabled') === true
335
+ && (metric('evaluationConnected') === false || metric('evaluationDegraded') === true), 'degraded', 'evaluation-disconnected');
336
+ add(metric('schedulerWakeError') === true, 'degraded', 'scheduler-wake-error');
337
+ add(metric('interventionRequired') === true, 'degraded', 'intervention-required');
338
+ break;
339
+ default:
340
+ break;
341
+ }
342
+ return output;
343
+ }
344
+ function summarize(providers, required) {
345
+ const assessments = [];
346
+ const warnings = [];
347
+ let ready = true;
348
+ let severity = 'healthy';
349
+ const append = (providerId, level, code, warning, blocksReadiness = false) => {
350
+ assessments.push(Object.freeze({ providerId, severity: level, code }));
351
+ warnings.push(warning);
352
+ if (level === 'unhealthy')
353
+ severity = 'unhealthy';
354
+ else if (severity === 'healthy')
355
+ severity = 'degraded';
356
+ if (blocksReadiness)
357
+ ready = false;
358
+ };
359
+ for (const provider of providers) {
360
+ const isRequired = required.has(provider.id);
361
+ if (provider.status === 'missing') {
362
+ if (isRequired)
363
+ append(provider.id, 'unhealthy', 'required-provider-missing', `provider-missing:${provider.id}`, true);
364
+ continue;
365
+ }
366
+ if (provider.status === 'error') {
367
+ append(provider.id, isRequired ? 'unhealthy' : 'degraded', 'health-seam-error', isRequired ? `provider-error:${provider.id}` : `provider-degraded:${provider.id}:health-seam-error`, isRequired);
368
+ continue;
369
+ }
370
+ for (const assessment of operationalAssessments(provider, isRequired)) {
371
+ append(provider.id, assessment.severity, assessment.code, `provider-${assessment.severity}:${provider.id}:${assessment.code}`, assessment.blocksReadiness === true);
372
+ }
373
+ }
374
+ return { ready, severity, assessments, warnings };
375
+ }
376
+ function metrics(id, value) {
377
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
378
+ throw new Error('invalid health payload');
379
+ const input = value;
380
+ const output = {};
381
+ for (const [key, specification] of Object.entries(keys[id])) {
382
+ const current = input[key];
383
+ if ((specification === 'optional-number' || specification === 'optional-boolean'
384
+ || specification === 'optional-production-status'
385
+ || specification === 'optional-bootstrap-status' || specification === 'optional-code'
386
+ || specification === 'optional-digest')
387
+ && current === undefined)
388
+ continue;
389
+ if (specification === 'number' || specification === 'optional-number') {
390
+ if (!Number.isSafeInteger(current) || current < 0)
391
+ throw new Error('invalid numeric health metric');
392
+ output[key] = current;
393
+ }
394
+ else if (specification === 'optional-production-status') {
395
+ if (typeof current !== 'string'
396
+ || !['none', 'running', 'succeeded', 'failed', 'unknown'].includes(current)) {
397
+ throw new Error('invalid production health status');
398
+ }
399
+ output[key] = current;
400
+ }
401
+ else if (specification === 'optional-bootstrap-status') {
402
+ if (typeof current !== 'string' || !['idle', 'running', 'succeeded', 'failed'].includes(current)) {
403
+ throw new Error('invalid bootstrap health status');
404
+ }
405
+ output[key] = current;
406
+ }
407
+ else if (specification === 'optional-code') {
408
+ if (typeof current !== 'string' || !/^[a-z\d][a-z\d._-]{0,63}$/u.test(current)) {
409
+ throw new Error('invalid health reason code');
410
+ }
411
+ output[key] = current;
412
+ }
413
+ else if (specification === 'optional-digest') {
414
+ if (typeof current !== 'string' || !/^[a-f\d]{64}$/u.test(current)) {
415
+ throw new Error('invalid health digest');
416
+ }
417
+ output[key] = current;
418
+ }
419
+ else if (specification === 'host-producers') {
420
+ if (!Array.isArray(current) || current.length > 3
421
+ || Array.from(current).some(item => item !== 'assistantAutomations' && item !== 'assistantDelivery' && item !== 'assistantGoals')
422
+ || new Set(current).size !== current.length
423
+ || current.some((item, index) => index > 0 && item < current[index - 1])) {
424
+ throw new Error('invalid verifier Host producer health metric');
425
+ }
426
+ output[key] = [...current];
427
+ }
428
+ else if (specification === 'boolean' || specification === 'optional-boolean') {
429
+ if (typeof current !== 'boolean')
430
+ throw new Error('invalid boolean health metric');
431
+ output[key] = current;
432
+ }
433
+ else {
434
+ if (typeof current !== 'string' || !specification.includes(current))
435
+ throw new Error('invalid status health metric');
436
+ output[key] = current;
437
+ }
438
+ }
439
+ if (id === 'assistantEvolution') {
440
+ const projectionKeys = [
441
+ 'qualityEligibleEpisodes', 'operationalEpisodes', 'legacyQuarantinedEpisodes',
442
+ 'unattributedQualityEligibleEpisodes', 'lastQualityEligibleEpisodeAt',
443
+ ];
444
+ const projectionCount = projectionKeys.filter(key => output[key] !== undefined).length;
445
+ if (projectionCount !== 0 && projectionCount !== projectionKeys.length) {
446
+ throw new Error('incomplete Evolution quality-evidence projection');
447
+ }
448
+ }
449
+ if (id === 'assistantEvaluation') {
450
+ const taskKeys = ['taskProjections', 'conflictedTaskProjections'];
451
+ const taskCount = taskKeys.filter(key => output[key] !== undefined).length;
452
+ if (taskCount !== 0 && taskCount !== taskKeys.length) {
453
+ throw new Error('incomplete Evaluation task projection health');
454
+ }
455
+ if (taskCount === taskKeys.length
456
+ && output.conflictedTaskProjections > output.taskProjections) {
457
+ throw new Error('inconsistent Evaluation task projection health');
458
+ }
459
+ const projectionKeys = ['pendingProjections', 'retryingProjections', 'projectionAttempts'];
460
+ const projectionCount = projectionKeys.filter(key => output[key] !== undefined).length;
461
+ if (projectionCount !== 0 && projectionCount !== projectionKeys.length) {
462
+ throw new Error('incomplete Evaluation projection health');
463
+ }
464
+ if (output.oldestPendingProjectionAt !== undefined
465
+ && (projectionCount === 0 || output.pendingProjections === 0)) {
466
+ throw new Error('inconsistent Evaluation oldest projection health');
467
+ }
468
+ if (projectionCount === projectionKeys.length
469
+ && (output.retryingProjections > output.pendingProjections
470
+ || output.projectionAttempts < output.retryingProjections)) {
471
+ throw new Error('inconsistent Evaluation projection health');
472
+ }
473
+ }
474
+ if (id === 'assistantAutomations') {
475
+ // openCircuits shipped one version earlier and remains independently
476
+ // optional. The later incident/alert projection is atomic: accepting a
477
+ // partial pair would make N and N-1 indistinguishable.
478
+ const projectionKeys = ['openIncidents', 'pendingIncidentAlerts'];
479
+ const projectionCount = projectionKeys.filter(key => output[key] !== undefined).length;
480
+ if (projectionCount !== 0 && projectionCount !== projectionKeys.length) {
481
+ throw new Error('incomplete Automations incident projection');
482
+ }
483
+ }
484
+ if (id === 'assistantDelivery') {
485
+ const projectionKeys = [
486
+ 'actionableDeadLetterInbox', 'resolvedDeadLetterInbox',
487
+ 'actionableDeadLetterOutbox', 'resolvedDeadLetterOutbox',
488
+ 'actionableUnknownOutbox', 'resolvedUnknownOutbox',
489
+ ];
490
+ const projectionCount = projectionKeys.filter(key => output[key] !== undefined).length;
491
+ if (projectionCount !== 0 && projectionCount !== projectionKeys.length) {
492
+ throw new Error('incomplete Delivery resolution projection');
493
+ }
494
+ if (projectionCount === projectionKeys.length) {
495
+ const partitions = [
496
+ ['deadLetterInbox', 'actionableDeadLetterInbox', 'resolvedDeadLetterInbox'],
497
+ ['deadLetterOutbox', 'actionableDeadLetterOutbox', 'resolvedDeadLetterOutbox'],
498
+ ['unknownOutbox', 'actionableUnknownOutbox', 'resolvedUnknownOutbox'],
499
+ ];
500
+ for (const [total, actionable, resolved] of partitions) {
501
+ if (output[actionable] + output[resolved] !== output[total]) {
502
+ throw new Error('inconsistent Delivery resolution projection');
503
+ }
504
+ }
505
+ }
506
+ const presentationKeys = ['pendingPresentations', 'deadPresentations'];
507
+ const presentationCount = presentationKeys.filter(key => output[key] !== undefined).length;
508
+ if (presentationCount !== 0 && presentationCount !== presentationKeys.length) {
509
+ throw new Error('incomplete Delivery presentation projection');
510
+ }
511
+ }
512
+ if (id === 'assistantRecovery') {
513
+ const projectionKeys = [
514
+ 'latestProductionStatus', 'consecutiveProductionFailures', 'lastProductionRunAt',
515
+ ];
516
+ const projectionCount = projectionKeys.filter(key => output[key] !== undefined).length;
517
+ if (projectionCount !== 0 && projectionCount !== projectionKeys.length) {
518
+ throw new Error('incomplete Recovery production projection');
519
+ }
520
+ const bootstrapStatus = output.bootstrapStatus;
521
+ const bootstrapUpdatedAt = output.bootstrapUpdatedAt;
522
+ const bootstrapFailureCode = output.bootstrapFailureCode;
523
+ if ((bootstrapStatus === undefined) !== (bootstrapUpdatedAt === undefined)
524
+ || (bootstrapStatus === 'failed') !== (bootstrapFailureCode !== undefined)) {
525
+ throw new Error('incomplete Recovery bootstrap projection');
526
+ }
527
+ const attestationInputKeys = [
528
+ 'bootstrapGeneration', 'bootstrapAttestationValid',
529
+ 'bootstrapAttestationSetDigest', 'bootstrapAttestations',
530
+ ];
531
+ const attestationInputCount = attestationInputKeys.filter(key => input[key] !== undefined).length;
532
+ if (attestationInputCount !== 0 && attestationInputCount !== attestationInputKeys.length) {
533
+ throw new Error('incomplete Recovery bootstrap attestation projection');
534
+ }
535
+ if (attestationInputCount === attestationInputKeys.length) {
536
+ const attestations = input.bootstrapAttestations;
537
+ if (!Array.isArray(attestations) || attestations.length > 1_000
538
+ || attestations.some((attestation) => {
539
+ if (typeof attestation !== 'object' || attestation === null || Array.isArray(attestation))
540
+ return true;
541
+ const value = attestation;
542
+ return Object.keys(value).sort().join(',')
543
+ !== 'activationNonce,activationPlanDigest,activationState,automationId'
544
+ || typeof value.automationId !== 'string'
545
+ || typeof value.activationNonce !== 'string'
546
+ || !['active', 'paused', 'preview'].includes(String(value.activationState))
547
+ || typeof value.activationPlanDigest !== 'string'
548
+ || !/^[a-f\d]{64}$/u.test(value.activationPlanDigest);
549
+ })) {
550
+ throw new Error('invalid Recovery bootstrap attestations');
551
+ }
552
+ }
553
+ }
554
+ return Object.freeze(output);
555
+ }
556
+ function isPlainRecord(value) {
557
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
558
+ }
559
+ function requireRecord(value, label) {
560
+ if (!isPlainRecord(value))
561
+ throw new Error(`invalid ${label} health payload`);
562
+ return value;
563
+ }
564
+ function presenceBoolean(record, key) {
565
+ const value = record[key];
566
+ if (value === null || value === undefined)
567
+ return false;
568
+ if (typeof value !== 'string')
569
+ throw new Error(`invalid ${key} health field`);
570
+ return value.length > 0;
571
+ }
572
+ function resolveErrorFlag(record, boolKey, errorKey) {
573
+ if (boolKey in record && record[boolKey] !== undefined)
574
+ return record[boolKey];
575
+ if (errorKey in record)
576
+ return presenceBoolean(record, errorKey);
577
+ return undefined;
578
+ }
579
+ function collectProviderHealth(id, provider) {
580
+ const healthFn = typeof provider.health === 'function' ? provider.health : undefined;
581
+ if (id === 'assistantProactive') {
582
+ const reader = healthFn ?? (typeof provider.intakeEvaluationHealth === 'function'
583
+ ? provider.intakeEvaluationHealth
584
+ : undefined);
585
+ if (reader === undefined)
586
+ return undefined;
587
+ const raw = requireRecord(reader.call(provider), 'proactive');
588
+ return { ...raw, hasError: resolveErrorFlag(raw, 'hasError', 'lastError') };
589
+ }
590
+ if (healthFn === undefined)
591
+ return undefined;
592
+ const value = healthFn.call(provider);
593
+ if (id === 'assistantDreaming') {
594
+ const raw = requireRecord(value, 'dreaming');
595
+ const counts = 'counts' in raw ? requireRecord(raw.counts, 'dreaming.counts') : raw;
596
+ return {
597
+ enabled: raw.enabled,
598
+ scheduler: raw.scheduler,
599
+ runs: counts.runs,
600
+ ideas: counts.ideas,
601
+ recorded: counts.recorded,
602
+ lastRunAt: raw.lastRunAt === null ? undefined : raw.lastRunAt,
603
+ };
604
+ }
605
+ if (id === 'assistantGrowthDriver') {
606
+ const raw = requireRecord(value, 'growthDriver');
607
+ const usageFn = typeof provider.usageHealth === 'function' ? provider.usageHealth : undefined;
608
+ const usage = usageFn === undefined ? undefined : requireRecord(usageFn.call(provider), 'growthDriver.usage');
609
+ const usageCounts = usage !== undefined && 'counts' in usage && usage.counts !== undefined
610
+ ? requireRecord(usage.counts, 'growthDriver.usage.counts')
611
+ : undefined;
612
+ const ownerAnchored = 'ownerAnchored' in raw && raw.ownerAnchored !== undefined && raw.ownerAnchored !== null
613
+ ? requireRecord(raw.ownerAnchored, 'growthDriver.ownerAnchored')
614
+ : undefined;
615
+ return {
616
+ outcome: raw.outcome,
617
+ usageEnabled: usage !== undefined ? usage.enabled : raw.usageEnabled,
618
+ usageConnected: usage !== undefined ? usage.connected : raw.usageConnected,
619
+ usageError: usage !== undefined ? ('lastError' in usage ? presenceBoolean(usage, 'lastError') : undefined) : raw.usageError,
620
+ usagePending: usageCounts !== undefined ? usageCounts.pending : raw.usagePending,
621
+ usageRunning: usageCounts !== undefined ? usageCounts.running : raw.usageRunning,
622
+ usageFailed: usageCounts !== undefined ? usageCounts.failed : raw.usageFailed,
623
+ usageUnknown: usageCounts !== undefined ? usageCounts.unknown : raw.usageUnknown,
624
+ ownerAnchoredAbstained: ownerAnchored !== undefined ? ownerAnchored.abstained : raw.ownerAnchoredAbstained,
625
+ };
626
+ }
627
+ if (id === 'assistantMemoryLearning') {
628
+ const raw = requireRecord(value, 'memoryLearning');
629
+ const counts = 'counts' in raw ? requireRecord(raw.counts, 'memoryLearning.counts') : raw;
630
+ return {
631
+ enabled: raw.enabled,
632
+ connected: raw.connected,
633
+ available: raw.available,
634
+ hasError: resolveErrorFlag(raw, 'hasError', 'lastError'),
635
+ remainingExtractions: raw.remainingExtractions,
636
+ pending: counts.pending,
637
+ queued: counts.queued,
638
+ running: counts.running,
639
+ unknown: counts.unknown,
640
+ adopted: counts.adopted,
641
+ failed: counts.failed,
642
+ };
643
+ }
644
+ if (id === 'assistantWorkItems') {
645
+ const raw = requireRecord(value, 'workItems');
646
+ const follows = 'follows' in raw ? requireRecord(raw.follows, 'workItems.follows') : undefined;
647
+ const authority = 'authority' in raw ? requireRecord(raw.authority, 'workItems.authority') : undefined;
648
+ const settlement = 'settlement' in raw ? requireRecord(raw.settlement, 'workItems.settlement') : undefined;
649
+ const evaluation = 'evaluation' in raw ? requireRecord(raw.evaluation, 'workItems.evaluation') : undefined;
650
+ const schedulerWake = 'schedulerWake' in raw ? requireRecord(raw.schedulerWake, 'workItems.schedulerWake') : undefined;
651
+ const diagnosis = 'diagnosis' in raw && raw.diagnosis !== undefined ? requireRecord(raw.diagnosis, 'workItems.diagnosis') : undefined;
652
+ const ownerContinuation = 'ownerContinuation' in raw && raw.ownerContinuation !== undefined
653
+ ? requireRecord(raw.ownerContinuation, 'workItems.ownerContinuation')
654
+ : undefined;
655
+ const intakeFn = typeof provider.intakeEvaluationHealth === 'function'
656
+ ? provider.intakeEvaluationHealth
657
+ : undefined;
658
+ const intakeRaw = intakeFn === undefined ? undefined : intakeFn.call(provider);
659
+ const intake = intakeRaw === undefined ? undefined : requireRecord(intakeRaw, 'workItems.intakeEvaluation');
660
+ const hasIntervention = 'interventionRequired' in raw
661
+ ? raw.interventionRequired
662
+ : Boolean(diagnosis?.interventionRequired === true || ownerContinuation?.interventionRequired === true);
663
+ return {
664
+ enabled: raw.enabled,
665
+ mode: raw.mode,
666
+ openItems: raw.openItems,
667
+ dispatchUnknown: raw.dispatchUnknown,
668
+ workerConnected: raw.workerConnected,
669
+ ownerRouteValid: raw.ownerRouteValid,
670
+ followsUnresolved: follows !== undefined ? follows.unresolved : raw.followsUnresolved,
671
+ followsDegraded: follows !== undefined ? presenceBoolean(follows, 'degraded') : raw.followsDegraded,
672
+ authorityParked: authority !== undefined ? authority.parked : raw.authorityParked,
673
+ settlementEnabled: settlement !== undefined ? settlement.enabled : raw.settlementEnabled,
674
+ settlementUnverified: settlement !== undefined ? settlement.unverified : raw.settlementUnverified,
675
+ settlementDegraded: settlement !== undefined ? presenceBoolean(settlement, 'degraded') : raw.settlementDegraded,
676
+ evaluationEnabled: evaluation !== undefined ? evaluation.enabled : raw.evaluationEnabled,
677
+ evaluationConnected: evaluation !== undefined ? evaluation.connected : raw.evaluationConnected,
678
+ evaluationDegraded: evaluation !== undefined ? presenceBoolean(evaluation, 'degraded') : raw.evaluationDegraded,
679
+ schedulerWakeSubscribed: schedulerWake !== undefined ? schedulerWake.subscribed : raw.schedulerWakeSubscribed,
680
+ schedulerWakeError: schedulerWake !== undefined ? presenceBoolean(schedulerWake, 'lastError') : raw.schedulerWakeError,
681
+ interventionRequired: hasIntervention,
682
+ intakeEvaluationRegistered: intake !== undefined ? intake.registered : raw.intakeEvaluationRegistered,
683
+ intakeEvaluationUnpersisted: intake !== undefined ? intake.unpersisted : raw.intakeEvaluationUnpersisted,
684
+ };
685
+ }
686
+ return value;
687
+ }
688
+ export class AssistantHealthService extends Service {
689
+ static Config = configSchema;
690
+ context;
691
+ policy;
692
+ required;
693
+ now;
694
+ active = true;
695
+ constructor(ctx, input = {}, options = {}) {
696
+ super(ctx, 'assistantHealth');
697
+ let config;
698
+ try {
699
+ config = configSchema(input);
700
+ }
701
+ catch (error) {
702
+ throw new Error(`assistant-health: invalid configuration: ${String(error)}`, { cause: error });
703
+ }
704
+ if (new Set(config.requiredProviders).size !== config.requiredProviders.length) {
705
+ throw new Error('assistant-health: requiredProviders contains a duplicate');
706
+ }
707
+ const policy = ctx.get('assistantPolicy');
708
+ if (policy === undefined)
709
+ throw new Error('assistant-health: assistantPolicy service is required');
710
+ this.context = ctx;
711
+ this.policy = policy;
712
+ this.required = new Set(config.requiredProviders);
713
+ this.now = options.now ?? Date.now;
714
+ ctx.inject(['tools'], toolsCtx => registerAssistantHealthTool(toolsCtx, this));
715
+ ctx.effect(() => () => { this.active = false; }, 'assistant-health.runtime');
716
+ }
717
+ liveness() {
718
+ this.assertActive();
719
+ return { alive: true };
720
+ }
721
+ readiness() {
722
+ this.assertActive();
723
+ const providers = this.collect();
724
+ const summary = summarize(providers, this.required);
725
+ return { ready: summary.ready, warnings: summary.warnings };
726
+ }
727
+ report(agent) {
728
+ this.assertActive();
729
+ const decision = this.policy.authorizeAgent(agent, 'inspect', { kind: 'tool', id: 'assistant-health' });
730
+ if (decision.effect !== 'allow') {
731
+ throw new AssistantHealthError('policy-denied', `assistant-health policy denied report: ${decision.reasonCode}`);
732
+ }
733
+ return this.snapshot();
734
+ }
735
+ /**
736
+ * Agent-free, content-free global snapshot for runbook admission and alerts.
737
+ * It is deliberately unscoped and cannot prove a workspace-local mutation.
738
+ * This remains detect-only: it does not expose or invoke any repair method.
739
+ */
740
+ hostGlobalSnapshot(input) {
741
+ this.assertActive();
742
+ if (typeof input !== 'object' || input === null || Array.isArray(input)
743
+ || Object.keys(input).sort().join(',') !== 'operationId,principal') {
744
+ throw new AssistantHealthError('invalid-input', 'Host global health input accepts only principal and operationId');
745
+ }
746
+ const principal = hostText(input.principal, 'principal', 500, 'missing-principal');
747
+ const operationId = hostText(input.operationId, 'operationId', 500);
748
+ const digest = createHash('sha256').update(JSON.stringify([
749
+ HOST_RECOVERY_BACKGROUND_ID,
750
+ principal,
751
+ operationId,
752
+ ])).digest('hex');
753
+ const decision = this.policy.authorize({
754
+ subject: {
755
+ kind: 'background',
756
+ id: HOST_RECOVERY_BACKGROUND_ID,
757
+ principal,
758
+ },
759
+ action: 'inspect',
760
+ resource: { kind: 'tool', id: 'assistant-health:global' },
761
+ context: { initiator: 'background' },
762
+ }, { idempotencyKey: `assistant-health-host:${digest}` });
763
+ if (decision.effect !== 'allow') {
764
+ throw new AssistantHealthError('policy-denied', `assistant-health policy denied Host global snapshot: ${decision.reasonCode}`);
765
+ }
766
+ return this.snapshot();
767
+ }
768
+ snapshot() {
769
+ const providers = this.collect();
770
+ const summary = summarize(providers, this.required);
771
+ return Object.freeze({
772
+ ready: summary.ready,
773
+ severity: summary.severity,
774
+ generatedAt: this.now(),
775
+ providers: Object.freeze(providers),
776
+ assessments: Object.freeze(summary.assessments),
777
+ warnings: Object.freeze(summary.warnings),
778
+ });
779
+ }
780
+ collect() {
781
+ const get = this.context.get.bind(this.context);
782
+ return providerIds.map(id => {
783
+ const provider = get(providerServiceNames[id]);
784
+ if (provider === undefined)
785
+ return Object.freeze({ id, status: 'missing', metrics: Object.freeze({}) });
786
+ try {
787
+ const raw = collectProviderHealth(id, provider);
788
+ if (raw === undefined)
789
+ return Object.freeze({ id, status: 'error', metrics: Object.freeze({}) });
790
+ return Object.freeze({ id, status: 'ready', metrics: metrics(id, raw) });
791
+ }
792
+ catch {
793
+ return Object.freeze({ id, status: 'error', metrics: Object.freeze({}) });
794
+ }
795
+ });
796
+ }
797
+ assertActive() {
798
+ if (!this.active)
799
+ throw new AssistantHealthError('disposed', 'assistant-health service is disposed');
800
+ }
801
+ }
802
+ export const Config = configSchema;
803
+ //# sourceMappingURL=service.js.map