@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.11

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 (160) hide show
  1. package/README.md +109 -1
  2. package/client.js +646 -621
  3. package/dist/approvals.js +160 -0
  4. package/dist/authorization.js +225 -0
  5. package/dist/canvas-http.js +248 -0
  6. package/dist/canvas-skills.js +56 -0
  7. package/dist/canvas-store.js +794 -0
  8. package/dist/canvas-tools.js +211 -0
  9. package/dist/cli.js +32 -12
  10. package/dist/context.js +60 -17
  11. package/dist/cron.js +1 -1
  12. package/dist/cua-access.js +79 -0
  13. package/dist/desk.js +314 -37
  14. package/dist/engine.js +178 -84
  15. package/dist/fs-safe.js +1 -1
  16. package/dist/host.js +1 -0
  17. package/dist/http-plugin.js +14 -4
  18. package/dist/http.js +402 -85
  19. package/dist/inbox.js +51 -40
  20. package/dist/index.js +201 -47
  21. package/dist/live-diff.js +3 -1
  22. package/dist/live-snapshot.js +2 -13
  23. package/dist/log/canonical.js +37 -0
  24. package/dist/log/plan.js +62 -0
  25. package/dist/log/routes.js +144 -0
  26. package/dist/log/snapshot-service.js +76 -0
  27. package/dist/log/source.js +173 -0
  28. package/dist/memory-catalog.js +798 -0
  29. package/dist/permissions.js +86 -0
  30. package/dist/provision.js +2 -0
  31. package/dist/questions.js +407 -0
  32. package/dist/runtime-registry.js +4 -4
  33. package/dist/session-files.js +2 -2
  34. package/dist/session-previews.js +5 -1
  35. package/dist/store.js +20 -5
  36. package/dist/tools.js +150 -32
  37. package/dist/triggers.js +83 -39
  38. package/dist/work-admit.js +222 -25
  39. package/dist/work-child.js +17 -9
  40. package/dist/work-http.js +52 -2
  41. package/dist/work-ledger.js +256 -16
  42. package/dist/work-mock-host.js +9 -6
  43. package/dist/work-mock.js +29 -19
  44. package/dist/work-tickets.js +423 -96
  45. package/dist/work-tools.js +43 -6
  46. package/dist/work-worker.js +1033 -207
  47. package/dist/workspace-files.js +319 -0
  48. package/dist/workspace-image.js +91 -0
  49. package/fixtures/mock-llm.mjs +17 -2
  50. package/package.json +16 -5
  51. package/public/assets/SourceEditor-CJwK846Z.css +1 -0
  52. package/public/assets/SourceEditor-uu0G7jsM.js +669 -0
  53. package/public/assets/abap-CRCWOmpq.js +1 -0
  54. package/public/assets/apex-DnsZk_dE.js +1 -0
  55. package/public/assets/azcli-1IWB1ccx.js +1 -0
  56. package/public/assets/bat-DPkNLes8.js +1 -0
  57. package/public/assets/bicep-Corcdgou.js +2 -0
  58. package/public/assets/cameligo-CGrWLZr3.js +1 -0
  59. package/public/assets/clojure-D9WOWImG.js +1 -0
  60. package/public/assets/codicon-DCmgc-ay.ttf +0 -0
  61. package/public/assets/coffee-B7EJu28W.js +1 -0
  62. package/public/assets/cpp-SEyurbux.js +1 -0
  63. package/public/assets/csharp-BoL64M5l.js +1 -0
  64. package/public/assets/csp-C46ZqvIl.js +1 -0
  65. package/public/assets/css-DQU6DXDx.js +3 -0
  66. package/public/assets/css.worker-DYpkewsP.js +79 -0
  67. package/public/assets/cssMode-C5DAFF5H.js +4 -0
  68. package/public/assets/cypher-D84EuPTj.js +1 -0
  69. package/public/assets/dart-D8lhlL1r.js +1 -0
  70. package/public/assets/dockerfile-DLk6rpji.js +1 -0
  71. package/public/assets/ecl-BO6FnfXk.js +1 -0
  72. package/public/assets/editor.worker-B4pQIWZD.js +12 -0
  73. package/public/assets/elixir-BRjLKONM.js +1 -0
  74. package/public/assets/flow9-Cac8vKd7.js +1 -0
  75. package/public/assets/freemarker2-DExNwSiZ.js +3 -0
  76. package/public/assets/fsharp-fd1GTHhf.js +1 -0
  77. package/public/assets/go-O9LJTZXk.js +1 -0
  78. package/public/assets/graphql-LQdxqEYJ.js +1 -0
  79. package/public/assets/handlebars-BK7YAvpQ.js +1 -0
  80. package/public/assets/hcl-DxDQ3s82.js +1 -0
  81. package/public/assets/html-CdDm_zae.js +1 -0
  82. package/public/assets/html.worker-tnXziJOq.js +456 -0
  83. package/public/assets/htmlMode-CLdn9oa1.js +4 -0
  84. package/public/assets/index-BB-QDSf2.css +1 -0
  85. package/public/assets/index-CsX-_qbo.js +62 -0
  86. package/public/assets/ini-BvajGCUy.js +1 -0
  87. package/public/assets/java-SYsfObOQ.js +1 -0
  88. package/public/assets/javascript-mLl83_3W.js +1 -0
  89. package/public/assets/json.worker-aFakAbRR.js +44 -0
  90. package/public/assets/jsonMode-B1-bihFd.js +10 -0
  91. package/public/assets/julia-DQXNmw_w.js +1 -0
  92. package/public/assets/kotlin-qQ0MG-9I.js +1 -0
  93. package/public/assets/less-GGFNNJHn.js +2 -0
  94. package/public/assets/lexon-Canl7DCW.js +1 -0
  95. package/public/assets/liquid-Cv8m0HUb.js +1 -0
  96. package/public/assets/lua-D28Ae8-K.js +1 -0
  97. package/public/assets/m3-DPitgjJI.js +1 -0
  98. package/public/assets/markdown-B811l8j2.js +1 -0
  99. package/public/assets/mdx-Q12b91rL.js +1 -0
  100. package/public/assets/mips-CdjsipkG.js +1 -0
  101. package/public/assets/msdax-CYqgjx_P.js +1 -0
  102. package/public/assets/mysql-BHd6q0vd.js +1 -0
  103. package/public/assets/objective-c-B1aVtJYH.js +1 -0
  104. package/public/assets/pascal-BhNW15KB.js +1 -0
  105. package/public/assets/pascaligo-5jv8CcQD.js +1 -0
  106. package/public/assets/perl-DlYyT36c.js +1 -0
  107. package/public/assets/pgsql-Dy0bjov7.js +1 -0
  108. package/public/assets/php-120yhfDK.js +1 -0
  109. package/public/assets/pla-CjnFlu4u.js +1 -0
  110. package/public/assets/postiats-CQpG440k.js +1 -0
  111. package/public/assets/powerquery-DdJtto1Z.js +1 -0
  112. package/public/assets/powershell-Bu_VLpJB.js +1 -0
  113. package/public/assets/protobuf-IBS6jZEB.js +2 -0
  114. package/public/assets/pug-kFxLfcjb.js +1 -0
  115. package/public/assets/python-Kda811W0.js +1 -0
  116. package/public/assets/qsharp-q7JyzKFN.js +1 -0
  117. package/public/assets/r-BIFz-_sK.js +1 -0
  118. package/public/assets/razor-CRuCpdOW.js +1 -0
  119. package/public/assets/redis-CHOsPHWR.js +1 -0
  120. package/public/assets/redshift-CBifECDb.js +1 -0
  121. package/public/assets/restructuredtext-CghPJEOS.js +1 -0
  122. package/public/assets/ruby-CYWGW-b1.js +1 -0
  123. package/public/assets/rust-DMDD0SHb.js +1 -0
  124. package/public/assets/sb-BYAiYHFx.js +1 -0
  125. package/public/assets/scala-Bqvq8jcR.js +1 -0
  126. package/public/assets/scheme-Dhb-2j9p.js +1 -0
  127. package/public/assets/scss-CTwUZ5N7.js +3 -0
  128. package/public/assets/shell-CsDZo4DB.js +1 -0
  129. package/public/assets/solidity-CME5AdoB.js +1 -0
  130. package/public/assets/sophia-RYC1BQQz.js +1 -0
  131. package/public/assets/sparql-KEyrF7De.js +1 -0
  132. package/public/assets/sql-BdTr02Mf.js +1 -0
  133. package/public/assets/st-C7iG7M4S.js +1 -0
  134. package/public/assets/swift-D7IUmUK8.js +1 -0
  135. package/public/assets/systemverilog-DgMryOEJ.js +1 -0
  136. package/public/assets/tcl-PloMZuKG.js +1 -0
  137. package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
  138. package/public/assets/tsMode-BGHcz-M3.js +11 -0
  139. package/public/assets/twig-BfRIq3la.js +1 -0
  140. package/public/assets/typescript-Db1e0DCT.js +1 -0
  141. package/public/assets/typespec-CzxlYoT_.js +1 -0
  142. package/public/assets/vb-BwAE3J76.js +1 -0
  143. package/public/assets/wgsl-B_1kOXbF.js +298 -0
  144. package/public/assets/xml-H3zzFmnd.js +1 -0
  145. package/public/assets/yaml-BQrKvmTF.js +1 -0
  146. package/public/index.html +2 -2
  147. package/skills/ui/baseline-ui/SKILL.md +85 -0
  148. package/skills/ui/bencium-innovative-ux-designer/SKILL.md +227 -0
  149. package/skills/ui/better-ui/SKILL.md +133 -0
  150. package/skills/ui/design-lab/SKILL.md +920 -0
  151. package/skills/ui/frontend-design/SKILL.md +71 -0
  152. package/skills/ui/impeccable/SKILL.md +93 -0
  153. package/skills/ui/interface-design/SKILL.md +320 -0
  154. package/skills/ui/sources.json +66 -0
  155. package/skills/ui/ui-design/SKILL.md +35 -0
  156. package/skills/ui/ui-skills-root/SKILL.md +59 -0
  157. package/skills/ui/visual-design-foundations/SKILL.md +318 -0
  158. package/skills/ui/web-design-guidelines/SKILL.md +39 -0
  159. package/public/assets/index-Be82iGwe.css +0 -1
  160. package/public/assets/index-ByU9a3Lh.js +0 -61
