@dsh-ray/assistant-web-owner 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.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +336 -2
  3. package/bin/dsh-autonomy-doctor.js +33 -0
  4. package/bin/dsh-web-owner-setup.js +33 -0
  5. package/cordis.patch.yml +6 -0
  6. package/lib/autonomy-grants.d.ts +295 -0
  7. package/lib/autonomy-grants.d.ts.map +1 -0
  8. package/lib/autonomy-grants.js +1218 -0
  9. package/lib/autonomy-grants.js.map +1 -0
  10. package/lib/autonomy.d.ts +46 -0
  11. package/lib/autonomy.d.ts.map +1 -0
  12. package/lib/autonomy.js +323 -0
  13. package/lib/autonomy.js.map +1 -0
  14. package/lib/client.d.ts +58 -0
  15. package/lib/client.d.ts.map +1 -0
  16. package/lib/client.js +20016 -0
  17. package/lib/client.js.map +1 -0
  18. package/lib/doctor.d.ts +63 -0
  19. package/lib/doctor.d.ts.map +1 -0
  20. package/lib/doctor.js +745 -0
  21. package/lib/doctor.js.map +1 -0
  22. package/lib/goal-admission.d.ts +94 -0
  23. package/lib/goal-admission.d.ts.map +1 -0
  24. package/lib/goal-admission.js +556 -0
  25. package/lib/goal-admission.js.map +1 -0
  26. package/lib/goal-setup.d.ts +15 -0
  27. package/lib/goal-setup.d.ts.map +1 -0
  28. package/lib/goal-setup.js +145 -0
  29. package/lib/goal-setup.js.map +1 -0
  30. package/lib/host-dsh.d.ts +18 -0
  31. package/lib/host-dsh.d.ts.map +1 -0
  32. package/lib/host-dsh.js +220 -0
  33. package/lib/host-dsh.js.map +1 -0
  34. package/lib/index.d.ts +65 -0
  35. package/lib/index.d.ts.map +1 -0
  36. package/lib/index.js +319 -0
  37. package/lib/index.js.map +1 -0
  38. package/lib/native-client.d.ts +18 -0
  39. package/lib/native-client.d.ts.map +1 -0
  40. package/lib/native-client.js +57 -0
  41. package/lib/native-client.js.map +1 -0
  42. package/lib/notices.d.ts +15 -0
  43. package/lib/notices.d.ts.map +1 -0
  44. package/lib/notices.js +17 -0
  45. package/lib/notices.js.map +1 -0
  46. package/lib/repair-setup.d.ts +50 -0
  47. package/lib/repair-setup.d.ts.map +1 -0
  48. package/lib/repair-setup.js +192 -0
  49. package/lib/repair-setup.js.map +1 -0
  50. package/lib/settings-route.d.ts +7 -0
  51. package/lib/settings-route.d.ts.map +1 -0
  52. package/lib/settings-route.js +38 -0
  53. package/lib/settings-route.js.map +1 -0
  54. package/lib/setup.d.ts +24 -0
  55. package/lib/setup.d.ts.map +1 -0
  56. package/lib/setup.js +601 -0
  57. package/lib/setup.js.map +1 -0
  58. package/lib/typert.d.ts +213 -0
  59. package/lib/typert.d.ts.map +1 -0
  60. package/lib/typert.js +71 -0
  61. package/lib/typert.js.map +1 -0
  62. package/lib/version.d.ts +2 -0
  63. package/lib/version.d.ts.map +1 -0
  64. package/lib/version.js +2 -0
  65. package/lib/version.js.map +1 -0
  66. package/package.json +187 -3
