trellis 2.0.8 → 2.0.13

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 (42) hide show
  1. package/README.md +279 -116
  2. package/dist/cli/index.js +655 -4
  3. package/dist/core/index.js +471 -2
  4. package/dist/embeddings/index.js +5 -1
  5. package/dist/{index-s603ev6w.js → index-5b01h414.js} +1 -1
  6. package/dist/index-5m0g9r0y.js +1100 -0
  7. package/dist/{index-zf6htvnm.js → index-7gvjxt27.js} +166 -2
  8. package/dist/index-hybgxe40.js +1174 -0
  9. package/dist/index.js +7 -2
  10. package/dist/transformers.node-bx3q9d7k.js +33130 -0
  11. package/package.json +9 -4
  12. package/src/cli/index.ts +939 -0
  13. package/src/core/agents/harness.ts +380 -0
  14. package/src/core/agents/index.ts +18 -0
  15. package/src/core/agents/types.ts +90 -0
  16. package/src/core/index.ts +85 -2
  17. package/src/core/kernel/trellis-kernel.ts +593 -0
  18. package/src/core/ontology/builtins.ts +248 -0
  19. package/src/core/ontology/index.ts +34 -0
  20. package/src/core/ontology/registry.ts +209 -0
  21. package/src/core/ontology/types.ts +124 -0
  22. package/src/core/ontology/validator.ts +382 -0
  23. package/src/core/persist/backend.ts +10 -0
  24. package/src/core/persist/sqlite-backend.ts +298 -0
  25. package/src/core/plugins/index.ts +17 -0
  26. package/src/core/plugins/registry.ts +322 -0
  27. package/src/core/plugins/types.ts +126 -0
  28. package/src/core/query/datalog.ts +188 -0
  29. package/src/core/query/engine.ts +370 -0
  30. package/src/core/query/index.ts +34 -0
  31. package/src/core/query/parser.ts +481 -0
  32. package/src/core/query/types.ts +200 -0
  33. package/src/embeddings/auto-embed.ts +248 -0
  34. package/src/embeddings/index.ts +7 -0
  35. package/src/embeddings/model.ts +21 -4
  36. package/src/embeddings/types.ts +8 -1
  37. package/src/index.ts +9 -0
  38. package/src/sync/http-transport.ts +144 -0
  39. package/src/sync/index.ts +11 -0
  40. package/src/sync/multi-repo.ts +200 -0
  41. package/src/sync/ws-transport.ts +145 -0
  42. package/dist/index-5bhe57y9.js +0 -326
