@yeaft/webchat-agent 0.1.665 → 0.1.667

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 (41) hide show
  1. package/connection/message-router.js +1 -24
  2. package/package.json +1 -1
  3. package/unify/cli.js +5 -84
  4. package/unify/config.js +2 -2
  5. package/unify/dream-v2/apply.js +1 -1
  6. package/unify/dream-v2/limits.js +1 -1
  7. package/unify/dream-v2/merge.js +1 -1
  8. package/unify/dream-v2/runner.js +2 -2
  9. package/unify/dream-v2/schedule.js +2 -2
  10. package/unify/dream-v2/segment.js +1 -1
  11. package/unify/dream-v2/session-wiring.js +2 -3
  12. package/unify/dream-v2/snapshot.js +1 -1
  13. package/unify/dream-v2/state.js +1 -1
  14. package/unify/dream-v2/triage.js +1 -1
  15. package/unify/engine.js +23 -133
  16. package/unify/eval/cases/memory.js +9 -142
  17. package/unify/features/summary.js +15 -98
  18. package/unify/index.js +0 -2
  19. package/unify/memory/ams.js +1 -1
  20. package/unify/memory/consolidate.js +10 -125
  21. package/unify/memory/segment-store.js +1 -1
  22. package/unify/memory/store-v2.js +6 -9
  23. package/unify/prompts.js +8 -50
  24. package/unify/session.js +2 -22
  25. package/unify/stop-hooks.js +8 -44
  26. package/unify/tools/index.js +0 -11
  27. package/unify/web-bridge.js +0 -98
  28. package/unify/memory/dream-shard.js +0 -722
  29. package/unify/memory/extract.js +0 -101
  30. package/unify/memory/layout.js +0 -358
  31. package/unify/memory/schema.js +0 -166
  32. package/unify/memory/shard-store.js +0 -373
  33. package/unify/memory/store.js +0 -578
  34. package/unify/memory/types.js +0 -139
  35. package/unify/memory/user-memory-store.js +0 -452
  36. package/unify/tools/memory-query.js +0 -134
  37. package/unify/tools/memory-read.js +0 -90
  38. package/unify/tools/memory-search.js +0 -140
  39. package/unify/tools/memory-trace.js +0 -135
  40. package/unify/tools/memory-write.js +0 -113
  41. package/unify/user-memory.js +0 -107
