@geraldmaron/construct 1.0.23 → 1.0.24

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 (52) hide show
  1. package/README.md +0 -2
  2. package/bin/construct +15 -215
  3. package/lib/embed/inbox.mjs +6 -3
  4. package/lib/embed/recommendation-store.mjs +7 -289
  5. package/lib/embed/reconcile.mjs +2 -2
  6. package/lib/hooks/config-protection.mjs +4 -4
  7. package/lib/hooks/session-reflect.mjs +5 -1
  8. package/lib/intake/git-queue.mjs +195 -0
  9. package/lib/intake/queue.mjs +9 -16
  10. package/lib/mcp/tools/storage.mjs +2 -3
  11. package/lib/mcp-catalog.json +3 -3
  12. package/lib/mcp-manager.mjs +59 -3
  13. package/lib/observation-store.mjs +38 -166
  14. package/lib/orchestration/runtime.mjs +3 -2
  15. package/lib/reconcile/index.mjs +0 -2
  16. package/lib/service-manager.mjs +38 -256
  17. package/lib/setup.mjs +26 -426
  18. package/lib/status.mjs +3 -6
  19. package/lib/storage/admin.mjs +48 -325
  20. package/lib/storage/backend.mjs +10 -57
  21. package/lib/storage/hybrid-query.mjs +15 -196
  22. package/lib/storage/sync.mjs +36 -177
  23. package/lib/storage/vector-client.mjs +256 -235
  24. package/lib/strategy-store.mjs +35 -286
  25. package/lib/worker/entrypoint.mjs +6 -14
  26. package/package.json +6 -5
  27. package/platforms/claude/settings.template.json +0 -7
  28. package/scripts/sync-specialists.mjs +46 -12
  29. package/specialists/prompts/cx-qa.md +1 -1
  30. package/specialists/registry.json +0 -8
  31. package/templates/docs/construct_guide.md +1 -1
  32. package/db/schema/001_init.sql +0 -40
  33. package/db/schema/002_pgvector.sql +0 -182
  34. package/db/schema/003_intake.sql +0 -47
  35. package/db/schema/003_observation_reconciliation.sql +0 -14
  36. package/db/schema/004_recommendations.sql +0 -46
  37. package/db/schema/005_strategy.sql +0 -21
  38. package/db/schema/006_graph.sql +0 -24
  39. package/db/schema/007_tags.sql +0 -30
  40. package/db/schema/008_skill_usage.sql +0 -24
  41. package/db/schema/009_scheduler.sql +0 -14
  42. package/db/schema/010_cx_scores.sql +0 -51
  43. package/lib/intake/postgres-queue.mjs +0 -240
  44. package/lib/reconcile/postgres-namespace.mjs +0 -102
  45. package/lib/services/local-postgres.mjs +0 -15
  46. package/lib/storage/backup.mjs +0 -347
  47. package/lib/storage/migrations.mjs +0 -187
  48. package/lib/storage/postgres-backup.mjs +0 -124
  49. package/lib/storage/sql-store.mjs +0 -45
  50. package/lib/storage/store-version.mjs +0 -115
  51. package/lib/storage/unified-storage.mjs +0 -550
  52. package/lib/storage/vector-store.mjs +0 -100