package/lib/doctor.js ADDED
@@ -0,0 +1,745 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstatSync, realpathSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { isAbsolute, join, normalize } from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { isMap, isScalar, isSeq, parseDocument, YAMLMap } from 'yaml';
8
+ import { literalAutonomyLinux, validateAutonomyLinuxPaths } from './autonomy.js';
9
+ import { dumpEffectiveProfile, globalDshDatabasePath, withinDshHome } from './host-dsh.js';
10
+ function fail(message) { throw new Error(`autonomy doctor: ${message}`); }
11
+ function literal(node, label) {
12
+ if (isScalar(node) && (node.tag === undefined || node.tag === 'tag:yaml.org,2002:str'))
13
+ return node.value;
14
+ fail(`${label} must be literal`);
15
+ }
16
+ function path(node, label, dshHome) {
17
+ let value;
18
+ if (dshHome !== undefined && isScalar(node) && node.tag === 'tag:yaml.org,2002:js' && typeof node.value === 'string') {
19
+ const match = /^dshHomePath\(['"]([^'"\n]+)['"]\)$/u.exec(node.value);
20
+ if (!match || isAbsolute(match[1]) || match[1].split('/').includes('..'))
21
+ fail(`${label} has an unsupported expression`);
22
+ value = join(dshHome, match[1]);
23
+ }
24
+ else
25
+ value = literal(node, label);
26
+ if (typeof value !== 'string' || !isAbsolute(value) || normalize(value) !== value || /[\p{Cc}*]/u.test(value))
27
+ fail(`${label} must be a canonical absolute path`);
28
+ return value;
29
+ }
30
+ function object(node, label) {
31
+ if (!isMap(node))
32
+ fail(`${label} must be a mapping`);
33
+ const result = Object.create(null);
34
+ for (const pair of node.items) {
35
+ const key = literal(pair.key, label);
36
+ if (typeof key !== 'string')
37
+ fail(`${label} keys must be strings`);
38
+ result[key] = literal(pair.value, `${label}.${key}`);
39
+ }
40
+ return result;
41
+ }
42
+ /** Inspect the composed profile without evaluating tagged expressions or changing its grants. */
43
+ export function inspectAutonomyProfile(source, profile, dshHome) {
44
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(profile) || !isAbsolute(dshHome) || normalize(dshHome) !== dshHome || /[\p{Cc}*]/u.test(dshHome))
45
+ fail('invalid profile or home');
46
+ const document = parseDocument(source, { customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: (value) => value }] });
47
+ if (document.errors.length || !isSeq(document.contents))
48
+ fail('effective profile must be an unambiguous sequence');
49
+ const rows = document.contents;
50
+ const config = (slug) => {
51
+ const id = `dsh-ray-${slug}`;
52
+ const name = `@dsh-ray/${slug}`;
53
+ const matches = rows.items.filter(item => isMap(item) && (item.get('id') === id || item.get('name') === name));
54
+ const row = matches[0];
55
+ if (matches.length !== 1 || !row || literal(row.get('id', true), slug) !== id || literal(row.get('name', true), slug) !== name || (row.has('disabled') && literal(row.get('disabled', true), id) !== false))
56
+ fail(`missing, disabled or ambiguous ${slug}`);
57
+ const value = row.get('config', true);
58
+ if (!isMap(value))
59
+ fail(`${slug} config must be a mapping`);
60
+ return value;
61
+ };
62
+ const isolation = config('assistant-isolation');
63
+ const owner = config('assistant-web-owner');
64
+ const delivery = config('assistant-delivery');
65
+ const principal = object(owner.get('principal', true), 'Web principal');
66
+ if (!isDeepStrictEqual({ ...principal }, { account: profile, tenant: 'local', user: 'operator' }))
67
+ fail('expected installer-managed Web owner');
68
+ const workspace = path(owner.get('workspace', true), 'Web workspace');
69
+ const preset = literal(owner.get('preset', true), 'Web preset');
70
+ if (typeof preset !== 'string' || !/^[a-z0-9][a-z0-9-]*$/u.test(preset))
71
+ fail('invalid Web preset');
72
+ const grants = isolation.get('grants', true);
73
+ if (!isSeq(grants) || grants.items.length !== 1)
74
+ fail('expected one installer-managed isolation grant');
75
+ const grant = object(grants.items[0], 'Isolation grant');
76
+ const fields = ['id', 'revision', 'principalDigest', 'principalRecordId', 'principalVersion', 'workspace', 'agentPreset', 'expiresAt', 'maxRuns', 'maxTotalDurationMs'];
77
+ if (Object.keys(grant).sort().join(',') !== fields.sort().join(',') || grant.id !== `autonomy-${profile}`
78
+ || grant.principalDigest !== createHash('sha256').update(`web/${profile}/local/operator`).digest('hex')
79
+ || grant.workspace !== workspace || grant.agentPreset !== preset
80
+ || typeof grant.principalRecordId !== 'string' || grant.principalRecordId.length === 0
81
+ || !['revision', 'principalVersion', 'expiresAt', 'maxRuns', 'maxTotalDurationMs'].every(key => Number.isSafeInteger(grant[key]) && grant[key] > 0))
82
+ fail('invalid managed grant or owner scope');
83
+ const stateRoot = path(isolation.get('stateRoot', true), 'Isolation stateRoot');
84
+ const common = { stateRoot,
85
+ databasePath: path(delivery.get('databasePath', true), 'Delivery databasePath', dshHome),
86
+ grant: { ...grant }, principal: { channel: 'web', account: profile, tenant: 'local', user: 'operator' } };
87
+ const declaredBackend = isolation.has('backend') ? literal(isolation.get('backend', true), 'Isolation backend') : undefined;
88
+ // Docker profiles are never interpreted or rewritten here. Fail closed with a
89
+ // migration hint so an old profile cannot be reported as healthy.
90
+ if (declaredBackend === 'docker' || isolation.has('image') || isolation.has('dockerPath') || isolation.has('socketPath'))
91
+ fail('Docker isolation was removed; migrate this profile explicitly to the linux-native backend');
92
+ if (declaredBackend !== undefined && declaredBackend !== 'linux-native')
93
+ fail('invalid isolation backend; migrate this profile explicitly to the linux-native backend');
94
+ if (!isolation.has('linux'))
95
+ fail('missing linux-native isolation descriptor; migrate this profile explicitly');
96
+ const linux = literalAutonomyLinux(isolation.get('linux', true));
97
+ validateAutonomyLinuxPaths(linux, stateRoot, dshHome);
98
+ return { ...common, backend: 'linux-native', linux };
99
+ }
100
+ /** A read-only snapshot, never pairing, migration, or an authorization for future execution. */
101
+ export function inspectAutonomyOwner(profile) {
102
+ let database;
103
+ try {
104
+ if (!lstatSync(profile.databasePath).isFile() || realpathSync(profile.grant.workspace) !== profile.grant.workspace)
105
+ return { status: 'unavailable' };
106
+ database = new DatabaseSync(profile.databasePath, { readOnly: true });
107
+ database.exec('PRAGMA query_only = ON; PRAGMA busy_timeout = 1000; BEGIN;');
108
+ // Deliberately pinned rather than imported: each Delivery schema must be
109
+ // reviewed before this self-contained read-only gate accepts it. v25 adds
110
+ // foreground completion sequencing, v26 restart fences, v27 progress
111
+ // handles, v28 foreground termination, v29 report/reply sidecars, v30 owner feedback and v31 attention audit.
112
+ // Principal authority is unchanged from v24; reply state is not an owner receipt.
113
+ // Unknown versions fail closed.
114
+ const schemaVersion = database.prepare('PRAGMA user_version').get().user_version;
115
+ if (![24, 25, 26, 27, 28, 29, 30, 31].includes(schemaVersion))
116
+ return { status: 'unavailable' };
117
+ const row = database.prepare('SELECT principal_json, role, status, version, linked_to_id FROM delivery_principals WHERE id = ?').get(profile.grant.principalRecordId);
118
+ if (!row || row.role !== 'owner' || row.status !== 'active' || row.version !== profile.grant.principalVersion || row.linked_to_id !== null
119
+ || typeof row.principal_json !== 'string' || !isDeepStrictEqual(JSON.parse(row.principal_json), profile.principal))
120
+ return { status: 'mismatch' };
121
+ return { status: 'matched' };
122
+ }
123
+ catch {
124
+ return { status: 'unavailable' };
125
+ }
126
+ finally {
127
+ database?.close();
128
+ }
129
+ }
130
+ /** Verify only the persisted backend descriptor; never fetch, prepare or renew. */
131
+ export async function probeAutonomyProfileRuntime(profile) {
132
+ const { verifyLinuxRuntime } = await import('@dsh-ray/assistant-isolation');
133
+ const { probeLinuxIsolationRuntime } = await import('@dsh-ray/assistant-isolation/native-resources');
134
+ await verifyLinuxRuntime(profile.linux.runtime);
135
+ await probeLinuxIsolationRuntime(profile.linux);
136
+ }
137
+ // ---------------------------------------------------------------------------
138
+ // Static autonomy readiness snapshot (ordinary-use learning assembly)
139
+ /** Installed bundles the ordinary-use learning assembly expects in one profile. */
140
+ const readinessBundleSlugs = [
141
+ 'personal-assistant',
142
+ 'assistant-work-items',
143
+ 'assistant-delivery',
144
+ 'assistant-evaluation',
145
+ 'assistant-verifier',
146
+ 'event-triggers',
147
+ 'assistant-memory-learning',
148
+ 'assistant-growth-driver',
149
+ 'assistant-proactive',
150
+ 'plugin-control-plane',
151
+ ];
152
+ /** Work-item intake evaluation levels; mirrors the work-items INTAKE_EVALUATION_LEVELS enum. */
153
+ const intakeEvaluationCeilings = new Set(['ignore', 'digest', 'notify', 'accept']);
154
+ const intakeRuleIdPattern = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
155
+ function readinessRows(source) {
156
+ try {
157
+ const document = parseDocument(source, { customTags: [{ tag: 'tag:yaml.org,2002:js', resolve: (value) => value }] });
158
+ return document.errors.length === 0 && isSeq(document.contents) ? document.contents : undefined;
159
+ }
160
+ catch {
161
+ return undefined;
162
+ }
163
+ }
164
+ function readinessRow(rows, slug) {
165
+ const id = `dsh-ray-${slug}`;
166
+ const name = `@dsh-ray/${slug}`;
167
+ const matches = rows.items.filter(item => isMap(item) && (item.get('id') === id || item.get('name') === name));
168
+ return matches.length === 1 ? matches[0] : undefined;
169
+ }
170
+ function readinessLoaded(rows, slug) {
171
+ const row = readinessRow(rows, slug);
172
+ return row === undefined ? undefined : row.get('disabled') !== true;
173
+ }
174
+ function readinessConfig(rows, slug) {
175
+ const config = readinessRow(rows, slug)?.get('config', true);
176
+ if (config === undefined)
177
+ return new YAMLMap();
178
+ return isMap(config) ? config : undefined;
179
+ }
180
+ function readinessPlain(node) {
181
+ if (node === undefined)
182
+ return undefined;
183
+ if (isScalar(node))
184
+ return node.value;
185
+ if (isMap(node) || isSeq(node))
186
+ return node.toJSON();
187
+ return node;
188
+ }
189
+ /** Read the raw YAML node at one dotted config key without evaluating tags. */
190
+ function readinessNode(rows, slug, key) {
191
+ const config = readinessConfig(rows, slug);
192
+ if (config === undefined)
193
+ return undefined;
194
+ let node = config;
195
+ for (const segment of key.split('.')) {
196
+ if (!isMap(node))
197
+ return undefined;
198
+ node = node.get(segment, true);
199
+ }
200
+ return node;
201
+ }
202
+ /** Read one dotted config value without evaluating tagged expressions. */
203
+ function readinessValue(rows, slug, key) {
204
+ return readinessPlain(readinessNode(rows, slug, key));
205
+ }
206
+ function inspectDatabasePathScope(rows, slug, key, globalSlug, dshHome) {
207
+ const node = readinessNode(rows, slug, key);
208
+ if (node === undefined)
209
+ return { configured: false, scoped: true };
210
+ if (!isScalar(node) || typeof node.value !== 'string')
211
+ return { configured: true, scoped: false, issue: 'invalid' };
212
+ let resolved = node.value;
213
+ if (node.tag === 'tag:yaml.org,2002:js') {
214
+ const match = /^dshHomePath\(['"]([^'"\n]+)['"]\)$/u.exec(resolved);
215
+ if (match === null || isAbsolute(match[1]) || match[1].split('/').includes('..')) {
216
+ return { configured: true, scoped: false, issue: 'invalid' };
217
+ }
218
+ if (dshHome === undefined)
219
+ return { configured: true, scoped: true };
220
+ resolved = join(dshHome, match[1]);
221
+ }
222
+ else if (node.tag !== undefined && node.tag !== 'tag:yaml.org,2002:str') {
223
+ return { configured: true, scoped: false, issue: 'invalid' };
224
+ }
225
+ else {
226
+ if (!isAbsolute(resolved) || resolved.includes('\0') || resolved.includes('*')) {
227
+ return { configured: true, scoped: false, issue: 'invalid' };
228
+ }
229
+ if (normalize(resolved) === normalize(globalDshDatabasePath(globalSlug))) {
230
+ return { configured: true, scoped: false, issue: 'global-default' };
231
+ }
232
+ }
233
+ if (dshHome === undefined)
234
+ return { configured: true, scoped: true };
235
+ try {
236
+ withinDshHome(resolved, dshHome, slug, fail);
237
+ return { configured: true, scoped: true };
238
+ }
239
+ catch {
240
+ return { configured: true, scoped: false, issue: 'outside-home' };
241
+ }
242
+ }
243
+ function validIntakeEvaluationRules(value) {
244
+ if (!Array.isArray(value) || value.length === 0 || value.length > 16)
245
+ return false;
246
+ const ids = new Set();
247
+ return value.every(rule => {
248
+ if (rule === null || typeof rule !== 'object' || Array.isArray(rule))
249
+ return false;
250
+ const record = rule;
251
+ if (Object.keys(record).sort().join(',') !== 'ceiling,ruleId')
252
+ return false;
253
+ const { ruleId, ceiling } = record;
254
+ if (typeof ruleId !== 'string' || !intakeRuleIdPattern.test(ruleId) || ids.has(ruleId))
255
+ return false;
256
+ ids.add(ruleId);
257
+ return typeof ceiling === 'string' && intakeEvaluationCeilings.has(ceiling);
258
+ });
259
+ }
260
+ function routeText(value) {
261
+ return typeof value === 'string' && value.length > 0 && value.length <= 200 ? value : null;
262
+ }
263
+ /**
264
+ * Inspect the composed profile without activating anything, calling a model or
265
+ * reading a database. Missing or mismatched configuration is reported as
266
+ * `not-ready` with a reason; this function never throws for an incomplete
267
+ * assembly, so a doctor run degrades into a snapshot instead of a crash.
268
+ */
269
+ export function inspectAutonomyReadiness(source, profile, dshHome) {
270
+ const runtime = { observed: false,
271
+ note: 'static composed profile only; runtime registration, model calls, external delivery and Policy readiness are not observed' };
272
+ const rows = readinessRows(source);
273
+ if (rows === undefined) {
274
+ const check = { id: 'profile-composition', required: true, status: 'not-ready',
275
+ summary: 'effective profile is not an unambiguous YAML sequence',
276
+ reasons: [{ code: 'profile-unreadable', message: 'the composed profile could not be parsed; doctor reports not-ready instead of crashing' }],
277
+ details: {} };
278
+ return { protocol: 'dsh-ray/autonomy-readiness/v1', profile, scope: 'ordinary-use-learning', ready: false, checks: [check], runtime };
279
+ }
280
+ const checks = [];
281
+ const missing = [];
282
+ const disabled = [];
283
+ for (const slug of readinessBundleSlugs) {
284
+ const loaded = readinessLoaded(rows, slug);
285
+ if (loaded === undefined)
286
+ missing.push(slug);
287
+ else if (!loaded)
288
+ disabled.push(slug);
289
+ }
290
+ checks.push({
291
+ id: 'bundles', required: true,
292
+ status: missing.length === 0 && disabled.length === 0 ? 'ready' : 'not-ready',
293
+ summary: `${readinessBundleSlugs.length - missing.length - disabled.length}/${readinessBundleSlugs.length} expected bundles loaded`,
294
+ reasons: [
295
+ ...missing.map(slug => ({ code: `bundle-missing:${slug}`, message: `@dsh-ray/${slug} is not installed in this profile` })),
296
+ ...disabled.map(slug => ({ code: `bundle-disabled:${slug}`, message: `@dsh-ray/${slug} is installed but its loader row is disabled` })),
297
+ ],
298
+ details: { expected: readinessBundleSlugs.length, missing, disabled },
299
+ });
300
+ const workItemsLoaded = readinessLoaded(rows, 'assistant-work-items');
301
+ const workItemsEnabled = readinessValue(rows, 'assistant-work-items', 'enabled');
302
+ const workItemsMode = readinessValue(rows, 'assistant-work-items', 'mode');
303
+ const intakeLedger = readinessValue(rows, 'assistant-work-items', 'intakeLedger.enabled');
304
+ const workItemsReasons = [];
305
+ if (workItemsLoaded !== true) {
306
+ workItemsReasons.push({ code: 'work-items-unavailable', message: 'assistant-work-items is not installed and loaded, so no observe ledger can be written' });
307
+ }
308
+ else {
309
+ if (workItemsEnabled !== true)
310
+ workItemsReasons.push({ code: 'work-items-not-enabled', message: 'assistant-work-items.enabled is off; the ledger is inert' });
311
+ if (workItemsMode !== 'observe')
312
+ workItemsReasons.push({ code: 'work-items-not-observe', message: `assistant-work-items.mode is ${JSON.stringify(workItemsMode ?? null)}; the default assembly stays observe-only` });
313
+ if (intakeLedger !== true)
314
+ workItemsReasons.push({ code: 'work-items-intake-disabled', message: 'assistant-work-items.intakeLedger.enabled is off; inbound metadata is not recorded' });
315
+ }
316
+ checks.push({
317
+ id: 'work-items-observe-intake', required: true,
318
+ status: workItemsReasons.length === 0 ? 'ready' : 'not-ready',
319
+ summary: workItemsReasons.length === 0 ? 'observe ledger enabled with the deterministic intake ledger' : 'observe ledger / intake not assembled',
320
+ reasons: workItemsReasons,
321
+ details: { enabled: workItemsEnabled === true, mode: workItemsMode ?? null, intakeLedgerEnabled: intakeLedger === true },
322
+ });
323
+ const proactiveLoaded = readinessLoaded(rows, 'assistant-proactive');
324
+ const intakeEvaluationEnabled = readinessValue(rows, 'assistant-proactive', 'intakeEvaluation.enabled');
325
+ const intakeProvider = routeText(readinessValue(rows, 'assistant-proactive', 'intakeEvaluation.provider'));
326
+ const intakeModel = routeText(readinessValue(rows, 'assistant-proactive', 'intakeEvaluation.model'));
327
+ const intakeRules = readinessValue(rows, 'assistant-proactive', 'intakeEvaluation.rules');
328
+ const workItemsEvaluation = readinessValue(rows, 'assistant-work-items', 'intakeLedger.evaluation.enabled');
329
+ const evaluatorReasons = [];
330
+ if (workItemsLoaded !== true)
331
+ evaluatorReasons.push({ code: 'intake-evaluator-work-items-missing', message: 'assistant-work-items is unavailable, so an evaluator cannot register' });
332
+ else if (workItemsEvaluation !== true)
333
+ evaluatorReasons.push({ code: 'intake-evaluator-work-items-evaluation-off', message: 'assistant-work-items.intakeLedger.evaluation.enabled is off; the queue would refuse an evaluator registration' });
334
+ if (proactiveLoaded !== true)
335
+ evaluatorReasons.push({ code: 'intake-evaluator-producer-missing', message: 'assistant-proactive is not installed and loaded, so no production intake evaluator exists' });
336
+ else {
337
+ if (intakeEvaluationEnabled !== true)
338
+ evaluatorReasons.push({ code: 'intake-evaluator-disabled', message: 'assistant-proactive.intakeEvaluation.enabled is off; the preset only enables it after the owner declared rules and a model route' });
339
+ if (intakeProvider === null)
340
+ evaluatorReasons.push({ code: 'intake-evaluator-provider-missing', message: 'assistant-proactive.intakeEvaluation.provider is not configured' });
341
+ if (intakeModel === null)
342
+ evaluatorReasons.push({ code: 'intake-evaluator-model-missing', message: 'assistant-proactive.intakeEvaluation.model is not configured' });
343
+ if (!validIntakeEvaluationRules(intakeRules))
344
+ evaluatorReasons.push({ code: 'intake-evaluator-rules-invalid', message: 'assistant-proactive.intakeEvaluation.rules needs 1-16 entries with unique ruleId and ceiling in ignore|digest|notify|accept' });
345
+ }
346
+ checks.push({
347
+ id: 'intake-evaluator', required: true,
348
+ status: evaluatorReasons.length === 0 ? 'ready' : 'not-ready',
349
+ summary: evaluatorReasons.length === 0
350
+ ? `configured with ${Array.isArray(intakeRules) ? intakeRules.length : 0} rules; runtime registration is not observable from a static dump`
351
+ : 'production intake evaluator not assembled',
352
+ reasons: evaluatorReasons,
353
+ details: { configured: evaluatorReasons.length === 0, runtimeRegistration: 'not-observed',
354
+ provider: intakeProvider, model: intakeModel,
355
+ rules: Array.isArray(intakeRules) ? intakeRules.length : 0,
356
+ workItemsEvaluationEnabled: workItemsEvaluation === true },
357
+ });
358
+ const deliveryLoaded = readinessLoaded(rows, 'assistant-delivery');
359
+ const ownerReportFeedback = readinessValue(rows, 'assistant-work-items', 'ownerReportFeedback') === true;
360
+ const ownerReplyContinuation = readinessValue(rows, 'assistant-work-items', 'ownerReplyContinuation') === true;
361
+ checks.push({
362
+ id: 'delivery-natural-feedback', required: true,
363
+ status: deliveryLoaded === true ? 'ready' : 'not-ready',
364
+ summary: deliveryLoaded === true
365
+ ? `Delivery loaded; the natural feedback parser ships with the bundle (work-item report feedback: ${ownerReportFeedback ? 'on' : 'off'}, reply continuation: ${ownerReplyContinuation ? 'on' : 'off'})`
366
+ : 'assistant-delivery is not installed and loaded, so owner replies cannot become trusted feedback',
367
+ reasons: deliveryLoaded === true ? [] : [{ code: 'delivery-unavailable', message: 'assistant-delivery is not installed and loaded in this profile' }],
368
+ details: { installed: deliveryLoaded === true, ownerReportFeedback, ownerReplyContinuation },
369
+ });
370
+ const learningReasons = [];
371
+ const memoryLoaded = readinessLoaded(rows, 'assistant-memory-learning');
372
+ const memoryFlag = readinessValue(rows, 'assistant-memory-learning', 'workItemExperiences') === true;
373
+ const reviewFlag = readinessValue(rows, 'assistant-verifier', 'memoryReviews.workItemExperiences') === true;
374
+ const adoptionFlag = readinessValue(rows, 'personal-assistant', 'personalMemory.automaticLearning.workItemExperiences') === true;
375
+ if (memoryLoaded !== true)
376
+ learningReasons.push({ code: 'memory-learning-unavailable', message: 'assistant-memory-learning is not installed and loaded' });
377
+ else if (!memoryFlag)
378
+ learningReasons.push({ code: 'memory-work-item-experiences-off', message: 'assistant-memory-learning.workItemExperiences is off; the preset only turns it on after both signed grants already carry the same flag' });
379
+ else {
380
+ if (!reviewFlag)
381
+ learningReasons.push({ code: 'memory-review-grant-not-expanded', message: 'assistant-verifier.memoryReviews.workItemExperiences is off; a fresh review grant is required' });
382
+ if (!adoptionFlag)
383
+ learningReasons.push({ code: 'memory-adoption-grant-not-expanded', message: 'personal-assistant.personalMemory.automaticLearning.workItemExperiences is off; a fresh adoption grant is required' });
384
+ }
385
+ const growthLoaded = readinessLoaded(rows, 'assistant-growth-driver');
386
+ const growthEnabled = readinessValue(rows, 'assistant-growth-driver', 'enabled') === true;
387
+ const usageEnabled = readinessValue(rows, 'assistant-growth-driver', 'usageLearning.enabled') === true;
388
+ const workItemFailures = readinessValue(rows, 'assistant-growth-driver', 'usageLearning.workItemFailures') === true;
389
+ if (growthLoaded !== true)
390
+ learningReasons.push({ code: 'growth-driver-unavailable', message: 'assistant-growth-driver is not installed and loaded' });
391
+ else if (!growthEnabled || !usageEnabled)
392
+ learningReasons.push({ code: 'growth-usage-learning-off', message: 'assistant-growth-driver enabled / usageLearning.enabled is off; ordinary usage is not scanned' });
393
+ else if (!workItemFailures)
394
+ learningReasons.push({ code: 'growth-work-item-failures-not-authorized', message: 'usageLearning.workItemFailures is off; it needs signed workItemAuthorities pins that a preset never invents or extends' });
395
+ const evaluationLoaded = readinessLoaded(rows, 'assistant-evaluation');
396
+ const notificationOutcomes = readinessValue(rows, 'assistant-evaluation', 'notificationOutcomesEnabled') === true;
397
+ if (evaluationLoaded !== true)
398
+ learningReasons.push({ code: 'evaluation-unavailable', message: 'assistant-evaluation is not installed and loaded' });
399
+ else if (!notificationOutcomes)
400
+ learningReasons.push({ code: 'evaluation-notification-outcomes-off', message: 'assistant-evaluation.notificationOutcomesEnabled is off; notification results are not synced into the ledger' });
401
+ const agreementPersist = readinessValue(rows, 'assistant-evaluation', 'intakeAttentionAgreementPersistIntervalMs');
402
+ const agreementEnabled = readinessValue(rows, 'assistant-evaluation', 'intakeAttentionAgreementEnabled') === true;
403
+ const agreementPersistConfigured = typeof agreementPersist === 'number' && Number.isSafeInteger(agreementPersist) && agreementPersist > 0;
404
+ if (evaluationLoaded === true && agreementPersistConfigured && (!notificationOutcomes || !agreementEnabled)) {
405
+ learningReasons.push({ code: 'evaluation-intake-agreement-persist-misconfigured',
406
+ message: 'assistant-evaluation.intakeAttentionAgreementPersistIntervalMs is set but intakeAttentionAgreementEnabled / notificationOutcomesEnabled is off; Evaluation refuses this configuration' });
407
+ }
408
+ checks.push({
409
+ id: 'background-learning', required: true,
410
+ status: learningReasons.length === 0 ? 'ready' : 'not-ready',
411
+ summary: learningReasons.length === 0 ? 'ordinary-use learning switches are assembled' : `${learningReasons.length} background learning switch(es) not ready`,
412
+ reasons: learningReasons,
413
+ details: { memoryWorkItemExperiences: memoryFlag, memoryReviewGrant: reviewFlag, memoryAdoptionGrant: adoptionFlag,
414
+ growthEnabled, growthUsageLearning: usageEnabled, growthWorkItemFailures: workItemFailures, notificationOutcomesEnabled: notificationOutcomes,
415
+ intakeAgreementPersistIntervalMs: agreementPersistConfigured ? agreementPersist : null,
416
+ intakeAgreementEnabled: agreementEnabled },
417
+ });
418
+ const controlLoaded = readinessLoaded(rows, 'plugin-control-plane');
419
+ const revisionCapabilities = readinessValue(rows, 'plugin-control-plane', 'revisionCapabilities');
420
+ const creationCapabilities = readinessValue(rows, 'plugin-control-plane', 'creationCapabilities');
421
+ const revisionVerifications = readinessValue(rows, 'plugin-control-plane', 'revisionVerifications');
422
+ const sourceJobs = readinessValue(rows, 'plugin-control-plane', 'sourceJobs');
423
+ const sourceBuild = readinessValue(rows, 'plugin-control-plane', 'sourceBuild');
424
+ const revisionJobs = sourceJobs !== null && typeof sourceJobs === 'object' && !Array.isArray(sourceJobs)
425
+ ? sourceJobs.revision : undefined;
426
+ const revisionConfigured = revisionCapabilities !== null && typeof revisionCapabilities === 'object' && !Array.isArray(revisionCapabilities)
427
+ && typeof revisionCapabilities.authorityId === 'string'
428
+ && typeof revisionCapabilities.keyId === 'string'
429
+ && typeof revisionCapabilities.namePrefix === 'string'
430
+ && typeof revisionCapabilities.expiresAt === 'number';
431
+ const revisionReasons = [];
432
+ if (controlLoaded !== true)
433
+ revisionReasons.push({ code: 'control-plane-unavailable', message: 'plugin-control-plane is not installed and loaded' });
434
+ else if (!revisionConfigured)
435
+ revisionReasons.push({ code: 'revision-capabilities-not-configured', message: 'revision adoption requires owner-generated ed25519 key material and explicit adoption/rollback grants; nothing is generated by a preset' });
436
+ else if (creationCapabilities === undefined || revisionVerifications === undefined || revisionJobs === undefined || sourceBuild === undefined) {
437
+ revisionReasons.push({ code: 'revision-prerequisites-missing', message: 'revisionCapabilities also needs creationCapabilities, revisionVerifications, sourceBuild and sourceJobs.revision; verify the owner setup' });
438
+ }
439
+ checks.push({
440
+ id: 'revision-adoption', required: true,
441
+ status: revisionReasons.length === 0 ? 'ready' : 'not-ready',
442
+ summary: revisionReasons.length === 0 ? 'verified revision adoption and exact parent rollback are configured' : 'revision adoption authorization is not configured',
443
+ reasons: revisionReasons,
444
+ details: { configured: revisionConfigured, prerequisites: { creationCapabilities: creationCapabilities !== undefined, revisionVerifications: revisionVerifications !== undefined, sourceBuild: sourceBuild !== undefined, revisionJobs: revisionJobs !== undefined } },
445
+ });
446
+ const triggersLoaded = readinessLoaded(rows, 'event-triggers');
447
+ const pollerEnabled = readinessValue(rows, 'event-triggers', 'pollerEnabled') === true;
448
+ const triggers = readinessValue(rows, 'event-triggers', 'triggers');
449
+ const triggerCount = Array.isArray(triggers) ? triggers.length : 0;
450
+ const pollerReasons = [];
451
+ if (triggersLoaded !== true)
452
+ pollerReasons.push({ code: 'event-triggers-unavailable', message: 'event-triggers is not installed and loaded' });
453
+ else if (!pollerEnabled)
454
+ pollerReasons.push({ code: 'event-poller-disabled', message: 'event-triggers.pollerEnabled is off; configured triggers never fire' });
455
+ checks.push({
456
+ id: 'event-poller', required: true,
457
+ status: pollerReasons.length === 0 ? 'ready' : 'not-ready',
458
+ summary: pollerReasons.length === 0
459
+ ? `poller enabled with ${triggerCount} trigger definition(s)${triggerCount === 0 ? '; none configured, so nothing will fire yet' : ''}`
460
+ : 'event poller not ready',
461
+ reasons: pollerReasons,
462
+ details: { pollerEnabled, triggers: triggerCount },
463
+ });
464
+ // Optional ring (Lead request): PTC presentation is a configuration hint only.
465
+ const toolPresentation = readinessValue(rows, 'assistant-growth-driver', 'toolPresentation');
466
+ const ptcConfigured = toolPresentation === 'ptc';
467
+ checks.push({
468
+ id: 'ptc-presentation', required: false,
469
+ status: ptcConfigured ? 'not-verified' : 'ready',
470
+ summary: ptcConfigured
471
+ ? 'toolPresentation=ptc; a live run still needs a mounted ctx.ptcRuntime, run_code that does not request human approval, and an exact Policy allow rule for the growth agent background run_code (this static doctor verifies none of the runtime conditions)'
472
+ : 'toolPresentation is native (PTC is an explicit owner opt-in)',
473
+ reasons: [],
474
+ details: { toolPresentation: typeof toolPresentation === 'string' ? toolPresentation : 'native' },
475
+ });
476
+ // Optional ring: assistant-dreaming fail-closed config & $DSH_HOME DB scoping.
477
+ const dreamingLoaded = readinessLoaded(rows, 'assistant-dreaming');
478
+ const dreamingEnabled = readinessValue(rows, 'assistant-dreaming', 'enabled') === true;
479
+ const dreamingRetired = readinessValue(rows, 'assistant-dreaming', 'retired') === true;
480
+ const dreamingDbScope = dreamingLoaded === true
481
+ ? inspectDatabasePathScope(rows, 'assistant-dreaming', 'databasePath', 'assistant-dreaming', dshHome)
482
+ : { configured: false, scoped: true };
483
+ const dreamingScope = readinessValue(rows, 'assistant-dreaming', 'scope');
484
+ const dreamingScopeValid = dreamingScope !== null && typeof dreamingScope === 'object' && !Array.isArray(dreamingScope)
485
+ && typeof dreamingScope.workspace === 'string' && isAbsolute(dreamingScope.workspace)
486
+ && routeText(dreamingScope.preset) !== null && routeText(dreamingScope.principalId) !== null && routeText(dreamingScope.ownerRouteId) !== null;
487
+ const dreamingModelValid = routeText(readinessValue(rows, 'assistant-dreaming', 'provider')) !== null
488
+ && routeText(readinessValue(rows, 'assistant-dreaming', 'model')) !== null;
489
+ const dreamingBudgetAmount = readinessValue(rows, 'assistant-dreaming', 'budgetAmount');
490
+ const dreamingBudgetValid = routeText(readinessValue(rows, 'assistant-dreaming', 'budgetId')) !== null
491
+ && typeof dreamingBudgetAmount === 'number' && Number.isSafeInteger(dreamingBudgetAmount) && dreamingBudgetAmount >= 1;
492
+ const combinedPolicyRules = [
493
+ readinessValue(rows, 'personal-assistant', 'assistantPolicy.rules'),
494
+ readinessValue(rows, 'assistant-policy', 'rules'),
495
+ ].flatMap(entry => Array.isArray(entry) ? entry : []);
496
+ const dreamOwnerTransitionRulesConfigured = ['dream.acknowledge', 'dream.validate', 'dream.reject', 'dream.retire']
497
+ .every(action => combinedPolicyRules.some(rule => rule !== null && typeof rule === 'object' && !Array.isArray(rule)
498
+ && rule.effect === 'allow'
499
+ && Array.isArray(rule.actions)
500
+ && rule.actions.includes(action)));
501
+ const dreamingReasons = [];
502
+ if (dreamingLoaded === true) {
503
+ if (!dreamingDbScope.scoped) {
504
+ dreamingReasons.push({
505
+ code: 'dreaming-database-not-scoped',
506
+ message: 'assistant-dreaming.databasePath must be $DSH_HOME-scoped rather than global ~/.dsh',
507
+ });
508
+ }
509
+ if (dreamingEnabled) {
510
+ if (dreamingRetired)
511
+ dreamingReasons.push({ code: 'dreaming-retired-while-enabled', message: 'assistant-dreaming.retired is true while enabled=true' });
512
+ if (!dreamingScopeValid)
513
+ dreamingReasons.push({ code: 'dreaming-scope-missing', message: 'assistant-dreaming requires explicit scope.{workspace,preset,principalId,ownerRouteId}' });
514
+ if (!dreamingDbScope.configured)
515
+ dreamingReasons.push({ code: 'dreaming-database-missing', message: 'assistant-dreaming requires an explicit $DSH_HOME-scoped databasePath' });
516
+ if (!dreamingModelValid)
517
+ dreamingReasons.push({ code: 'dreaming-model-missing', message: 'assistant-dreaming requires explicit provider and model' });
518
+ if (!dreamingBudgetValid)
519
+ dreamingReasons.push({ code: 'dreaming-budget-missing', message: 'assistant-dreaming requires explicit budgetId and positive integer budgetAmount' });
520
+ }
521
+ }
522
+ checks.push({
523
+ id: 'dreaming', required: false,
524
+ status: dreamingReasons.length === 0 ? 'ready' : 'not-ready',
525
+ summary: dreamingReasons.length > 0
526
+ ? 'assistant-dreaming has incomplete or un-scoped configuration'
527
+ : dreamingLoaded === undefined
528
+ ? 'assistant-dreaming is not installed (optional)'
529
+ : dreamingLoaded === false
530
+ ? 'assistant-dreaming is disabled in this profile'
531
+ : dreamingEnabled
532
+ ? 'assistant-dreaming is enabled with explicit owner scope, $DSH_HOME databasePath, model route and finite budget'
533
+ : 'assistant-dreaming is dormant (enabled=false)',
534
+ reasons: dreamingReasons,
535
+ details: {
536
+ installed: dreamingLoaded !== undefined,
537
+ loaded: dreamingLoaded === true,
538
+ enabled: dreamingEnabled,
539
+ retired: dreamingRetired,
540
+ databaseConfigured: dreamingDbScope.configured,
541
+ databaseScoped: dreamingDbScope.scoped,
542
+ scopeConfigured: dreamingScopeValid,
543
+ modelConfigured: dreamingModelValid,
544
+ budgetConfigured: dreamingBudgetValid,
545
+ notifyOwner: readinessValue(rows, 'assistant-dreaming', 'notifyOwner') === true,
546
+ dreamOwnerTransitionRulesConfigured,
547
+ },
548
+ });
549
+ // Optional ring: assistant-proactive opportunities & assistant-goals DB scoping and readiness.
550
+ const proactiveActive = proactiveLoaded === true;
551
+ const proactiveDbScope = proactiveActive
552
+ ? inspectDatabasePathScope(rows, 'assistant-proactive', 'databasePath', 'assistant-proactive', dshHome)
553
+ : { configured: false, scoped: true };
554
+ const proactiveProfilesRaw = readinessValue(rows, 'assistant-proactive', 'profiles');
555
+ const proactiveProfiles = Array.isArray(proactiveProfilesRaw) ? proactiveProfilesRaw : [];
556
+ const invalidPreparedProfile = proactiveProfiles.some(entry => {
557
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry))
558
+ return true;
559
+ const prep = entry.preparation;
560
+ if (prep === undefined)
561
+ return false;
562
+ return routeText(prep.provider) === null || routeText(prep.model) === null || routeText(prep.budgetId) === null;
563
+ });
564
+ const goalsLoaded = readinessLoaded(rows, 'assistant-goals') === true;
565
+ const goalsDbScope = goalsLoaded
566
+ ? inspectDatabasePathScope(rows, 'assistant-goals', 'databasePath', 'assistant-goals', dshHome)
567
+ : { configured: false, scoped: true };
568
+ const proactiveGoalsReasons = [];
569
+ if (proactiveActive && !proactiveDbScope.scoped) {
570
+ proactiveGoalsReasons.push({ code: 'proactive-database-not-scoped', message: 'assistant-proactive.databasePath leaks outside $DSH_HOME or uses global ~/.dsh' });
571
+ }
572
+ if (proactiveActive && invalidPreparedProfile) {
573
+ proactiveGoalsReasons.push({ code: 'proactive-profile-preparation-invalid', message: 'one or more assistant-proactive profiles omit preparation provider, model or budgetId' });
574
+ }
575
+ if (goalsLoaded && !goalsDbScope.scoped) {
576
+ proactiveGoalsReasons.push({ code: 'goals-database-not-scoped', message: 'assistant-goals.databasePath leaks outside $DSH_HOME or uses global ~/.dsh' });
577
+ }
578
+ checks.push({
579
+ id: 'proactive-opportunities', required: false,
580
+ status: proactiveGoalsReasons.length === 0 ? 'ready' : 'not-ready',
581
+ summary: proactiveGoalsReasons.length === 0
582
+ ? `proactive profiles (${proactiveProfiles.length}) and goals DB scoping ready`
583
+ : 'proactive/goals state scoping or profile preparation is incomplete',
584
+ reasons: proactiveGoalsReasons,
585
+ details: {
586
+ proactiveLoaded: proactiveActive,
587
+ proactiveDatabaseConfigured: proactiveDbScope.configured,
588
+ proactiveDatabaseScoped: proactiveDbScope.scoped,
589
+ proactiveProfileCount: proactiveProfiles.length,
590
+ intakeEvaluationEnabled: readinessValue(rows, 'assistant-proactive', 'intakeEvaluation.enabled') === true,
591
+ goalsLoaded,
592
+ goalsDatabaseConfigured: goalsDbScope.configured,
593
+ goalsDatabaseScoped: goalsDbScope.scoped,
594
+ goalsEventWaits: readinessValue(rows, 'assistant-goals', 'eventWaits') === true,
595
+ goalsVerifyNativeRounds: readinessValue(rows, 'assistant-goals', 'verifyNativeRounds') === true,
596
+ goalsVerifyGoalOutcome: readinessValue(rows, 'assistant-goals', 'verifyGoalOutcome') === true,
597
+ goalsExecutionBudgetConfigured: readinessValue(rows, 'assistant-goals', 'executionBudget') !== undefined,
598
+ },
599
+ });
600
+ // Optional ring: DB scoping and extended autonomy flags for work-items, memory-learning, growth-driver and evaluation.
601
+ const workItemsDbScope = readinessLoaded(rows, 'assistant-work-items') === true
602
+ ? inspectDatabasePathScope(rows, 'assistant-work-items', 'databasePath', 'assistant-work-items', dshHome)
603
+ : { configured: false, scoped: true };
604
+ const memoryDbScope = readinessLoaded(rows, 'assistant-memory-learning') === true
605
+ ? inspectDatabasePathScope(rows, 'assistant-memory-learning', 'databasePath', 'assistant-memory-learning', dshHome)
606
+ : { configured: false, scoped: true };
607
+ const growthUsageDbScope = readinessLoaded(rows, 'assistant-growth-driver') === true
608
+ ? inspectDatabasePathScope(rows, 'assistant-growth-driver', 'usageLearning.databasePath', 'assistant-growth-driver', dshHome)
609
+ : { configured: false, scoped: true };
610
+ const subsystemReasons = [];
611
+ if (!workItemsDbScope.scoped)
612
+ subsystemReasons.push({ code: 'work-items-database-not-scoped', message: 'assistant-work-items.databasePath leaks outside $DSH_HOME or uses global ~/.dsh' });
613
+ if (!memoryDbScope.scoped)
614
+ subsystemReasons.push({ code: 'memory-learning-database-not-scoped', message: 'assistant-memory-learning.databasePath leaks outside $DSH_HOME or uses global ~/.dsh' });
615
+ if (!growthUsageDbScope.scoped)
616
+ subsystemReasons.push({ code: 'growth-usage-database-not-scoped', message: 'assistant-growth-driver.usageLearning.databasePath leaks outside $DSH_HOME or uses global ~/.dsh' });
617
+ const memoryAuthorities = [
618
+ routeText(readinessValue(rows, 'assistant-memory-learning', 'owner.authorityId')),
619
+ routeText(readinessValue(rows, 'assistant-memory-learning', 'authorityId')),
620
+ routeText(readinessValue(rows, 'assistant-verifier', 'memoryReviews.authorityId')),
621
+ routeText(readinessValue(rows, 'personal-assistant', 'personalMemory.automaticLearning.authorityId')),
622
+ ];
623
+ const memoryAuthoritiesDistinct = memoryAuthorities.every(item => item !== null)
624
+ && new Set(memoryAuthorities).size === 4;
625
+ checks.push({
626
+ id: 'autonomy-subsystems', required: false,
627
+ status: subsystemReasons.length === 0 ? 'ready' : 'not-ready',
628
+ summary: subsystemReasons.length === 0
629
+ ? 'work-items, memory-learning, growth-driver and evaluation state paths are clean'
630
+ : 'one or more autonomy subsystem database paths escape $DSH_HOME or point to global ~/.dsh',
631
+ reasons: subsystemReasons,
632
+ details: {
633
+ workItemsAdmitEnabled: readinessValue(rows, 'assistant-work-items', 'intakeLedger.evaluation.admit.enabled') === true,
634
+ workItemsSettlementEnabled: readinessValue(rows, 'assistant-work-items', 'settlement.enabled') === true,
635
+ workItemsVerdictGateEnabled: readinessValue(rows, 'assistant-work-items', 'acceptance.verdictGate.enabled') === true,
636
+ workItemsDatabaseScoped: workItemsDbScope.scoped,
637
+ memoryLearningDatabaseConfigured: memoryDbScope.configured,
638
+ memoryLearningDatabaseScoped: memoryDbScope.scoped,
639
+ memoryAuthoritiesDistinct,
640
+ growthDreamingIdeasEnabled: readinessValue(rows, 'assistant-growth-driver', 'dreamingIdeas.enabled') === true,
641
+ dreamOwnerTransitionRulesConfigured,
642
+ growthUsageLearningEnabled: readinessValue(rows, 'assistant-growth-driver', 'usageLearning.enabled') === true,
643
+ growthUsageDatabaseConfigured: growthUsageDbScope.configured,
644
+ growthUsageDatabaseScoped: growthUsageDbScope.scoped,
645
+ growthWorkflowOwnerAnchoredEnabled: readinessValue(rows, 'assistant-growth-driver', 'workflowOwnerAnchored.enabled') === true,
646
+ growthPluginSourceProposalsEnabled: readinessValue(rows, 'assistant-growth-driver', 'pluginSourceProposals.enabled') === true,
647
+ evaluationAttentionTuningAutoAdopt: readinessValue(rows, 'assistant-evaluation', 'attentionTuningAutoAdopt') === true,
648
+ evaluationAttentionLooseningEnabled: readinessValue(rows, 'assistant-evaluation', 'attentionLooseningEnabled') === true,
649
+ evaluationAttentionOwnerQuestionDeliveryEnabled: readinessValue(rows, 'assistant-evaluation', 'attentionOwnerQuestionDeliveryEnabled') === true,
650
+ },
651
+ });
652
+ const ready = checks.filter(check => check.required).every(check => check.status === 'ready');
653
+ return { protocol: 'dsh-ray/autonomy-readiness/v1', profile, scope: 'ordinary-use-learning', ready, checks, runtime };
654
+ }
655
+ /** Deterministic human-readable form of the same snapshot the JSON line carries. */
656
+ export function formatAutonomyReadiness(report) {
657
+ const label = (status) => status === 'ready' ? 'ready ' : status === 'not-ready' ? 'not-ready ' : 'not-verified';
658
+ const lines = [`Autonomy readiness (static composed profile, no model, no writes): ${report.ready ? 'READY' : 'NOT READY'} (profile ${report.profile})`];
659
+ for (const check of report.checks) {
660
+ lines.push(` ${label(check.status)} ${check.id}: ${check.summary}`);
661
+ for (const reason of check.reasons)
662
+ lines.push(` - [${reason.code}] ${reason.message}`);
663
+ }
664
+ lines.push(` runtime: not observed (${report.runtime.note})`);
665
+ return `${lines.join('\n')}\n`;
666
+ }
667
+ export async function runAutonomyDoctor(argv = process.argv.slice(2)) {
668
+ const usage = [
669
+ 'Usage: dsh-autonomy-doctor [--profile web] [--dsh-home <absolute-path>] [--readiness]',
670
+ 'Default: checks the installed finite isolation grant, paired owner and a temporary backend-specific probe.',
671
+ '--readiness: prints the static ordinary-use-learning readiness snapshot (text plus one JSON line) and exits 1 when a mandatory ring is not ready.',
672
+ 'The readiness snapshot reads only the composed profile: it never activates a Host, calls a model, writes state, renews grants or verifies runtime registration, Policy or external delivery.',
673
+ '',
674
+ ].join('\n');
675
+ if (argv.includes('--help') || argv.includes('-h')) {
676
+ process.stdout.write(usage);
677
+ return;
678
+ }
679
+ let profile = 'web';
680
+ let dshHome = process.env.DSH_HOME ?? join(homedir(), '.dsh');
681
+ let readinessOnly = false;
682
+ for (let index = 0; index < argv.length;) {
683
+ const option = argv[index];
684
+ if (option === '--readiness') {
685
+ readinessOnly = true;
686
+ index += 1;
687
+ continue;
688
+ }
689
+ const value = argv[index + 1];
690
+ if (!['--profile', '--dsh-home'].includes(option ?? '') || value === undefined || value.startsWith('--'))
691
+ fail('invalid arguments');
692
+ if (option === '--profile')
693
+ profile = value;
694
+ else
695
+ dshHome = value;
696
+ index += 2;
697
+ }
698
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(profile) || !isAbsolute(dshHome) || normalize(dshHome) !== dshHome || /[\p{Cc}*]/u.test(dshHome))
699
+ fail('invalid profile or home');
700
+ const dump = () => dumpEffectiveProfile(dshHome, profile, fail, 'could not compose profile; inspect installed bundles and configuration');
701
+ if (readinessOnly) {
702
+ let source;
703
+ try {
704
+ source = await dump();
705
+ }
706
+ catch (error) {
707
+ const message = error instanceof Error ? error.message : String(error);
708
+ const report = { protocol: 'dsh-ray/autonomy-readiness/v1', profile, scope: 'ordinary-use-learning', ready: false,
709
+ checks: [{ id: 'profile-composition', required: true, status: 'not-ready', summary: 'the profile could not be composed',
710
+ reasons: [{ code: 'profile-composition-failed', message }], details: {} }],
711
+ runtime: { observed: false, note: 'static composed profile only; nothing was activated' } };
712
+ process.stdout.write(formatAutonomyReadiness(report));
713
+ process.stdout.write(`${JSON.stringify(report)}\n`);
714
+ process.exitCode = 1;
715
+ return;
716
+ }
717
+ const report = inspectAutonomyReadiness(source, profile, dshHome);
718
+ process.stdout.write(formatAutonomyReadiness(report));
719
+ process.stdout.write(`${JSON.stringify(report)}\n`);
720
+ if (!report.ready)
721
+ process.exitCode = 1;
722
+ return;
723
+ }
724
+ const source = await dump();
725
+ // Finite-isolation mode keeps its existing output exactly: the ordinary-use
726
+ // readiness snapshot is an explicit `--readiness` opt-in so an autonomy
727
+ // profile's diagnostic run is unchanged.
728
+ const parsed = inspectAutonomyProfile(source, profile, dshHome);
729
+ const { inspectIsolationGrant } = await import('@dsh-ray/assistant-isolation');
730
+ if (typeof inspectIsolationGrant !== 'function')
731
+ fail('install the matching assistant-isolation version with grant diagnostics; no state was changed');
732
+ const owner = inspectAutonomyOwner(parsed);
733
+ const grant = inspectIsolationGrant({ stateRoot: parsed.stateRoot, grant: parsed.grant });
734
+ // Report persisted state before dispatching a disposable, separately bounded probe.
735
+ process.stdout.write(`${JSON.stringify({ scope: 'finite-isolation', owner, grant, modelAndGoals: 'not-checked', externalActions: 'not-checked' })}\n`);
736
+ if (owner.status !== 'matched' || grant.status !== 'available')
737
+ fail('owner or persisted grant checks failed; no authority was renewed');
738
+ await probeAutonomyProfileRuntime(parsed);
739
+ if (!isDeepStrictEqual(inspectAutonomyProfile(await dump(), profile, dshHome), parsed)
740
+ || inspectAutonomyOwner(parsed).status !== 'matched'
741
+ || inspectIsolationGrant({ stateRoot: parsed.stateRoot, grant: parsed.grant }).status !== 'available')
742
+ fail('configuration or authority changed during probe; retry diagnostics');
743
+ process.stdout.write('Finite isolation configuration, owner, persisted grant and temporary runtime probe passed. This is a diagnostic snapshot; Policy, live resource admission, model budgets, Goal verification and external Actions still require their own checks.\n');
744
+ }
745
+ //# sourceMappingURL=doctor.js.map