@@ -1,373 +0,0 @@
1
- /**
2
- * shard-store.js — task-334f R6 semantic-shard memory store (VP/task/user).
3
- *
4
- * This sits ON TOP OF 334o's `storage/shard-store.js` primitive. It adds:
5
- * - R6 entry schema (shard / sourceRef / supersedes / supersededBy / authoredBy)
6
- * - Frontmatter body serialisation (markdown-friendly, grep-able on disk)
7
- * - Supersede chain management (Δ26.2 Phase B)
8
- * - Atomic re-compression handoff (`memory-<shard>.md.compacting`)
9
- * - Migration stub from legacy R5 `memory-NNN.md` → semantic shards (334i)
10
- *
11
- * Hard boundaries (task-334f guardrails):
12
- * - does NOT touch 334o's jsonl-log layer
13
- * - does NOT run dream extract / re-compression decisions (334g)
14
- * - does NOT implement user-memory business logic (334l reuses this lib)
15
- */
16
-
17
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync } from 'fs';
18
- import { join } from 'path';
19
- import { openShardStore, writeAtomic } from '../storage/index.js';
20
- import {
21
- rebuildShardIndexFromDisk,
22
- saveShardIndex,
23
- } from '../storage/shard-index.js';
24
- import {
25
- buildShardSchema,
26
- softCapFor,
27
- PROJECT_DERIVE_THRESHOLD,
28
- MAX_VP_SHARDS,
29
- validateR6Entry,
30
- AUTHORED_BY,
31
- } from './schema.js';
32
-
33
- const COMPACTING_SUFFIX = '.compacting';
34
-
35
- /**
36
- * Open (or create) an R6 memory shard store rooted at `dir`.
37
- *
38
- * @param {string} dir filesystem directory (e.g. `~/.yeaft/memory/vp/<vpId>`)
39
- * @param {'vp'|'task'|'user'} kind
40
- * @param {{ extraShards?: string[] }} [opts]
41
- * @returns {object} handle with put/get/query/remove/compact/...
42
- */
43
- export function openMemoryShardStore(dir, kind = 'vp', opts = {}) {
44
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
45
-
46
- // Hydrate any pre-existing project-* shards from disk so the schema
47
- // allow-list recognises them on this open.
48
- const extraShards = new Set(opts.extraShards || []);
49
- for (const name of discoverOnDiskShards(dir)) {
50
- if (!extraShards.has(name)) extraShards.add(name);
51
- }
52
- const schema = buildShardSchema(kind, { extraShards: [...extraShards] });
53
- const inner = openShardStore(dir, schema);
54
-
55
- /**
56
- * Put an R6 entry. Merges the rich entry schema into `body` (frontmatter)
57
- * and surfaces the 5 filter-worthy fields through `meta`.
58
- */
59
- function put(entry) {
60
- validateR6Entry(entry);
61
- const body = serialiseR6Body(entry);
62
- const meta = pickMeta(entry);
63
- const res = inner.put({
64
- id: entry.id,
65
- shard: entry.shard,
66
- body,
67
- meta,
68
- });
69
- return res;
70
- }
71
-
72
- /** Retrieve an R6 entry (returns the parsed frontmatter + body). */
73
- function get(id) {
74
- const raw = inner.get(id);
75
- if (!raw) return null;
76
- const parsed = parseR6Body(raw.body);
77
- return {
78
- ...parsed,
79
- id: raw.id,
80
- shard: raw.shard,
81
- _meta: raw.meta || {},
82
- };
83
- }
84
-
85
- /** Query. See storage/shard-store.js for the filter shape. */
86
- function query(filter = {}) {
87
- const res = inner.query(filter);
88
- return {
89
- results: res.results.map(mapRecordToThinEntry),
90
- needsRecompression: res.needsRecompression.slice(),
91
- };
92
- }
93
-
94
- /** Remove an entry; underlying shard compacts immediately. */
95
- function remove(id) { return inner.remove(id); }
96
-
97
- /**
98
- * Supersede: create a new entry N that replaces olds M[...].
99
- * Writes N with supersedes=M[...], then marks each M.supersededBy=N.
100
- * Old entries are NOT removed — they stay for audit / memory_trace.
101
- */
102
- function supersede({ newEntry, oldIds }) {
103
- validateR6Entry(newEntry);
104
- if (!Array.isArray(oldIds) || oldIds.length === 0) {
105
- throw new Error('supersede: oldIds required (non-empty)');
106
- }
107
- const supersedes = oldIds.slice();
108
- const write = { ...newEntry, supersedes };
109
- const r = put(write);
110
-
111
- for (const oldId of oldIds) {
112
- const existing = get(oldId);
113
- if (!existing) continue;
114
- const updated = { ...existing, supersededBy: newEntry.id };
115
- put(updated);
116
- }
117
- return r;
118
- }
119
-
120
- /**
121
- * Atomic re-compression handoff:
122
- * caller writes the new shard body to `memory-<shard>.md.compacting`,
123
- * then calls `commitRecompression(shard)` which atomically renames it
124
- * over the live file. Readers always see either the old or the new file.
125
- *
126
- * Consumers (334g dream) build the new body themselves; we just manage
127
- * the rename + stats recomputation.
128
- */
129
- function stageRecompression(shardName, newBody) {
130
- const tmpPath = join(dir, `memory-${shardName}.md${COMPACTING_SUFFIX}`);
131
- writeAtomic(tmpPath, newBody);
132
- return tmpPath;
133
- }
134
-
135
- function commitRecompression(shardName) {
136
- const livePath = join(dir, `memory-${shardName}.md`);
137
- const tmpPath = join(dir, `memory-${shardName}.md${COMPACTING_SUFFIX}`);
138
- if (!existsSync(tmpPath)) {
139
- throw new Error(`commitRecompression: no tmp file at ${tmpPath}`);
140
- }
141
- renameSync(tmpPath, livePath);
142
- // The caller-supplied body replaced the whole shard. The old index rows
143
- // for this shard are stale (new ids / offsets). Rebuild that shard's
144
- // index rows from disk by delegating to the storage primitive — it walks
145
- // START/END markers and recomputes offsets. We keep other shards intact.
146
- const schema = buildShardSchema(kind, { extraShards: [...extraShards] });
147
- const rebuilt = rebuildShardIndexFromDisk(dir, schema);
148
- const innerIndex = inner.getIndex();
149
- // Swap this shard's rows + bucket.
150
- innerIndex.entries = innerIndex.entries.filter(e => e.shard !== shardName)
151
- .concat(rebuilt.entries.filter(e => e.shard === shardName));
152
- if (rebuilt.shards[shardName]) {
153
- innerIndex.shards[shardName] = rebuilt.shards[shardName];
154
- }
155
- saveShardIndex(dir, innerIndex);
156
- }
157
-
158
- function abortRecompression(shardName) {
159
- const tmpPath = join(dir, `memory-${shardName}.md${COMPACTING_SUFFIX}`);
160
- if (existsSync(tmpPath)) unlinkSync(tmpPath);
161
- }
162
-
163
- /** Return shard-level stats (byte count, entry count, soft cap). */
164
- function stats() {
165
- const raw = inner.stats();
166
- const shards = {};
167
- for (const [name, bucket] of Object.entries(raw.shards)) {
168
- shards[name] = { ...bucket, softCap: softCapFor(name) };
169
- }
170
- return { shards, count: raw.count };
171
- }
172
-
173
- /**
174
- * Hint for the dream layer — returns `project-<slug>` candidate when
175
- * ≥ PROJECT_DERIVE_THRESHOLD entries share a groupId and no project
176
- * shard exists for that slug yet. Returns `null` otherwise.
177
- *
178
- * The actual derive (creating the shard file + re-compressing entries
179
- * into it) is 334g dream work; this slice only advertises the hint so
180
- * dream can schedule.
181
- */
182
- function projectDeriveHint() {
183
- const groupCounts = new Map();
184
- const { results } = inner.query({});
185
- for (const rec of results) {
186
- const gid = rec.meta?.groupId;
187
- if (!gid) continue;
188
- groupCounts.set(gid, (groupCounts.get(gid) || 0) + 1);
189
- }
190
- for (const [gid, count] of groupCounts) {
191
- if (count < PROJECT_DERIVE_THRESHOLD) continue;
192
- const slug = slugify(gid);
193
- const shardName = `project-${slug}`;
194
- const shardNames = Object.keys(inner.stats().shards);
195
- if (shardNames.includes(shardName)) continue;
196
- if (shardNames.length >= MAX_VP_SHARDS) continue;
197
- return { groupId: gid, shard: shardName, count };
198
- }
199
- return null;
200
- }
201
-
202
- function close() { /* underlying store is stateless (index saved on every op) */ }
203
-
204
- return {
205
- put,
206
- get,
207
- query,
208
- remove,
209
- supersede,
210
- stageRecompression,
211
- commitRecompression,
212
- abortRecompression,
213
- stats,
214
- projectDeriveHint,
215
- close,
216
- _innerForTest: inner,
217
- };
218
- }
219
-
220
- // ─── Serialisation ──────────────────────────────────────────────
221
-
222
- function serialiseR6Body(entry) {
223
- const fm = ['---'];
224
- fm.push(`id: ${entry.id}`);
225
- if (entry.vp) fm.push(`vp: ${entry.vp}`);
226
- if (entry.taskId) fm.push(`taskId: ${entry.taskId}`);
227
- fm.push(`kind: ${entry.kind}`);
228
- fm.push(`shard: ${entry.shard}`);
229
- if (entry.sourceRef) {
230
- fm.push('sourceRef:');
231
- if (entry.sourceRef.groupId) fm.push(` groupId: ${entry.sourceRef.groupId}`);
232
- if (entry.sourceRef.taskId) fm.push(` taskId: ${entry.sourceRef.taskId}`);
233
- if (Array.isArray(entry.sourceRef.msgIds) && entry.sourceRef.msgIds.length) {
234
- fm.push(` msgIds: [${entry.sourceRef.msgIds.join(', ')}]`);
235
- }
236
- if (entry.sourceRef.timeWindow) fm.push(` timeWindow: ${entry.sourceRef.timeWindow}`);
237
- if (entry.sourceRef.hint) fm.push(` hint: ${JSON.stringify(entry.sourceRef.hint)}`);
238
- }
239
- if (Array.isArray(entry.supersedes) && entry.supersedes.length) {
240
- fm.push(`supersedes: [${entry.supersedes.join(', ')}]`);
241
- }
242
- if (entry.supersededBy) fm.push(`supersededBy: ${entry.supersededBy}`);
243
- if (entry.pinned != null) fm.push(`pinned: ${entry.pinned ? 'true' : 'false'}`);
244
- if (Array.isArray(entry.tags) && entry.tags.length) {
245
- fm.push(`tags: [${entry.tags.join(', ')}]`);
246
- }
247
- if (entry.authoredBy) fm.push(`authoredBy: ${entry.authoredBy}`);
248
- const now = new Date().toISOString();
249
- fm.push(`createdAt: ${entry.createdAt || now}`);
250
- fm.push(`updatedAt: ${now}`);
251
- fm.push('---');
252
- fm.push('');
253
- fm.push(entry.body || entry.content || '');
254
- return fm.join('\n');
255
- }
256
-
257
- function parseR6Body(raw) {
258
- if (!raw || !raw.startsWith('---')) return { body: raw || '' };
259
- const endIdx = raw.indexOf('\n---', 3);
260
- if (endIdx === -1) return { body: raw };
261
- const fm = raw.slice(4, endIdx).trim();
262
- const body = raw.slice(endIdx + 4).replace(/^\n+/, '');
263
- const out = { body };
264
- let inSourceRef = false;
265
- const sourceRef = {};
266
- for (const line of fm.split('\n')) {
267
- if (/^sourceRef:\s*$/.test(line)) { inSourceRef = true; continue; }
268
- if (inSourceRef && /^\s+/.test(line)) {
269
- const m = line.match(/^\s+(\w+):\s*(.*)$/);
270
- if (!m) continue;
271
- const [, k, v] = m;
272
- if (k === 'msgIds') {
273
- sourceRef.msgIds = v.replace(/^\[|\]$/g, '').split(',').map(s => s.trim()).filter(Boolean);
274
- } else if (k === 'hint') {
275
- try { sourceRef.hint = JSON.parse(v); } catch { sourceRef.hint = v; }
276
- } else {
277
- sourceRef[k] = v;
278
- }
279
- continue;
280
- }
281
- inSourceRef = false;
282
- const m = line.match(/^(\w+):\s*(.*)$/);
283
- if (!m) continue;
284
- const [, k, v] = m;
285
- switch (k) {
286
- case 'id': out.id = v; break;
287
- case 'vp': out.vp = v; break;
288
- case 'taskId': out.taskId = v; break;
289
- case 'kind': out.kind = v; break;
290
- case 'shard': out.shard = v; break;
291
- case 'supersededBy': out.supersededBy = v; break;
292
- case 'pinned': out.pinned = v === 'true'; break;
293
- case 'authoredBy': out.authoredBy = v; break;
294
- case 'createdAt': out.createdAt = v; break;
295
- case 'updatedAt': out.updatedAt = v; break;
296
- case 'supersedes':
297
- out.supersedes = v.replace(/^\[|\]$/g, '').split(',').map(s => s.trim()).filter(Boolean);
298
- break;
299
- case 'tags':
300
- out.tags = v.replace(/^\[|\]$/g, '').split(',').map(s => s.trim()).filter(Boolean);
301
- break;
302
- default: break;
303
- }
304
- }
305
- if (Object.keys(sourceRef).length > 0) out.sourceRef = sourceRef;
306
- return out;
307
- }
308
-
309
- function pickMeta(entry) {
310
- // Meta is only the fields the 334o query() layer filters on.
311
- const meta = {};
312
- if (entry.kind) meta.kind = entry.kind;
313
- if (entry.tags) meta.tags = entry.tags.slice();
314
- if (entry.pinned) meta.pinned = true;
315
- if (entry.sourceRef?.groupId) meta.groupId = entry.sourceRef.groupId;
316
- if (entry.sourceRef?.taskId) meta.taskId = entry.sourceRef.taskId;
317
- if (entry.supersededBy) meta.supersededBy = entry.supersededBy;
318
- return meta;
319
- }
320
-
321
- function mapRecordToThinEntry(rec) {
322
- return {
323
- id: rec.id,
324
- shard: rec.shard,
325
- kind: rec.meta?.kind,
326
- tags: rec.meta?.tags || [],
327
- pinned: Boolean(rec.meta?.pinned),
328
- groupId: rec.meta?.groupId,
329
- taskId: rec.meta?.taskId,
330
- supersededBy: rec.meta?.supersededBy || null,
331
- };
332
- }
333
-
334
- function slugify(s) {
335
- return String(s || '')
336
- .toLowerCase()
337
- .replace(/[^a-z0-9]+/g, '-')
338
- .replace(/^-+|-+$/g, '')
339
- .slice(0, 40);
340
- }
341
-
342
- function discoverOnDiskShards(dir) {
343
- try {
344
- return readdirSync(dir)
345
- .filter(f => /^memory-[A-Za-z0-9_-]+\.md$/.test(f))
346
- .map(f => f.replace(/^memory-/, '').replace(/\.md$/, ''));
347
- } catch { return []; }
348
- }
349
-
350
- // ─── Migration stub (§Δ23 / 334i) ───────────────────────────────
351
-
352
- /**
353
- * Migration stub: map a legacy R5 `memory-NNN.md` shard file path into a
354
- * semantic shard assignment. Actual batch migration runs in 334i; this
355
- * slice only defines the classifier API so dependent code can stub it.
356
- *
357
- * @param {object} legacyEntry parsed legacy entry { kind, scope, tags, ... }
358
- * @returns {string} semantic shard name ("skill" / "lessons" / ...)
359
- */
360
- export function classifyLegacyEntryToShard(legacyEntry) {
361
- if (!legacyEntry || typeof legacyEntry !== 'object') return 'skill';
362
- const kind = legacyEntry.kind || 'fact';
363
- switch (kind) {
364
- case 'lesson': return 'lessons';
365
- case 'preference': return 'preferences';
366
- case 'identity': return 'preferences';
367
- case 'relation': return 'relations';
368
- case 'skill': return 'skill';
369
- default: return 'skill';
370
- }
371
- }
372
-
373
- export { AUTHORED_BY };