@@ -0,0 +1,593 @@
1
+ /**
2
+ * TrellisKernel — Generic Graph Kernel
3
+ *
4
+ * The composition root for the Trellis semantic kernel. Orchestrates the
5
+ * EAV store, persistence backend, middleware chain, and snapshot lifecycle.
6
+ *
7
+ * The VCS engine (`TrellisVcsEngine`) sits on top of this generic kernel.
8
+ * Non-VCS consumers can use TrellisKernel directly for pure graph CRUD.
9
+ *
10
+ * @module trellis/core
11
+ */
12
+
13
+ import { EAVStore } from '../store/eav-store.js';
14
+ import type { Fact, Link, Atom } from '../store/eav-store.js';
15
+ import type {
16
+ KernelOp,
17
+ KernelOpKind,
18
+ KernelBackend,
19
+ } from '../persist/backend.js';
20
+ import type {
21
+ KernelMiddleware,
22
+ MiddlewareContext,
23
+ OpMiddlewareNext,
24
+ } from './middleware.js';
25
+ import { QueryEngine } from '../query/engine.js';
26
+ import type { Query } from '../query/types.js';
27
+ import type { QueryResult } from '../query/engine.js';
28
+
29
+ // ---------------------------------------------------------------------------
30
+ // Types
31
+ // ---------------------------------------------------------------------------
32
+
33
+ export interface KernelConfig {
34
+ /** Persistence backend (SQLite or in-memory). */
35
+ backend: KernelBackend;
36
+ /** Agent ID for attributing operations. */
37
+ agentId: string;
38
+ /** Middleware chain applied to every mutation. */
39
+ middleware?: KernelMiddleware[];
40
+ /** Auto-snapshot after this many ops (0 = disabled). */
41
+ snapshotThreshold?: number;
42
+ }
43
+
44
+ export interface MutateResult {
45
+ op: KernelOp;
46
+ factsDelta: { added: number; deleted: number };
47
+ linksDelta: { added: number; deleted: number };
48
+ }
49
+
50
+ export interface EntityRecord {
51
+ id: string;
52
+ type: string;
53
+ facts: Fact[];
54
+ links: Link[];
55
+ }
56
+
57
+ // ---------------------------------------------------------------------------
58
+ // Content-addressed hash
59
+ // ---------------------------------------------------------------------------
60
+
61
+ async function hashOp(
62
+ kind: string,
63
+ timestamp: string,
64
+ agentId: string,
65
+ previousHash: string | undefined,
66
+ payload: string,
67
+ ): Promise<string> {
68
+ const data = `${kind}|${timestamp}|${agentId}|${previousHash ?? ''}|${payload}`;
69
+ const buf = new TextEncoder().encode(data);
70
+ const hashBuf = await crypto.subtle.digest('SHA-256', buf);
71
+ const hex = Array.from(new Uint8Array(hashBuf))
72
+ .map((b) => b.toString(16).padStart(2, '0'))
73
+ .join('');
74
+ return `trellis:op:${hex}`;
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // Kernel
79
+ // ---------------------------------------------------------------------------
80
+
81
+ export class TrellisKernel {
82
+ private store: EAVStore;
83
+ private backend: KernelBackend;
84
+ private middleware: KernelMiddleware[];
85
+ private agentId: string;
86
+ private snapshotThreshold: number;
87
+ private opsSinceSnapshot: number = 0;
88
+ private _booted: boolean = false;
89
+
90
+ constructor(config: KernelConfig) {
91
+ this.store = new EAVStore();
92
+ this.backend = config.backend;
93
+ this.agentId = config.agentId;
94
+ this.middleware = config.middleware ?? [];
95
+ this.snapshotThreshold = config.snapshotThreshold ?? 0;
96
+ }
97
+
98
+ // -------------------------------------------------------------------------
99
+ // Lifecycle
100
+ // -------------------------------------------------------------------------
101
+
102
+ /**
103
+ * Initialize the backend and replay persisted state.
104
+ * Loads latest snapshot if available, then replays ops after it.
105
+ */
106
+ boot(): { opsReplayed: number; fromSnapshot: boolean } {
107
+ this.backend.init();
108
+
109
+ let opsReplayed = 0;
110
+ let fromSnapshot = false;
111
+
112
+ // Try loading from snapshot
113
+ const snapshot = this.backend.loadLatestSnapshot();
114
+ if (snapshot) {
115
+ this.store.restore(snapshot.data);
116
+ fromSnapshot = true;
117
+
118
+ // Replay only ops after the snapshot
119
+ const recentOps = this.backend.readAfter(snapshot.lastOpHash);
120
+ for (const op of recentOps) {
121
+ this._replayOp(op);
122
+ opsReplayed++;
123
+ }
124
+ } else {
125
+ // Full replay
126
+ const allOps = this.backend.readAll();
127
+ for (const op of allOps) {
128
+ this._replayOp(op);
129
+ opsReplayed++;
130
+ }
131
+ }
132
+
133
+ this._booted = true;
134
+ return { opsReplayed, fromSnapshot };
135
+ }
136
+
137
+ /**
138
+ * Close the backend connection.
139
+ */
140
+ close(): void {
141
+ this.backend.close?.();
142
+ this._booted = false;
143
+ }
144
+
145
+ isBooted(): boolean {
146
+ return this._booted;
147
+ }
148
+
149
+ // -------------------------------------------------------------------------
150
+ // Mutations
151
+ // -------------------------------------------------------------------------
152
+
153
+ /**
154
+ * Apply a mutation to the graph. Creates an op, runs it through middleware,
155
+ * decomposes into EAV primitives, persists, and returns the result.
156
+ */
157
+ async mutate(
158
+ kind: KernelOpKind | string,
159
+ payload: {
160
+ facts?: Fact[];
161
+ links?: Link[];
162
+ deleteFacts?: Fact[];
163
+ deleteLinks?: Link[];
164
+ meta?: Record<string, unknown>;
165
+ },
166
+ ctx?: Partial<MiddlewareContext>,
167
+ ): Promise<MutateResult> {
168
+ const timestamp = new Date().toISOString();
169
+ const lastOp = this.backend.getLastOp();
170
+ const agentId = ctx?.agentId ?? this.agentId;
171
+
172
+ const payloadStr = JSON.stringify(payload);
173
+ const hash = await hashOp(
174
+ kind,
175
+ timestamp,
176
+ agentId,
177
+ lastOp?.hash,
178
+ payloadStr,
179
+ );
180
+
181
+ const op: KernelOp = {
182
+ hash,
183
+ kind: kind as KernelOpKind,
184
+ timestamp,
185
+ agentId,
186
+ previousHash: lastOp?.hash,
187
+ facts: [...(payload.facts ?? [])],
188
+ links: [...(payload.links ?? [])],
189
+ deleteFacts: payload.deleteFacts?.length
190
+ ? [...payload.deleteFacts]
191
+ : undefined,
192
+ deleteLinks: payload.deleteLinks?.length
193
+ ? [...payload.deleteLinks]
194
+ : undefined,
195
+ };
196
+
197
+ // Attach meta as extra properties for middleware consumption
198
+ const extOp = op as any;
199
+ if (payload.meta) {
200
+ for (const [k, v] of Object.entries(payload.meta)) {
201
+ extOp[k] = v;
202
+ }
203
+ }
204
+
205
+ // Run through middleware chain
206
+ const mwCtx: MiddlewareContext = { agentId, ...ctx };
207
+ await this._runMiddleware(op, mwCtx);
208
+
209
+ // Apply to store
210
+ let factsAdded = 0;
211
+ let factsDeleted = 0;
212
+ let linksAdded = 0;
213
+ let linksDeleted = 0;
214
+
215
+ if (payload.deleteFacts && payload.deleteFacts.length > 0) {
216
+ this.store.deleteFacts(payload.deleteFacts);
217
+ factsDeleted = payload.deleteFacts.length;
218
+ }
219
+ if (payload.deleteLinks && payload.deleteLinks.length > 0) {
220
+ this.store.deleteLinks(payload.deleteLinks);
221
+ linksDeleted = payload.deleteLinks.length;
222
+ }
223
+ if (payload.facts && payload.facts.length > 0) {
224
+ this.store.addFacts(payload.facts);
225
+ factsAdded = payload.facts.length;
226
+ }
227
+ if (payload.links && payload.links.length > 0) {
228
+ this.store.addLinks(payload.links);
229
+ linksAdded = payload.links.length;
230
+ }
231
+
232
+ // Persist
233
+ this.backend.append(op);
234
+
235
+ // Auto-snapshot
236
+ this.opsSinceSnapshot++;
237
+ if (
238
+ this.snapshotThreshold > 0 &&
239
+ this.opsSinceSnapshot >= this.snapshotThreshold
240
+ ) {
241
+ this.checkpoint();
242
+ }
243
+
244
+ return {
245
+ op,
246
+ factsDelta: { added: factsAdded, deleted: factsDeleted },
247
+ linksDelta: { added: linksAdded, deleted: linksDeleted },
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Create a snapshot of the current store state.
253
+ */
254
+ checkpoint(): void {
255
+ const lastOp = this.backend.getLastOp();
256
+ if (!lastOp) return;
257
+ this.backend.saveSnapshot(lastOp.hash, this.store.snapshot());
258
+ this.opsSinceSnapshot = 0;
259
+ }
260
+
261
+ // -------------------------------------------------------------------------
262
+ // Queries
263
+ // -------------------------------------------------------------------------
264
+
265
+ /**
266
+ * Get the underlying EAV store for direct queries.
267
+ */
268
+ getStore(): EAVStore {
269
+ return this.store;
270
+ }
271
+
272
+ /**
273
+ * Get the persistence backend.
274
+ */
275
+ getBackend(): KernelBackend {
276
+ return this.backend;
277
+ }
278
+
279
+ /**
280
+ * Get the agent ID.
281
+ */
282
+ getAgentId(): string {
283
+ return this.agentId;
284
+ }
285
+
286
+ /**
287
+ * Read all persisted ops.
288
+ */
289
+ readAllOps(): KernelOp[] {
290
+ return this.backend.readAll();
291
+ }
292
+
293
+ /**
294
+ * Get the last persisted op.
295
+ */
296
+ getLastOp(): KernelOp | undefined {
297
+ return this.backend.getLastOp();
298
+ }
299
+
300
+ /**
301
+ * Create a QueryEngine bound to this kernel's store.
302
+ */
303
+ createQueryEngine(): QueryEngine {
304
+ return new QueryEngine(this.store);
305
+ }
306
+
307
+ /**
308
+ * Execute an EQL-S query, routing through middleware handleQuery hooks.
309
+ * If no middleware intercepts, the query runs directly against the store.
310
+ */
311
+ async query(q: Query): Promise<QueryResult> {
312
+ const engine = new QueryEngine(this.store);
313
+ const ctx: MiddlewareContext = { agentId: this.agentId };
314
+
315
+ // Build middleware chain for queries
316
+ const chain = this.middleware.filter((m) => m.handleQuery);
317
+
318
+ if (chain.length === 0) {
319
+ return engine.execute(q);
320
+ }
321
+
322
+ let result: QueryResult | undefined;
323
+ let idx = 0;
324
+
325
+ const next = (query: unknown, context: MiddlewareContext): QueryResult => {
326
+ if (idx < chain.length) {
327
+ const mw = chain[idx++];
328
+ return mw.handleQuery!(query, context, next);
329
+ }
330
+ result = engine.execute(query as Query);
331
+ return result;
332
+ };
333
+
334
+ result = next(q, ctx);
335
+ return result!;
336
+ }
337
+
338
+ /**
339
+ * Time-travel: reconstruct the store state at a specific op hash.
340
+ * Returns a new EAVStore with state replayed up to (and including) that op.
341
+ */
342
+ timeTravel(opHash: string): EAVStore {
343
+ const ops = this.backend.readUntil(opHash);
344
+ const snapshot = new EAVStore();
345
+
346
+ for (const op of ops) {
347
+ if (op.deleteFacts && op.deleteFacts.length > 0) {
348
+ snapshot.deleteFacts(op.deleteFacts);
349
+ }
350
+ if (op.deleteLinks && op.deleteLinks.length > 0) {
351
+ snapshot.deleteLinks(op.deleteLinks);
352
+ }
353
+ if (op.facts && op.facts.length > 0) {
354
+ snapshot.addFacts(op.facts);
355
+ }
356
+ if (op.links && op.links.length > 0) {
357
+ snapshot.addLinks(op.links);
358
+ }
359
+ }
360
+
361
+ return snapshot;
362
+ }
363
+
364
+ // -------------------------------------------------------------------------
365
+ // Entity CRUD (high-level graph operations)
366
+ // -------------------------------------------------------------------------
367
+
368
+ /**
369
+ * Create a new entity with the given type and attributes.
370
+ * Returns the entity ID.
371
+ */
372
+ async createEntity(
373
+ entityId: string,
374
+ type: string,
375
+ attributes: Record<string, Atom> = {},
376
+ links?: Array<{ attribute: string; targetEntityId: string }>,
377
+ ): Promise<MutateResult> {
378
+ const facts: Fact[] = [
379
+ { e: entityId, a: 'type', v: type },
380
+ { e: entityId, a: 'createdAt', v: new Date().toISOString() },
381
+ ];
382
+
383
+ for (const [attr, value] of Object.entries(attributes)) {
384
+ facts.push({ e: entityId, a: attr, v: value });
385
+ }
386
+
387
+ const linkRecords: Link[] = (links ?? []).map((l) => ({
388
+ e1: entityId,
389
+ a: l.attribute,
390
+ e2: l.targetEntityId,
391
+ }));
392
+
393
+ return this.mutate('addFacts', {
394
+ facts,
395
+ links: linkRecords.length > 0 ? linkRecords : undefined,
396
+ });
397
+ }
398
+
399
+ /**
400
+ * Get an entity by ID, returning all its facts and links.
401
+ */
402
+ getEntity(entityId: string): EntityRecord | null {
403
+ const facts = this.store.getFactsByEntity(entityId);
404
+ if (facts.length === 0) return null;
405
+
406
+ const typeFact = facts.find((f) => f.a === 'type');
407
+
408
+ return {
409
+ id: entityId,
410
+ type: (typeFact?.v as string) ?? 'unknown',
411
+ facts,
412
+ links: this.store.getLinksByEntity(entityId),
413
+ };
414
+ }
415
+
416
+ /**
417
+ * Update an entity's attributes. Deletes old values and adds new ones.
418
+ */
419
+ async updateEntity(
420
+ entityId: string,
421
+ updates: Record<string, Atom>,
422
+ ): Promise<MutateResult> {
423
+ const existingFacts = this.store.getFactsByEntity(entityId);
424
+ const deleteFacts: Fact[] = [];
425
+ const addFacts: Fact[] = [];
426
+
427
+ for (const [attr, newValue] of Object.entries(updates)) {
428
+ // Find existing facts for this attribute
429
+ const existing = existingFacts.filter((f) => f.a === attr);
430
+ deleteFacts.push(...existing);
431
+ addFacts.push({ e: entityId, a: attr, v: newValue });
432
+ }
433
+
434
+ // Add updatedAt
435
+ const updatedAtFacts = existingFacts.filter((f) => f.a === 'updatedAt');
436
+ deleteFacts.push(...updatedAtFacts);
437
+ addFacts.push({ e: entityId, a: 'updatedAt', v: new Date().toISOString() });
438
+
439
+ return this.mutate('addFacts', {
440
+ facts: addFacts,
441
+ deleteFacts,
442
+ });
443
+ }
444
+
445
+ /**
446
+ * Delete an entity and all its facts and links.
447
+ */
448
+ async deleteEntity(entityId: string): Promise<MutateResult> {
449
+ const facts = this.store.getFactsByEntity(entityId);
450
+ const links = this.store.getLinksByEntity(entityId);
451
+
452
+ return this.mutate('deleteFacts', {
453
+ deleteFacts: facts,
454
+ deleteLinks: links,
455
+ });
456
+ }
457
+
458
+ /**
459
+ * List entities by type, with optional attribute filters.
460
+ */
461
+ listEntities(type?: string, filters?: Record<string, Atom>): EntityRecord[] {
462
+ let entityIds: Set<string>;
463
+
464
+ if (type) {
465
+ const typeFacts = this.store.getFactsByValue('type', type);
466
+ entityIds = new Set(typeFacts.map((f) => f.e));
467
+ } else {
468
+ const allTypeFacts = this.store.getFactsByAttribute('type');
469
+ entityIds = new Set(allTypeFacts.map((f) => f.e));
470
+ }
471
+
472
+ // Apply attribute filters
473
+ if (filters) {
474
+ for (const [attr, value] of Object.entries(filters)) {
475
+ const matchingFacts = this.store.getFactsByValue(attr, value);
476
+ const matchingEntities = new Set(matchingFacts.map((f) => f.e));
477
+ for (const id of entityIds) {
478
+ if (!matchingEntities.has(id)) {
479
+ entityIds.delete(id);
480
+ }
481
+ }
482
+ }
483
+ }
484
+
485
+ return Array.from(entityIds)
486
+ .map((id) => this.getEntity(id)!)
487
+ .filter(Boolean);
488
+ }
489
+
490
+ /**
491
+ * Add a link between two entities.
492
+ */
493
+ async addLink(
494
+ sourceId: string,
495
+ attribute: string,
496
+ targetId: string,
497
+ ): Promise<MutateResult> {
498
+ return this.mutate('addLinks', {
499
+ links: [{ e1: sourceId, a: attribute, e2: targetId }],
500
+ });
501
+ }
502
+
503
+ /**
504
+ * Remove a link between two entities.
505
+ */
506
+ async removeLink(
507
+ sourceId: string,
508
+ attribute: string,
509
+ targetId: string,
510
+ ): Promise<MutateResult> {
511
+ return this.mutate('deleteLinks', {
512
+ deleteLinks: [{ e1: sourceId, a: attribute, e2: targetId }],
513
+ });
514
+ }
515
+
516
+ /**
517
+ * Add a fact to an entity.
518
+ */
519
+ async addFact(
520
+ entityId: string,
521
+ attribute: string,
522
+ value: Atom,
523
+ ): Promise<MutateResult> {
524
+ return this.mutate('addFacts', {
525
+ facts: [{ e: entityId, a: attribute, v: value }],
526
+ });
527
+ }
528
+
529
+ /**
530
+ * Remove a fact from an entity.
531
+ */
532
+ async removeFact(
533
+ entityId: string,
534
+ attribute: string,
535
+ value: Atom,
536
+ ): Promise<MutateResult> {
537
+ return this.mutate('deleteFacts', {
538
+ deleteFacts: [{ e: entityId, a: attribute, v: value }],
539
+ });
540
+ }
541
+
542
+ // -------------------------------------------------------------------------
543
+ // Middleware
544
+ // -------------------------------------------------------------------------
545
+
546
+ addMiddleware(mw: KernelMiddleware): void {
547
+ this.middleware.push(mw);
548
+ }
549
+
550
+ removeMiddleware(name: string): void {
551
+ this.middleware = this.middleware.filter((m) => m.name !== name);
552
+ }
553
+
554
+ // -------------------------------------------------------------------------
555
+ // Internal
556
+ // -------------------------------------------------------------------------
557
+
558
+ private async _runMiddleware(
559
+ op: KernelOp,
560
+ ctx: MiddlewareContext,
561
+ ): Promise<void> {
562
+ const chain = [...this.middleware];
563
+ let idx = 0;
564
+
565
+ const next: OpMiddlewareNext = async (op, ctx) => {
566
+ const mw = chain[idx++];
567
+ if (mw?.handleOp) {
568
+ await mw.handleOp(op, ctx, next);
569
+ }
570
+ };
571
+
572
+ if (chain.length > 0) {
573
+ await next(op, ctx);
574
+ }
575
+ }
576
+
577
+ private _replayOp(op: KernelOp): void {
578
+ // Replay without persisting or middleware — just apply to store
579
+ // Deletions first, then additions (same order as mutate)
580
+ if (op.deleteFacts && op.deleteFacts.length > 0) {
581
+ this.store.deleteFacts(op.deleteFacts);
582
+ }
583
+ if (op.deleteLinks && op.deleteLinks.length > 0) {
584
+ this.store.deleteLinks(op.deleteLinks);
585
+ }
586
+ if (op.facts && op.facts.length > 0) {
587
+ this.store.addFacts(op.facts);
588
+ }
589
+ if (op.links && op.links.length > 0) {
590
+ this.store.addLinks(op.links);
591
+ }
592
+ }
593
+ }