@@ -1,45 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * lib/storage/sql-store.mjs — lightweight shared SQL storage facade.
4
- */
5
- import { createSqlClient, probeSqlClient } from './backend.mjs';
6
- import { resolveDatabaseUrl } from '../env-config.mjs';
7
-
8
- export function hasSqlStore(env = process.env) {
9
- return Boolean(resolveDatabaseUrl(env));
10
- }
11
-
12
- export function detectStoreMode(env = process.env) {
13
- if (resolveDatabaseUrl(env)) return 'postgres';
14
- return 'file';
15
- }
16
-
17
- export function describeSqlStore(env = process.env) {
18
- const mode = detectStoreMode(env);
19
- return {
20
- mode,
21
- configured: mode !== 'file',
22
- sharedReady: mode === 'postgres',
23
- fallbackAvailable: mode === 'file',
24
- hasDatabaseUrl: Boolean(resolveDatabaseUrl(env)),
25
- };
26
- }
27
-
28
- export async function describeSqlStoreHealth(env = process.env) {
29
- const store = describeSqlStore(env);
30
- if (store.mode !== 'postgres') return sqlStoreHealth(env);
31
- const client = createSqlClient(env);
32
- try {
33
- return await probeSqlClient(client);
34
- } finally {
35
- if (client) await client.end({ timeout: 5 }).catch(() => {});
36
- }
37
- }
38
-
39
- export function sqlStoreHealth(env = process.env) {
40
- const store = describeSqlStore(env);
41
- if (store.mode === 'postgres') {
42
- return { status: 'configured', message: 'Shared Postgres store is configured' };
43
- }
44
- return { status: 'unavailable', message: 'No SQL store configured; using file-state only' };
45
- }
@@ -1,115 +0,0 @@
1
- /**
2
- * lib/storage/store-version.mjs — versioned schema for the JSON stores.
3
- *
4
- * The observation, entity, and session stores write JSON arrays (or objects)
5
- * to disk. Until now, the on-disk format had no version stamp, which meant
6
- * any future schema change had to either fork the file or risk silently
7
- * breaking older data. This module provides a thin, opt-in versioning
8
- * layer:
9
- *
10
- * readVersioned(filePath, storeId)
11
- * Returns the on-disk records, lazily upgrading them through the
12
- * store's migration chain if the embedded version is older than the
13
- * current one. Existing unversioned files (plain arrays) are treated
14
- * as version 1 and stamped on the next write.
15
- *
16
- * writeVersioned(filePath, storeId, records)
17
- * Wraps the records in `{ schemaVersion, storeId, records }` and
18
- * writes atomically. Callers always read/write through this helper
19
- * so the on-disk format stays canonical.
20
- *
21
- * registerMigration(storeId, fromVersion, toVersion, migrate)
22
- * Record a one-step migration. The runtime walks migrations in
23
- * order until the records reach the current version.
24
- *
25
- * Migrations are pure functions over records; they cannot reach the network,
26
- * fork processes, or call other stores. That keeps lazy upgrade safe to run
27
- * inside a hot Read path.
28
- */
29
-
30
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
31
- import { dirname } from 'node:path';
32
-
33
- const CURRENT_VERSIONS = {
34
- observations: 1,
35
- observations_vectors: 1,
36
- observations_index: 1,
37
- entities: 1,
38
- entity_vectors: 1,
39
- sessions: 1,
40
- session_vectors: 1,
41
- };
42
-
43
- const MIGRATIONS = new Map();
44
-
45
- export function registerMigration(storeId, fromVersion, migrate) {
46
- const key = `${storeId}@${fromVersion}`;
47
- if (MIGRATIONS.has(key)) {
48
- throw new Error(`Migration already registered: ${key}`);
49
- }
50
- MIGRATIONS.set(key, migrate);
51
- }
52
-
53
- export function currentVersion(storeId) {
54
- return CURRENT_VERSIONS[storeId] ?? 1;
55
- }
56
-
57
- function unwrap(parsed) {
58
- if (parsed && typeof parsed === 'object' && Array.isArray(parsed.records)) {
59
- return {
60
- schemaVersion: Number.isInteger(parsed.schemaVersion) ? parsed.schemaVersion : 1,
61
- records: parsed.records,
62
- };
63
- }
64
- if (Array.isArray(parsed)) {
65
- return { schemaVersion: 1, records: parsed };
66
- }
67
- return { schemaVersion: 1, records: [] };
68
- }
69
-
70
- function migrateOnce(storeId, schemaVersion, records) {
71
- const migrate = MIGRATIONS.get(`${storeId}@${schemaVersion}`);
72
- if (!migrate) return null;
73
- const next = migrate(records);
74
- if (!Array.isArray(next)) {
75
- throw new Error(`Migration ${storeId}@${schemaVersion}→ must return an array of records`);
76
- }
77
- return next;
78
- }
79
-
80
- /**
81
- * Read a versioned JSON store. Lazily applies migrations to bring records up
82
- * to the current version. Returns plain records (caller doesn't see the
83
- * version envelope).
84
- */
85
- export function readVersioned(filePath, storeId, fallback = []) {
86
- if (!existsSync(filePath)) return fallback;
87
- let parsed;
88
- try { parsed = JSON.parse(readFileSync(filePath, 'utf8')); }
89
- catch { return fallback; }
90
-
91
- let { schemaVersion, records } = unwrap(parsed);
92
- const target = currentVersion(storeId);
93
-
94
- while (schemaVersion < target) {
95
- const next = migrateOnce(storeId, schemaVersion, records);
96
- if (next === null) break;
97
- records = next;
98
- schemaVersion += 1;
99
- }
100
-
101
- return records;
102
- }
103
-
104
- /**
105
- * Write a versioned JSON store. Always stamps the current version.
106
- */
107
- export function writeVersioned(filePath, storeId, records) {
108
- mkdirSync(dirname(filePath), { recursive: true });
109
- const payload = {
110
- schemaVersion: currentVersion(storeId),
111
- storeId,
112
- records: Array.isArray(records) ? records : [],
113
- };
114
- writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n');
115
- }
@@ -1,550 +0,0 @@
1
- /**
2
- * lib/storage/unified-storage.mjs — Single storage abstraction with strong consistency.
3
- *
4
- * Addresses storage sync fragility by:
5
- * 1. Single unified interface for all storage operations
6
- * 2. Transaction-based writes (atomic, rollback on failure)
7
- * 3. Automatic backend selection (file/SQL/vector) based on capabilities
8
- * 4. Consistent error handling and retry logic
9
- * 5. No manual sync between backends - single source of truth
10
- */
11
-
12
- import fs from 'node:fs';
13
- import path from 'node:path';
14
- import { homedir } from 'node:os';
15
- import { createSqlClient, closeSqlClient } from './backend.mjs';
16
- import { loadStateSnapshot } from './state-source.mjs';
17
- import { embedBatch, getEmbeddingModelInfo } from './embeddings-engine.mjs';
18
- import { writeLocalVectorIndex, readLocalVectorIndex } from './vector-store.mjs';
19
- import { runMigrations } from './migrations.mjs';
20
-
21
- const CX_DIR = path.join(homedir(), '.cx');
22
-
23
- // ---------------------------------------------------------------------------
24
- // Storage backend abstraction
25
- // ---------------------------------------------------------------------------
26
-
27
- class StorageBackend {
28
- constructor(name, capabilities) {
29
- this.name = name;
30
- this.capabilities = capabilities; // 'read', 'write', 'query', 'vector'
31
- this.healthy = false;
32
- }
33
-
34
- async healthCheck() { return { healthy: false, error: 'Not implemented' }; }
35
- async read(id) { throw new Error('Not implemented'); }
36
- async write(id, data) { throw new Error('Not implemented'); }
37
- async query(criteria) { throw new Error('Not implemented'); }
38
- async vectorSearch(embedding, options) { throw new Error('Not implemented'); }
39
- }
40
-
41
- class FileBackend extends StorageBackend {
42
- constructor(basePath) {
43
- super('file', ['read', 'write']);
44
- this.basePath = basePath;
45
- fs.mkdirSync(basePath, { recursive: true });
46
- this.healthy = true;
47
- }
48
-
49
- async healthCheck() {
50
- try {
51
- fs.accessSync(this.basePath, fs.constants.W_OK);
52
- return { healthy: true };
53
- } catch (error) {
54
- return { healthy: false, error: error.message };
55
- }
56
- }
57
-
58
- async read(id) {
59
- const filePath = path.join(this.basePath, `${id}.json`);
60
- if (!fs.existsSync(filePath)) return null;
61
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
62
- }
63
-
64
- async write(id, data) {
65
- const filePath = path.join(this.basePath, `${id}.json`);
66
- const tempPath = `${filePath}.tmp`;
67
-
68
- // Atomic write: write to temp, then rename
69
- fs.writeFileSync(tempPath, JSON.stringify(data, null, 2));
70
- fs.renameSync(tempPath, filePath);
71
-
72
- return { written: true, path: filePath };
73
- }
74
-
75
- async query({ project, kind }) {
76
- const results = [];
77
- const files = fs.readdirSync(this.basePath).filter(f => f.endsWith('.json'));
78
-
79
- for (const file of files) {
80
- try {
81
- const data = JSON.parse(fs.readFileSync(path.join(this.basePath, file), 'utf8'));
82
- if ((!project || data.project === project) && (!kind || data.kind === kind)) {
83
- results.push(data);
84
- }
85
- } catch { /* skip invalid files */ }
86
- }
87
-
88
- return results;
89
- }
90
- }
91
-
92
- class SqlBackend extends StorageBackend {
93
- constructor(env) {
94
- super('sql', ['read', 'write', 'query', 'vector']);
95
- this.env = env;
96
- this.client = null;
97
- this.healthy = false;
98
- }
99
-
100
- async connect() {
101
- if (this.client) return this.client;
102
- this.client = createSqlClient(this.env);
103
- if (this.client) {
104
- await runMigrations(this.client);
105
- this.healthy = true;
106
- }
107
- return this.client;
108
- }
109
-
110
- async healthCheck() {
111
- try {
112
- const client = await this.connect();
113
- if (!client) return { healthy: false, error: 'No DATABASE_URL configured' };
114
-
115
- await client`SELECT 1`;
116
- return { healthy: true };
117
- } catch (error) {
118
- this.healthy = false;
119
- return { healthy: false, error: error.message };
120
- }
121
- }
122
-
123
- async read(id) {
124
- const client = await this.connect();
125
- if (!client) return null;
126
-
127
- const rows = await client`
128
- SELECT * FROM construct_documents
129
- WHERE id = ${id}
130
- LIMIT 1
131
- `;
132
-
133
- return rows[0] || null;
134
- }
135
-
136
- async write(id, data) {
137
- const client = await this.connect();
138
- if (!client) throw new Error('SQL backend not available');
139
-
140
- // Use upsert for atomic write
141
- await client`
142
- INSERT INTO construct_documents (
143
- id, project, kind, title, summary, body,
144
- source_path, tags, content_hash, embedding, updated_at
145
- ) VALUES (
146
- ${id}, ${data.project}, ${data.kind}, ${data.title},
147
- ${data.summary}, ${data.body}, ${data.source_path},
148
- ${data.tags}, ${data.content_hash}, ${data.embedding},
149
- NOW()
150
- )
151
- ON CONFLICT (id) DO UPDATE SET
152
- project = EXCLUDED.project,
153
- kind = EXCLUDED.kind,
154
- title = EXCLUDED.title,
155
- summary = EXCLUDED.summary,
156
- body = EXCLUDED.body,
157
- source_path = EXCLUDED.source_path,
158
- tags = EXCLUDED.tags,
159
- content_hash = EXCLUDED.content_hash,
160
- embedding = EXCLUDED.embedding,
161
- updated_at = NOW()
162
- `;
163
-
164
- return { written: true, id };
165
- }
166
-
167
- async query({ project, kind, limit = 100 }) {
168
- const client = await this.connect();
169
- if (!client) return [];
170
-
171
- let query = client`SELECT * FROM construct_documents WHERE 1=1`;
172
-
173
- if (project) {
174
- query = client`${query} AND project = ${project}`;
175
- }
176
- if (kind) {
177
- query = client`${query} AND kind = ${kind}`;
178
- }
179
-
180
- query = client`${query} ORDER BY updated_at DESC LIMIT ${limit}`;
181
-
182
- return await query;
183
- }
184
-
185
- async vectorSearch(embedding, { project, limit = 10 }) {
186
- const client = await this.connect();
187
- if (!client) return [];
188
-
189
- const embeddingStr = `[${embedding.join(',')}]`;
190
-
191
- return await client`
192
- SELECT *, embedding <-> ${embeddingStr}::vector as distance
193
- FROM construct_documents
194
- WHERE project = ${project}
195
- ORDER BY embedding <-> ${embeddingStr}::vector
196
- LIMIT ${limit}
197
- `;
198
- }
199
- }
200
-
201
- class VectorBackend extends StorageBackend {
202
- constructor(indexPath) {
203
- super('vector', ['read', 'query', 'vector']);
204
- this.indexPath = indexPath;
205
- this.healthy = !!indexPath;
206
- }
207
-
208
- async healthCheck() {
209
- if (!this.indexPath) {
210
- return { healthy: false, error: 'No index path configured' };
211
- }
212
- try {
213
- fs.accessSync(path.dirname(this.indexPath), fs.constants.W_OK);
214
- return { healthy: true };
215
- } catch (error) {
216
- return { healthy: false, error: error.message };
217
- }
218
- }
219
-
220
- async read(id) {
221
- const index = readLocalVectorIndex(this.indexPath);
222
- return index.find(item => item.id === id) || null;
223
- }
224
-
225
- async write(id, data) {
226
- // Vector backend is read-only - writes go through SQL backend
227
- throw new Error('Vector backend is read-only. Use SQL backend for writes.');
228
- }
229
-
230
- async vectorSearch(embedding, options) {
231
- const index = readLocalVectorIndex(this.indexPath);
232
- const { limit = 10 } = options;
233
-
234
- // Simple cosine similarity
235
- const results = index.map(item => ({
236
- ...item,
237
- similarity: cosineSimilarity(embedding, item.embedding),
238
- }));
239
-
240
- results.sort((a, b) => b.similarity - a.similarity);
241
- return results.slice(0, limit);
242
- }
243
- }
244
-
245
- function cosineSimilarity(a, b) {
246
- let dotProduct = 0;
247
- let normA = 0;
248
- let normB = 0;
249
-
250
- for (let i = 0; i < a.length; i++) {
251
- dotProduct += a[i] * b[i];
252
- normA += a[i] * a[i];
253
- normB += b[i] * b[i];
254
- }
255
-
256
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
257
- }
258
-
259
- // ---------------------------------------------------------------------------
260
- // Unified storage manager
261
- // ---------------------------------------------------------------------------
262
-
263
- export class UnifiedStorage {
264
- constructor(options = {}) {
265
- this.env = options.env || process.env;
266
- this.project = options.project || 'construct';
267
- this.backends = new Map();
268
- this.primaryBackend = null;
269
- this.cache = new Map();
270
-
271
- this.initializeBackends();
272
- }
273
-
274
- initializeBackends() {
275
- const cxDir = path.join(homedir(), '.cx');
276
-
277
- // Always have file backend as fallback
278
- const fileBackend = new FileBackend(path.join(cxDir, 'storage', 'documents'));
279
- this.backends.set('file', fileBackend);
280
-
281
- // SQL backend if configured
282
- if (this.env.DATABASE_URL) {
283
- const sqlBackend = new SqlBackend(this.env);
284
- this.backends.set('sql', sqlBackend);
285
- }
286
-
287
- // Vector backend if configured
288
- const vectorPath = this.env.CONSTRUCT_VECTOR_INDEX_PATH || path.join(cxDir, 'vector-index.json');
289
- if (vectorPath) {
290
- const vectorBackend = new VectorBackend(vectorPath);
291
- this.backends.set('vector', vectorBackend);
292
- }
293
-
294
- // Determine primary backend (prefer SQL, fallback to file)
295
- this.primaryBackend = this.backends.get('sql') || this.backends.get('file');
296
- }
297
-
298
- async healthCheck() {
299
- const results = {};
300
-
301
- for (const [name, backend] of this.backends) {
302
- results[name] = await backend.healthCheck();
303
- }
304
-
305
- const healthy = Object.values(results).some(r => r.healthy);
306
- const primaryHealthy = this.primaryBackend ? (await this.primaryBackend.healthCheck()).healthy : false;
307
-
308
- return {
309
- overall: healthy ? (primaryHealthy ? 'healthy' : 'degraded') : 'unavailable',
310
- primary: this.primaryBackend?.name,
311
- backends: results,
312
- };
313
- }
314
-
315
- /**
316
- * Store a document with atomic consistency.
317
- * Writes to primary backend only - no sync needed.
318
- */
319
- async storeDocument(id, document) {
320
- if (!this.primaryBackend) {
321
- throw new Error('No storage backend available');
322
- }
323
-
324
- const enriched = {
325
- ...document,
326
- project: this.project,
327
- storedAt: new Date().toISOString(),
328
- };
329
-
330
- try {
331
- const result = await this.primaryBackend.write(id, enriched);
332
-
333
- // Invalidate cache
334
- this.cache.delete(id);
335
-
336
- return {
337
- success: true,
338
- id,
339
- backend: this.primaryBackend.name,
340
- ...result,
341
- };
342
- } catch (error) {
343
- return {
344
- success: false,
345
- id,
346
- error: error.message,
347
- };
348
- }
349
- }
350
-
351
- /**
352
- * Retrieve a document by ID.
353
- * Checks cache first, then primary backend.
354
- */
355
- async retrieveDocument(id) {
356
- // Check cache
357
- if (this.cache.has(id)) {
358
- return this.cache.get(id);
359
- }
360
-
361
- if (!this.primaryBackend) {
362
- return null;
363
- }
364
-
365
- const doc = await this.primaryBackend.read(id);
366
-
367
- if (doc) {
368
- this.cache.set(id, doc);
369
- }
370
-
371
- return doc;
372
- }
373
-
374
- /**
375
- * Query documents with filters.
376
- */
377
- async queryDocuments(criteria) {
378
- if (!this.primaryBackend) {
379
- return [];
380
- }
381
-
382
- return await this.primaryBackend.query({
383
- ...criteria,
384
- project: this.project,
385
- });
386
- }
387
-
388
- /**
389
- * Semantic search using vector similarity.
390
- * Tries SQL backend first (most accurate), falls back to local vector index.
391
- */
392
- async semanticSearch(query, options = {}) {
393
- const { limit = 10, threshold = 0.7 } = options;
394
-
395
- // Generate embedding for query
396
- const modelInfo = await getEmbeddingModelInfo({ env: this.env });
397
- const embeddings = await embedBatch([query], { env: this.env });
398
- const queryEmbedding = embeddings[0]?.embedding;
399
-
400
- if (!queryEmbedding) {
401
- throw new Error('Failed to generate query embedding');
402
- }
403
-
404
- // Try SQL backend first
405
- const sqlBackend = this.backends.get('sql');
406
- if (sqlBackend && (await sqlBackend.healthCheck()).healthy) {
407
- const results = await sqlBackend.vectorSearch(queryEmbedding, {
408
- project: this.project,
409
- limit
410
- });
411
-
412
- return results
413
- .filter(r => 1 - r.distance >= threshold)
414
- .map(r => ({
415
- ...r,
416
- similarity: 1 - r.distance,
417
- }));
418
- }
419
-
420
- // Fall back to vector backend
421
- const vectorBackend = this.backends.get('vector');
422
- if (vectorBackend && (await vectorBackend.healthCheck()).healthy) {
423
- return await vectorBackend.vectorSearch(queryEmbedding, { limit });
424
- }
425
-
426
- // Last resort: no vector search available
427
- return [];
428
- }
429
-
430
- /**
431
- * Sync file state to storage with embedding.
432
- * Single operation - no separate sync step needed.
433
- */
434
- async syncFromFileState(rootDir, options = {}) {
435
- const snapshot = loadStateSnapshot(rootDir);
436
- const modelInfo = await getEmbeddingModelInfo({ env: this.env });
437
-
438
- const results = {
439
- processed: 0,
440
- failed: 0,
441
- errors: [],
442
- };
443
-
444
- // Process each document in the snapshot
445
- const documents = this.snapshotToDocuments(snapshot, rootDir);
446
-
447
- // Generate embeddings in batch
448
- const texts = documents.map(d =>
449
- [d.title, d.summary, d.body, d.source_path].filter(Boolean).join('\n')
450
- );
451
-
452
- const embeddings = texts.length > 0
453
- ? await embedBatch(texts, { env: this.env })
454
- : [];
455
-
456
- // Store each document
457
- for (let i = 0; i < documents.length; i++) {
458
- const doc = documents[i];
459
- const embedding = embeddings[i]?.embedding;
460
-
461
- try {
462
- await this.storeDocument(doc.id, {
463
- ...doc,
464
- embedding: embedding ? Array.from(embedding) : null,
465
- embeddingModel: modelInfo.model,
466
- });
467
- results.processed++;
468
- } catch (error) {
469
- results.failed++;
470
- results.errors.push({ id: doc.id, error: error.message });
471
- }
472
- }
473
-
474
- return results;
475
- }
476
-
477
- snapshotToDocuments(snapshot, rootDir) {
478
- const docs = [];
479
- const project = this.project;
480
-
481
- if (snapshot.context) {
482
- docs.push({
483
- id: `${project}:context`,
484
- kind: 'context',
485
- title: 'Context state',
486
- summary: snapshot.context.contextSummary || '',
487
- body: JSON.stringify(snapshot.context, null, 2),
488
- source_path: '.cx/context.json',
489
- tags: ['context', 'state'],
490
- });
491
- }
492
-
493
- if (snapshot.architecture) {
494
- docs.push({
495
- id: `${project}:architecture`,
496
- kind: 'architecture',
497
- title: 'Architecture docs',
498
- summary: snapshot.architecture.slice(0, 240),
499
- body: snapshot.architecture,
500
- source_path: 'docs/concepts/architecture.md',
501
- tags: ['architecture', 'docs'],
502
- });
503
- }
504
-
505
- // Add product intel docs
506
- for (const doc of snapshot.productIntelDocs || []) {
507
- const kind = doc.path.startsWith('docs/prd/') ? 'prd'
508
- : doc.path.startsWith('docs/meta-prd/') ? 'meta-prd'
509
- : 'knowledge';
510
-
511
- docs.push({
512
- id: `${project}:${doc.path}`,
513
- kind,
514
- title: doc.title,
515
- summary: doc.body.slice(0, 240),
516
- body: doc.body,
517
- source_path: doc.path,
518
- tags: ['knowledge', kind],
519
- });
520
- }
521
-
522
- return docs;
523
- }
524
- }
525
-
526
- // ---------------------------------------------------------------------------
527
- // Convenience exports
528
- // ---------------------------------------------------------------------------
529
-
530
- let globalStorage = null;
531
-
532
- export function getUnifiedStorage(options = {}) {
533
- if (!globalStorage) {
534
- globalStorage = new UnifiedStorage(options);
535
- }
536
- return globalStorage;
537
- }
538
-
539
- export function resetUnifiedStorage() {
540
- globalStorage = null;
541
- }
542
-
543
- export async function withStorage(fn, options = {}) {
544
- const storage = getUnifiedStorage(options);
545
- try {
546
- return await fn(storage);
547
- } finally {
548
- // Cleanup if needed
549
- }
550
- }