@dsh-ray/assistant-delivery 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 (185) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +611 -2
  3. package/bin/dsh-restart-supervisor.js +102 -0
  4. package/cordis.patch.yml +29 -0
  5. package/lib/acceptance.d.ts +54 -0
  6. package/lib/acceptance.d.ts.map +1 -0
  7. package/lib/acceptance.js +2 -0
  8. package/lib/acceptance.js.map +1 -0
  9. package/lib/agent-runtime.d.ts +247 -0
  10. package/lib/agent-runtime.d.ts.map +1 -0
  11. package/lib/agent-runtime.js +4458 -0
  12. package/lib/agent-runtime.js.map +1 -0
  13. package/lib/approval-status-context.d.ts +8 -0
  14. package/lib/approval-status-context.d.ts.map +1 -0
  15. package/lib/approval-status-context.js +55 -0
  16. package/lib/approval-status-context.js.map +1 -0
  17. package/lib/attention-audit-store.d.ts +54 -0
  18. package/lib/attention-audit-store.d.ts.map +1 -0
  19. package/lib/attention-audit-store.js +213 -0
  20. package/lib/attention-audit-store.js.map +1 -0
  21. package/lib/attention-enforcement.d.ts +75 -0
  22. package/lib/attention-enforcement.d.ts.map +1 -0
  23. package/lib/attention-enforcement.js +84 -0
  24. package/lib/attention-enforcement.js.map +1 -0
  25. package/lib/attention.d.ts +208 -0
  26. package/lib/attention.d.ts.map +1 -0
  27. package/lib/attention.js +288 -0
  28. package/lib/attention.js.map +1 -0
  29. package/lib/canonical.d.ts +28 -0
  30. package/lib/canonical.d.ts.map +1 -0
  31. package/lib/canonical.js +190 -0
  32. package/lib/canonical.js.map +1 -0
  33. package/lib/coordinator.d.ts +134 -0
  34. package/lib/coordinator.d.ts.map +1 -0
  35. package/lib/coordinator.js +746 -0
  36. package/lib/coordinator.js.map +1 -0
  37. package/lib/feedback-command.d.ts +105 -0
  38. package/lib/feedback-command.d.ts.map +1 -0
  39. package/lib/feedback-command.js +547 -0
  40. package/lib/feedback-command.js.map +1 -0
  41. package/lib/foreground-observation.d.ts +66 -0
  42. package/lib/foreground-observation.d.ts.map +1 -0
  43. package/lib/foreground-observation.js +13 -0
  44. package/lib/foreground-observation.js.map +1 -0
  45. package/lib/foreground-termination.d.ts +31 -0
  46. package/lib/foreground-termination.d.ts.map +1 -0
  47. package/lib/foreground-termination.js +42 -0
  48. package/lib/foreground-termination.js.map +1 -0
  49. package/lib/goal-wake-types.d.ts +93 -0
  50. package/lib/goal-wake-types.d.ts.map +1 -0
  51. package/lib/goal-wake-types.js +70 -0
  52. package/lib/goal-wake-types.js.map +1 -0
  53. package/lib/in-process-reload-runtime.d.ts +120 -0
  54. package/lib/in-process-reload-runtime.d.ts.map +1 -0
  55. package/lib/in-process-reload-runtime.js +1280 -0
  56. package/lib/in-process-reload-runtime.js.map +1 -0
  57. package/lib/inbound-images.d.ts +38 -0
  58. package/lib/inbound-images.d.ts.map +1 -0
  59. package/lib/inbound-images.js +269 -0
  60. package/lib/inbound-images.js.map +1 -0
  61. package/lib/index.d.ts +41 -0
  62. package/lib/index.d.ts.map +1 -0
  63. package/lib/index.js +25 -0
  64. package/lib/index.js.map +1 -0
  65. package/lib/learning-command.d.ts +40 -0
  66. package/lib/learning-command.d.ts.map +1 -0
  67. package/lib/learning-command.js +57 -0
  68. package/lib/learning-command.js.map +1 -0
  69. package/lib/native-termination.d.ts +12 -0
  70. package/lib/native-termination.d.ts.map +1 -0
  71. package/lib/native-termination.js +57 -0
  72. package/lib/native-termination.js.map +1 -0
  73. package/lib/native-web-owner.d.ts +97 -0
  74. package/lib/native-web-owner.d.ts.map +1 -0
  75. package/lib/native-web-owner.js +338 -0
  76. package/lib/native-web-owner.js.map +1 -0
  77. package/lib/operator-snapshot.d.ts +107 -0
  78. package/lib/operator-snapshot.d.ts.map +1 -0
  79. package/lib/operator-snapshot.js +1013 -0
  80. package/lib/operator-snapshot.js.map +1 -0
  81. package/lib/operator.d.ts +25 -0
  82. package/lib/operator.d.ts.map +1 -0
  83. package/lib/operator.js +48 -0
  84. package/lib/operator.js.map +1 -0
  85. package/lib/progress-attention.d.ts +55 -0
  86. package/lib/progress-attention.d.ts.map +1 -0
  87. package/lib/progress-attention.js +128 -0
  88. package/lib/progress-attention.js.map +1 -0
  89. package/lib/reply-replay.d.ts +52 -0
  90. package/lib/reply-replay.d.ts.map +1 -0
  91. package/lib/reply-replay.js +122 -0
  92. package/lib/reply-replay.js.map +1 -0
  93. package/lib/restart-native.d.ts +47 -0
  94. package/lib/restart-native.d.ts.map +1 -0
  95. package/lib/restart-native.js +170 -0
  96. package/lib/restart-native.js.map +1 -0
  97. package/lib/restart-runtime.d.ts +38 -0
  98. package/lib/restart-runtime.d.ts.map +1 -0
  99. package/lib/restart-runtime.js +335 -0
  100. package/lib/restart-runtime.js.map +1 -0
  101. package/lib/restart-store.d.ts +132 -0
  102. package/lib/restart-store.d.ts.map +1 -0
  103. package/lib/restart-store.js +757 -0
  104. package/lib/restart-store.js.map +1 -0
  105. package/lib/restart-supervisor.d.ts +129 -0
  106. package/lib/restart-supervisor.d.ts.map +1 -0
  107. package/lib/restart-supervisor.js +615 -0
  108. package/lib/restart-supervisor.js.map +1 -0
  109. package/lib/service.d.ts +1279 -0
  110. package/lib/service.d.ts.map +1 -0
  111. package/lib/service.js +8694 -0
  112. package/lib/service.js.map +1 -0
  113. package/lib/session-commands.d.ts +52 -0
  114. package/lib/session-commands.d.ts.map +1 -0
  115. package/lib/session-commands.js +180 -0
  116. package/lib/session-commands.js.map +1 -0
  117. package/lib/session-lease-runtime.d.ts +70 -0
  118. package/lib/session-lease-runtime.d.ts.map +1 -0
  119. package/lib/session-lease-runtime.js +395 -0
  120. package/lib/session-lease-runtime.js.map +1 -0
  121. package/lib/session-lease-types.d.ts +27 -0
  122. package/lib/session-lease-types.d.ts.map +1 -0
  123. package/lib/session-lease-types.js +2 -0
  124. package/lib/session-lease-types.js.map +1 -0
  125. package/lib/sqlite.d.ts +8 -0
  126. package/lib/sqlite.d.ts.map +1 -0
  127. package/lib/sqlite.js +1665 -0
  128. package/lib/sqlite.js.map +1 -0
  129. package/lib/store.d.ts +1267 -0
  130. package/lib/store.d.ts.map +1 -0
  131. package/lib/store.js +8039 -0
  132. package/lib/store.js.map +1 -0
  133. package/lib/tools.d.ts +4 -0
  134. package/lib/tools.d.ts.map +1 -0
  135. package/lib/tools.js +73 -0
  136. package/lib/tools.js.map +1 -0
  137. package/lib/types.d.ts +1091 -0
  138. package/lib/types.d.ts.map +1 -0
  139. package/lib/types.js +10 -0
  140. package/lib/types.js.map +1 -0
  141. package/lib/version-query.d.ts +77 -0
  142. package/lib/version-query.d.ts.map +1 -0
  143. package/lib/version-query.js +2208 -0
  144. package/lib/version-query.js.map +1 -0
  145. package/lib/version.d.ts +2 -0
  146. package/lib/version.d.ts.map +1 -0
  147. package/lib/version.js +2 -0
  148. package/lib/version.js.map +1 -0
  149. package/lib/work-item-engineering-context.d.ts +127 -0
  150. package/lib/work-item-engineering-context.d.ts.map +1 -0
  151. package/lib/work-item-engineering-context.js +151 -0
  152. package/lib/work-item-engineering-context.js.map +1 -0
  153. package/lib/work-item-feedback-schema.d.ts +2 -0
  154. package/lib/work-item-feedback-schema.d.ts.map +1 -0
  155. package/lib/work-item-feedback-schema.js +29 -0
  156. package/lib/work-item-feedback-schema.js.map +1 -0
  157. package/lib/work-item-feedback-store.d.ts +29 -0
  158. package/lib/work-item-feedback-store.d.ts.map +1 -0
  159. package/lib/work-item-feedback-store.js +111 -0
  160. package/lib/work-item-feedback-store.js.map +1 -0
  161. package/lib/work-item-feedback.d.ts +157 -0
  162. package/lib/work-item-feedback.d.ts.map +1 -0
  163. package/lib/work-item-feedback.js +2 -0
  164. package/lib/work-item-feedback.js.map +1 -0
  165. package/lib/work-item-replies-schema.d.ts +3 -0
  166. package/lib/work-item-replies-schema.d.ts.map +1 -0
  167. package/lib/work-item-replies-schema.js +45 -0
  168. package/lib/work-item-replies-schema.js.map +1 -0
  169. package/lib/work-item-replies-store.d.ts +43 -0
  170. package/lib/work-item-replies-store.d.ts.map +1 -0
  171. package/lib/work-item-replies-store.js +203 -0
  172. package/lib/work-item-replies-store.js.map +1 -0
  173. package/lib/work-item-replies.d.ts +93 -0
  174. package/lib/work-item-replies.d.ts.map +1 -0
  175. package/lib/work-item-replies.js +15 -0
  176. package/lib/work-item-replies.js.map +1 -0
  177. package/lib/workflow-auto-producer.d.ts +37 -0
  178. package/lib/workflow-auto-producer.d.ts.map +1 -0
  179. package/lib/workflow-auto-producer.js +58 -0
  180. package/lib/workflow-auto-producer.js.map +1 -0
  181. package/lib/workflow-command.d.ts +16 -0
  182. package/lib/workflow-command.d.ts.map +1 -0
  183. package/lib/workflow-command.js +52 -0
  184. package/lib/workflow-command.js.map +1 -0
  185. package/package.json +181 -3