@@ -0,0 +1,798 @@
1
+ import { splitPersona } from "./context.js";
2
+ import { toolError } from "./errors.js";
3
+ import { assertSessionId } from "./engine.js";
4
+ import { sha256 } from "./fs-safe.js";
5
+ const TYPES = new Set(['persona', 'profile', 'fact', 'episodic', 'procedural', 'state', 'skill']);
6
+ const LIFECYCLES = new Set(['active', 'corrected', 'forgotten', 'candidate']);
7
+ const SCOPES = new Set(['user', 'session', 'work', 'skill']);
8
+ const TYPE_ORDER = ['persona', 'profile', 'fact', 'episodic', 'procedural', 'state', 'skill'];
9
+ const READ_CAP = 500;
10
+ const ENTITY_ID = /^(persona|profile|fact|episodic|procedural|state|skill):([A-Za-z0-9][A-Za-z0-9._-]{0,64})$/;
11
+ const PREFIX = '/session-foundations/api/memory';
12
+ const FACT_LIST = `
13
+ SELECT id, kind,
14
+ CASE WHEN status = 'forgotten' THEN '' ELSE content END AS content,
15
+ status, source_event_id, source_type, supersedes, revision, priority, created_at, updated_at
16
+ FROM facts WHERE session_id = ? ORDER BY updated_at DESC, id DESC LIMIT ?
17
+ `;
18
+ const MEMORY_LIST = `
19
+ SELECT id,
20
+ CASE WHEN status = 'forgotten' THEN '' ELSE ifnull(title, '') END AS title,
21
+ CASE WHEN status = 'forgotten' THEN '' ELSE content END AS content,
22
+ status, source_event_id, source_type, supersedes, revision, created_at, updated_at
23
+ FROM memories WHERE session_id = ? ORDER BY updated_at DESC, id DESC LIMIT ?
24
+ `;
25
+ /** A missing or unrecognized source is unknown. It is never treated as the user. */
26
+ export function creatorFrom(sourceType) {
27
+ if (sourceType === 'user_confirm' || sourceType === 'user')
28
+ return 'user';
29
+ if (sourceType === 'explicit_tool' || sourceType === 'import')
30
+ return 'tool';
31
+ if (sourceType === 'candidate_extract')
32
+ return 'model';
33
+ if (sourceType === 'migration' || sourceType === 'system')
34
+ return 'system';
35
+ return 'unknown';
36
+ }
37
+ export function handleMemoryRoute(engine, path, url) {
38
+ if (path !== `${PREFIX}/entities` &&
39
+ path !== `${PREFIX}/frames` &&
40
+ path !== `${PREFIX}/context` &&
41
+ !path.startsWith(`${PREFIX}/entities/`)) {
42
+ return null;
43
+ }
44
+ try {
45
+ if (path === `${PREFIX}/entities`)
46
+ return listRoute(engine, url);
47
+ if (path === `${PREFIX}/frames`)
48
+ return framesRoute(engine, url);
49
+ if (path === `${PREFIX}/context`)
50
+ return contextRoute(engine, url);
51
+ return detailRoute(engine, path.slice(`${PREFIX}/entities/`.length), url);
52
+ }
53
+ catch (error) {
54
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
55
+ if (code === 'VALIDATION') {
56
+ return { status: 400, body: toolError('VALIDATION', error instanceof Error ? error.message : 'invalid') };
57
+ }
58
+ if (code === 'NOT_FOUND') {
59
+ return { status: 404, body: toolError('NOT_FOUND', error instanceof Error ? error.message : 'not found') };
60
+ }
61
+ throw error;
62
+ }
63
+ }
64
+ function listRoute(engine, url) {
65
+ const sessionId = requireSession(url);
66
+ const type = enumParam(url, 'type', TYPES);
67
+ const lifecycle = enumParam(url, 'lifecycle', LIFECYCLES);
68
+ const scope = enumParam(url, 'scope', SCOPES);
69
+ const q = textParam(url, 'q', 200);
70
+ const limit = intParam(url, 'limit', 60, 100);
71
+ const offset = intParam(url, 'cursor', 0, 100000);
72
+ const { entities, capped } = collect(engine, sessionId);
73
+ const filtered = entities.filter(entity => {
74
+ if (type && entity.type !== type)
75
+ return false;
76
+ if (lifecycle && entity.lifecycle !== lifecycle)
77
+ return false;
78
+ if (scope && entity.scope !== scope)
79
+ return false;
80
+ return matchesQuery(entity, q);
81
+ });
82
+ filtered.sort(compareEntities);
83
+ const page = filtered.slice(offset, offset + limit);
84
+ const next = offset + limit < filtered.length ? String(offset + limit) : null;
85
+ return {
86
+ status: 200,
87
+ body: { ok: true, sessionId, entities: page, nextCursor: next, capped },
88
+ };
89
+ }
90
+ function detailRoute(engine, rawId, url) {
91
+ const sessionId = requireSession(url);
92
+ const parsed = parseEntityId(rawId);
93
+ if (!parsed)
94
+ fail('VALIDATION', 'entity id is invalid.');
95
+ const entity = readEntity(engine, sessionId, parsed.type, parsed.key);
96
+ if (!entity)
97
+ fail('NOT_FOUND', 'No memory entity was found in this session.');
98
+ return { status: 200, body: { ok: true, entity } };
99
+ }
100
+ function framesRoute(engine, url) {
101
+ const sessionId = requireSession(url);
102
+ const limit = intParam(url, 'limit', 20, 50);
103
+ const rows = engine.store.db
104
+ .prepare(`SELECT revision, frozen_at, presence FROM view_revisions WHERE session_id = ? ORDER BY revision DESC LIMIT ?`)
105
+ .all(sessionId, limit);
106
+ return {
107
+ status: 200,
108
+ body: {
109
+ ok: true,
110
+ frames: rows.map(row => ({
111
+ revision: Number(row.revision),
112
+ frozenAt: text(row.frozen_at),
113
+ presence: text(row.presence),
114
+ hasManifest: false,
115
+ })),
116
+ },
117
+ };
118
+ }
119
+ function contextRoute(engine, url) {
120
+ const sessionId = requireSession(url);
121
+ const revision = optionalRevision(url);
122
+ const ids = idList(url);
123
+ if (revision == null) {
124
+ return {
125
+ status: 200,
126
+ body: {
127
+ ok: true,
128
+ frame: null,
129
+ citations: ids.map(id => ({ id, form: 'unknown', reason: 'no_frame' })),
130
+ },
131
+ };
132
+ }
133
+ const row = engine.store.db
134
+ .prepare(`SELECT revision, frozen_at, presence FROM view_revisions WHERE session_id = ? AND revision = ?`)
135
+ .get(sessionId, revision);
136
+ if (!row)
137
+ fail('NOT_FOUND', 'That context frame was not found in this session.');
138
+ return {
139
+ status: 200,
140
+ body: {
141
+ ok: true,
142
+ frame: {
143
+ revision: Number(row.revision),
144
+ frozenAt: text(row.frozen_at),
145
+ presence: text(row.presence),
146
+ hasManifest: false,
147
+ },
148
+ citations: ids.map(id => ({ id, form: 'unknown', reason: 'no_manifest' })),
149
+ },
150
+ };
151
+ }
152
+ function collect(engine, sessionId) {
153
+ const entities = [];
154
+ let capped = false;
155
+ const facts = engine.store.db.prepare(FACT_LIST).all(sessionId, READ_CAP + 1);
156
+ if (facts.length > READ_CAP)
157
+ capped = true;
158
+ for (const row of facts.slice(0, READ_CAP)) {
159
+ const entity = factEntity(row, false);
160
+ if (entity)
161
+ entities.push(entity);
162
+ }
163
+ const memories = engine.store.db.prepare(MEMORY_LIST).all(sessionId, READ_CAP + 1);
164
+ if (memories.length > READ_CAP)
165
+ capped = true;
166
+ for (const row of memories.slice(0, READ_CAP)) {
167
+ const entity = memoryEntity(row, false);
168
+ if (entity)
169
+ entities.push(entity);
170
+ }
171
+ const persona = personaEntity(engine, sessionId, false);
172
+ if (persona)
173
+ entities.push(persona);
174
+ const state = stateEntity(engine, sessionId, false);
175
+ if (state)
176
+ entities.push(state);
177
+ const skills = engine.store.db
178
+ .prepare(`
179
+ SELECT skill_id, scope, version, content_hash, CASE WHEN revoked = 1 THEN '' ELSE summary END AS summary,
180
+ enabled, revoked, bound_at
181
+ FROM skill_bindings WHERE session_id = ? ORDER BY skill_id LIMIT ?
182
+ `)
183
+ .all(sessionId, READ_CAP + 1);
184
+ if (skills.length > READ_CAP)
185
+ capped = true;
186
+ for (const row of skills.slice(0, READ_CAP))
187
+ entities.push(skillEntity(row, null));
188
+ return { entities, capped };
189
+ }
190
+ function readEntity(engine, sessionId, type, key) {
191
+ if (type === 'procedural')
192
+ return null;
193
+ if (type === 'persona')
194
+ return personaDetail(engine, sessionId, key);
195
+ if (type === 'state')
196
+ return key === 'current' ? stateDetail(engine, sessionId) : null;
197
+ if (type === 'skill')
198
+ return skillDetail(engine, sessionId, key);
199
+ if (type === 'profile' || type === 'fact')
200
+ return factDetail(engine, sessionId, type, key);
201
+ if (type === 'episodic')
202
+ return memoryDetail(engine, sessionId, key);
203
+ return null;
204
+ }
205
+ function factDetail(engine, sessionId, type, key) {
206
+ const id = numberKey(key);
207
+ if (id == null)
208
+ return null;
209
+ const row = factRow(engine, sessionId, id);
210
+ if (!row)
211
+ return null;
212
+ const entity = factEntity(row, true);
213
+ if (!entity || entity.type !== type)
214
+ return null;
215
+ const chain = walkFacts(engine, sessionId, id).map(item => chainItem(factEntity(item, false), item.updated_at));
216
+ return {
217
+ ...entity,
218
+ chain: chain.filter((item) => item != null),
219
+ changes: changesFor(engine, sessionId, 'fact', key),
220
+ };
221
+ }
222
+ function memoryDetail(engine, sessionId, key) {
223
+ const id = numberKey(key);
224
+ if (id == null)
225
+ return null;
226
+ const row = memoryRow(engine, sessionId, id);
227
+ if (!row)
228
+ return null;
229
+ const entity = memoryEntity(row, true);
230
+ if (!entity)
231
+ return null;
232
+ const chain = walkMemories(engine, sessionId, id).map(item => chainItem(memoryEntity(item, false), item.updated_at));
233
+ return {
234
+ ...entity,
235
+ chain: chain.filter((item) => item != null),
236
+ changes: changesFor(engine, sessionId, 'memory', key),
237
+ };
238
+ }
239
+ function personaDetail(engine, sessionId, key) {
240
+ const entity = personaEntity(engine, sessionId, true);
241
+ if (!entity || entity.id !== `persona:${key}`)
242
+ return null;
243
+ return { ...entity, chain: [], changes: [] };
244
+ }
245
+ function stateDetail(engine, sessionId) {
246
+ const entity = stateEntity(engine, sessionId, true);
247
+ if (!entity)
248
+ return null;
249
+ return { ...entity, chain: [], changes: changesFor(engine, sessionId, 'state', 'current') };
250
+ }
251
+ function skillDetail(engine, sessionId, key) {
252
+ const row = engine.store.db
253
+ .prepare(`
254
+ SELECT skill_id, scope, version, content_hash, CASE WHEN revoked = 1 THEN '' ELSE summary END AS summary,
255
+ enabled, revoked, bound_at
256
+ FROM skill_bindings WHERE session_id = ? AND skill_id = ?
257
+ `)
258
+ .get(sessionId, key);
259
+ if (!row)
260
+ return null;
261
+ const revoked = Number(row.revoked) === 1;
262
+ let body = null;
263
+ let bodyState = 'absent';
264
+ if (revoked)
265
+ bodyState = 'hidden';
266
+ else {
267
+ const bytes = engine.store.readBlob('skill', text(row.content_hash));
268
+ if (bytes == null || sha256(bytes) !== text(row.content_hash))
269
+ bodyState = 'mismatch';
270
+ else {
271
+ body = bytes.toString('utf8');
272
+ bodyState = body.trim() === '' ? 'absent' : 'visible';
273
+ }
274
+ }
275
+ return { ...skillEntity(row, bodyState === 'visible' ? body : null), body, bodyState, chain: [], changes: [] };
276
+ }
277
+ function factEntity(row, withBody) {
278
+ const lifecycle = lifecycleOf(text(row.status));
279
+ if (!lifecycle)
280
+ return null;
281
+ const type = text(row.kind) === 'user_profile' || text(row.kind) === 'profile' ? 'profile' : 'fact';
282
+ const tombstone = lifecycle === 'forgotten';
283
+ const content = tombstone ? '' : text(row.content);
284
+ const creator = creatorFrom(row.source_type);
285
+ const entity = {
286
+ id: `${type}:${Number(row.id)}`,
287
+ type,
288
+ scope: 'session',
289
+ lifecycle,
290
+ title: '',
291
+ summary: tombstone ? '' : clip(content),
292
+ revision: Number(row.revision),
293
+ createdAt: text(row.created_at) || null,
294
+ updatedAt: text(row.updated_at) || null,
295
+ creator,
296
+ tombstone,
297
+ priority: Number(row.priority),
298
+ };
299
+ if (type === 'profile' && !tombstone) {
300
+ const attributes = attributesFrom(content);
301
+ if (attributes.length > 0)
302
+ entity.attributes = attributes;
303
+ }
304
+ if (!withBody)
305
+ return entity;
306
+ const bodyState = tombstone ? 'hidden' : content.trim() === '' ? 'absent' : 'visible';
307
+ return {
308
+ ...entity,
309
+ body: bodyState === 'visible' ? content : null,
310
+ bodyState,
311
+ source: sourceOf(row.source_type, entity.createdAt, entity.updatedAt, row.source_event_id),
312
+ };
313
+ }
314
+ function memoryEntity(row, withBody) {
315
+ const lifecycle = lifecycleOf(text(row.status));
316
+ if (!lifecycle)
317
+ return null;
318
+ const tombstone = lifecycle === 'forgotten';
319
+ const content = tombstone ? '' : text(row.content);
320
+ const entity = {
321
+ id: `episodic:${Number(row.id)}`,
322
+ type: 'episodic',
323
+ scope: 'session',
324
+ lifecycle,
325
+ title: tombstone ? '' : text(row.title).trim(),
326
+ summary: tombstone ? '' : clip(content),
327
+ revision: Number(row.revision),
328
+ createdAt: text(row.created_at) || null,
329
+ updatedAt: text(row.updated_at) || null,
330
+ creator: creatorFrom(row.source_type),
331
+ tombstone,
332
+ };
333
+ if (!withBody)
334
+ return entity;
335
+ const bodyState = tombstone ? 'hidden' : content.trim() === '' ? 'absent' : 'visible';
336
+ return {
337
+ ...entity,
338
+ body: bodyState === 'visible' ? content : null,
339
+ bodyState,
340
+ source: sourceOf(row.source_type, entity.createdAt, entity.updatedAt, row.source_event_id),
341
+ };
342
+ }
343
+ function personaEntity(engine, sessionId, withBody) {
344
+ const binding = engine.binding(sessionId);
345
+ const personaId = binding?.persona_version_id;
346
+ if (personaId == null)
347
+ return null;
348
+ const persona = engine.persona(Number(personaId));
349
+ if (!persona)
350
+ return null;
351
+ const recorded = typeof persona.created_by === 'string' && persona.created_by !== '';
352
+ let body = '';
353
+ let bodyState = 'absent';
354
+ if (engine.personaBlobOk(persona)) {
355
+ const bytes = engine.store.readBlob('persona', persona.content_hash);
356
+ body = bytes ? bytes.toString('utf8') : '';
357
+ bodyState = body.trim() === '' ? 'absent' : 'visible';
358
+ }
359
+ else
360
+ bodyState = 'mismatch';
361
+ const split = bodyState === 'visible' ? splitPersona(body) : { name: '', body: '' };
362
+ const entity = {
363
+ id: `persona:${Number(persona.id)}`,
364
+ type: 'persona',
365
+ scope: 'user',
366
+ lifecycle: 'active',
367
+ title: split.name || clip(split.body, 80),
368
+ summary: clip(split.body || body),
369
+ revision: Number(persona.id),
370
+ createdAt: text(persona.created_at) || null,
371
+ updatedAt: text(persona.created_at) || null,
372
+ creator: creatorFrom(recorded ? persona.created_by : null),
373
+ tombstone: false,
374
+ versionLabel: String(persona.id),
375
+ };
376
+ if (bodyState === 'mismatch')
377
+ entity.summary = '';
378
+ if (!withBody)
379
+ return entity;
380
+ const note = typeof persona.note === 'string' && persona.note.trim() !== '' ? persona.note : null;
381
+ return {
382
+ ...entity,
383
+ body: bodyState === 'visible' ? body : null,
384
+ bodyState,
385
+ note,
386
+ source: {
387
+ creator: entity.creator,
388
+ recorded,
389
+ createdAt: entity.createdAt,
390
+ updatedAt: entity.updatedAt,
391
+ eventId: null,
392
+ },
393
+ };
394
+ }
395
+ function stateEntity(engine, sessionId, withBody) {
396
+ const row = engine.store.db
397
+ .prepare('SELECT revision, payload_json, updated_at FROM working_state WHERE session_id = ?')
398
+ .get(sessionId);
399
+ if (!row)
400
+ return null;
401
+ let payload = null;
402
+ try {
403
+ const parsed = JSON.parse(text(row.payload_json));
404
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
405
+ payload = parsed;
406
+ }
407
+ catch {
408
+ payload = null;
409
+ }
410
+ const goal = payload && typeof payload.currentGoal === 'string' ? payload.currentGoal.trim() : '';
411
+ const notes = payload && typeof payload.notes === 'string' ? payload.notes.trim() : '';
412
+ const todos = Array.isArray(payload?.todos) ? payload.todos : [];
413
+ const blockers = todos
414
+ .map(todo => todoText(todo))
415
+ .filter((todo) => todo != null && (todo.status === 'blocked' || todo.status === 'block'))
416
+ .map(todo => todo.text);
417
+ const nextTodo = todos
418
+ .map(todo => todoText(todo))
419
+ .find((todo) => todo != null && todo.status !== 'done' && todo.status !== 'blocked' && todo.status !== 'block');
420
+ const next = nextTodo?.text ?? '';
421
+ const entity = {
422
+ id: 'state:current',
423
+ type: 'state',
424
+ scope: 'session',
425
+ lifecycle: 'active',
426
+ title: '',
427
+ summary: clip([goal, ...blockers, next].filter(part => part !== '').join(' · ')),
428
+ revision: Number(row.revision),
429
+ createdAt: null,
430
+ updatedAt: text(row.updated_at) || null,
431
+ creator: 'unknown',
432
+ tombstone: false,
433
+ goal,
434
+ blockers,
435
+ next,
436
+ };
437
+ if (!withBody)
438
+ return entity;
439
+ const bodyState = payload == null ? 'mismatch' : notes === '' ? 'absent' : 'visible';
440
+ return {
441
+ ...entity,
442
+ body: bodyState === 'visible' ? notes : null,
443
+ bodyState,
444
+ source: { creator: 'unknown', recorded: false, createdAt: null, updatedAt: entity.updatedAt, eventId: null },
445
+ };
446
+ }
447
+ function skillEntity(row, body) {
448
+ const revoked = Number(row.revoked) === 1;
449
+ const enabled = Number(row.enabled) === 1 && !revoked;
450
+ const summary = revoked ? '' : clip(text(row.summary));
451
+ return {
452
+ id: `skill:${text(row.skill_id)}`,
453
+ type: 'skill',
454
+ scope: 'skill',
455
+ lifecycle: revoked ? 'forgotten' : 'active',
456
+ title: text(row.skill_id),
457
+ summary,
458
+ revision: null,
459
+ createdAt: text(row.bound_at) || null,
460
+ updatedAt: text(row.bound_at) || null,
461
+ creator: 'unknown',
462
+ tombstone: revoked,
463
+ versionLabel: text(row.version),
464
+ enabled,
465
+ bindingScope: text(row.scope) === 'private' ? 'private' : 'public',
466
+ ...(body != null ? { body, bodyState: 'visible' } : {}),
467
+ };
468
+ }
469
+ function chainItem(entity, at) {
470
+ if (!entity)
471
+ return null;
472
+ return {
473
+ id: entity.id,
474
+ lifecycle: entity.lifecycle,
475
+ at: at || entity.updatedAt,
476
+ summary: entity.tombstone ? '' : entity.summary,
477
+ tombstone: entity.tombstone,
478
+ };
479
+ }
480
+ function changesFor(engine, sessionId, kind, key) {
481
+ const rows = engine.store.db
482
+ .prepare(`
483
+ SELECT id, tool_name, request_json, result_json, outcome, created_at
484
+ FROM mutations WHERE scope = ? ORDER BY id DESC LIMIT 80
485
+ `)
486
+ .all(sessionId);
487
+ const changes = [];
488
+ for (const row of rows) {
489
+ if (!mutationTouches(row, kind, key))
490
+ continue;
491
+ changes.push({
492
+ id: Number(row.id),
493
+ tool: text(row.tool_name),
494
+ outcome: text(row.outcome),
495
+ at: text(row.created_at),
496
+ });
497
+ if (changes.length >= 20)
498
+ break;
499
+ }
500
+ return changes;
501
+ }
502
+ function mutationTouches(row, kind, key) {
503
+ if (kind === 'state')
504
+ return row.tool_name === 'foundations_state_update';
505
+ const target = kind === 'fact' ? 'fact' : 'memory';
506
+ const id = Number(key);
507
+ if (!Number.isInteger(id))
508
+ return false;
509
+ return payloadHits(row.request_json, target, id) || payloadHits(row.result_json, target, id);
510
+ }
511
+ function payloadHits(json, target, id) {
512
+ let parsed;
513
+ try {
514
+ parsed = JSON.parse(json);
515
+ }
516
+ catch {
517
+ return false;
518
+ }
519
+ const found = new Set();
520
+ let sawTarget = false;
521
+ walkPayload(parsed, (entryKey, value) => {
522
+ if (entryKey === 'target' && value === target)
523
+ sawTarget = true;
524
+ if ((entryKey === 'id' || entryKey === 'supersedes') && value === id)
525
+ found.add(id);
526
+ });
527
+ return sawTarget && found.has(id);
528
+ }
529
+ function walkPayload(value, visit) {
530
+ if (!value || typeof value !== 'object')
531
+ return;
532
+ if (Array.isArray(value)) {
533
+ for (const item of value)
534
+ walkPayload(item, visit);
535
+ return;
536
+ }
537
+ for (const [key, child] of Object.entries(value)) {
538
+ visit(key, child);
539
+ if (child && typeof child === 'object')
540
+ walkPayload(child, visit);
541
+ }
542
+ }
543
+ function factRow(engine, sessionId, id) {
544
+ return (engine.store.db
545
+ .prepare(`
546
+ SELECT id, kind,
547
+ CASE WHEN status = 'forgotten' THEN '' ELSE content END AS content,
548
+ status, source_event_id, source_type, supersedes, revision, priority, created_at, updated_at
549
+ FROM facts WHERE session_id = ? AND id = ?
550
+ `)
551
+ .get(sessionId, id) ?? null);
552
+ }
553
+ function memoryRow(engine, sessionId, id) {
554
+ return (engine.store.db
555
+ .prepare(`
556
+ SELECT id,
557
+ CASE WHEN status = 'forgotten' THEN '' ELSE ifnull(title, '') END AS title,
558
+ CASE WHEN status = 'forgotten' THEN '' ELSE content END AS content,
559
+ status, source_event_id, source_type, supersedes, revision, created_at, updated_at
560
+ FROM memories WHERE session_id = ? AND id = ?
561
+ `)
562
+ .get(sessionId, id) ?? null);
563
+ }
564
+ function walkFacts(engine, sessionId, start) {
565
+ return walk(id => factRow(engine, sessionId, id), id => linkedIds(engine, 'facts', sessionId, id), start);
566
+ }
567
+ function walkMemories(engine, sessionId, start) {
568
+ return walk(id => memoryRow(engine, sessionId, id), id => linkedIds(engine, 'memories', sessionId, id), start);
569
+ }
570
+ function walk(load, children, start) {
571
+ const seen = new Set();
572
+ const rows = [];
573
+ const add = (row) => {
574
+ if (!row || seen.has(Number(row.id)))
575
+ return false;
576
+ seen.add(Number(row.id));
577
+ rows.push(row);
578
+ return true;
579
+ };
580
+ let current = load(start);
581
+ for (let i = 0; i < 8 && current; i++) {
582
+ const next = current.supersedes == null ? null : Number(current.supersedes);
583
+ if (!add(current))
584
+ break;
585
+ current = next == null ? null : load(next);
586
+ }
587
+ let frontier = [start];
588
+ for (let depth = 0; depth < 8 && frontier.length > 0; depth++) {
589
+ const next = [];
590
+ for (const id of frontier) {
591
+ for (const child of children(id)) {
592
+ const row = load(child);
593
+ if (row && add(row))
594
+ next.push(Number(row.id));
595
+ }
596
+ }
597
+ frontier = next;
598
+ }
599
+ rows.sort((a, b) => Number(a.id) - Number(b.id));
600
+ return rows;
601
+ }
602
+ function linkedIds(engine, table, sessionId, id) {
603
+ const rows = engine.store.db
604
+ .prepare(`SELECT id FROM ${table} WHERE session_id = ? AND supersedes = ?`)
605
+ .all(sessionId, id);
606
+ return rows.map(row => Number(row.id));
607
+ }
608
+ function sourceOf(sourceType, createdAt, updatedAt, eventId) {
609
+ const recorded = typeof sourceType === 'string' && sourceType !== '';
610
+ const event = eventId == null || eventId === '' ? null : String(eventId);
611
+ return { creator: creatorFrom(recorded ? sourceType : null), recorded, createdAt, updatedAt, eventId: event };
612
+ }
613
+ function lifecycleOf(status) {
614
+ if (status === 'active')
615
+ return 'active';
616
+ if (status === 'superseded')
617
+ return 'corrected';
618
+ if (status === 'forgotten')
619
+ return 'forgotten';
620
+ if (status === 'candidate')
621
+ return 'candidate';
622
+ return null;
623
+ }
624
+ function attributesFrom(content) {
625
+ const attributes = [];
626
+ for (const line of content.split('\n')) {
627
+ const match = /^([^::]{1,40})[::]\s*(.+)$/.exec(line.trim());
628
+ if (!match)
629
+ continue;
630
+ attributes.push({ name: match[1]?.trim() ?? '', value: match[2]?.trim() ?? '' });
631
+ if (attributes.length >= 12)
632
+ break;
633
+ }
634
+ return attributes.filter(item => item.name !== '' && item.value !== '');
635
+ }
636
+ function todoText(value) {
637
+ if (!value || typeof value !== 'object')
638
+ return null;
639
+ const textValue = 'text' in value && typeof value.text === 'string' ? value.text.trim() : '';
640
+ if (textValue === '')
641
+ return null;
642
+ const status = 'status' in value && typeof value.status === 'string' ? value.status : '';
643
+ return { text: textValue, status };
644
+ }
645
+ function matchesQuery(entity, q) {
646
+ if (q === '')
647
+ return true;
648
+ const needle = q.toLowerCase();
649
+ if (entity.tombstone)
650
+ return entity.id.toLowerCase().includes(needle);
651
+ const attributes = (entity.attributes ?? []).map(item => `${item.name} ${item.value}`).join('\n');
652
+ const steps = (entity.steps ?? []).join('\n');
653
+ const haystack = [entity.id, entity.title, entity.summary, attributes, steps, entity.goal ?? '', entity.next ?? '']
654
+ .join('\n')
655
+ .toLowerCase();
656
+ return haystack.includes(needle);
657
+ }
658
+ function compareEntities(a, b) {
659
+ const typeDelta = TYPE_ORDER.indexOf(a.type) - TYPE_ORDER.indexOf(b.type);
660
+ if (typeDelta !== 0)
661
+ return typeDelta;
662
+ const time = (b.updatedAt ?? '').localeCompare(a.updatedAt ?? '');
663
+ if (time !== 0)
664
+ return time;
665
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
666
+ }
667
+ export function queryMemory(engine, sessionId, options) {
668
+ assertSessionId(sessionId);
669
+ const { entities, capped } = collect(engine, sessionId);
670
+ const filtered = entities.filter(entity => !options.type || entity.type === options.type);
671
+ filtered.sort(compareEntities);
672
+ const page = filtered.slice(options.offset, options.offset + options.limit);
673
+ const next = options.offset + options.limit < filtered.length ? String(options.offset + options.limit) : null;
674
+ return { entities: page.map(briefMemory), nextCursor: next, capped };
675
+ }
676
+ export function readMemoryEntity(engine, sessionId, id) {
677
+ assertSessionId(sessionId);
678
+ const parsed = parseEntityId(id);
679
+ if (!parsed)
680
+ return null;
681
+ return readEntity(engine, sessionId, parsed.type, parsed.key);
682
+ }
683
+ function briefMemory(entity) {
684
+ return {
685
+ id: entity.id,
686
+ type: entity.type,
687
+ scope: entity.scope,
688
+ lifecycle: entity.lifecycle,
689
+ title: entity.title,
690
+ summary: entity.summary,
691
+ revision: entity.revision,
692
+ updatedAt: entity.updatedAt,
693
+ tombstone: entity.tombstone,
694
+ ...(entity.priority != null ? { priority: entity.priority } : {}),
695
+ };
696
+ }
697
+ function parseEntityId(raw) {
698
+ let decoded = raw;
699
+ try {
700
+ decoded = decodeURIComponent(raw);
701
+ }
702
+ catch {
703
+ decoded = raw;
704
+ }
705
+ const match = ENTITY_ID.exec(decoded);
706
+ if (!match)
707
+ return null;
708
+ const type = match[1];
709
+ const key = match[2] ?? '';
710
+ if (!TYPES.has(type) || key === '')
711
+ return null;
712
+ return { type, key };
713
+ }
714
+ function idList(url) {
715
+ const raw = url.searchParams.get('ids') ?? '';
716
+ if (raw.trim() === '')
717
+ return [];
718
+ const ids = raw
719
+ .split(',')
720
+ .map(item => item.trim())
721
+ .filter(item => item !== '');
722
+ if (ids.length > 100)
723
+ fail('VALIDATION', 'ids accepts at most 100 entries.');
724
+ const unique = [];
725
+ for (const id of ids) {
726
+ const parsed = parseEntityId(id);
727
+ if (!parsed)
728
+ fail('VALIDATION', 'entity id is invalid.');
729
+ const canonical = `${parsed.type}:${parsed.key}`;
730
+ if (!unique.includes(canonical))
731
+ unique.push(canonical);
732
+ }
733
+ return unique;
734
+ }
735
+ function requireSession(url) {
736
+ const sessionId = url.searchParams.get('sessionId') ?? '';
737
+ if (sessionId === '')
738
+ fail('VALIDATION', 'sessionId is required.');
739
+ assertSessionId(sessionId);
740
+ return sessionId;
741
+ }
742
+ function enumParam(url, name, allowed) {
743
+ const value = url.searchParams.get(name);
744
+ if (value == null || value === '')
745
+ return null;
746
+ if (!allowed.has(value))
747
+ fail('VALIDATION', `${name} is invalid.`);
748
+ return value;
749
+ }
750
+ function textParam(url, name, max) {
751
+ const value = (url.searchParams.get(name) ?? '').trim();
752
+ if (value.length > max)
753
+ fail('VALIDATION', `${name} is too long.`);
754
+ return value;
755
+ }
756
+ function intParam(url, name, fallback, max) {
757
+ const raw = url.searchParams.get(name);
758
+ if (raw == null || raw === '')
759
+ return fallback;
760
+ if (!/^\d+$/.test(raw))
761
+ fail('VALIDATION', `${name} is invalid.`);
762
+ const value = Number(raw);
763
+ if (!Number.isInteger(value) || value < 0)
764
+ fail('VALIDATION', `${name} is invalid.`);
765
+ return Math.min(max, value);
766
+ }
767
+ function optionalRevision(url) {
768
+ const raw = url.searchParams.get('revision');
769
+ if (raw == null || raw === '')
770
+ return null;
771
+ if (!/^\d+$/.test(raw))
772
+ fail('VALIDATION', 'revision is invalid.');
773
+ const value = Number(raw);
774
+ if (!Number.isInteger(value) || value < 1 || value > 1_000_000_000)
775
+ fail('VALIDATION', 'revision is invalid.');
776
+ return value;
777
+ }
778
+ function numberKey(key) {
779
+ if (!/^\d+$/.test(key))
780
+ return null;
781
+ const value = Number(key);
782
+ return Number.isInteger(value) ? value : null;
783
+ }
784
+ function clip(value, max = 240) {
785
+ const flat = value
786
+ .replace(/[ \t]+/g, ' ')
787
+ .replace(/\n+/g, '\n')
788
+ .trim();
789
+ if (flat.length <= max)
790
+ return flat;
791
+ return `${flat.slice(0, max - 1)}…`;
792
+ }
793
+ function text(value) {
794
+ return typeof value === 'string' ? value : value == null ? '' : '';
795
+ }
796
+ function fail(code, message) {
797
+ throw Object.assign(new Error(message), { code });
798
+ }