@elvisw/dsh-magic-context 0.0.0-stage → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE +93 -0
  3. package/README.md +452 -2
  4. package/README.zh-CN.md +368 -0
  5. package/cordis.patch.yml +20 -0
  6. package/lib/client.js +2270 -0
  7. package/lib/core/compartments.js +424 -0
  8. package/lib/core/corpus-store.js +176 -0
  9. package/lib/core/directive-detect.js +147 -0
  10. package/lib/core/domain-reconcile.js +394 -0
  11. package/lib/core/domains.js +127 -0
  12. package/lib/core/embedding-local.js +247 -0
  13. package/lib/core/global-autostage.js +223 -0
  14. package/lib/core/global-domains.js +302 -0
  15. package/lib/core/journal.js +248 -0
  16. package/lib/core/llm-deadline.js +53 -0
  17. package/lib/core/machine-domain.js +106 -0
  18. package/lib/core/maintenance.js +380 -0
  19. package/lib/core/memory-bridge.js +818 -0
  20. package/lib/core/memory-categories.js +84 -0
  21. package/lib/core/memory-scoring.js +65 -0
  22. package/lib/core/memory-search.js +414 -0
  23. package/lib/core/memory-write.js +1176 -0
  24. package/lib/core/policy.js +111 -0
  25. package/lib/core/profile-confirmation.js +55 -0
  26. package/lib/core/profile-review.js +375 -0
  27. package/lib/core/profile-write.js +283 -0
  28. package/lib/core/reference-seeds.js +63 -0
  29. package/lib/core/route-health.js +106 -0
  30. package/lib/core/stores.js +1021 -0
  31. package/lib/core/tagger.js +7 -0
  32. package/lib/core/types.js +15 -0
  33. package/lib/core/vector-backfill.js +140 -0
  34. package/lib/core/vector-lane.js +184 -0
  35. package/lib/dsh/command-surface.js +376 -0
  36. package/lib/dsh/compaction-engine.js +231 -0
  37. package/lib/dsh/config-switches.js +56 -0
  38. package/lib/dsh/config.js +13 -0
  39. package/lib/dsh/context-pressure.js +36 -0
  40. package/lib/dsh/drop-landing.js +42 -0
  41. package/lib/dsh/emergency.js +89 -0
  42. package/lib/dsh/flush-command.js +148 -0
  43. package/lib/dsh/global-review.js +412 -0
  44. package/lib/dsh/historian.js +907 -0
  45. package/lib/dsh/live-journal.js +81 -0
  46. package/lib/dsh/maintenance-wiring.js +229 -0
  47. package/lib/dsh/management-pass.js +564 -0
  48. package/lib/dsh/memory-lane.js +535 -0
  49. package/lib/dsh/pre-step.js +675 -0
  50. package/lib/dsh/project-drift.js +116 -0
  51. package/lib/dsh/recomp.js +192 -0
  52. package/lib/dsh/reduce-guidance.js +188 -0
  53. package/lib/dsh/seams.js +588 -0
  54. package/lib/dsh/search-hint.js +186 -0
  55. package/lib/dsh/session-notice.js +100 -0
  56. package/lib/dsh/status-command.js +75 -0
  57. package/lib/dsh/telemetry.js +349 -0
  58. package/lib/dsh/tool-bridge.js +1009 -0
  59. package/lib/dsh/volatile.js +89 -0
  60. package/lib/index.js +931 -0
  61. package/package.json +108 -4
  62. package/tools/migrate-profile-package-name.mjs +317 -0
  63. package/vendor/onnx/LICENSE +27 -0
  64. package/vendor/onnx/ort-wasm-simd-threaded.mjs +59 -0
  65. package/vendor/onnx/ort-wasm-simd-threaded.wasm +0 -0
  66. package/vendor/onnx/ort.node.min.mjs +8 -0