@@ -0,0 +1,2208 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { version as assistantVersion } from './version.js';
7
+ const MAX_HOST_METADATA_BYTES = 16 * 1024;
8
+ const MAX_PACKAGE_JSON_BYTES = 64 * 1024;
9
+ const MAX_UPGRADE_HISTORY_BYTES = 4 * 1024 * 1024;
10
+ const MAX_PATCH_SCAN_BYTES = 512 * 1024;
11
+ function normalizePluginKey(name) {
12
+ const trimmed = name.trim();
13
+ return trimmed.startsWith('@dsh-ray/') ? trimmed.slice('@dsh-ray/'.length) : trimmed;
14
+ }
15
+ function rec(value) {
16
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
17
+ ? value
18
+ : {};
19
+ }
20
+ function textOrNull(value) {
21
+ if (typeof value !== 'string')
22
+ return null;
23
+ const trimmed = value.trim();
24
+ return trimmed === '' ? null : trimmed;
25
+ }
26
+ function nonNegIntOrNull(value) {
27
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0)
28
+ return null;
29
+ return Math.trunc(value);
30
+ }
31
+ function truncateText(raw, maxLen) {
32
+ if (raw.length <= maxLen)
33
+ return raw;
34
+ if (maxLen <= 1)
35
+ return raw.slice(0, maxLen);
36
+ let cut = maxLen - 1;
37
+ const lastCode = raw.charCodeAt(cut - 1);
38
+ if (lastCode >= 0xd800 && lastCode <= 0xdbff && cut > 1) {
39
+ cut -= 1;
40
+ }
41
+ return `${raw.slice(0, cut)}…`;
42
+ }
43
+ function boundNonEmptyString(raw, maxLen) {
44
+ if (typeof raw !== 'string')
45
+ return undefined;
46
+ const trimmed = raw.trim();
47
+ if (trimmed === '')
48
+ return undefined;
49
+ return truncateText(trimmed, maxLen);
50
+ }
51
+ function cleanAbsolutePath(raw) {
52
+ if (typeof raw !== 'string')
53
+ return undefined;
54
+ const trimmed = raw.trim();
55
+ if (trimmed === '' || trimmed.includes('\0') || !isAbsolute(trimmed))
56
+ return undefined;
57
+ return resolve(trimmed);
58
+ }
59
+ function filePathFromUriOrPath(raw) {
60
+ if (typeof raw !== 'string')
61
+ return undefined;
62
+ const trimmed = raw.trim();
63
+ if (trimmed === '' || trimmed.includes('\0'))
64
+ return undefined;
65
+ if (trimmed.startsWith('file://')) {
66
+ try {
67
+ return cleanAbsolutePath(new URL(trimmed).pathname);
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ return cleanAbsolutePath(trimmed);
74
+ }
75
+ function extractHomeAndProfileFromProfileFile(profileFile) {
76
+ const parent = dirname(profileFile);
77
+ const grandParent = dirname(parent);
78
+ if (basename(parent) === 'profiles') {
79
+ const stem = basename(profileFile, extname(profileFile));
80
+ return {
81
+ home: grandParent,
82
+ ...(stem === '' ? {} : { profile: stem }),
83
+ };
84
+ }
85
+ if (basename(grandParent) === 'profiles') {
86
+ const profileName = basename(parent);
87
+ return {
88
+ home: dirname(grandParent),
89
+ ...(profileName === '' ? {} : { profile: profileName }),
90
+ };
91
+ }
92
+ return {};
93
+ }
94
+ function resolveIncludeProfilePath(loader) {
95
+ if (typeof loader?.resolve !== 'function')
96
+ return undefined;
97
+ try {
98
+ const includeEntry = loader.resolve('include');
99
+ if (!includeEntry || typeof includeEntry !== 'object')
100
+ return undefined;
101
+ const treePath = filePathFromUriOrPath(includeEntry.subtree?.filename);
102
+ if (treePath)
103
+ return treePath;
104
+ const cfgPath = filePathFromUriOrPath(rec(includeEntry.options?.config)['path']);
105
+ if (cfgPath)
106
+ return cfgPath;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ return undefined;
112
+ }
113
+ function safeListProfiles(dshHome, canonicalDshHome) {
114
+ const profilesDir = join(dshHome, 'profiles');
115
+ if (!existsSync(profilesDir))
116
+ return [];
117
+ try {
118
+ const st = lstatSync(profilesDir);
119
+ if (!st.isDirectory() || st.isSymbolicLink())
120
+ return [];
121
+ const realDir = realpathSync(profilesDir);
122
+ if (realDir !== canonicalDshHome && !realDir.startsWith(`${canonicalDshHome}${sep}`))
123
+ return [];
124
+ const names = new Set();
125
+ for (const entry of readdirSync(realDir, { withFileTypes: true })) {
126
+ if (entry.isSymbolicLink())
127
+ continue;
128
+ if (entry.isDirectory()) {
129
+ names.add(entry.name);
130
+ }
131
+ else if (entry.isFile() && (entry.name.endsWith('.yml') || entry.name.endsWith('.yaml'))) {
132
+ const stem = basename(entry.name, extname(entry.name));
133
+ if (stem !== '')
134
+ names.add(stem);
135
+ }
136
+ }
137
+ return [...names].sort((a, b) => a.localeCompare(b));
138
+ }
139
+ catch {
140
+ return [];
141
+ }
142
+ }
143
+ function resolveBoundary(ctx, options, diagnostics) {
144
+ const profileContext = ctx.get('profileContext');
145
+ const settings = ctx.get('settings');
146
+ const loader = ctx.get('loader');
147
+ const includeProfileFile = resolveIncludeProfilePath(loader);
148
+ const includeDerived = includeProfileFile ? extractHomeAndProfileFromProfileFile(includeProfileFile) : {};
149
+ const inProcessProfile = cleanAbsolutePath(options.inProcessProfilePath);
150
+ const inProcessDerived = inProcessProfile ? extractHomeAndProfileFromProfileFile(inProcessProfile) : {};
151
+ let dshHome = cleanAbsolutePath(options.dshHome)
152
+ ?? cleanAbsolutePath(profileContext?.home);
153
+ if (!dshHome) {
154
+ const profileDir = cleanAbsolutePath(profileContext?.dir);
155
+ if (profileDir && basename(dirname(profileDir)) === 'profiles') {
156
+ dshHome = dirname(dirname(profileDir));
157
+ }
158
+ }
159
+ if (!dshHome) {
160
+ const docPath = cleanAbsolutePath(settings?.documentPath);
161
+ if (docPath) {
162
+ if (basename(dirname(docPath)) === 'profiles') {
163
+ dshHome = dirname(dirname(docPath));
164
+ }
165
+ else if (basename(dirname(dirname(docPath))) === 'profiles') {
166
+ dshHome = dirname(dirname(dirname(docPath)));
167
+ }
168
+ else {
169
+ dshHome = dirname(docPath);
170
+ }
171
+ }
172
+ }
173
+ if (!dshHome && includeDerived.home) {
174
+ dshHome = includeDerived.home;
175
+ }
176
+ if (!dshHome && inProcessDerived.home) {
177
+ dshHome = inProcessDerived.home;
178
+ }
179
+ if (!dshHome) {
180
+ const dbPath = cleanAbsolutePath(options.configDatabasePath);
181
+ if (dbPath && basename(dirname(dbPath)) === 'assistant-delivery') {
182
+ dshHome = dirname(dirname(dbPath));
183
+ }
184
+ }
185
+ if (!dshHome) {
186
+ dshHome = cleanAbsolutePath(process.env['DSH_HOME']);
187
+ }
188
+ let profile = textOrNull(options.profile)
189
+ ?? textOrNull(profileContext?.name)
190
+ ?? null;
191
+ if (!profile) {
192
+ const profileDir = cleanAbsolutePath(profileContext?.dir);
193
+ if (profileDir && basename(dirname(profileDir)) === 'profiles') {
194
+ profile = basename(profileDir);
195
+ }
196
+ }
197
+ if (!profile && includeDerived.profile) {
198
+ profile = includeDerived.profile;
199
+ }
200
+ if (!profile && inProcessDerived.profile) {
201
+ profile = inProcessDerived.profile;
202
+ }
203
+ if (!profile) {
204
+ profile = textOrNull(process.env['DSH_PROFILE']);
205
+ }
206
+ if (!dshHome) {
207
+ return {
208
+ dshHome: null,
209
+ canonicalDshHome: null,
210
+ homeUnsafe: false,
211
+ profile,
212
+ profiles: [],
213
+ };
214
+ }
215
+ let canonicalDshHome = null;
216
+ let homeUnsafe = false;
217
+ if (existsSync(dshHome)) {
218
+ try {
219
+ const st = lstatSync(dshHome);
220
+ if (!st.isDirectory() || st.isSymbolicLink()) {
221
+ homeUnsafe = true;
222
+ diagnostics.push('dshHome is not a regular directory');
223
+ }
224
+ else {
225
+ canonicalDshHome = realpathSync(dshHome);
226
+ }
227
+ }
228
+ catch (error) {
229
+ homeUnsafe = true;
230
+ diagnostics.push(`dshHome inspection failed: ${error instanceof Error ? error.message : String(error)}`);
231
+ }
232
+ }
233
+ const profiles = canonicalDshHome && !homeUnsafe
234
+ ? safeListProfiles(dshHome, canonicalDshHome)
235
+ : [];
236
+ return {
237
+ dshHome,
238
+ canonicalDshHome,
239
+ homeUnsafe,
240
+ profile,
241
+ profiles,
242
+ };
243
+ }
244
+ function readBoundedRegularFile(filePath, boundary, maxBytes) {
245
+ if (!boundary.dshHome || !boundary.canonicalDshHome || boundary.homeUnsafe)
246
+ return undefined;
247
+ if (!existsSync(filePath))
248
+ return undefined;
249
+ const target = resolve(filePath);
250
+ try {
251
+ const st = lstatSync(target);
252
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
253
+ return undefined;
254
+ if (st.size < 0 || st.size > maxBytes)
255
+ return undefined;
256
+ const realTarget = realpathSync(target);
257
+ const logicallyWithin = target.startsWith(`${boundary.dshHome}${sep}`)
258
+ || target.startsWith(`${boundary.canonicalDshHome}${sep}`);
259
+ if (!logicallyWithin || !realTarget.startsWith(`${boundary.canonicalDshHome}${sep}`)) {
260
+ return undefined;
261
+ }
262
+ return readFileSync(realTarget, 'utf8');
263
+ }
264
+ catch {
265
+ return undefined;
266
+ }
267
+ }
268
+ function readBoundHostMetadata(boundary) {
269
+ if (!boundary.dshHome || !boundary.canonicalDshHome || boundary.homeUnsafe) {
270
+ return { boundVersion: null, boundStatus: boundary.homeUnsafe ? 'unreadable' : 'missing' };
271
+ }
272
+ const filePath = join(boundary.canonicalDshHome, '.dsh-ray-host.json');
273
+ if (!existsSync(filePath))
274
+ return { boundVersion: null, boundStatus: 'missing' };
275
+ try {
276
+ const st = lstatSync(filePath);
277
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) {
278
+ return { boundVersion: null, boundStatus: 'corrupt' };
279
+ }
280
+ if (st.size <= 0 || st.size > MAX_HOST_METADATA_BYTES) {
281
+ return { boundVersion: null, boundStatus: 'corrupt' };
282
+ }
283
+ const realTarget = realpathSync(filePath);
284
+ if (!realTarget.startsWith(`${boundary.canonicalDshHome}${sep}`)) {
285
+ return { boundVersion: null, boundStatus: 'corrupt' };
286
+ }
287
+ const parsed = JSON.parse(readFileSync(realTarget, 'utf8'));
288
+ const obj = rec(parsed);
289
+ if (obj['schemaVersion'] !== 1) {
290
+ return { boundVersion: null, boundStatus: 'corrupt' };
291
+ }
292
+ const version = textOrNull(obj['version']);
293
+ if (version === null) {
294
+ return { boundVersion: null, boundStatus: 'corrupt' };
295
+ }
296
+ return { boundVersion: version, boundStatus: 'ready' };
297
+ }
298
+ catch (error) {
299
+ if (error instanceof SyntaxError)
300
+ return { boundVersion: null, boundStatus: 'corrupt' };
301
+ return { boundVersion: null, boundStatus: 'unreadable' };
302
+ }
303
+ }
304
+ function readRunningHostVersion() {
305
+ try {
306
+ const req = createRequire(import.meta.url);
307
+ for (const candidate of ['@deepseek-ai/dsh/package.json', '@deepseek-ai/dsh-app-boot/package.json']) {
308
+ try {
309
+ const resolved = req.resolve(candidate);
310
+ const parsed = JSON.parse(readFileSync(resolved, 'utf8'));
311
+ if (parsed.name === '@deepseek-ai/dsh') {
312
+ const ver = textOrNull(parsed.version);
313
+ if (ver !== null)
314
+ return ver;
315
+ }
316
+ }
317
+ catch {
318
+ // Optional runtime layout lookup.
319
+ }
320
+ }
321
+ }
322
+ catch {
323
+ // Fallback below.
324
+ }
325
+ const entry = process.argv[1];
326
+ if (typeof entry === 'string' && entry.trim() !== '') {
327
+ let dir = dirname(resolve(entry));
328
+ for (let i = 0; i < 6; i++) {
329
+ const pkgPath = join(dir, 'package.json');
330
+ try {
331
+ if (existsSync(pkgPath)) {
332
+ const parsed = JSON.parse(readFileSync(pkgPath, 'utf8'));
333
+ if (parsed.name === '@deepseek-ai/dsh') {
334
+ const ver = textOrNull(parsed.version);
335
+ if (ver !== null)
336
+ return ver;
337
+ }
338
+ }
339
+ }
340
+ catch {
341
+ // Continue walk-up.
342
+ }
343
+ const parent = dirname(dir);
344
+ if (parent === dir)
345
+ break;
346
+ dir = parent;
347
+ }
348
+ }
349
+ return null;
350
+ }
351
+ function hasTable(db, tableName) {
352
+ return db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name = ?").get(tableName) !== undefined;
353
+ }
354
+ function hasColumn(db, tableName, columnName) {
355
+ if (!hasTable(db, tableName))
356
+ return false;
357
+ const cols = db.prepare(`PRAGMA table_info(${tableName})`).all();
358
+ return cols.some(col => col.name === columnName);
359
+ }
360
+ function countQuery(db, sql, ...params) {
361
+ const row = db.prepare(sql).get(...params);
362
+ return nonNegIntOrNull(row?.n) ?? 0;
363
+ }
364
+ function isAbsentOrZeroRegularFile(sidecarPath) {
365
+ try {
366
+ const st = lstatSync(sidecarPath);
367
+ return st.isFile() && !st.isSymbolicLink() && st.nlink === 1 && st.size === 0;
368
+ }
369
+ catch (error) {
370
+ return error.code === 'ENOENT';
371
+ }
372
+ }
373
+ function isAbsentFile(sidecarPath) {
374
+ try {
375
+ lstatSync(sidecarPath);
376
+ return false;
377
+ }
378
+ catch (error) {
379
+ return error.code === 'ENOENT';
380
+ }
381
+ }
382
+ function isAbsentOrRegularFile(sidecarPath) {
383
+ try {
384
+ const st = lstatSync(sidecarPath);
385
+ return st.isFile() && !st.isSymbolicLink() && st.nlink === 1;
386
+ }
387
+ catch (error) {
388
+ return error.code === 'ENOENT';
389
+ }
390
+ }
391
+ function canPreferImmutable(realTarget) {
392
+ return isAbsentOrZeroRegularFile(`${realTarget}-wal`) && isAbsentFile(`${realTarget}-shm`);
393
+ }
394
+ function canFallbackImmutable(realTarget) {
395
+ return isAbsentOrZeroRegularFile(`${realTarget}-wal`) && isAbsentOrRegularFile(`${realTarget}-shm`);
396
+ }
397
+ function tryOpenReadOnlySqlite(openTarget) {
398
+ let db;
399
+ try {
400
+ db = new DatabaseSync(openTarget, { readOnly: true });
401
+ const check = db.prepare('PRAGMA quick_check').get();
402
+ if (!check || Object.values(check)[0] !== 'ok') {
403
+ db.close();
404
+ return { ok: false, integrityFailed: true };
405
+ }
406
+ return { ok: true, db };
407
+ }
408
+ catch (error) {
409
+ if (db) {
410
+ try {
411
+ db.close();
412
+ }
413
+ catch { /* ignore */ }
414
+ }
415
+ return { ok: false, integrityFailed: false, error };
416
+ }
417
+ }
418
+ function withReadOnlySqlite(dbPath, boundary, seenRealPaths, inspectedLedgers, diagnostics, fn) {
419
+ if (!boundary.dshHome || !boundary.canonicalDshHome || boundary.homeUnsafe)
420
+ return undefined;
421
+ const target = resolve(dbPath);
422
+ let realTarget;
423
+ try {
424
+ let st;
425
+ try {
426
+ st = lstatSync(target);
427
+ }
428
+ catch (error) {
429
+ if (error.code === 'ENOENT')
430
+ return undefined;
431
+ throw error;
432
+ }
433
+ if (!st.isFile() || st.isSymbolicLink()) {
434
+ diagnostics.push(`skipped non-regular or symlink sqlite ledger: ${basename(target)}`);
435
+ return undefined;
436
+ }
437
+ if (st.nlink !== 1) {
438
+ diagnostics.push(`skipped hardlink sqlite ledger: ${basename(target)}`);
439
+ return undefined;
440
+ }
441
+ realTarget = realpathSync(target);
442
+ const logicallyWithin = target.startsWith(`${boundary.dshHome}${sep}`)
443
+ || target.startsWith(`${boundary.canonicalDshHome}${sep}`);
444
+ if (!logicallyWithin || !realTarget.startsWith(`${boundary.canonicalDshHome}${sep}`)) {
445
+ diagnostics.push(`skipped out-of-boundary sqlite ledger: ${basename(target)}`);
446
+ return undefined;
447
+ }
448
+ }
449
+ catch {
450
+ return undefined;
451
+ }
452
+ if (seenRealPaths.has(realTarget))
453
+ return undefined;
454
+ seenRealPaths.add(realTarget);
455
+ if (!isAbsentOrRegularFile(`${realTarget}-wal`) || !isAbsentOrRegularFile(`${realTarget}-shm`)) {
456
+ diagnostics.push(`skipped unsafe sqlite sidecar: ${realTarget}`);
457
+ return undefined;
458
+ }
459
+ const immutableUri = pathToFileURL(realTarget);
460
+ immutableUri.search = 'mode=ro&immutable=1';
461
+ let db;
462
+ if (canPreferImmutable(realTarget)) {
463
+ const immutableRes = tryOpenReadOnlySqlite(immutableUri.href);
464
+ if (immutableRes.ok) {
465
+ db = immutableRes.db;
466
+ }
467
+ else if (immutableRes.integrityFailed) {
468
+ diagnostics.push(`sqlite quick_check failed: ${realTarget}`);
469
+ return undefined;
470
+ }
471
+ else {
472
+ const plainRes = tryOpenReadOnlySqlite(realTarget);
473
+ if (plainRes.ok) {
474
+ db = plainRes.db;
475
+ }
476
+ else if (plainRes.integrityFailed) {
477
+ diagnostics.push(`sqlite quick_check failed: ${realTarget}`);
478
+ return undefined;
479
+ }
480
+ else {
481
+ const err = plainRes.error ?? immutableRes.error;
482
+ diagnostics.push(`sqlite read failed (${realTarget}): ${err instanceof Error ? err.message : String(err)}`);
483
+ return undefined;
484
+ }
485
+ }
486
+ }
487
+ else {
488
+ const primaryRes = tryOpenReadOnlySqlite(realTarget);
489
+ if (primaryRes.ok) {
490
+ db = primaryRes.db;
491
+ }
492
+ else if (primaryRes.integrityFailed) {
493
+ diagnostics.push(`sqlite quick_check failed: ${realTarget}`);
494
+ return undefined;
495
+ }
496
+ else if (canFallbackImmutable(realTarget)) {
497
+ const immutableRes = tryOpenReadOnlySqlite(immutableUri.href);
498
+ if (immutableRes.ok) {
499
+ db = immutableRes.db;
500
+ }
501
+ else if (immutableRes.integrityFailed) {
502
+ diagnostics.push(`sqlite quick_check failed: ${realTarget}`);
503
+ return undefined;
504
+ }
505
+ else {
506
+ const err = immutableRes.error ?? primaryRes.error;
507
+ diagnostics.push(`sqlite read failed (${realTarget}): ${err instanceof Error ? err.message : String(err)}`);
508
+ return undefined;
509
+ }
510
+ }
511
+ else {
512
+ diagnostics.push(`sqlite read failed (${realTarget}): ${primaryRes.error instanceof Error ? primaryRes.error.message : String(primaryRes.error)}`);
513
+ return undefined;
514
+ }
515
+ }
516
+ try {
517
+ inspectedLedgers.push(realTarget);
518
+ return fn(db, realTarget);
519
+ }
520
+ catch (error) {
521
+ diagnostics.push(`sqlite read failed (${realTarget}): `
522
+ + (error instanceof Error ? error.message : String(error)));
523
+ return undefined;
524
+ }
525
+ finally {
526
+ try {
527
+ db.close();
528
+ }
529
+ catch {
530
+ // Ignore close failures on read-only handles.
531
+ }
532
+ }
533
+ }
534
+ function parseDshHomePathArgs(rawArgs) {
535
+ const segments = [];
536
+ let remainder = rawArgs.trim();
537
+ while (remainder.length > 0) {
538
+ const match = /^(?:'([^'\r\n]+)'|"([^"\r\n]+)")\s*(?:,\s*(.*))?$/u.exec(remainder);
539
+ if (!match)
540
+ return undefined;
541
+ const seg = match[1] ?? match[2];
542
+ if (!seg || seg.includes('\0'))
543
+ return undefined;
544
+ segments.push(seg);
545
+ remainder = (match[3] ?? '').trim();
546
+ }
547
+ return segments.length > 0 ? segments : undefined;
548
+ }
549
+ function isWithinDshHome(resolvedPath, dshHome, canonicalHome) {
550
+ const canon = canonicalHome ?? dshHome;
551
+ return resolvedPath === dshHome
552
+ || resolvedPath.startsWith(`${dshHome}${sep}`)
553
+ || resolvedPath === canon
554
+ || resolvedPath.startsWith(`${canon}${sep}`);
555
+ }
556
+ function resolvePathExpr(rawValue, dshHome, canonicalHome = null, diagnostics) {
557
+ let trimmed;
558
+ if (typeof rawValue === 'string') {
559
+ trimmed = rawValue.trim();
560
+ }
561
+ else if (typeof rawValue === 'object' && rawValue !== null && '__jsExpr' in rawValue) {
562
+ const rawExpr = rawValue.__jsExpr;
563
+ if (typeof rawExpr !== 'string')
564
+ return undefined;
565
+ trimmed = rawExpr.trim();
566
+ }
567
+ else {
568
+ return undefined;
569
+ }
570
+ if (!trimmed || trimmed === ':memory:' || trimmed.includes('\0'))
571
+ return undefined;
572
+ const jsMatch = /^(?:(?:!!js|!js)\s+)?dshHomePath\(\s*([\s\S]+?)\s*\)$/u.exec(trimmed);
573
+ if (jsMatch?.[1] !== undefined) {
574
+ const args = parseDshHomePathArgs(jsMatch[1]);
575
+ if (!args) {
576
+ diagnostics?.push(`skipped unparseable dshHomePath ledger path: ${trimmed}`);
577
+ return undefined;
578
+ }
579
+ const resolved = resolve(dshHome, ...args);
580
+ if (!isWithinDshHome(resolved, dshHome, canonicalHome)) {
581
+ diagnostics?.push(`skipped out-of-bounds dshHomePath ledger path: ${trimmed}`);
582
+ return undefined;
583
+ }
584
+ return resolved;
585
+ }
586
+ if (isAbsolute(trimmed)) {
587
+ const resolved = resolve(trimmed);
588
+ if (!isWithinDshHome(resolved, dshHome, canonicalHome)) {
589
+ diagnostics?.push(`skipped out-of-bounds ledger path: ${trimmed}`);
590
+ return undefined;
591
+ }
592
+ return resolved;
593
+ }
594
+ return undefined;
595
+ }
596
+ function classifyPluginFamily(idOrName) {
597
+ if (idOrName.includes('assistant-work-items') || idOrName.endsWith('/assistant-work-items'))
598
+ return 'workItems';
599
+ if (idOrName.includes('assistant-growth-driver') || idOrName.endsWith('/assistant-growth-driver'))
600
+ return 'growthDriver';
601
+ if (idOrName.includes('assistant-dreaming') || idOrName.endsWith('/assistant-dreaming'))
602
+ return 'dreaming';
603
+ if (idOrName.includes('assistant-recovery') || idOrName.endsWith('/assistant-recovery'))
604
+ return 'recovery';
605
+ if (idOrName.includes('assistant-goals') || idOrName.endsWith('/assistant-goals'))
606
+ return 'goals';
607
+ if (idOrName.includes('assistant-memory-learning') || idOrName.endsWith('/assistant-memory-learning'))
608
+ return 'memoryLearning';
609
+ if (idOrName.includes('personal-memory') || idOrName.endsWith('/personal-memory'))
610
+ return 'memory';
611
+ if (idOrName.includes('preference-learning') || idOrName.endsWith('/preference-learning'))
612
+ return 'preference';
613
+ if (idOrName.includes('assistant-evolution') || idOrName.endsWith('/assistant-evolution'))
614
+ return 'evolution';
615
+ if (idOrName.includes('assistant-skills') || idOrName.endsWith('/assistant-skills'))
616
+ return 'skills';
617
+ if (idOrName.includes('assistant-growth-experiments') || idOrName.endsWith('/assistant-growth-experiments'))
618
+ return 'growthExperiments';
619
+ if (idOrName.includes('assistant-association') || idOrName.endsWith('/assistant-association'))
620
+ return 'association';
621
+ if (idOrName.includes('assistant-evaluation') || idOrName.endsWith('/assistant-evaluation'))
622
+ return 'evaluation';
623
+ if (idOrName.includes('assistant-verifier') || idOrName.endsWith('/assistant-verifier'))
624
+ return 'verifier';
625
+ if (idOrName.includes('plugin-control-plane') || idOrName.endsWith('/plugin-control-plane'))
626
+ return 'controlPlane';
627
+ return undefined;
628
+ }
629
+ function addVerifierVariants(set, basePath) {
630
+ set.add(basePath);
631
+ set.add(`${basePath}.creation-reviews`);
632
+ set.add(`${basePath}.source-reviews`);
633
+ set.add(`${basePath}.memory-reviews`);
634
+ set.add(`${basePath}.revision-reviews`);
635
+ set.add(`${basePath}.revision-regressions`);
636
+ }
637
+ function normalizePluginPackageName(id, name) {
638
+ if (name.startsWith('@dsh-ray/'))
639
+ return name;
640
+ if (id.startsWith('dsh-ray-'))
641
+ return `@dsh-ray/${id.slice('dsh-ray-'.length)}`;
642
+ return undefined;
643
+ }
644
+ function stripYamlCommentAndQuotes(raw) {
645
+ let out = '';
646
+ let quote = null;
647
+ for (let i = 0; i < raw.length; i += 1) {
648
+ const ch = raw[i];
649
+ if (quote !== null) {
650
+ if (ch === '\\' && quote === '"' && i + 1 < raw.length) {
651
+ out += raw[i + 1];
652
+ i += 1;
653
+ continue;
654
+ }
655
+ if (ch === quote) {
656
+ quote = null;
657
+ }
658
+ out += ch;
659
+ }
660
+ else {
661
+ if (ch === '"' || ch === "'") {
662
+ quote = ch;
663
+ out += ch;
664
+ }
665
+ else if (ch === '#' && (i === 0 || /\s/u.test(raw[i - 1]))) {
666
+ break;
667
+ }
668
+ else {
669
+ out += ch;
670
+ }
671
+ }
672
+ }
673
+ const trimmed = out.trim();
674
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2)
675
+ || (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2)) {
676
+ return trimmed.slice(1, -1);
677
+ }
678
+ return trimmed;
679
+ }
680
+ function collectPatchDbPaths(patchPath, boundary, into, patchStates, diagnostics) {
681
+ if (!boundary.dshHome || !boundary.canonicalDshHome || boundary.homeUnsafe)
682
+ return;
683
+ let st;
684
+ try {
685
+ st = lstatSync(patchPath);
686
+ }
687
+ catch (error) {
688
+ if (error.code === 'ENOENT')
689
+ return;
690
+ diagnostics.push(`failed to stat config ${patchPath}: ${error instanceof Error ? error.message : String(error)}`);
691
+ return;
692
+ }
693
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) {
694
+ diagnostics.push(`skipped non-regular, symlink, or hardlink config: ${patchPath}`);
695
+ return;
696
+ }
697
+ if (st.size < 0 || st.size > MAX_PATCH_SCAN_BYTES)
698
+ return;
699
+ let realPatch;
700
+ try {
701
+ realPatch = realpathSync(patchPath);
702
+ }
703
+ catch {
704
+ diagnostics.push(`skipped unresolvable config: ${patchPath}`);
705
+ return;
706
+ }
707
+ const resolvedPatch = resolve(patchPath);
708
+ const logicallyWithin = resolvedPatch.startsWith(`${boundary.dshHome}${sep}`)
709
+ || resolvedPatch.startsWith(`${boundary.canonicalDshHome}${sep}`);
710
+ if (!logicallyWithin || !realPatch.startsWith(`${boundary.canonicalDshHome}${sep}`)) {
711
+ diagnostics.push(`skipped out-of-bounds config: ${patchPath}`);
712
+ return;
713
+ }
714
+ let source;
715
+ try {
716
+ source = readFileSync(realPatch, 'utf8');
717
+ }
718
+ catch (error) {
719
+ diagnostics.push(`failed to read config ${patchPath}: ${error instanceof Error ? error.message : String(error)}`);
720
+ return;
721
+ }
722
+ let current;
723
+ let itemIndent = -1;
724
+ let section = 'item';
725
+ let configIndent = -1;
726
+ let subIndent = -1;
727
+ const flush = () => {
728
+ if (!current)
729
+ return;
730
+ const row = current;
731
+ current = undefined;
732
+ const pkgName = normalizePluginPackageName(row.id, row.name);
733
+ if (pkgName && patchStates) {
734
+ patchStates.set(pkgName, {
735
+ disabled: row.disabled,
736
+ configEnabled: row.configEnabled,
737
+ });
738
+ }
739
+ const fam = classifyPluginFamily(row.id) ?? classifyPluginFamily(row.name);
740
+ if (fam) {
741
+ if (fam === 'growthDriver') {
742
+ const usagePath = resolvePathExpr(row.usageDatabasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
743
+ if (usagePath)
744
+ into.growthDriver.add(usagePath);
745
+ const dbPath = resolvePathExpr(row.databasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
746
+ if (dbPath)
747
+ into.growthDriver.add(dbPath);
748
+ }
749
+ else if (fam === 'controlPlane') {
750
+ const dbPath = resolvePathExpr(row.databasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
751
+ if (dbPath)
752
+ into.controlPlane.add(dbPath);
753
+ const stateDir = resolvePathExpr(row.statePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
754
+ if (stateDir) {
755
+ into.controlPlane.add(join(stateDir, 'control.sqlite'));
756
+ into.controlPlane.add(join(stateDir, 'creation-adoptions.sqlite'));
757
+ into.controlPlane.add(join(stateDir, 'revision-adoptions.sqlite'));
758
+ }
759
+ }
760
+ else if (fam === 'goals') {
761
+ const dbPath = resolvePathExpr(row.databasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
762
+ if (dbPath) {
763
+ into.goals.add(`${dbPath}.strategies`);
764
+ into.goals.add(dbPath);
765
+ }
766
+ }
767
+ else if (fam === 'verifier') {
768
+ const dbPath = resolvePathExpr(row.databasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
769
+ if (dbPath)
770
+ addVerifierVariants(into.verifier, dbPath);
771
+ }
772
+ else {
773
+ const dbPath = resolvePathExpr(row.databasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
774
+ if (dbPath)
775
+ into[fam].add(dbPath);
776
+ }
777
+ }
778
+ if (row.id.includes('personal-assistant') || row.name.endsWith('/personal-assistant')) {
779
+ const pmPath = resolvePathExpr(row.personalMemoryDatabasePath, boundary.dshHome, boundary.canonicalDshHome, diagnostics);
780
+ if (pmPath)
781
+ into.memory.add(pmPath);
782
+ }
783
+ };
784
+ for (const rawLine of source.split(/\r?\n/u)) {
785
+ const trimmedRight = rawLine.trimEnd();
786
+ if (trimmedRight.trim() === '' || trimmedRight.trim().startsWith('#'))
787
+ continue;
788
+ const indent = rawLine.length - rawLine.trimStart().length;
789
+ const stripped = rawLine.trimStart();
790
+ const listMatch = /^-\s+(.*)$/u.exec(stripped);
791
+ if (listMatch) {
792
+ flush();
793
+ current = { id: '', name: '', disabled: false, configEnabled: undefined };
794
+ itemIndent = indent;
795
+ section = 'item';
796
+ configIndent = -1;
797
+ subIndent = -1;
798
+ const kv = /^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/u.exec(listMatch[1]);
799
+ if (kv) {
800
+ const k = kv[1];
801
+ const v = stripYamlCommentAndQuotes(kv[2]);
802
+ if (k === 'id')
803
+ current.id = v;
804
+ else if (k === 'name')
805
+ current.name = v;
806
+ else if (k === 'disabled')
807
+ current.disabled = v === 'true';
808
+ }
809
+ continue;
810
+ }
811
+ if (!current)
812
+ continue;
813
+ if (indent <= itemIndent) {
814
+ flush();
815
+ continue;
816
+ }
817
+ if (section === 'usageLearning' || section === 'personalMemory') {
818
+ if (indent <= subIndent)
819
+ section = 'config';
820
+ }
821
+ if (section === 'config' && indent <= configIndent) {
822
+ section = 'item';
823
+ }
824
+ const kv = /^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/u.exec(stripped);
825
+ if (!kv)
826
+ continue;
827
+ const key = kv[1];
828
+ const val = stripYamlCommentAndQuotes(kv[2]);
829
+ if (section === 'item') {
830
+ if (key === 'id')
831
+ current.id = val;
832
+ else if (key === 'name')
833
+ current.name = val;
834
+ else if (key === 'disabled')
835
+ current.disabled = val === 'true';
836
+ else if (key === 'config' && val === '') {
837
+ section = 'config';
838
+ configIndent = indent;
839
+ }
840
+ }
841
+ else if (section === 'config') {
842
+ if (key === 'enabled')
843
+ current.configEnabled = val === 'true' ? true : val === 'false' ? false : undefined;
844
+ else if (key === 'databasePath')
845
+ current.databasePath = val;
846
+ else if (key === 'statePath')
847
+ current.statePath = val;
848
+ else if (key === 'usageLearning' && val === '') {
849
+ section = 'usageLearning';
850
+ subIndent = indent;
851
+ }
852
+ else if (key === 'personalMemory' && val === '') {
853
+ section = 'personalMemory';
854
+ subIndent = indent;
855
+ }
856
+ }
857
+ else if (section === 'usageLearning') {
858
+ if (key === 'databasePath')
859
+ current.usageDatabasePath = val;
860
+ }
861
+ else if (section === 'personalMemory') {
862
+ if (key === 'databasePath')
863
+ current.personalMemoryDatabasePath = val;
864
+ }
865
+ }
866
+ flush();
867
+ }
868
+ function discoverCandidateSqlitePaths(ctx, boundary, targetProfiles, patchDbMap) {
869
+ const candidates = new Set();
870
+ const addPath = (value) => {
871
+ if (value)
872
+ candidates.add(value);
873
+ };
874
+ if (boundary.dshHome) {
875
+ const loader = ctx.get('loader');
876
+ if (typeof loader?.entries === 'function') {
877
+ try {
878
+ for (const entry of loader.entries()) {
879
+ const modName = typeof entry.options?.name === 'string' ? entry.options.name : '';
880
+ const rawCfg = rec(entry.options?.config);
881
+ const effCfg = rec(entry.fiber?.config);
882
+ for (const cfg of [effCfg, rawCfg]) {
883
+ const dbPath = resolvePathExpr(cfg['databasePath'], boundary.dshHome, boundary.canonicalDshHome);
884
+ if (dbPath) {
885
+ if (modName.includes('assistant-goals')) {
886
+ addPath(`${dbPath}.strategies`);
887
+ addPath(dbPath);
888
+ }
889
+ else if (modName.includes('assistant-verifier')) {
890
+ addVerifierVariants(candidates, dbPath);
891
+ }
892
+ else {
893
+ addPath(dbPath);
894
+ }
895
+ }
896
+ addPath(resolvePathExpr(rec(cfg['usageLearning'])['databasePath'], boundary.dshHome, boundary.canonicalDshHome));
897
+ addPath(resolvePathExpr(rec(cfg['personalMemory'])['databasePath'], boundary.dshHome, boundary.canonicalDshHome));
898
+ const stateDir = resolvePathExpr(cfg['statePath'], boundary.dshHome, boundary.canonicalDshHome);
899
+ if (stateDir) {
900
+ addPath(join(stateDir, 'control.sqlite'));
901
+ addPath(join(stateDir, 'creation-adoptions.sqlite'));
902
+ addPath(join(stateDir, 'revision-adoptions.sqlite'));
903
+ }
904
+ }
905
+ }
906
+ }
907
+ catch {
908
+ // Best-effort loader inspection.
909
+ }
910
+ }
911
+ for (const set of Object.values(patchDbMap)) {
912
+ for (const p of set)
913
+ addPath(p);
914
+ }
915
+ const dshHome = boundary.dshHome;
916
+ // Canonical default $DSH_HOME paths across all 15 families
917
+ addPath(join(dshHome, 'assistant-work-items', 'state.sqlite'));
918
+ addPath(join(dshHome, 'assistant-growth-driver', 'usage.sqlite'));
919
+ addPath(join(dshHome, 'assistant-growth-driver', 'state.sqlite'));
920
+ addPath(join(dshHome, 'assistant-dreaming', 'state.sqlite'));
921
+ addPath(join(dshHome, 'assistant-dreaming', 'dreaming.sqlite'));
922
+ addPath(join(dshHome, 'assistant-recovery', 'state.sqlite'));
923
+ addPath(join(dshHome, 'assistant-recovery', 'recovery.sqlite'));
924
+ for (const b of [
925
+ join(dshHome, 'assistant-goals.sqlite'),
926
+ join(dshHome, 'assistant-goals', 'state.sqlite'),
927
+ join(dshHome, 'assistant-goals', 'goals.sqlite'),
928
+ ]) {
929
+ addPath(`${b}.strategies`);
930
+ addPath(b);
931
+ }
932
+ addPath(join(dshHome, 'assistant-goals', 'strategies.sqlite'));
933
+ addPath(join(dshHome, 'assistant-goals', 'strategy.sqlite'));
934
+ addPath(join(dshHome, 'assistant-memory-learning', 'learning.sqlite'));
935
+ addPath(join(dshHome, 'assistant-memory-learning', 'state.sqlite'));
936
+ addPath(join(dshHome, 'personal-memory', 'memory.sqlite'));
937
+ addPath(join(dshHome, 'personal-memory', 'state.sqlite'));
938
+ addPath(join(dshHome, 'preference-learning', 'preferences.sqlite'));
939
+ addPath(join(dshHome, 'preference-learning', 'state.sqlite'));
940
+ addPath(join(dshHome, 'assistant-evolution', 'evolution.sqlite'));
941
+ addPath(join(dshHome, 'assistant-evolution', 'state.sqlite'));
942
+ addPath(join(dshHome, 'assistant-skills', 'skills.sqlite'));
943
+ addPath(join(dshHome, 'assistant-skills', 'state.sqlite'));
944
+ addPath(join(dshHome, 'assistant-skills.sqlite'));
945
+ addPath(join(dshHome, 'assistant-growth-experiments', 'growth.sqlite'));
946
+ addPath(join(dshHome, 'assistant-growth-experiments', 'state.sqlite'));
947
+ addPath(join(dshHome, 'assistant-association', 'association.sqlite'));
948
+ addPath(join(dshHome, 'assistant-association', 'state.sqlite'));
949
+ addPath(join(dshHome, 'association.sqlite'));
950
+ addPath(join(dshHome, 'assistant-association.sqlite'));
951
+ addPath(join(dshHome, 'assistant-evaluation', 'evaluation.sqlite'));
952
+ addPath(join(dshHome, 'assistant-evaluation', 'state.sqlite'));
953
+ addVerifierVariants(candidates, join(dshHome, 'assistant-verifier', 'verification.sqlite'));
954
+ addVerifierVariants(candidates, join(dshHome, 'assistant-verifier', 'state.sqlite'));
955
+ addPath(join(dshHome, 'plugin-control-plane', 'control.sqlite'));
956
+ addPath(join(dshHome, 'plugin-control-plane', 'state.sqlite'));
957
+ addPath(join(dshHome, 'plugin-control-plane', 'creation-adoptions.sqlite'));
958
+ addPath(join(dshHome, 'plugin-control-plane', 'revision-adoptions.sqlite'));
959
+ // Profile-scoped candidate paths (strictly isolated to targetProfiles)
960
+ for (const prof of targetProfiles) {
961
+ addPath(join(dshHome, 'assistant-work-items', `${prof}.sqlite`));
962
+ addPath(join(dshHome, 'assistant-growth-driver', `${prof}-usage.sqlite`));
963
+ addPath(join(dshHome, 'assistant-growth-driver', `${prof}.sqlite`));
964
+ addPath(join(dshHome, 'assistant-dreaming', `${prof}.sqlite`));
965
+ addPath(join(dshHome, 'assistant-recovery', `${prof}.sqlite`));
966
+ addPath(join(dshHome, 'assistant-goals', `${prof}.sqlite.strategies`));
967
+ addPath(join(dshHome, 'assistant-goals', `${prof}.sqlite`));
968
+ addPath(join(dshHome, 'assistant-memory-learning', `${prof}.sqlite`));
969
+ addPath(join(dshHome, 'personal-memory', `${prof}.sqlite`));
970
+ addPath(join(dshHome, 'preference-learning', `${prof}.sqlite`));
971
+ addPath(join(dshHome, 'assistant-evolution', `${prof}.sqlite`));
972
+ addPath(join(dshHome, 'assistant-skills', `${prof}.sqlite`));
973
+ addPath(join(dshHome, 'assistant-growth-experiments', `${prof}.sqlite`));
974
+ addPath(join(dshHome, 'assistant-association', `${prof}.sqlite`));
975
+ addPath(join(dshHome, 'assistant-evaluation', `${prof}.sqlite`));
976
+ addVerifierVariants(candidates, join(dshHome, 'assistant-verifier', `${prof}.sqlite`));
977
+ addPath(join(dshHome, 'plugin-control-plane', `${prof}.sqlite`));
978
+ addPath(join(dshHome, 'plugin-control-plane', `${prof}-creation-adoptions.sqlite`));
979
+ addPath(join(dshHome, 'plugin-control-plane', `${prof}-revision-adoptions.sqlite`));
980
+ addPath(join(dshHome, `${prof}-creation-adoptions.sqlite`));
981
+ addPath(join(dshHome, `${prof}-revision-adoptions.sqlite`));
982
+ addPath(join(dshHome, 'rsi-authorities', prof, 'state', 'control-plane', 'control.sqlite'));
983
+ addPath(join(dshHome, 'rsi-authorities', prof, 'state', 'control-plane', 'creation-adoptions.sqlite'));
984
+ addPath(join(dshHome, 'rsi-authorities', prof, 'state', 'control-plane', 'revision-adoptions.sqlite'));
985
+ }
986
+ }
987
+ return [...candidates];
988
+ }
989
+ function readNodeModulesPackages(dir, boundary) {
990
+ const found = new Map();
991
+ if (!boundary.dshHome || !boundary.canonicalDshHome || boundary.homeUnsafe)
992
+ return found;
993
+ const scopeDir = join(dir, '@dsh-ray');
994
+ if (!existsSync(scopeDir))
995
+ return found;
996
+ const pnpmStoreRoot = resolve(dir, '.pnpm');
997
+ try {
998
+ const st = lstatSync(scopeDir);
999
+ if (!st.isDirectory() || st.isSymbolicLink())
1000
+ return found;
1001
+ const realScope = realpathSync(scopeDir);
1002
+ if (!realScope.startsWith(`${boundary.canonicalDshHome}${sep}`))
1003
+ return found;
1004
+ for (const entry of readdirSync(realScope, { withFileTypes: true })) {
1005
+ if (entry.name.startsWith('.') || entry.name.startsWith('@'))
1006
+ continue;
1007
+ if (!entry.isDirectory() && !entry.isSymbolicLink())
1008
+ continue;
1009
+ const entryPath = join(realScope, entry.name);
1010
+ let pkgDir = entryPath;
1011
+ let installKind = 'npm';
1012
+ if (entry.isSymbolicLink()) {
1013
+ try {
1014
+ pkgDir = realpathSync(entryPath);
1015
+ const dirStat = lstatSync(pkgDir);
1016
+ if (!dirStat.isDirectory())
1017
+ continue;
1018
+ installKind = (pkgDir === pnpmStoreRoot || pkgDir.startsWith(`${pnpmStoreRoot}${sep}`))
1019
+ ? 'npm'
1020
+ : 'local';
1021
+ }
1022
+ catch {
1023
+ continue;
1024
+ }
1025
+ }
1026
+ const pkgJsonPath = join(pkgDir, 'package.json');
1027
+ try {
1028
+ const pkgStat = lstatSync(pkgJsonPath);
1029
+ if (!pkgStat.isFile() || pkgStat.isSymbolicLink())
1030
+ continue;
1031
+ if (pkgStat.size < 0 || pkgStat.size > MAX_PACKAGE_JSON_BYTES)
1032
+ continue;
1033
+ const parsed = JSON.parse(readFileSync(pkgJsonPath, 'utf8'));
1034
+ const pkgName = textOrNull(parsed.name);
1035
+ if (pkgName !== null && pkgName.startsWith('@dsh-ray/')) {
1036
+ found.set(pkgName, { version: textOrNull(parsed.version), installKind });
1037
+ }
1038
+ }
1039
+ catch {
1040
+ // Ignore unreadable or malformed package.json.
1041
+ }
1042
+ }
1043
+ }
1044
+ catch {
1045
+ // Ignore unreadable directory.
1046
+ }
1047
+ return found;
1048
+ }
1049
+ function addMetric(current, delta) {
1050
+ return (current ?? 0) + delta;
1051
+ }
1052
+ function maxMetric(current, candidate) {
1053
+ return current === null ? candidate : Math.max(current, candidate);
1054
+ }
1055
+ function callHealthSyncOrAsync(service) {
1056
+ const healthFn = rec(service)['health'];
1057
+ if (typeof healthFn !== 'function')
1058
+ return Promise.resolve(undefined);
1059
+ return Promise.resolve()
1060
+ .then(() => healthFn.call(service))
1061
+ .then(res => (typeof res === 'object' && res !== null && !Array.isArray(res)
1062
+ ? res
1063
+ : undefined))
1064
+ .catch(() => undefined);
1065
+ }
1066
+ export async function collectDeliveryVersionReport(input, extraOptions) {
1067
+ const options = 'ctx' in input
1068
+ ? input
1069
+ : { ctx: input, ...extraOptions };
1070
+ const ctx = options.ctx;
1071
+ const diagnostics = [...(options.extraDiagnostics ?? [])];
1072
+ const inspectedLedgers = [];
1073
+ const seenRealPaths = new Set();
1074
+ const boundary = resolveBoundary(ctx, options, diagnostics);
1075
+ const generatedAt = typeof options.now === 'number' && Number.isFinite(options.now) && options.now >= 0
1076
+ ? Math.trunc(options.now)
1077
+ : Date.now();
1078
+ const hostMeta = readBoundHostMetadata(boundary);
1079
+ const runningVersion = readRunningHostVersion();
1080
+ const targetProfiles = boundary.profile !== null
1081
+ ? [boundary.profile]
1082
+ : (boundary.profiles.length > 0 ? boundary.profiles : ['web', 'lark', 'supervised']);
1083
+ const patchDbMap = {
1084
+ workItems: new Set(),
1085
+ growthDriver: new Set(),
1086
+ dreaming: new Set(),
1087
+ recovery: new Set(),
1088
+ goals: new Set(),
1089
+ memoryLearning: new Set(),
1090
+ memory: new Set(),
1091
+ preference: new Set(),
1092
+ evolution: new Set(),
1093
+ skills: new Set(),
1094
+ growthExperiments: new Set(),
1095
+ association: new Set(),
1096
+ evaluation: new Set(),
1097
+ verifier: new Set(),
1098
+ controlPlane: new Set(),
1099
+ };
1100
+ const patchStatesByProfile = new Map();
1101
+ const homePatchStates = new Map();
1102
+ if (boundary.dshHome && !boundary.homeUnsafe) {
1103
+ if (boundary.profile === null) {
1104
+ collectPatchDbPaths(join(boundary.dshHome, 'cordis.yml'), boundary, patchDbMap, homePatchStates, diagnostics);
1105
+ collectPatchDbPaths(join(boundary.dshHome, 'cordis.patch.yml'), boundary, patchDbMap, homePatchStates, diagnostics);
1106
+ }
1107
+ for (const prof of targetProfiles) {
1108
+ const profStates = new Map(homePatchStates);
1109
+ collectPatchDbPaths(join(boundary.dshHome, 'profiles', prof, 'cordis.yml'), boundary, patchDbMap, profStates, diagnostics);
1110
+ collectPatchDbPaths(join(boundary.dshHome, 'profiles', prof, 'cordis.patch.yml'), boundary, patchDbMap, profStates, diagnostics);
1111
+ patchStatesByProfile.set(prof, profStates);
1112
+ }
1113
+ }
1114
+ const evolvedByPlanId = new Map();
1115
+ const evolvedMap = new Map();
1116
+ const coreByKey = new Map();
1117
+ let pluginSourceAvailable = false;
1118
+ const upsertEvolved = (rawName, patch) => {
1119
+ const trimmed = rawName.trim();
1120
+ if (trimmed === '')
1121
+ return undefined;
1122
+ const key = normalizePluginKey(trimmed);
1123
+ const boundedName = truncateText(trimmed, 200);
1124
+ const boundedVersion = boundNonEmptyString(patch.version, 128) ?? null;
1125
+ const nextTier = boundedVersion !== null ? (patch.versionTier ?? 1) : 0;
1126
+ const existing = evolvedMap.get(key);
1127
+ if (existing) {
1128
+ if (trimmed.startsWith('@dsh-ray/') && !existing.name.startsWith('@dsh-ray/')) {
1129
+ existing.name = boundedName;
1130
+ }
1131
+ if (patch.fromAdoptionJournal)
1132
+ existing.fromAdoptionJournal = true;
1133
+ if (boundedVersion !== null && (existing.version === null || nextTier <= existing.versionTier)) {
1134
+ existing.version = boundedVersion;
1135
+ existing.versionTier = nextTier;
1136
+ }
1137
+ if (patch.enabled !== undefined) {
1138
+ existing.enabled = existing.enabled === true || patch.enabled;
1139
+ }
1140
+ return existing;
1141
+ }
1142
+ const created = {
1143
+ name: boundedName,
1144
+ version: boundedVersion,
1145
+ versionTier: nextTier,
1146
+ fromAdoptionJournal: patch.fromAdoptionJournal === true,
1147
+ kind: 'evolved',
1148
+ installKind: 'adopted',
1149
+ ...(patch.enabled === undefined ? {} : { enabled: patch.enabled }),
1150
+ };
1151
+ evolvedMap.set(key, created);
1152
+ return created;
1153
+ };
1154
+ // Self-iteration counters (null = no ledger/service present; 0 = present with 0 rows)
1155
+ let workItemsTotal = null;
1156
+ let workItemsSettled = null;
1157
+ let growthUsageJobsTotal = null;
1158
+ let dreamingRuns = null;
1159
+ let recoveryRuns = null;
1160
+ let goalStrategyRuns = null;
1161
+ let candidatesGenerated = null;
1162
+ let candidatesAdopted = null;
1163
+ let pluginsCreated = null;
1164
+ let pluginsRevised = null;
1165
+ let taskVerificationsDone = null;
1166
+ let rollbacks = null;
1167
+ let evolutionRulesAdopted = null;
1168
+ let associationParamVersion = null;
1169
+ let associationProfileAdoptions = null;
1170
+ let evaluationAttentionTuningAdoptions = null;
1171
+ let evaluationLooseningDecisionsAdopted = null;
1172
+ let activeMemories = null;
1173
+ let activePreferenceOverlays = null;
1174
+ let workflowCandidatesPromoted = null;
1175
+ let skillDeployments = null;
1176
+ let selfUpgrades = null;
1177
+ let backupSnapshotsCount = null;
1178
+ let sawControlPlaneDb = false;
1179
+ let sawCreatedSource = false;
1180
+ let sawRevisedSource = false;
1181
+ let sawControlAdoptionSource = false;
1182
+ let sawActivationPlansTable = false;
1183
+ const createdPlanIds = new Set();
1184
+ const revisedPlanIds = new Set();
1185
+ const controlAdoptedPlanIds = new Set();
1186
+ const sourceIdToActivationId = new Map();
1187
+ const linkedActivationIds = new Set();
1188
+ const sourcePlanIds = new Set();
1189
+ const sourceModeById = new Map();
1190
+ const watchClosedByPlan = new Set();
1191
+ const activatedActIds = new Set();
1192
+ const bufferedCreations = [];
1193
+ const bufferedRevisions = [];
1194
+ const bufferedWatches = [];
1195
+ const bufferedSourcePlans = [];
1196
+ const bufferedActivationPlans = [];
1197
+ let sawPrefHypotheses = false;
1198
+ let prefHypothesesTotal = 0;
1199
+ let prefHypothesesActiveFallback = 0;
1200
+ let prefHypothesesRolledBackFallback = 0;
1201
+ let sawPrefTransitions = false;
1202
+ let prefTransitionsCreated = 0;
1203
+ let prefTransitionsActivated = 0;
1204
+ let prefTransitionsRolledBack = 0;
1205
+ let hasCpActivationDb = false;
1206
+ let hasEvoProposalsDb = false;
1207
+ let hasEvoRulesDb = false;
1208
+ let hasEvoRollbacksDb = false;
1209
+ let hasPrefDb = false;
1210
+ let hasMemoryLearningDb = false;
1211
+ const dbPaths = discoverCandidateSqlitePaths(ctx, boundary, targetProfiles, patchDbMap);
1212
+ for (const dbPath of dbPaths) {
1213
+ withReadOnlySqlite(dbPath, boundary, seenRealPaths, inspectedLedgers, diagnostics, db => {
1214
+ // Work items
1215
+ if (hasTable(db, 'work_item')) {
1216
+ workItemsTotal = addMetric(workItemsTotal, countQuery(db, 'SELECT COUNT(*) AS n FROM work_item'));
1217
+ }
1218
+ if (hasTable(db, 'work_item_outcome') && hasColumn(db, 'work_item_outcome', 'item_id')) {
1219
+ workItemsSettled = addMetric(workItemsSettled, countQuery(db, 'SELECT COUNT(DISTINCT item_id) AS n FROM work_item_outcome'));
1220
+ }
1221
+ else if (hasTable(db, 'work_item') && hasColumn(db, 'work_item', 'state')) {
1222
+ workItemsSettled = addMetric(workItemsSettled, countQuery(db, "SELECT COUNT(*) AS n FROM work_item WHERE state IN ('ready','blocked','failed','dropped')"));
1223
+ }
1224
+ // Growth driver usage jobs
1225
+ if (hasTable(db, 'usage_jobs')) {
1226
+ const jobs = countQuery(db, 'SELECT COUNT(*) AS n FROM usage_jobs');
1227
+ growthUsageJobsTotal = addMetric(growthUsageJobsTotal, jobs);
1228
+ candidatesGenerated = addMetric(candidatesGenerated, jobs);
1229
+ }
1230
+ // Dreaming
1231
+ if (hasTable(db, 'dream_runs')) {
1232
+ dreamingRuns = addMetric(dreamingRuns, countQuery(db, 'SELECT COUNT(*) AS n FROM dream_runs'));
1233
+ }
1234
+ // Recovery
1235
+ if (hasTable(db, 'recovery_runs')) {
1236
+ recoveryRuns = addMetric(recoveryRuns, countQuery(db, 'SELECT COUNT(*) AS n FROM recovery_runs'));
1237
+ }
1238
+ // Goal strategy
1239
+ if (hasTable(db, 'goal_strategy_records')) {
1240
+ goalStrategyRuns = addMetric(goalStrategyRuns, countQuery(db, 'SELECT COUNT(*) AS n FROM goal_strategy_records'));
1241
+ }
1242
+ // Plugin control plane: source_adoptions, source_plans, activation_watch, activation_plans, creation-adoptions, revision-adoptions
1243
+ if (hasTable(db, 'source_adoptions')
1244
+ && hasColumn(db, 'source_adoptions', 'source_plan_id')
1245
+ && hasColumn(db, 'source_adoptions', 'activation_plan_id')) {
1246
+ sawControlPlaneDb = true;
1247
+ const links = db.prepare('SELECT source_plan_id, activation_plan_id FROM source_adoptions').all();
1248
+ for (const link of links) {
1249
+ if (typeof link.source_plan_id === 'string' && typeof link.activation_plan_id === 'string') {
1250
+ linkedActivationIds.add(link.activation_plan_id);
1251
+ sourceIdToActivationId.set(link.source_plan_id, link.activation_plan_id);
1252
+ }
1253
+ }
1254
+ }
1255
+ if (hasTable(db, 'source_plans') && hasColumn(db, 'source_plans', 'id')) {
1256
+ sawControlPlaneDb = true;
1257
+ sawCreatedSource = true;
1258
+ sawRevisedSource = true;
1259
+ sawControlAdoptionSource = true;
1260
+ const hasMode = hasColumn(db, 'source_plans', 'mode');
1261
+ const hasPluginName = hasColumn(db, 'source_plans', 'plugin_name');
1262
+ const hasStatus = hasColumn(db, 'source_plans', 'status');
1263
+ const cols = [
1264
+ 'id',
1265
+ ...(hasPluginName ? ['plugin_name'] : []),
1266
+ ...(hasMode ? ['mode'] : []),
1267
+ ...(hasStatus ? ['status'] : []),
1268
+ ];
1269
+ const rows = db.prepare(`SELECT ${cols.join(', ')} FROM source_plans`).all();
1270
+ candidatesGenerated = addMetric(candidatesGenerated, rows.length);
1271
+ for (const row of rows) {
1272
+ if (typeof row.id !== 'string')
1273
+ continue;
1274
+ const mode = hasMode && typeof row.mode === 'string' ? row.mode : null;
1275
+ sourcePlanIds.add(row.id);
1276
+ sourceModeById.set(row.id, mode);
1277
+ bufferedSourcePlans.push({
1278
+ id: row.id,
1279
+ ...(typeof row.plugin_name === 'string' ? { pluginName: row.plugin_name } : {}),
1280
+ mode,
1281
+ ...(hasStatus && typeof row.status === 'string' ? { status: row.status } : {}),
1282
+ });
1283
+ }
1284
+ }
1285
+ if (hasTable(db, 'activation_watch')) {
1286
+ sawControlPlaneDb = true;
1287
+ const hasPlanId = hasColumn(db, 'activation_watch', 'plan_id');
1288
+ const hasPkgName = hasColumn(db, 'activation_watch', 'package_name');
1289
+ const hasVer = hasColumn(db, 'activation_watch', 'package_version');
1290
+ const hasState = hasColumn(db, 'activation_watch', 'state');
1291
+ const cols = [
1292
+ ...(hasPlanId ? ['plan_id'] : []),
1293
+ ...(hasPkgName ? ['package_name'] : []),
1294
+ ...(hasVer ? ['package_version'] : []),
1295
+ ...(hasState ? ['state'] : []),
1296
+ ];
1297
+ if (cols.length > 0) {
1298
+ const rows = db.prepare(`SELECT ${cols.join(', ')} FROM activation_watch`).all();
1299
+ for (const row of rows) {
1300
+ const state = typeof row.state === 'string' ? row.state : '';
1301
+ if (typeof row.plan_id === 'string' && (state === 'closed-regressed' || state === 'closed-retracted')) {
1302
+ watchClosedByPlan.add(row.plan_id);
1303
+ }
1304
+ if (typeof row.package_name === 'string' && row.package_name.trim() !== '') {
1305
+ bufferedWatches.push({
1306
+ packageName: row.package_name.trim(),
1307
+ packageVersion: typeof row.package_version === 'string' && row.package_version.trim() !== ''
1308
+ ? row.package_version.trim()
1309
+ : null,
1310
+ state,
1311
+ });
1312
+ }
1313
+ }
1314
+ }
1315
+ }
1316
+ if (hasTable(db, 'activation_plans') && hasColumn(db, 'activation_plans', 'id') && hasColumn(db, 'activation_plans', 'status')) {
1317
+ sawControlPlaneDb = true;
1318
+ hasCpActivationDb = true;
1319
+ sawControlAdoptionSource = true;
1320
+ sawActivationPlansTable = true;
1321
+ const hasProfileCol = hasColumn(db, 'activation_plans', 'profile');
1322
+ const hasCandidateCol = hasColumn(db, 'activation_plans', 'candidate_json');
1323
+ const hasUpdatedCol = hasColumn(db, 'activation_plans', 'updated_at');
1324
+ const actRows = db.prepare(`SELECT id, ${hasProfileCol ? 'profile,' : ''} ${hasCandidateCol ? 'candidate_json,' : ''} status${hasUpdatedCol ? ', updated_at' : ''} FROM activation_plans${hasUpdatedCol ? ' ORDER BY updated_at ASC, rowid ASC' : ''}`).all();
1325
+ for (const row of actRows) {
1326
+ if (typeof row.id !== 'string' || typeof row.status !== 'string')
1327
+ continue;
1328
+ if (boundary.profile !== null && hasProfileCol && typeof row.profile === 'string' && row.profile !== boundary.profile) {
1329
+ continue;
1330
+ }
1331
+ if (row.status === 'activated')
1332
+ activatedActIds.add(row.id);
1333
+ bufferedActivationPlans.push({
1334
+ id: row.id,
1335
+ ...(typeof row.profile === 'string' ? { profile: row.profile } : {}),
1336
+ ...(typeof row.candidate_json === 'string' ? { candidateJson: row.candidate_json } : {}),
1337
+ status: row.status,
1338
+ });
1339
+ }
1340
+ }
1341
+ const isRevisionJournal = hasTable(db, 'entries') || hasTable(db, 'versions') || hasTable(db, 'rollbacks');
1342
+ if (!isRevisionJournal && hasTable(db, 'adoptions') && !hasColumn(db, 'adoptions', 'parent_plan_id') && hasColumn(db, 'adoptions', 'plan_id') && hasColumn(db, 'adoptions', 'status')) {
1343
+ sawControlPlaneDb = true;
1344
+ sawCreatedSource = true;
1345
+ sawControlAdoptionSource = true;
1346
+ const hasCert = hasColumn(db, 'adoptions', 'certificate_json');
1347
+ const hasReceipt = hasColumn(db, 'adoptions', 'receipt_json');
1348
+ const rows = db.prepare(`SELECT plan_id, status${hasCert ? ', certificate_json' : ''}${hasReceipt ? ', receipt_json' : ''} FROM adoptions`).all();
1349
+ for (const row of rows) {
1350
+ if (typeof row.plan_id !== 'string' || typeof row.status !== 'string')
1351
+ continue;
1352
+ bufferedCreations.push({
1353
+ planId: row.plan_id,
1354
+ status: row.status,
1355
+ ...(typeof row.certificate_json === 'string' ? { certificateJson: row.certificate_json } : {}),
1356
+ ...(typeof row.receipt_json === 'string' ? { receiptJson: row.receipt_json } : {}),
1357
+ });
1358
+ }
1359
+ }
1360
+ if (isRevisionJournal) {
1361
+ sawControlPlaneDb = true;
1362
+ if (hasTable(db, 'rollbacks')) {
1363
+ rollbacks = addMetric(rollbacks, countQuery(db, 'SELECT COUNT(*) AS n FROM rollbacks'));
1364
+ }
1365
+ const adoptionStatusByPlan = new Map();
1366
+ if (hasTable(db, 'adoptions') && hasColumn(db, 'adoptions', 'plan_id') && hasColumn(db, 'adoptions', 'status')) {
1367
+ sawRevisedSource = true;
1368
+ sawControlAdoptionSource = true;
1369
+ const aRows = db.prepare('SELECT plan_id, status FROM adoptions').all();
1370
+ for (const ar of aRows) {
1371
+ if (typeof ar.plan_id === 'string' && typeof ar.status === 'string') {
1372
+ adoptionStatusByPlan.set(ar.plan_id, ar.status);
1373
+ if (ar.status === 'active') {
1374
+ revisedPlanIds.add(ar.plan_id);
1375
+ controlAdoptedPlanIds.add(ar.plan_id);
1376
+ }
1377
+ }
1378
+ }
1379
+ }
1380
+ else if (hasTable(db, 'versions') && hasColumn(db, 'versions', 'plan_id') && hasColumn(db, 'versions', 'role')) {
1381
+ sawRevisedSource = true;
1382
+ sawControlAdoptionSource = true;
1383
+ const vRows = db.prepare("SELECT plan_id FROM versions WHERE role = 'revision'").all();
1384
+ for (const vr of vRows) {
1385
+ if (typeof vr.plan_id === 'string' && vr.plan_id !== '') {
1386
+ revisedPlanIds.add(vr.plan_id);
1387
+ controlAdoptedPlanIds.add(vr.plan_id);
1388
+ }
1389
+ }
1390
+ }
1391
+ if (hasTable(db, 'entries')) {
1392
+ const hasEntryId = hasColumn(db, 'entries', 'entry_id');
1393
+ const hasName = hasColumn(db, 'entries', 'name');
1394
+ const hasParentPlan = hasColumn(db, 'entries', 'parent_plan_id');
1395
+ const hasCurrentPlan = hasColumn(db, 'entries', 'current_plan_id');
1396
+ const hasRev = hasColumn(db, 'entries', 'revision');
1397
+ const cols = [
1398
+ ...(hasEntryId ? ['entry_id'] : []),
1399
+ ...(hasName ? ['name'] : []),
1400
+ ...(hasParentPlan ? ['parent_plan_id'] : []),
1401
+ ...(hasCurrentPlan ? ['current_plan_id'] : []),
1402
+ ...(hasRev ? ['revision'] : []),
1403
+ ];
1404
+ const entryList = [];
1405
+ if (cols.length > 0) {
1406
+ const eRows = db.prepare(`SELECT ${cols.join(', ')} FROM entries`).all();
1407
+ for (const er of eRows) {
1408
+ entryList.push({
1409
+ ...(typeof er.entry_id === 'string' ? { entryId: er.entry_id } : {}),
1410
+ ...(typeof er.name === 'string' ? { name: er.name } : {}),
1411
+ ...(typeof er.parent_plan_id === 'string' ? { parentPlanId: er.parent_plan_id } : {}),
1412
+ ...(typeof er.current_plan_id === 'string' ? { currentPlanId: er.current_plan_id } : {}),
1413
+ ...(typeof er.revision === 'number' && Number.isFinite(er.revision) ? { revision: Math.trunc(er.revision) } : {}),
1414
+ });
1415
+ }
1416
+ }
1417
+ bufferedRevisions.push({ adoptionStatusByPlan, entries: entryList });
1418
+ }
1419
+ }
1420
+ // Verifier
1421
+ if (hasTable(db, 'acceptance_jobs') && hasColumn(db, 'acceptance_jobs', 'state')) {
1422
+ taskVerificationsDone = addMetric(taskVerificationsDone, countQuery(db, "SELECT COUNT(*) AS n FROM acceptance_jobs WHERE state = 'done'"));
1423
+ }
1424
+ // Evolution
1425
+ if (hasTable(db, 'evolution_proposals')) {
1426
+ hasEvoProposalsDb = true;
1427
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM evolution_proposals'));
1428
+ }
1429
+ if (hasTable(db, 'evolution_rules')) {
1430
+ hasEvoRulesDb = true;
1431
+ const rules = countQuery(db, 'SELECT COUNT(*) AS n FROM evolution_rules');
1432
+ evolutionRulesAdopted = addMetric(evolutionRulesAdopted, rules);
1433
+ candidatesAdopted = addMetric(candidatesAdopted, rules);
1434
+ }
1435
+ if (hasTable(db, 'evolution_autonomous_rollbacks')) {
1436
+ hasEvoRollbacksDb = true;
1437
+ rollbacks = addMetric(rollbacks, countQuery(db, 'SELECT COUNT(*) AS n FROM evolution_autonomous_rollbacks'));
1438
+ }
1439
+ // Association
1440
+ if (hasTable(db, 'assoc_param_profile_heads') && hasColumn(db, 'assoc_param_profile_heads', 'active_version')) {
1441
+ const row = db.prepare('SELECT MAX(active_version) AS v FROM assoc_param_profile_heads').get();
1442
+ const ver = nonNegIntOrNull(row?.v) ?? 0;
1443
+ associationParamVersion = maxMetric(associationParamVersion, ver);
1444
+ }
1445
+ if (hasTable(db, 'assoc_param_profile_events') && hasColumn(db, 'assoc_param_profile_events', 'kind')) {
1446
+ associationProfileAdoptions = addMetric(associationProfileAdoptions, countQuery(db, "SELECT COUNT(*) AS n FROM assoc_param_profile_events WHERE kind = 'adopted'"));
1447
+ rollbacks = addMetric(rollbacks, countQuery(db, "SELECT COUNT(*) AS n FROM assoc_param_profile_events WHERE kind = 'rolled-back'"));
1448
+ }
1449
+ if (hasTable(db, 'assoc_skill_candidates')) {
1450
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM assoc_skill_candidates'));
1451
+ }
1452
+ if (hasTable(db, 'assoc_param_relax_proposals')) {
1453
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM assoc_param_relax_proposals'));
1454
+ }
1455
+ // Evaluation
1456
+ if (hasTable(db, 'evaluation_attention_tuning_events') && hasColumn(db, 'evaluation_attention_tuning_events', 'kind')) {
1457
+ evaluationAttentionTuningAdoptions = addMetric(evaluationAttentionTuningAdoptions, countQuery(db, "SELECT COUNT(*) AS n FROM evaluation_attention_tuning_events WHERE kind = 'adopted'"));
1458
+ rollbacks = addMetric(rollbacks, countQuery(db, "SELECT COUNT(*) AS n FROM evaluation_attention_tuning_events WHERE kind = 'rolled-back'"));
1459
+ }
1460
+ if (hasTable(db, 'evaluation_attention_loosening_proposals')) {
1461
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM evaluation_attention_loosening_proposals'));
1462
+ }
1463
+ if (hasTable(db, 'evaluation_attention_loosening_decisions') && hasColumn(db, 'evaluation_attention_loosening_decisions', 'decision')) {
1464
+ const adopted = countQuery(db, "SELECT COUNT(*) AS n FROM evaluation_attention_loosening_decisions WHERE decision = 'adopted'");
1465
+ evaluationLooseningDecisionsAdopted = addMetric(evaluationLooseningDecisionsAdopted, adopted);
1466
+ }
1467
+ // Personal memory
1468
+ if (hasTable(db, 'memory_records') && hasColumn(db, 'memory_records', 'status')) {
1469
+ activeMemories = addMetric(activeMemories, countQuery(db, "SELECT COUNT(*) AS n FROM memory_records WHERE status = 'active'"));
1470
+ }
1471
+ // Preference learning
1472
+ if (hasTable(db, 'preference_hypotheses')) {
1473
+ hasPrefDb = true;
1474
+ sawPrefHypotheses = true;
1475
+ prefHypothesesTotal += countQuery(db, 'SELECT COUNT(*) AS n FROM preference_hypotheses');
1476
+ if (hasColumn(db, 'preference_hypotheses', 'effect_state')) {
1477
+ const activeCount = countQuery(db, "SELECT COUNT(*) AS n FROM preference_hypotheses WHERE effect_state = 'active'");
1478
+ activePreferenceOverlays = addMetric(activePreferenceOverlays, activeCount);
1479
+ prefHypothesesActiveFallback += activeCount;
1480
+ prefHypothesesRolledBackFallback += countQuery(db, "SELECT COUNT(*) AS n FROM preference_hypotheses WHERE effect_state = 'rolled-back'");
1481
+ }
1482
+ }
1483
+ if (hasTable(db, 'preference_transitions') && hasColumn(db, 'preference_transitions', 'reason')) {
1484
+ hasPrefDb = true;
1485
+ sawPrefTransitions = true;
1486
+ prefTransitionsCreated += countQuery(db, "SELECT COUNT(*) AS n FROM preference_transitions WHERE reason = 'created'");
1487
+ prefTransitionsActivated += countQuery(db, "SELECT COUNT(*) AS n FROM preference_transitions WHERE reason = 'activated'");
1488
+ prefTransitionsRolledBack += countQuery(db, "SELECT COUNT(*) AS n FROM preference_transitions WHERE reason IN ('regression', 'operator-request')");
1489
+ }
1490
+ // Memory learning jobs
1491
+ if (hasTable(db, 'jobs')) {
1492
+ hasMemoryLearningDb = true;
1493
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM jobs'));
1494
+ if (hasColumn(db, 'jobs', 'state')) {
1495
+ candidatesAdopted = addMetric(candidatesAdopted, countQuery(db, "SELECT COUNT(*) AS n FROM jobs WHERE state = 'adopted'"));
1496
+ }
1497
+ }
1498
+ // Growth experiments / workflows
1499
+ if (hasTable(db, 'workflow_candidates')) {
1500
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM workflow_candidates'));
1501
+ if (hasColumn(db, 'workflow_candidates', 'state')) {
1502
+ const promoted = countQuery(db, "SELECT COUNT(*) AS n FROM workflow_candidates WHERE state = 'promoted'");
1503
+ workflowCandidatesPromoted = addMetric(workflowCandidatesPromoted, promoted);
1504
+ candidatesAdopted = addMetric(candidatesAdopted, promoted);
1505
+ rollbacks = addMetric(rollbacks, countQuery(db, "SELECT COUNT(*) AS n FROM workflow_candidates WHERE state = 'rolled-back'"));
1506
+ }
1507
+ }
1508
+ // Skills
1509
+ if (hasTable(db, 'skill_candidates')) {
1510
+ candidatesGenerated = addMetric(candidatesGenerated, countQuery(db, 'SELECT COUNT(*) AS n FROM skill_candidates'));
1511
+ }
1512
+ if (hasTable(db, 'skill_deployments') && hasColumn(db, 'skill_deployments', 'state')) {
1513
+ const deployed = countQuery(db, "SELECT COUNT(*) AS n FROM skill_deployments WHERE state IN ('canary', 'promoted')");
1514
+ skillDeployments = addMetric(skillDeployments, deployed);
1515
+ candidatesAdopted = addMetric(candidatesAdopted, deployed);
1516
+ rollbacks = addMetric(rollbacks, countQuery(db, "SELECT COUNT(*) AS n FROM skill_deployments WHERE state IN ('rolled-back', 'revoked')"));
1517
+ }
1518
+ });
1519
+ }
1520
+ // Finalize preference aggregates
1521
+ if (sawPrefHypotheses) {
1522
+ candidatesGenerated = addMetric(candidatesGenerated, prefHypothesesTotal);
1523
+ }
1524
+ else if (sawPrefTransitions) {
1525
+ candidatesGenerated = addMetric(candidatesGenerated, prefTransitionsCreated);
1526
+ }
1527
+ if (sawPrefTransitions) {
1528
+ candidatesAdopted = addMetric(candidatesAdopted, prefTransitionsActivated);
1529
+ rollbacks = addMetric(rollbacks, prefTransitionsRolledBack);
1530
+ }
1531
+ else if (sawPrefHypotheses) {
1532
+ candidatesAdopted = addMetric(candidatesAdopted, prefHypothesesActiveFallback);
1533
+ rollbacks = addMetric(rollbacks, prefHypothesesRolledBackFallback);
1534
+ }
1535
+ // Finalize control-plane Passes 0 -> A -> B -> C
1536
+ const normalizePlanId = (id) => sourceIdToActivationId.get(id) ?? id;
1537
+ if (revisedPlanIds.size > 0) {
1538
+ const normalizedRev = new Set();
1539
+ for (const pid of revisedPlanIds)
1540
+ normalizedRev.add(normalizePlanId(pid));
1541
+ revisedPlanIds.clear();
1542
+ for (const pid of normalizedRev)
1543
+ revisedPlanIds.add(pid);
1544
+ }
1545
+ if (controlAdoptedPlanIds.size > 0) {
1546
+ const normalizedCtrl = new Set();
1547
+ for (const pid of controlAdoptedPlanIds)
1548
+ normalizedCtrl.add(normalizePlanId(pid));
1549
+ controlAdoptedPlanIds.clear();
1550
+ for (const pid of normalizedCtrl)
1551
+ controlAdoptedPlanIds.add(pid);
1552
+ }
1553
+ // Pass A: creation-adoptions
1554
+ for (const row of bufferedCreations) {
1555
+ let cert = {};
1556
+ if (typeof row.certificateJson === 'string' && row.certificateJson !== '') {
1557
+ try {
1558
+ cert = rec(JSON.parse(row.certificateJson));
1559
+ }
1560
+ catch {
1561
+ cert = {};
1562
+ }
1563
+ }
1564
+ const plan = rec(cert['plan']);
1565
+ let receipt = {};
1566
+ if (typeof row.receiptJson === 'string' && row.receiptJson !== '') {
1567
+ try {
1568
+ receipt = rec(JSON.parse(row.receiptJson));
1569
+ }
1570
+ catch {
1571
+ receipt = {};
1572
+ }
1573
+ }
1574
+ const capName = textOrNull(plan['name'])
1575
+ ?? textOrNull(cert['packageName'])
1576
+ ?? textOrNull(cert['pluginName'])
1577
+ ?? textOrNull(cert['name'])
1578
+ ?? row.planId;
1579
+ const capVer = textOrNull(receipt['version'])
1580
+ ?? textOrNull(plan['version'])
1581
+ ?? textOrNull(cert['version'])
1582
+ ?? textOrNull(cert['pluginVersion']);
1583
+ const entry = upsertEvolved(capName, {
1584
+ version: capVer,
1585
+ versionTier: capVer !== null ? 1 : 0,
1586
+ fromAdoptionJournal: true,
1587
+ enabled: row.status === 'active',
1588
+ });
1589
+ const canonicalId = normalizePlanId(row.planId);
1590
+ if (entry) {
1591
+ evolvedByPlanId.set(row.planId, entry);
1592
+ evolvedByPlanId.set(canonicalId, entry);
1593
+ }
1594
+ if (row.status === 'active' || row.status === 'authorized') {
1595
+ createdPlanIds.add(canonicalId);
1596
+ controlAdoptedPlanIds.add(canonicalId);
1597
+ }
1598
+ }
1599
+ // Pass B: revision-adoptions entries
1600
+ for (const revDb of bufferedRevisions) {
1601
+ for (const er of revDb.entries) {
1602
+ const currentStatus = er.currentPlanId ? revDb.adoptionStatusByPlan.get(er.currentPlanId) : undefined;
1603
+ const revVersion = er.revision !== undefined ? `v${er.revision}` : null;
1604
+ const parentEntry = er.parentPlanId
1605
+ ? (evolvedByPlanId.get(normalizePlanId(er.parentPlanId)) ?? evolvedByPlanId.get(er.parentPlanId))
1606
+ : undefined;
1607
+ if (parentEntry) {
1608
+ upsertEvolved(parentEntry.name, {
1609
+ version: revVersion,
1610
+ versionTier: revVersion !== null ? 2 : 0,
1611
+ fromAdoptionJournal: true,
1612
+ enabled: currentStatus === 'active',
1613
+ });
1614
+ }
1615
+ else {
1616
+ const rawName = textOrNull(er.name)
1617
+ ?? er.parentPlanId
1618
+ ?? er.entryId
1619
+ ?? 'evolved-capability';
1620
+ upsertEvolved(rawName, {
1621
+ version: revVersion,
1622
+ versionTier: revVersion !== null ? 2 : 0,
1623
+ fromAdoptionJournal: true,
1624
+ enabled: currentStatus === 'active',
1625
+ });
1626
+ }
1627
+ }
1628
+ }
1629
+ // Pass C: control.sqlite (activation_watch -> source_plans -> activation_plans)
1630
+ for (const w of bufferedWatches) {
1631
+ if (w.state === '' || w.state === 'watching') {
1632
+ upsertEvolved(w.packageName, {
1633
+ version: w.packageVersion,
1634
+ versionTier: w.packageVersion !== null ? 1 : 0,
1635
+ enabled: w.state === 'watching',
1636
+ });
1637
+ }
1638
+ }
1639
+ for (const sp of bufferedSourcePlans) {
1640
+ if (sp.status === 'release-complete') {
1641
+ const canonicalId = normalizePlanId(sp.id);
1642
+ controlAdoptedPlanIds.add(canonicalId);
1643
+ if (sp.mode === 'modify' || sp.mode === 'prepared-revise') {
1644
+ revisedPlanIds.add(canonicalId);
1645
+ }
1646
+ else {
1647
+ createdPlanIds.add(canonicalId);
1648
+ const pkgName = textOrNull(sp.pluginName);
1649
+ if (pkgName) {
1650
+ upsertEvolved(pkgName, {
1651
+ version: null,
1652
+ versionTier: 0,
1653
+ enabled: activatedActIds.has(canonicalId),
1654
+ });
1655
+ }
1656
+ }
1657
+ }
1658
+ }
1659
+ const sourceModeByActivationId = new Map();
1660
+ for (const [srcId, actId] of sourceIdToActivationId) {
1661
+ if (sourceModeById.has(srcId)) {
1662
+ sourceModeByActivationId.set(actId, sourceModeById.get(srcId) ?? null);
1663
+ }
1664
+ }
1665
+ let unlinkedApCount = 0;
1666
+ let rollbackApCount = 0;
1667
+ for (const act of bufferedActivationPlans) {
1668
+ if (!linkedActivationIds.has(act.id) && !sourcePlanIds.has(act.id)) {
1669
+ unlinkedApCount += 1;
1670
+ }
1671
+ if (act.status === 'activated') {
1672
+ controlAdoptedPlanIds.add(act.id);
1673
+ }
1674
+ if (act.status === 'rolled-back' || act.status === 'rollback-pending') {
1675
+ rollbackApCount += 1;
1676
+ }
1677
+ const linkedMode = sourceModeByActivationId.get(act.id);
1678
+ if (linkedMode === 'modify' || linkedMode === 'prepared-revise') {
1679
+ continue;
1680
+ }
1681
+ let candidate = {};
1682
+ if (typeof act.candidateJson === 'string' && act.candidateJson !== '') {
1683
+ try {
1684
+ candidate = rec(JSON.parse(act.candidateJson));
1685
+ }
1686
+ catch {
1687
+ candidate = {};
1688
+ }
1689
+ }
1690
+ const pkgName = textOrNull(candidate['package']) ?? textOrNull(candidate['name']);
1691
+ if (!pkgName)
1692
+ continue;
1693
+ const pkgVer = textOrNull(candidate['version']);
1694
+ const patchDisabled = targetProfiles.length > 0
1695
+ && targetProfiles.every(p => {
1696
+ const ps = patchStatesByProfile.get(p)?.get(pkgName);
1697
+ return ps?.disabled === true || ps?.configEnabled === false;
1698
+ });
1699
+ const enabled = act.status === 'activated' && !watchClosedByPlan.has(act.id) && !patchDisabled;
1700
+ const boundedPkgName = boundNonEmptyString(pkgName, 200);
1701
+ if (!boundedPkgName)
1702
+ continue;
1703
+ const key = normalizePluginKey(boundedPkgName);
1704
+ const existing = evolvedMap.get(key);
1705
+ evolvedMap.set(key, {
1706
+ name: boundedPkgName,
1707
+ version: pkgVer ?? existing?.version ?? null,
1708
+ versionTier: pkgVer !== null ? 1 : (existing?.versionTier ?? 0),
1709
+ fromAdoptionJournal: existing?.fromAdoptionJournal ?? false,
1710
+ kind: 'evolved',
1711
+ installKind: 'adopted',
1712
+ enabled,
1713
+ });
1714
+ }
1715
+ if (sawActivationPlansTable) {
1716
+ candidatesGenerated = addMetric(candidatesGenerated, unlinkedApCount);
1717
+ rollbacks = addMetric(rollbacks, rollbackApCount);
1718
+ }
1719
+ if (sawCreatedSource)
1720
+ pluginsCreated = createdPlanIds.size;
1721
+ if (sawRevisedSource)
1722
+ pluginsRevised = revisedPlanIds.size;
1723
+ if (sawControlAdoptionSource) {
1724
+ candidatesAdopted = addMetric(candidatesAdopted, controlAdoptedPlanIds.size);
1725
+ }
1726
+ // Upgrade history & backup snapshots
1727
+ if (boundary.dshHome && boundary.canonicalDshHome && !boundary.homeUnsafe) {
1728
+ const upgradeHistoryPath = join(boundary.dshHome, '.dsh-ray', 'upgrade-history.jsonl');
1729
+ const historyText = readBoundedRegularFile(upgradeHistoryPath, boundary, MAX_UPGRADE_HISTORY_BYTES);
1730
+ if (historyText !== undefined) {
1731
+ let upgradeCount = 0;
1732
+ for (const line of historyText.split(/\r?\n/u)) {
1733
+ const trimmed = line.trim();
1734
+ if (trimmed === '')
1735
+ continue;
1736
+ try {
1737
+ const parsed = JSON.parse(trimmed);
1738
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
1739
+ upgradeCount += 1;
1740
+ }
1741
+ catch {
1742
+ // Ignore trailing/corrupt line in JSONL without crashing.
1743
+ }
1744
+ }
1745
+ selfUpgrades = upgradeCount;
1746
+ }
1747
+ const backupDir = join(boundary.dshHome, '.dsh-ray-upgrade-backups');
1748
+ if (existsSync(backupDir)) {
1749
+ try {
1750
+ const st = lstatSync(backupDir);
1751
+ if (st.isDirectory() && !st.isSymbolicLink()) {
1752
+ const realBackupDir = realpathSync(backupDir);
1753
+ if (realBackupDir.startsWith(`${boundary.canonicalDshHome}${sep}`)) {
1754
+ let count = 0;
1755
+ for (const entry of readdirSync(realBackupDir, { withFileTypes: true })) {
1756
+ if (!entry.name.startsWith('.') && entry.isDirectory() && !entry.isSymbolicLink())
1757
+ count += 1;
1758
+ }
1759
+ backupSnapshotsCount = count;
1760
+ }
1761
+ }
1762
+ }
1763
+ catch {
1764
+ // Ignore unreadable backup dir.
1765
+ }
1766
+ }
1767
+ }
1768
+ // Cordis health() fallbacks when SQLite ledgers are absent or :memory:
1769
+ const [workItemsHealth, growthDriverHealth, dreamingHealth, recoveryHealth, goalsHealth, controlPlaneHealth, verifierHealth, evolutionHealth, memoryHealth, prefHealth, memoryLearningHealth, growthExpHealth,] = await Promise.all([
1770
+ workItemsTotal === null ? callHealthSyncOrAsync(ctx.get('assistantWorkItems')) : Promise.resolve(undefined),
1771
+ growthUsageJobsTotal === null ? callHealthSyncOrAsync(ctx.get('assistantGrowthDriver')) : Promise.resolve(undefined),
1772
+ dreamingRuns === null ? callHealthSyncOrAsync(ctx.get('assistantDreaming')) : Promise.resolve(undefined),
1773
+ recoveryRuns === null ? callHealthSyncOrAsync(ctx.get('assistantRecovery')) : Promise.resolve(undefined),
1774
+ goalStrategyRuns === null ? callHealthSyncOrAsync(ctx.get('assistantGoals')) : Promise.resolve(undefined),
1775
+ (!hasCpActivationDb) ? callHealthSyncOrAsync(ctx.get('pluginControlPlane')) : Promise.resolve(undefined),
1776
+ taskVerificationsDone === null ? callHealthSyncOrAsync(ctx.get('assistantVerifier')) : Promise.resolve(undefined),
1777
+ (!hasEvoProposalsDb || !hasEvoRulesDb || !hasEvoRollbacksDb) ? callHealthSyncOrAsync(ctx.get('assistantEvolution')) : Promise.resolve(undefined),
1778
+ activeMemories === null ? callHealthSyncOrAsync(ctx.get('personalMemory')) : Promise.resolve(undefined),
1779
+ (!hasPrefDb) ? callHealthSyncOrAsync(ctx.get('assistantPreferenceLearning')) : Promise.resolve(undefined),
1780
+ (!hasMemoryLearningDb) ? callHealthSyncOrAsync(ctx.get('assistantMemoryLearning')) : Promise.resolve(undefined),
1781
+ workflowCandidatesPromoted === null ? callHealthSyncOrAsync(ctx.get('assistantGrowthExperiments')) : Promise.resolve(undefined),
1782
+ ]);
1783
+ if (workItemsTotal === null && workItemsHealth) {
1784
+ const open = nonNegIntOrNull(workItemsHealth['openItems']);
1785
+ if (open !== null)
1786
+ workItemsTotal = open;
1787
+ }
1788
+ if (growthUsageJobsTotal === null && growthDriverHealth) {
1789
+ const pending = nonNegIntOrNull(growthDriverHealth['usagePending']) ?? 0;
1790
+ const running = nonNegIntOrNull(growthDriverHealth['usageRunning']) ?? 0;
1791
+ const failed = nonNegIntOrNull(growthDriverHealth['usageFailed']) ?? 0;
1792
+ const unknown = nonNegIntOrNull(growthDriverHealth['usageUnknown']) ?? 0;
1793
+ if ('usagePending' in growthDriverHealth || 'usageEnabled' in growthDriverHealth) {
1794
+ growthUsageJobsTotal = pending + running + failed + unknown;
1795
+ }
1796
+ }
1797
+ if (dreamingRuns === null && dreamingHealth) {
1798
+ const runs = nonNegIntOrNull(dreamingHealth['runs']);
1799
+ if (runs !== null)
1800
+ dreamingRuns = runs;
1801
+ }
1802
+ if (recoveryRuns === null && recoveryHealth) {
1803
+ const running = nonNegIntOrNull(recoveryHealth['runningRuns']) ?? 0;
1804
+ const failed = nonNegIntOrNull(recoveryHealth['failedRuns']) ?? 0;
1805
+ const unknown = nonNegIntOrNull(recoveryHealth['unknownRuns']) ?? 0;
1806
+ if ('runningRuns' in recoveryHealth)
1807
+ recoveryRuns = running + failed + unknown;
1808
+ }
1809
+ if (goalStrategyRuns === null && goalsHealth && goalsHealth['ready'] === true) {
1810
+ goalStrategyRuns = 0;
1811
+ }
1812
+ if (controlPlaneHealth && !hasCpActivationDb) {
1813
+ const activeActivations = nonNegIntOrNull(controlPlaneHealth['activeActivations']);
1814
+ if (activeActivations !== null)
1815
+ candidatesAdopted = addMetric(candidatesAdopted, activeActivations);
1816
+ const rollbackPending = nonNegIntOrNull(controlPlaneHealth['rollbackPending']);
1817
+ if (rollbackPending !== null)
1818
+ rollbacks = addMetric(rollbacks, rollbackPending);
1819
+ }
1820
+ if (taskVerificationsDone === null && verifierHealth && verifierHealth['ready'] === true) {
1821
+ taskVerificationsDone = 0;
1822
+ }
1823
+ if (evolutionHealth) {
1824
+ if (!hasEvoRulesDb) {
1825
+ const activeRules = nonNegIntOrNull(evolutionHealth['activeRules']);
1826
+ const retiredRules = nonNegIntOrNull(evolutionHealth['retiredRules']);
1827
+ if (activeRules !== null || retiredRules !== null) {
1828
+ const adoptedRules = (activeRules ?? 0) + (retiredRules ?? 0);
1829
+ evolutionRulesAdopted = addMetric(evolutionRulesAdopted, adoptedRules);
1830
+ candidatesAdopted = addMetric(candidatesAdopted, adoptedRules);
1831
+ }
1832
+ }
1833
+ if (!hasEvoProposalsDb) {
1834
+ const pendingProposals = nonNegIntOrNull(evolutionHealth['pendingProposals']);
1835
+ if (pendingProposals !== null)
1836
+ candidatesGenerated = addMetric(candidatesGenerated, pendingProposals);
1837
+ }
1838
+ if (!hasEvoRollbacksDb) {
1839
+ const autoRollbacks = nonNegIntOrNull(evolutionHealth['autonomousRollbacks']);
1840
+ if (autoRollbacks !== null)
1841
+ rollbacks = addMetric(rollbacks, autoRollbacks);
1842
+ }
1843
+ }
1844
+ if (activeMemories === null && memoryHealth) {
1845
+ const activeRecords = nonNegIntOrNull(memoryHealth['activeRecords']);
1846
+ if (activeRecords !== null)
1847
+ activeMemories = activeRecords;
1848
+ }
1849
+ if (prefHealth && !hasPrefDb) {
1850
+ const active = nonNegIntOrNull(prefHealth['active']);
1851
+ if (active !== null)
1852
+ activePreferenceOverlays = addMetric(activePreferenceOverlays, active);
1853
+ const hypotheses = nonNegIntOrNull(prefHealth['hypotheses']);
1854
+ if (hypotheses !== null)
1855
+ candidatesGenerated = addMetric(candidatesGenerated, hypotheses);
1856
+ const rolledBack = nonNegIntOrNull(prefHealth['rolledBack']);
1857
+ if (rolledBack !== null)
1858
+ rollbacks = addMetric(rollbacks, rolledBack);
1859
+ }
1860
+ if (!hasMemoryLearningDb && memoryLearningHealth) {
1861
+ const adopted = nonNegIntOrNull(memoryLearningHealth['adopted']);
1862
+ if (adopted !== null)
1863
+ candidatesAdopted = addMetric(candidatesAdopted, adopted);
1864
+ }
1865
+ if (workflowCandidatesPromoted === null && growthExpHealth) {
1866
+ const promoted = nonNegIntOrNull(growthExpHealth['promoted']);
1867
+ if (promoted !== null)
1868
+ workflowCandidatesPromoted = promoted;
1869
+ }
1870
+ // Plugin inventory: pluginManager.listBundles -> loader.entries -> node_modules (Tier 3 fallback)
1871
+ let runtimePluginSourceUsed = false;
1872
+ const pluginManager = ctx.get('pluginManager');
1873
+ if (typeof pluginManager?.listBundles === 'function') {
1874
+ try {
1875
+ const bundles = await pluginManager.listBundles();
1876
+ pluginSourceAvailable = true;
1877
+ runtimePluginSourceUsed = true;
1878
+ for (const bundle of bundles) {
1879
+ const pkgName = textOrNull(bundle.name);
1880
+ if (!pkgName || !pkgName.startsWith('@dsh-ray/'))
1881
+ continue;
1882
+ if (bundle.error?.code === 'not-bundle')
1883
+ continue;
1884
+ const boundedName = boundNonEmptyString(pkgName, 200);
1885
+ if (!boundedName)
1886
+ continue;
1887
+ const boundedVer = boundNonEmptyString(bundle.version, 128) ?? null;
1888
+ const key = normalizePluginKey(boundedName);
1889
+ const existingEvolved = evolvedMap.get(key);
1890
+ if (existingEvolved) {
1891
+ existingEvolved.name = boundedName;
1892
+ if (boundedVer !== null && (existingEvolved.version === null || /^v\d+$/u.test(existingEvolved.version))) {
1893
+ existingEvolved.version = boundedVer;
1894
+ existingEvolved.versionTier = 3;
1895
+ }
1896
+ existingEvolved.enabled = Boolean(bundle.enabled);
1897
+ continue;
1898
+ }
1899
+ if (coreByKey.has(key))
1900
+ continue;
1901
+ coreByKey.set(key, {
1902
+ name: boundedName,
1903
+ version: boundedVer,
1904
+ installKind: 'npm',
1905
+ enabledStates: [Boolean(bundle.enabled)],
1906
+ });
1907
+ }
1908
+ }
1909
+ catch {
1910
+ diagnostics.push('pluginManager.listBundles failed');
1911
+ }
1912
+ }
1913
+ const loader = ctx.get('loader');
1914
+ if (typeof loader?.entries === 'function') {
1915
+ try {
1916
+ pluginSourceAvailable = true;
1917
+ runtimePluginSourceUsed = true;
1918
+ for (const entry of loader.entries()) {
1919
+ const pkgName = textOrNull(entry.options?.name);
1920
+ if (!pkgName || !pkgName.startsWith('@dsh-ray/'))
1921
+ continue;
1922
+ const boundedName = boundNonEmptyString(pkgName, 200);
1923
+ if (!boundedName)
1924
+ continue;
1925
+ const key = normalizePluginKey(boundedName);
1926
+ const enabled = !(entry.disabled === true || entry.options?.disabled === true);
1927
+ const existingEvolved = evolvedMap.get(key);
1928
+ if (existingEvolved) {
1929
+ existingEvolved.name = boundedName;
1930
+ existingEvolved.enabled = enabled;
1931
+ continue;
1932
+ }
1933
+ const existingCore = coreByKey.get(key);
1934
+ if (existingCore) {
1935
+ existingCore.enabledStates = [enabled];
1936
+ }
1937
+ else {
1938
+ coreByKey.set(key, {
1939
+ name: boundedName,
1940
+ version: null,
1941
+ installKind: 'local',
1942
+ enabledStates: [enabled],
1943
+ });
1944
+ }
1945
+ }
1946
+ }
1947
+ catch {
1948
+ diagnostics.push('loader.entries failed');
1949
+ }
1950
+ }
1951
+ if (boundary.dshHome && !boundary.homeUnsafe) {
1952
+ const nmDirs = [
1953
+ { dir: join(boundary.dshHome, 'node_modules'), profName: null },
1954
+ ...targetProfiles.map(prof => ({
1955
+ dir: join(boundary.dshHome, 'profiles', prof, 'node_modules'),
1956
+ profName: prof,
1957
+ })),
1958
+ ];
1959
+ for (const { dir: nmDir, profName } of nmDirs) {
1960
+ const found = readNodeModulesPackages(nmDir, boundary);
1961
+ if (found.size > 0)
1962
+ pluginSourceAvailable = true;
1963
+ const profPatchStates = profName ? patchStatesByProfile.get(profName) : undefined;
1964
+ for (const [pkgName, info] of found) {
1965
+ const boundedName = boundNonEmptyString(pkgName, 200);
1966
+ if (!boundedName)
1967
+ continue;
1968
+ const key = normalizePluginKey(boundedName);
1969
+ const diskVer = boundNonEmptyString(info.version, 128) ?? null;
1970
+ const existingEvolved = evolvedMap.get(key);
1971
+ if (existingEvolved) {
1972
+ existingEvolved.name = boundedName;
1973
+ if (diskVer !== null && (existingEvolved.version === null || /^v\d+$/u.test(existingEvolved.version))) {
1974
+ existingEvolved.version = diskVer;
1975
+ existingEvolved.versionTier = 3;
1976
+ }
1977
+ continue;
1978
+ }
1979
+ const ps = profPatchStates?.get(pkgName);
1980
+ const yamlEnabledVal = ps !== undefined
1981
+ ? !(ps.disabled || ps.configEnabled === false)
1982
+ : undefined;
1983
+ const existingCore = coreByKey.get(key);
1984
+ if (existingCore) {
1985
+ if (existingCore.version === null && diskVer !== null)
1986
+ existingCore.version = diskVer;
1987
+ if (info.installKind === 'npm' && existingCore.installKind === 'local' && runtimePluginSourceUsed) {
1988
+ existingCore.installKind = 'npm';
1989
+ }
1990
+ else if (info.installKind === 'local') {
1991
+ existingCore.installKind = 'local';
1992
+ }
1993
+ if (!runtimePluginSourceUsed)
1994
+ existingCore.enabledStates.push(yamlEnabledVal);
1995
+ }
1996
+ else {
1997
+ coreByKey.set(key, {
1998
+ name: boundedName,
1999
+ version: diskVer,
2000
+ installKind: info.installKind,
2001
+ enabledStates: runtimePluginSourceUsed ? [] : [yamlEnabledVal],
2002
+ });
2003
+ }
2004
+ }
2005
+ }
2006
+ }
2007
+ // Finalize plugin partition
2008
+ const corePlugins = [...coreByKey.values()]
2009
+ .map((entry) => {
2010
+ const boundedName = boundNonEmptyString(entry.name, 200);
2011
+ if (boundedName === undefined)
2012
+ return undefined;
2013
+ const boundedVer = entry.version === null ? null : boundNonEmptyString(entry.version, 128) ?? null;
2014
+ const defined = entry.enabledStates.filter((v) => v !== undefined);
2015
+ const enabled = defined.length > 0 ? defined.some(Boolean) : undefined;
2016
+ return {
2017
+ name: boundedName,
2018
+ version: boundedVer,
2019
+ kind: 'core',
2020
+ ...(entry.installKind === undefined ? {} : { installKind: entry.installKind }),
2021
+ ...(enabled === undefined ? {} : { enabled }),
2022
+ };
2023
+ })
2024
+ .filter((entry) => entry !== undefined)
2025
+ .sort((a, b) => a.name.localeCompare(b.name));
2026
+ const evolvedPlugins = [...evolvedMap.values()]
2027
+ .map((entry) => {
2028
+ const boundedName = boundNonEmptyString(entry.name, 200);
2029
+ if (boundedName === undefined)
2030
+ return undefined;
2031
+ const rawVer = entry.version === null && entry.fromAdoptionJournal ? 'v1' : entry.version;
2032
+ const boundedVer = rawVer === null ? null : boundNonEmptyString(rawVer, 128) ?? null;
2033
+ return {
2034
+ name: boundedName,
2035
+ version: boundedVer,
2036
+ kind: 'evolved',
2037
+ installKind: 'adopted',
2038
+ ...(entry.enabled === undefined ? {} : { enabled: entry.enabled }),
2039
+ };
2040
+ })
2041
+ .filter((entry) => entry !== undefined)
2042
+ .sort((a, b) => a.name.localeCompare(b.name));
2043
+ const activeEvolvedCount = evolvedPlugins.filter(entry => entry.enabled === true).length;
2044
+ const pluginsState = corePlugins.length > 0 || evolvedPlugins.length > 0
2045
+ ? 'ok'
2046
+ : (pluginSourceAvailable || boundary.profiles.length > 0 || sawControlPlaneDb)
2047
+ ? 'zero'
2048
+ : 'unavailable';
2049
+ const numericMetrics = [
2050
+ workItemsTotal,
2051
+ workItemsSettled,
2052
+ growthUsageJobsTotal,
2053
+ dreamingRuns,
2054
+ recoveryRuns,
2055
+ goalStrategyRuns,
2056
+ candidatesGenerated,
2057
+ candidatesAdopted,
2058
+ pluginsCreated,
2059
+ pluginsRevised,
2060
+ taskVerificationsDone,
2061
+ rollbacks,
2062
+ evolutionRulesAdopted,
2063
+ associationParamVersion,
2064
+ associationProfileAdoptions,
2065
+ evaluationAttentionTuningAdoptions,
2066
+ evaluationLooseningDecisionsAdopted,
2067
+ activeMemories,
2068
+ activePreferenceOverlays,
2069
+ workflowCandidatesPromoted,
2070
+ skillDeployments,
2071
+ selfUpgrades,
2072
+ backupSnapshotsCount,
2073
+ ];
2074
+ const hasAnySource = numericMetrics.some(value => value !== null);
2075
+ const hasNonZero = numericMetrics.some(value => value !== null && value > 0);
2076
+ const dataState = !hasAnySource
2077
+ ? 'no-data'
2078
+ : (hasNonZero ? 'data' : 'zero');
2079
+ const iterationDriversSum = (workItemsTotal ?? 0)
2080
+ + (growthUsageJobsTotal ?? 0)
2081
+ + (dreamingRuns ?? 0)
2082
+ + (recoveryRuns ?? 0)
2083
+ + (goalStrategyRuns ?? 0)
2084
+ + (evolutionRulesAdopted ?? 0)
2085
+ + (associationProfileAdoptions ?? 0)
2086
+ + (evaluationAttentionTuningAdoptions ?? 0)
2087
+ + (evaluationLooseningDecisionsAdopted ?? 0)
2088
+ + (selfUpgrades ?? 0);
2089
+ const totalIterations = dataState === 'no-data'
2090
+ ? null
2091
+ : iterationDriversSum > 0
2092
+ ? iterationDriversSum
2093
+ : dataState === 'data'
2094
+ ? Math.max(candidatesGenerated ?? 0, candidatesAdopted ?? 0, pluginsCreated ?? 0, pluginsRevised ?? 0, activeMemories ?? 0, activePreferenceOverlays ?? 0, workflowCandidatesPromoted ?? 0, skillDeployments ?? 0, taskVerificationsDone ?? 0, 1)
2095
+ : 0;
2096
+ const boundedDshHome = boundary.dshHome === null
2097
+ ? undefined
2098
+ : truncateText(boundary.canonicalDshHome ?? boundary.dshHome, 4_096);
2099
+ const boundedAssistantVersion = boundNonEmptyString(assistantVersion, 128) ?? '0.0.0';
2100
+ const boundedBoundVersion = boundNonEmptyString(hostMeta.boundVersion, 128) ?? null;
2101
+ const boundedBoundStatus = boundNonEmptyString(hostMeta.boundStatus, 64) ?? 'unknown';
2102
+ const boundedRunningVersion = boundNonEmptyString(runningVersion, 128) ?? null;
2103
+ const boundedProfile = boundNonEmptyString(boundary.profile, 128);
2104
+ const boundedProfiles = boundary.profiles
2105
+ .map(p => boundNonEmptyString(p, 128))
2106
+ .filter((p) => p !== undefined)
2107
+ .slice(0, 64);
2108
+ const boundedInspectedLedgers = [...new Set(inspectedLedgers)]
2109
+ .sort()
2110
+ .map(entry => boundNonEmptyString(entry, 4_096))
2111
+ .filter((entry) => entry !== undefined)
2112
+ .slice(0, 256);
2113
+ const boundedDiagnostics = diagnostics
2114
+ .map(entry => boundNonEmptyString(entry, 1_024))
2115
+ .filter((entry) => entry !== undefined)
2116
+ .slice(0, 128);
2117
+ return {
2118
+ schemaVersion: 1,
2119
+ protocol: 'dsh-ray/version/v1',
2120
+ generatedAt,
2121
+ ...(boundedDshHome === undefined ? {} : { dshHome: boundedDshHome }),
2122
+ assistant: {
2123
+ name: 'dsh-ray',
2124
+ version: boundedAssistantVersion,
2125
+ },
2126
+ host: {
2127
+ packageName: '@deepseek-ai/dsh',
2128
+ boundVersion: boundedBoundVersion,
2129
+ boundStatus: boundedBoundStatus,
2130
+ runningVersion: boundedRunningVersion,
2131
+ },
2132
+ ...(boundedProfile === undefined ? {} : { profile: boundedProfile }),
2133
+ ...(boundedProfiles.length === 0 ? {} : { profiles: boundedProfiles }),
2134
+ plugins: {
2135
+ state: pluginsState,
2136
+ coreCount: corePlugins.length,
2137
+ evolvedCount: evolvedPlugins.length,
2138
+ activeEvolvedCount,
2139
+ core: corePlugins.slice(0, 256),
2140
+ evolved: evolvedPlugins.slice(0, 256),
2141
+ },
2142
+ selfIteration: {
2143
+ dataState,
2144
+ totalIterations,
2145
+ workItemsTotal,
2146
+ workItemsSettled,
2147
+ growthUsageJobsTotal,
2148
+ dreamingRuns,
2149
+ recoveryRuns,
2150
+ goalStrategyRuns,
2151
+ candidatesGenerated,
2152
+ candidatesAdopted,
2153
+ pluginsCreated,
2154
+ pluginsRevised,
2155
+ taskVerificationsDone,
2156
+ rollbacks,
2157
+ evolutionRulesAdopted,
2158
+ associationParamVersion,
2159
+ associationProfileAdoptions,
2160
+ evaluationAttentionTuningAdoptions,
2161
+ evaluationLooseningDecisionsAdopted,
2162
+ activeMemories,
2163
+ activePreferenceOverlays,
2164
+ workflowCandidatesPromoted,
2165
+ skillDeployments,
2166
+ selfUpgrades,
2167
+ backupSnapshotsCount,
2168
+ },
2169
+ ...(boundedInspectedLedgers.length === 0 ? {} : { inspectedLedgers: boundedInspectedLedgers }),
2170
+ ...(boundedDiagnostics.length === 0 ? {} : { diagnostics: boundedDiagnostics }),
2171
+ };
2172
+ }
2173
+ function fmtCount(value) {
2174
+ return value === null ? '无数据' : String(value);
2175
+ }
2176
+ export function formatAssistantVersionSummary(report) {
2177
+ const s = report.selfIteration;
2178
+ const lines = [
2179
+ `助手版本:${report.assistant.name} v${report.assistant.version}`
2180
+ + (report.assistant.cliVersion ? `(CLI v${report.assistant.cliVersion})` : ''),
2181
+ `Host(${report.host.packageName}):运行 ${report.host.runningVersion ?? '未知'};绑定 ${report.host.boundVersion ?? '未绑定'}(${report.host.boundStatus})`,
2182
+ ];
2183
+ if (report.profile !== undefined && report.profile !== null) {
2184
+ lines.push(`当前 Profile:${report.profile}`
2185
+ + (report.profiles && report.profiles.length > 0 ? `(全部:${report.profiles.join(', ')})` : ''));
2186
+ }
2187
+ if (report.plugins.state === 'unavailable') {
2188
+ lines.push('插件概览:暂无插件目录信息');
2189
+ }
2190
+ else {
2191
+ lines.push(`插件概览:核心插件 ${report.plugins.coreCount} 个;自演进插件 ${report.plugins.evolvedCount} 个(启用 ${report.plugins.activeEvolvedCount} 个)`);
2192
+ if (report.plugins.evolved.length > 0) {
2193
+ const preview = report.plugins.evolved
2194
+ .slice(0, 8)
2195
+ .map(p => `${p.name}${p.version ? `@${p.version}` : ''}`)
2196
+ .join('、');
2197
+ lines.push(`自演进插件列表:${preview}${report.plugins.evolved.length > 8 ? ' 等' : ''}`);
2198
+ }
2199
+ }
2200
+ if (s.dataState === 'no-data') {
2201
+ lines.push('自迭代演进统计:无数据(未检测到已初始化的账本或运行记录)');
2202
+ }
2203
+ else {
2204
+ lines.push(`自迭代演进统计(${s.dataState === 'zero' ? '暂无记录' : '已采集'}):`, `- 累计自迭代次数:${fmtCount(s.totalIterations)}`, `- 工作项(总计 / 已结算):${fmtCount(s.workItemsTotal)} / ${fmtCount(s.workItemsSettled)};用法学习任务:${fmtCount(s.growthUsageJobsTotal)}`, `- 做梦 / 修复 / 策略运行:${fmtCount(s.dreamingRuns)} / ${fmtCount(s.recoveryRuns)} / ${fmtCount(s.goalStrategyRuns)}`, `- 候选生成 / 独立采用:${fmtCount(s.candidatesGenerated)} / ${fmtCount(s.candidatesAdopted)};独立验证完成:${fmtCount(s.taskVerificationsDone)};回滚:${fmtCount(s.rollbacks)}`, `- 插件创建 / 插件修订:${fmtCount(s.pluginsCreated)} / ${fmtCount(s.pluginsRevised)};演进规则采用:${fmtCount(s.evolutionRulesAdopted)}`, `- 联想参数版本 / 档位采用:${fmtCount(s.associationParamVersion)} / ${fmtCount(s.associationProfileAdoptions)};评估调优 / 放宽采用:${fmtCount(s.evaluationAttentionTuningAdoptions)} / ${fmtCount(s.evaluationLooseningDecisionsAdopted)}`, `- 激活记忆 / 偏好叠加:${fmtCount(s.activeMemories)} / ${fmtCount(s.activePreferenceOverlays)};工作流晋升 / 技能部署:${fmtCount(s.workflowCandidatesPromoted)} / ${fmtCount(s.skillDeployments)}`, `- 自我升级次数 / 备份快照:${fmtCount(s.selfUpgrades)} / ${fmtCount(s.backupSnapshotsCount)}`);
2205
+ }
2206
+ return lines.join('\n');
2207
+ }
2208
+ //# sourceMappingURL=version-query.js.map