@@ -0,0 +1,349 @@
1
+ import { SCHEMA_VERSION } from "../core/stores.js";
2
+ const DAY_MS = 24 * 60 * 60_000;
3
+ /**
4
+ * Normalize the `?session=` query value.
5
+ * @param raw - the request URL's first `session` parameter.
6
+ * @returns the Session id, or undefined for absent/empty (whole-store scope).
7
+ */
8
+ export function sessionOf(raw) {
9
+ if (raw === null || raw === undefined)
10
+ return undefined;
11
+ const value = raw.trim();
12
+ return value === '' ? undefined : value;
13
+ }
14
+ export function createTelemetryService(deps) {
15
+ const now = deps.now ?? Date.now;
16
+ const pollMs = deps.pollMs ?? 2_000;
17
+ const streams = new Set();
18
+ /**
19
+ * Browser halves that ever attached, and when the newest one did.
20
+ *
21
+ * `sseClients` in the summary is the only machine-readable proof that a
22
+ * browser half is actually connected and receiving journal rows — without it
23
+ * "is the UI showing anything?" can only be answered by looking at the screen.
24
+ */
25
+ let attachedTotal = 0;
26
+ let lastAttachedAt;
27
+ /** The newest journal row of a scope, or undefined. */
28
+ const newestOf = (sessionId) => {
29
+ try {
30
+ return deps.stores.listJournal({
31
+ limit: 1,
32
+ ...sessionId === undefined ? {} : { sessionId },
33
+ })[0];
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ };
39
+ /** The newest `memory-recall` row of a scope, or undefined. */
40
+ const latestRecall = (sessionId) => {
41
+ try {
42
+ return deps.stores.listJournal({
43
+ kinds: ['memory-recall'],
44
+ limit: 1,
45
+ ...sessionId === undefined ? {} : { sessionId },
46
+ })[0];
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ };
52
+ /**
53
+ * The project this scope is working on, read from the newest recall: the
54
+ * Session's own when one is named, the most recent one overall otherwise.
55
+ */
56
+ const project = (sessionId) => {
57
+ const recall = latestRecall(sessionId);
58
+ const identity = recall?.data?.identity;
59
+ const memories = recall?.data?.rows;
60
+ return {
61
+ ...typeof identity === 'string' ? { identity } : {},
62
+ ...typeof memories === 'number' ? { memories } : {},
63
+ };
64
+ };
65
+ const health = (sessionId) => {
66
+ const since = now() - DAY_MS;
67
+ // Errors reported by the RUNNING process, not by the last day. The pill is a
68
+ // live health badge: after a restart it must not keep flagging failures that
69
+ // the current build already fixed (the historian token-cap failures stayed
70
+ // red for a day until this existed).
71
+ const bootSince = deps.startedAt === undefined ? since : Math.max(deps.startedAt, since);
72
+ /** First-wins capture: journal rows iterate newest-first, so the newest
73
+ * reading for a field simply arrives first. */
74
+ const firstNum = (current, value) => current === undefined && typeof value === 'number' ? value : current;
75
+ // 24h counters: kind → aggregate field (single scan; error level handled inline).
76
+ const KIND_COUNTS = {
77
+ pass: 'passes24h',
78
+ 'drop-landed': 'drops24h',
79
+ 'compartment-published': 'compartments24h',
80
+ 'emergency-reclaim': 'emergency24h',
81
+ 'memory-promote': 'promote24h',
82
+ };
83
+ const h = { passes24h: 0, drops24h: 0, compartments24h: 0, emergency24h: 0, promote24h: 0 };
84
+ let errors24h = 0;
85
+ let errorsSinceBoot = 0;
86
+ let reclaimed24h = 0;
87
+ let lastPressure;
88
+ let lastTokens;
89
+ let lastContextWindow;
90
+ let surfaceTokens;
91
+ let surfaceWindow;
92
+ try {
93
+ for (const row of deps.stores.journalByKind(since, sessionId)) {
94
+ if (row.level === 'error')
95
+ errors24h += row.count;
96
+ const field = KIND_COUNTS[row.kind];
97
+ if (field !== undefined)
98
+ h[field] = (h[field] ?? 0) + row.count;
99
+ }
100
+ for (const row of deps.stores.journalByKind(bootSince, sessionId)) {
101
+ if (row.level === 'error')
102
+ errorsSinceBoot += row.count;
103
+ }
104
+ // The pill's one number: the newest pressure reading, plus the 24h net
105
+ // reclaim the execute band actually produced (sum of negative deltas).
106
+ for (const entry of deps.stores.listJournal({ limit: 300, ...(sessionId === undefined ? {} : { sessionId }) })) {
107
+ if (entry.kind === 'context-pressure' && entry.data !== undefined) {
108
+ // The native meter's own numbers (contextPressure projection): the
109
+ // projected occupancy answers the NEXT request, while the pass
110
+ // ledger below only moves when a management pass runs. Preferred
111
+ // whenever a reading exists — newest row wins by iteration order.
112
+ lastTokens = firstNum(lastTokens, entry.data.projectedTokens);
113
+ lastContextWindow = firstNum(lastContextWindow, entry.data.contextWindow);
114
+ if (lastPressure === undefined && typeof entry.data.projectedTokens === 'number' && typeof entry.data.contextWindow === 'number' && entry.data.contextWindow > 0) {
115
+ lastPressure = entry.data.projectedTokens / entry.data.contextWindow * 100;
116
+ }
117
+ continue;
118
+ }
119
+ if (entry.kind !== 'pass' || entry.data === undefined)
120
+ continue;
121
+ lastPressure = firstNum(lastPressure, entry.data.pressure);
122
+ // The post-compaction SURFACE account (execute passes only), separate
123
+ // from the projected occupancy above: different denominators of truth.
124
+ if (entry.data.decision === 'execute') {
125
+ surfaceTokens = firstNum(surfaceTokens, entry.data.tokensBefore);
126
+ surfaceWindow = firstNum(surfaceWindow, entry.data.contextWindow);
127
+ const delta = entry.data.tokensDelta;
128
+ if (typeof delta === 'number' && delta < 0)
129
+ reclaimed24h += -delta;
130
+ }
131
+ lastTokens = firstNum(lastTokens, entry.data.tokensBefore);
132
+ lastContextWindow = firstNum(lastContextWindow, entry.data.contextWindow);
133
+ }
134
+ }
135
+ catch {
136
+ /* a locked or missing table must not break the UI */
137
+ }
138
+ // Bounds are global-store facts: read once, serve both the scoped and the
139
+ // whole-store fields (a failed read leaves them at zero — diagnostic only).
140
+ let boundsRows = 0;
141
+ let boundsNewest;
142
+ try {
143
+ const bounds = deps.stores.journalBounds();
144
+ boundsRows = bounds.rows;
145
+ boundsNewest = bounds.newest;
146
+ }
147
+ catch {
148
+ /* diagnostic fields degrade to zero */
149
+ }
150
+ const journalRows = sessionId === undefined
151
+ ? boundsRows
152
+ : (() => {
153
+ try {
154
+ return deps.stores.journalByKind(undefined, sessionId).reduce((total, row) => total + row.count, 0);
155
+ }
156
+ catch {
157
+ return 0;
158
+ }
159
+ })();
160
+ const lastEventAt = sessionId === undefined ? boundsNewest : newestOf(sessionId)?.at;
161
+ let memoryStats;
162
+ let maintenanceLast;
163
+ try {
164
+ // The KPI must count the SAME project the header reports, or a global
165
+ // summary shows one project's identity above another project's totals
166
+ // (measured: identity git:93eea8… with 101 rows that belonged to
167
+ // git:a81f6372…, because the fallback picked the first-seen identity of a
168
+ // process serving several sessions). `project()` resolves it from the
169
+ // newest recall of this scope — the same source as `project.identity`.
170
+ const scopeIdentity = project(sessionId).identity;
171
+ memoryStats = deps.memoryStats?.(sessionId, typeof scopeIdentity === 'string' ? scopeIdentity : undefined);
172
+ maintenanceLast = deps.maintenanceLast?.();
173
+ }
174
+ catch {
175
+ /* stats are panel decoration; never let them break the summary */
176
+ }
177
+ return {
178
+ journalRows,
179
+ journalRowsAll: boundsRows,
180
+ lastEventAt,
181
+ passes24h: h.passes24h,
182
+ errors24h,
183
+ errorsSinceBoot,
184
+ drops24h: h.drops24h,
185
+ compartments24h: h.compartments24h,
186
+ emergency24h: h.emergency24h,
187
+ promote24h: h.promote24h,
188
+ reclaimed24h,
189
+ lastPressure,
190
+ lastTokens,
191
+ lastContextWindow,
192
+ // Frozen summary shape (telemetry.spec asserts it): same value as
193
+ // project.memories, kept for JSON-consumer compatibility.
194
+ memoriesRecalled: typeof latestRecall(sessionId)?.data?.rows === 'number'
195
+ ? latestRecall(sessionId)?.data?.rows
196
+ : 0,
197
+ // The post-compaction SURFACE account (newest execute pass), separate
198
+ // from the projected occupancy: the panel labels the two explicitly.
199
+ ...(surfaceTokens !== undefined ? { surfaceLedger: { tokens: surfaceTokens, ...(surfaceWindow !== undefined ? { window: surfaceWindow } : {}) } } : {}),
200
+ ...(memoryStats !== undefined ? { memoryStats } : {}),
201
+ ...(maintenanceLast !== undefined ? { maintenanceLast } : {}),
202
+ };
203
+ };
204
+ const recent = (limit, sessionId) => {
205
+ try {
206
+ // Newest-first from the store; the UI wants chronological order.
207
+ return deps.stores.listJournal({
208
+ limit,
209
+ ...sessionId === undefined ? {} : { sessionId },
210
+ })
211
+ .map(entry => ({
212
+ at: entry.at,
213
+ level: entry.level,
214
+ kind: entry.kind,
215
+ summary: entry.summary,
216
+ ...entry.sessionId === undefined ? {} : { sessionId: entry.sessionId },
217
+ // The record model reads numbers off `data` (inserted/ms/pressure);
218
+ // without it the snapshot strip falls back to the raw English
219
+ // summary while the live stream renders properly.
220
+ ...entry.data === undefined ? {} : { data: entry.data },
221
+ }))
222
+ .reverse();
223
+ }
224
+ catch {
225
+ return [];
226
+ }
227
+ };
228
+ const summary = (sessionId) => ({
229
+ scope: sessionId === undefined ? 'global' : 'session',
230
+ ...sessionId === undefined ? {} : { sessionId },
231
+ adapter: {
232
+ schemaVersion: SCHEMA_VERSION,
233
+ uptimeMs: deps.startedAt === undefined ? undefined : now() - deps.startedAt,
234
+ sseClients: streams.size,
235
+ sseAttachedTotal: attachedTotal,
236
+ ...lastAttachedAt === undefined ? {} : { sseLastAttachedAt: lastAttachedAt },
237
+ ...deps.meta(),
238
+ },
239
+ project: project(sessionId),
240
+ health: health(sessionId),
241
+ recent: recent(20, sessionId),
242
+ });
243
+ const sendJson = (res, status, payload) => {
244
+ const body = JSON.stringify(payload);
245
+ res.writeHead(status, {
246
+ 'content-type': 'application/json; charset=utf-8',
247
+ 'cache-control': 'no-store',
248
+ 'content-length': String(Buffer.byteLength(body)),
249
+ });
250
+ res.end(body);
251
+ };
252
+ const openStream = (res, sessionId) => {
253
+ res.writeHead(200, {
254
+ 'content-type': 'text/event-stream; charset=utf-8',
255
+ 'cache-control': 'no-store',
256
+ connection: 'keep-alive',
257
+ 'x-accel-buffering': 'no',
258
+ });
259
+ const write = (chunk) => {
260
+ try {
261
+ res.write?.(chunk);
262
+ }
263
+ catch {
264
+ /* the client went away */
265
+ }
266
+ };
267
+ write(`event: snapshot\ndata: ${JSON.stringify(summary(sessionId))}\n\n`);
268
+ // Poll the journal rather than holding a query open: reads are cheap, the
269
+ // writer is a different connection, and a restart of the store is invisible.
270
+ // The cursor starts at this scope's newest row, so a Session stream never
271
+ // replays another Session's history.
272
+ let lastSeen = 0;
273
+ try {
274
+ lastSeen = Number((sessionId === undefined
275
+ ? deps.stores.journalBounds().newest
276
+ : newestOf(sessionId)?.at) ?? 0);
277
+ }
278
+ catch {
279
+ lastSeen = 0;
280
+ }
281
+ const timer = setInterval(() => {
282
+ try {
283
+ const fresh = deps.stores.listJournal({
284
+ since: lastSeen + 1,
285
+ limit: 20,
286
+ ...sessionId === undefined ? {} : { sessionId },
287
+ });
288
+ for (const entry of [...fresh].reverse()) {
289
+ lastSeen = Math.max(lastSeen, entry.at);
290
+ write(`event: journal\ndata: ${JSON.stringify({
291
+ at: entry.at,
292
+ level: entry.level,
293
+ kind: entry.kind,
294
+ summary: entry.summary,
295
+ ...entry.sessionId === undefined ? {} : { sessionId: entry.sessionId },
296
+ data: entry.data,
297
+ })}\n\n`);
298
+ }
299
+ }
300
+ catch {
301
+ /* keep the stream alive on a transient read failure */
302
+ }
303
+ }, pollMs);
304
+ const keepAlive = setInterval(() => write(': keep-alive\n\n'), 15_000);
305
+ const stop = () => {
306
+ clearInterval(timer);
307
+ clearInterval(keepAlive);
308
+ streams.delete(stream);
309
+ try {
310
+ res.end();
311
+ }
312
+ catch {
313
+ /* already closed */
314
+ }
315
+ };
316
+ const stream = { stop };
317
+ streams.add(stream);
318
+ attachedTotal += 1;
319
+ lastAttachedAt = now();
320
+ res.on?.('close', stop);
321
+ };
322
+ return {
323
+ get openStreams() {
324
+ return streams.size;
325
+ },
326
+ summary,
327
+ handle: (req, res) => {
328
+ const base = '/mc-telemetry';
329
+ // A throwaway base keeps `new URL` total for an origin-form request target.
330
+ const requestUrl = new URL(req.url ?? '/', 'http://telemetry.invalid');
331
+ const url = requestUrl.pathname;
332
+ const path = url.startsWith(base) ? url.slice(base.length) || '/' : url;
333
+ const sessionId = sessionOf(requestUrl.searchParams.get('session'));
334
+ if (path === '/summary' || path === '/' || path === '') {
335
+ sendJson(res, 200, summary(sessionId));
336
+ return;
337
+ }
338
+ if (path === '/events') {
339
+ openStream(res, sessionId);
340
+ return;
341
+ }
342
+ sendJson(res, 404, { error: 'unknown telemetry route', routes: ['/summary', '/events'] });
343
+ },
344
+ close: () => {
345
+ for (const stream of [...streams])
346
+ stream.stop();
347
+ },
348
+ };
349
+ }