@semiont/make-meaning 0.5.3 → 0.5.4

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 (93) hide show
  1. package/dist/annotation-assembly.d.ts +8 -0
  2. package/dist/annotation-assembly.d.ts.map +1 -0
  3. package/dist/annotation-context.d.ts +104 -0
  4. package/dist/annotation-context.d.ts.map +1 -0
  5. package/dist/annotation-operations.d.ts +41 -0
  6. package/dist/annotation-operations.d.ts.map +1 -0
  7. package/dist/batch-utils.d.ts +14 -0
  8. package/dist/batch-utils.d.ts.map +1 -0
  9. package/dist/bootstrap/entity-types.d.ts +26 -0
  10. package/dist/bootstrap/entity-types.d.ts.map +1 -0
  11. package/dist/browser.d.ts +45 -0
  12. package/dist/browser.d.ts.map +1 -0
  13. package/dist/clone-token-manager.d.ts +31 -0
  14. package/dist/clone-token-manager.d.ts.map +1 -0
  15. package/dist/config.d.ts +55 -0
  16. package/dist/config.d.ts.map +1 -0
  17. package/dist/embedding-store.d.ts +63 -0
  18. package/dist/embedding-store.d.ts.map +1 -0
  19. package/dist/event-enrichment.d.ts +5 -0
  20. package/dist/event-enrichment.d.ts.map +1 -0
  21. package/dist/exchange/backup-exporter.d.ts +43 -0
  22. package/dist/exchange/backup-exporter.d.ts.map +1 -0
  23. package/dist/exchange/backup-importer.d.ts +41 -0
  24. package/dist/exchange/backup-importer.d.ts.map +1 -0
  25. package/dist/exchange/index.d.ts +10 -0
  26. package/dist/exchange/index.d.ts.map +1 -0
  27. package/dist/exchange/linked-data-exporter.d.ts +42 -0
  28. package/dist/exchange/linked-data-exporter.d.ts.map +1 -0
  29. package/dist/exchange/linked-data-importer.d.ts +44 -0
  30. package/dist/exchange/linked-data-importer.d.ts.map +1 -0
  31. package/dist/exchange/manifest.d.ts +42 -0
  32. package/dist/exchange/manifest.d.ts.map +1 -0
  33. package/dist/exchange/replay.d.ts +37 -0
  34. package/dist/exchange/replay.d.ts.map +1 -0
  35. package/dist/exchange/tar.d.ts +34 -0
  36. package/dist/exchange/tar.d.ts.map +1 -0
  37. package/dist/gatherer.d.ts +45 -0
  38. package/dist/gatherer.d.ts.map +1 -0
  39. package/dist/generation/resource-generation.d.ts +20 -0
  40. package/dist/generation/resource-generation.d.ts.map +1 -0
  41. package/dist/graph/consumer.d.ts +104 -0
  42. package/dist/graph/consumer.d.ts.map +1 -0
  43. package/dist/graph-context.d.ts +56 -0
  44. package/dist/graph-context.d.ts.map +1 -0
  45. package/dist/handlers/annotation-assembly.d.ts +19 -0
  46. package/dist/handlers/annotation-assembly.d.ts.map +1 -0
  47. package/dist/handlers/annotation-lookups.d.ts +8 -0
  48. package/dist/handlers/annotation-lookups.d.ts.map +1 -0
  49. package/dist/handlers/bind-update-body.d.ts +19 -0
  50. package/dist/handlers/bind-update-body.d.ts.map +1 -0
  51. package/dist/handlers/index.d.ts +27 -0
  52. package/dist/handlers/index.d.ts.map +1 -0
  53. package/dist/handlers/job-commands.d.ts +5 -0
  54. package/dist/handlers/job-commands.d.ts.map +1 -0
  55. package/dist/index.d.ts +37 -1244
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +3 -16
  58. package/dist/index.js.map +1 -1
  59. package/dist/knowledge-base.d.ts +40 -0
  60. package/dist/knowledge-base.d.ts.map +1 -0
  61. package/dist/knowledge-system.d.ts +32 -0
  62. package/dist/knowledge-system.d.ts.map +1 -0
  63. package/dist/llm-context.d.ts +26 -0
  64. package/dist/llm-context.d.ts.map +1 -0
  65. package/dist/local-content-transport.d.ts +41 -0
  66. package/dist/local-content-transport.d.ts.map +1 -0
  67. package/dist/local-transport.d.ts +80 -0
  68. package/dist/local-transport.d.ts.map +1 -0
  69. package/dist/matcher.d.ts +60 -0
  70. package/dist/matcher.d.ts.map +1 -0
  71. package/dist/resource-context.d.ts +44 -0
  72. package/dist/resource-context.d.ts.map +1 -0
  73. package/dist/resource-operations.d.ts +38 -0
  74. package/dist/resource-operations.d.ts.map +1 -0
  75. package/dist/service.d.ts +21 -0
  76. package/dist/service.d.ts.map +1 -0
  77. package/dist/smelter-actor-state-unit.d.ts +31 -0
  78. package/dist/smelter-actor-state-unit.d.ts.map +1 -0
  79. package/dist/smelter-main.d.ts +16 -2
  80. package/dist/smelter-main.d.ts.map +1 -0
  81. package/dist/smelter-main.js +6 -2
  82. package/dist/smelter-main.js.map +1 -1
  83. package/dist/smelter.d.ts +95 -0
  84. package/dist/smelter.d.ts.map +1 -0
  85. package/dist/stower.d.ts +69 -0
  86. package/dist/stower.d.ts.map +1 -0
  87. package/dist/views/entity-types-reader.d.ts +12 -0
  88. package/dist/views/entity-types-reader.d.ts.map +1 -0
  89. package/dist/views/projection-validators.d.ts +80 -0
  90. package/dist/views/projection-validators.d.ts.map +1 -0
  91. package/dist/views/tag-schemas-reader.d.ts +14 -0
  92. package/dist/views/tag-schemas-reader.d.ts.map +1 -0
  93. package/package.json +3 -3
package/dist/index.d.ts CHANGED
@@ -1,1244 +1,37 @@
1
- import { JobQueue } from '@semiont/jobs';
2
- import { SemiontProject } from '@semiont/core/node';
3
- import { GraphServiceConfig, VectorsServiceConfig, EmbeddingServiceConfig, EventBus, Logger, StoredEvent, ResourceId, ResourceDescriptor, AnnotationId, components, ITransport, BaseUrl, ConnectionState, SemiontError, UserDID, EventMap, IContentTransport, PutBinaryRequest, PutBinaryOptions, ContentFormat as ContentFormat$1, AccessToken, Annotation, UserId, CreationMethod, ResourceAnnotations, AnnotationCategory, GraphPath, GraphConnection } from '@semiont/core';
4
- export { AssembledAnnotation, applyBodyOperations, assembleAnnotation } from '@semiont/core';
5
- import { EventStore, ViewStorage } from '@semiont/event-sourcing';
6
- import { WorkingTreeStore } from '@semiont/content';
7
- import { GraphDatabase } from '@semiont/graph';
8
- import { VectorStore, EmbeddingProvider } from '@semiont/vectors';
9
- import { InferenceClient } from '@semiont/inference';
10
- import { BehaviorSubject, Observable } from 'rxjs';
11
- import { StateUnit, WorkerBus } from '@semiont/sdk';
12
- import { Writable, Readable } from 'node:stream';
13
-
14
- /**
15
- * Inference configuration for a single actor or worker.
16
- */
17
- interface InferenceConfig {
18
- type: 'anthropic' | 'ollama';
19
- model: string;
20
- maxTokens?: number;
21
- apiKey?: string;
22
- endpoint?: string;
23
- baseURL?: string;
24
- }
25
- /**
26
- * Per-actor inference overrides.
27
- * Stower never calls an LLM, so it has no entry here.
28
- */
29
- interface ActorInferenceConfig {
30
- gatherer?: InferenceConfig;
31
- matcher?: InferenceConfig;
32
- }
33
- /**
34
- * Per-worker-type inference overrides.
35
- * Falls back to `workers.default` if a specific worker is not listed.
36
- */
37
- interface WorkerInferenceConfig {
38
- default?: InferenceConfig;
39
- 'reference-annotation'?: InferenceConfig;
40
- 'highlight-annotation'?: InferenceConfig;
41
- 'assessment-annotation'?: InferenceConfig;
42
- 'comment-annotation'?: InferenceConfig;
43
- 'tag-annotation'?: InferenceConfig;
44
- 'generation'?: InferenceConfig;
45
- }
46
- /** Narrow config type — only the fields make-meaning actually reads */
47
- interface MakeMeaningConfig {
48
- services: {
49
- graph?: GraphServiceConfig;
50
- vectors?: VectorsServiceConfig;
51
- embedding?: EmbeddingServiceConfig;
52
- };
53
- /** Per-actor inference config */
54
- actors?: ActorInferenceConfig;
55
- /** Per-worker-type inference config */
56
- workers?: WorkerInferenceConfig;
57
- }
58
-
59
- /**
60
- * GraphDB Consumer
61
- *
62
- * Subscribes to resource events and updates GraphDB accordingly.
63
- * Makes GraphDB a projection of Event Store events (single source of truth).
64
- *
65
- * Uses an RxJS pipeline with adaptive burst buffering:
66
- * - First event after idle passes through immediately (zero latency)
67
- * - Subsequent events in a burst are batched and flushed together
68
- * - After idle, returns to passthrough mode
69
- *
70
- * Per-resource ordering is preserved via groupBy(resourceId) + concatMap.
71
- * Cross-resource parallelism is provided via mergeMap over groups.
72
- *
73
- * Burst buffer thresholds (see BATCH-GRAPH-CONSUMER-RX.md for tuning guidance):
74
- * BURST_WINDOW_MS = 50 — debounce window before flushing a batch
75
- * MAX_BATCH_SIZE = 500 — force flush to bound memory
76
- * IDLE_TIMEOUT_MS = 200 — silence before returning to passthrough
77
- *
78
- * ## Per-resource serialization
79
- *
80
- * `groupBy(resourceId) + concatMap(...)` is the stream-consumer flavor of
81
- * per-resource serialization — the same invariant enforced by `Smelter`,
82
- * `Gatherer`, and (in a different shape) `ViewManager`. See
83
- * `packages/core/src/serialize-per-key.ts` for the shared primitive used
84
- * by RPC-style services.
85
- */
86
-
87
- declare class GraphDBConsumer {
88
- private eventStore;
89
- private graphDb;
90
- private coreEventBus;
91
- private static readonly GRAPH_RELEVANT_EVENTS;
92
- private static readonly BURST_WINDOW_MS;
93
- private static readonly MAX_BATCH_SIZE;
94
- private static readonly IDLE_TIMEOUT_MS;
95
- private _globalSubscriptions;
96
- private eventSubject;
97
- private pipelineSubscription;
98
- private lastProcessed;
99
- private readonly logger;
100
- constructor(eventStore: EventStore, graphDb: GraphDatabase, coreEventBus: EventBus, logger: Logger);
101
- initialize(): Promise<void>;
102
- /**
103
- * Subscribe globally to ALL events, pre-filter to graph-relevant types,
104
- * and wire through the RxJS burst-buffered pipeline.
105
- */
106
- private subscribeToGlobalEvents;
107
- /**
108
- * Wrap applyEventToGraph in try/catch so one failed event doesn't kill the pipeline.
109
- */
110
- private safeApplyEvent;
111
- private ensureInitialized;
112
- /**
113
- * Stop the consumer, flush remaining buffered events, and unsubscribe.
114
- */
115
- stop(): Promise<void>;
116
- /**
117
- * Process a batch of events for the same resource.
118
- * Partitions into consecutive same-type runs for batch optimization.
119
- */
120
- private processBatch;
121
- /**
122
- * Batch-optimized processing for consecutive events of the same type.
123
- * Uses batch graph methods where available, falls back to sequential.
124
- */
125
- private applyBatchByType;
126
- /**
127
- * Build a ResourceDescriptor from a resource.created event.
128
- * Extracted for reuse by both applyEventToGraph and applyBatchByType.
129
- */
130
- private buildResourceDescriptor;
131
- /**
132
- * Apply a single event to GraphDB.
133
- */
134
- protected applyEventToGraph(storedEvent: StoredEvent): Promise<void>;
135
- /**
136
- * Rebuild entire resource from events.
137
- * Bypasses the live pipeline — reads directly from event store.
138
- */
139
- rebuildResource(resourceId: ResourceId): Promise<void>;
140
- /**
141
- * Rebuild entire GraphDB from all events.
142
- * Uses two-pass approach to ensure all resources exist before creating REFERENCES edges.
143
- * Bypasses the live pipeline — reads directly from event store.
144
- */
145
- rebuildAll(): Promise<void>;
146
- /**
147
- * Get consumer health metrics.
148
- */
149
- getHealthMetrics(): {
150
- subscriptions: number;
151
- lastProcessed: Record<string, number>;
152
- pipelineActive: boolean;
153
- };
154
- /**
155
- * Shutdown consumer.
156
- */
157
- shutdown(): Promise<void>;
158
- }
159
-
160
- /**
161
- * Knowledge Base
162
- *
163
- * The durable store that records what intelligent actors decide.
164
- * Groups the KB subsystems from ARCHITECTURE.md:
165
- *
166
- * - Event Log (immutable append-only) — via EventStore
167
- * - Materialized Views (fast single-doc queries) — via ViewStorage
168
- * - Content Store (working-tree files, URI-addressed) — via WorkingTreeStore
169
- * - Graph (eventually consistent relationship projection) — via GraphDatabase
170
- * - Graph Consumer (event-to-graph projection) — via GraphDBConsumer
171
- * - Vectors (semantic search) — via VectorStore (optional, read-only)
172
- *
173
- * The Smelter (event-to-vector projection) runs as an external actor
174
- * via @semiont/make-meaning/smelter-main. It subscribes to domain events
175
- * via the EventBus gateway, embeds content, and writes to Qdrant directly.
176
- */
177
-
178
- interface KnowledgeBase {
179
- eventStore: EventStore;
180
- views: ViewStorage;
181
- content: WorkingTreeStore;
182
- graph: GraphDatabase;
183
- graphConsumer: GraphDBConsumer;
184
- vectors?: VectorStore;
185
- projectionsDir: string;
186
- }
187
- interface CreateKnowledgeBaseOptions {
188
- vectorStore?: VectorStore;
189
- skipRebuild?: boolean;
190
- }
191
- declare function createKnowledgeBase(eventStore: EventStore, project: SemiontProject, graphDb: GraphDatabase, eventBus: EventBus, logger: Logger, options?: CreateKnowledgeBaseOptions): Promise<KnowledgeBase>;
192
-
193
- /**
194
- * Stower Actor
195
- *
196
- * The single write gateway to the Knowledge Base. Subscribes to command
197
- * events on the EventBus and translates them into domain events on the
198
- * EventStore + content writes to the RepresentationStore.
199
- *
200
- * From ARCHITECTURE.md:
201
- * The Knowledge Base has exactly three actor interfaces:
202
- * - Stower (write) — this actor
203
- * - Gatherer (read context)
204
- * - Matcher (read search)
205
- *
206
- * No other code should call eventStore.appendEvent() or repStore.store().
207
- *
208
- * Subscriptions:
209
- * - yield:create → resource.created (+ content store) → yield:created / yield:create-failed
210
- * - yield:update → resource.updated (+ content store) → yield:updated / yield:update-failed
211
- * - yield:mv → resource.moved (+ working tree move) → yield:moved / yield:move-failed
212
- * - mark:create → annotation.added → mark:created / mark:create-failed
213
- * - mark:delete → annotation.removed → mark:deleted / mark:delete-failed
214
- * - mark:update-body → annotation.body.updated → (no result event yet)
215
- * - mark:archive → resource.archived (+ file removal) (resource-scoped, no result event)
216
- * - mark:unarchive → resource.unarchived (resource-scoped, no result event)
217
- * - frame:add-entity-type → entitytype.added → frame:entity-type-added / frame:entity-type-add-failed
218
- * - frame:add-tag-schema → tagschema.added → frame:tag-schema-added / frame:tag-schema-add-failed
219
- * - mark:update-entity-types → entitytag.added / entitytag.removed
220
- * - job:start → job.started
221
- * - job:complete → job.completed
222
- * - job:fail → job.failed
223
- *
224
- * Note: `job:report-progress` is intentionally NOT persisted. Progress
225
- * events are ephemeral UI feedback and would clutter the event log
226
- * (historical logs show ~3× as many progress entries as start+complete
227
- * combined). UI consumers subscribe to the bus directly for live
228
- * progress; the event log keeps only the durable lifecycle boundaries.
229
- */
230
-
231
- interface CreateResourceResult {
232
- resourceId: ResourceId;
233
- resource: ResourceDescriptor;
234
- }
235
- declare class Stower {
236
- private kb;
237
- private eventBus;
238
- private subscription;
239
- private readonly logger;
240
- constructor(kb: KnowledgeBase, eventBus: EventBus, logger: Logger);
241
- initialize(): Promise<void>;
242
- private handleYieldCreate;
243
- private handleYieldUpdate;
244
- private handleYieldMv;
245
- private handleMarkCreate;
246
- private handleMarkDelete;
247
- private handleMarkUpdateBody;
248
- private handleMarkArchive;
249
- private handleMarkUnarchive;
250
- private handleAddEntityType;
251
- private handleAddTagSchema;
252
- private handleUpdateEntityTypes;
253
- private handleJobStart;
254
- private handleJobComplete;
255
- private handleJobFail;
256
- stop(): Promise<void>;
257
- }
258
-
259
- /**
260
- * Gatherer Actor
261
- *
262
- * LLM context assembly for the Knowledge System. Subscribes to gather events,
263
- * queries KB stores via context modules, and emits results back to the bus.
264
- *
265
- * From ARCHITECTURE.md:
266
- * "When a Generator Agent or Linker Agent emits a gather event, the Gatherer
267
- * receives it from the bus, queries the relevant KB stores, and assembles
268
- * the context needed for downstream work."
269
- *
270
- * Handles:
271
- * - gather:requested — annotation-level LLM context assembly
272
- * - gather:resource-requested — resource-level LLM context assembly
273
- *
274
- * RxJS pipeline uses groupBy(resourceId) + concatMap for per-resource isolation.
275
- *
276
- * ## Per-resource serialization
277
- *
278
- * `groupBy(resourceId) + concatMap(...)` is the stream-consumer flavor of
279
- * per-resource serialization — the same invariant enforced by `Smelter`,
280
- * `GraphDBConsumer`, and (in a different shape) `ViewManager`. See
281
- * `packages/core/src/serialize-per-key.ts` for the shared primitive used
282
- * by RPC-style services.
283
- */
284
-
285
- declare class Gatherer$1 {
286
- private kb;
287
- private eventBus;
288
- private inferenceClient;
289
- private embeddingProvider?;
290
- private subscriptions;
291
- private readonly logger;
292
- constructor(kb: KnowledgeBase, eventBus: EventBus, inferenceClient: InferenceClient, logger: Logger, embeddingProvider?: EmbeddingProvider | undefined);
293
- initialize(): Promise<void>;
294
- private handleAnnotationGather;
295
- private handleResourceGather;
296
- generateAnnotationSummary(annotationId: AnnotationId, resourceId: ResourceId): Promise<components['schemas']['ContextualSummaryResponse']>;
297
- stop(): Promise<void>;
298
- }
299
-
300
- /**
301
- * Matcher Actor
302
- *
303
- * Candidate search for the bind flow. Subscribes to match:search-requested,
304
- * queries the KB graph for matching resources, scores them, and emits results.
305
- *
306
- * Handles:
307
- * - match:search-requested — multi-source retrieval + composite scoring
308
- *
309
- * The write side (annotation.body.updated) stays in the route where userId
310
- * is available from auth context.
311
- */
312
-
313
- declare class Matcher {
314
- private kb;
315
- private eventBus;
316
- private inferenceClient;
317
- private embeddingProvider?;
318
- private subscriptions;
319
- private readonly logger;
320
- constructor(kb: KnowledgeBase, eventBus: EventBus, logger: Logger, inferenceClient: InferenceClient, embeddingProvider?: EmbeddingProvider | undefined);
321
- initialize(): Promise<void>;
322
- private handleSearch;
323
- /**
324
- * Context-driven search: multi-source retrieval + composite scoring
325
- *
326
- * Retrieval sources:
327
- * 1. Name match — graph.searchResources(searchTerm)
328
- * 2. Entity type match — graph.listResources({ entityTypes })
329
- * 3. Graph neighborhood — connections from GatheredContext
330
- *
331
- * Ranking signals:
332
- * - Entity type overlap (Jaccard similarity)
333
- * - Bidirectionality (already connected both ways)
334
- * - Citation weight (well-connected = important)
335
- * - Name match quality (exact > prefix > contains)
336
- * - Recency (newer resources scored higher)
337
- */
338
- private contextDrivenSearch;
339
- /**
340
- * LLM-based semantic relevance scoring (GraphRAG-style)
341
- *
342
- * Batches candidates into a single prompt asking the LLM to score
343
- * each candidate's semantic relevance given the passage and graph context.
344
- *
345
- * @returns Map of resourceId → score (0-1)
346
- */
347
- private inferenceSemanticScore;
348
- /**
349
- * Search vectors for semantically similar resources.
350
- * Returns empty array if vectors or embedding provider are not configured.
351
- */
352
- private searchVectors;
353
- stop(): Promise<void>;
354
- }
355
-
356
- /**
357
- * Browser Actor
358
- *
359
- * Filesystem-shaped reads and KB graph reads for the Knowledge System.
360
- * Merges live filesystem state with KB metadata for tracked resources.
361
- *
362
- * Handles:
363
- * - browse:resource-requested — single resource metadata (materialized from events)
364
- * - browse:resources-requested — list resources
365
- * - browse:annotations-requested — all annotations for a resource
366
- * - browse:annotation-requested — single annotation with resolved resource
367
- * - browse:events-requested — resource event history
368
- * - browse:annotation-history-requested — annotation event history
369
- * - browse:referenced-by-requested — find annotations in the KB graph that reference a resource
370
- * - browse:entity-types-requested — list entity types from the project projection
371
- * - browse:tag-schemas-requested — list tag schemas from the project projection
372
- * - browse:directory-requested — list a project directory, merging fs + ViewStorage
373
- */
374
-
375
- declare class Browser {
376
- private views;
377
- private kb;
378
- private eventBus;
379
- private project;
380
- private subscriptions;
381
- private readonly logger;
382
- constructor(views: ViewStorage, kb: KnowledgeBase, eventBus: EventBus, project: SemiontProject, logger: Logger);
383
- initialize(): Promise<void>;
384
- private handleBrowseResource;
385
- private handleBrowseResources;
386
- private handleBrowseAnnotations;
387
- private handleBrowseAnnotation;
388
- private handleBrowseEvents;
389
- private handleBrowseAnnotationHistory;
390
- private handleReferencedBy;
391
- private handleEntityTypes;
392
- private handleTagSchemas;
393
- private handleBrowseDirectory;
394
- stop(): Promise<void>;
395
- }
396
-
397
- /**
398
- * Clone Token Manager
399
- *
400
- * Reactive actor that handles clone token operations via the EventBus.
401
- * Manages an in-memory token store for resource cloning workflows.
402
- *
403
- * Handles:
404
- * - yield:clone-token-requested — generate a clone token for a resource
405
- * - yield:clone-resource-requested — look up a resource by clone token
406
- * - yield:clone-create — create a new resource from a clone token
407
- *
408
- * From COMPLETE-EVENT-PROTOCOL.md:
409
- * "Clone tokens produce new resources — that's yield."
410
- */
411
-
412
- declare class CloneTokenManager {
413
- private kb;
414
- private eventBus;
415
- private subscriptions;
416
- private readonly logger;
417
- private readonly tokens;
418
- constructor(kb: KnowledgeBase, eventBus: EventBus, logger: Logger);
419
- initialize(): Promise<void>;
420
- private handleGenerateToken;
421
- private handleGetResource;
422
- private handleCreateResource;
423
- stop(): Promise<void>;
424
- }
425
-
426
- /**
427
- * Knowledge System
428
- *
429
- * Binds the KnowledgeBase to the actors that provide disciplined access to it.
430
- * Nothing outside the KnowledgeSystem reads or writes the KnowledgeBase directly.
431
- *
432
- * - kb: the durable store (event log, views, content, graph)
433
- * - stower: write actor — weaves new knowledge in
434
- * - gatherer: read actor — traces threads to build context
435
- * - matcher: search actor — finds related threads
436
- * - browser: filesystem actor — lists project directories
437
- * - cloneTokenManager: token actor — manages resource clone tokens
438
- *
439
- * EventBus, JobQueue, and workers are peers to KnowledgeSystem, not members.
440
- */
441
-
442
- interface KnowledgeSystem {
443
- kb: KnowledgeBase;
444
- stower: Stower;
445
- gatherer: Gatherer$1;
446
- matcher: Matcher;
447
- browser: Browser;
448
- cloneTokenManager: CloneTokenManager;
449
- stop: () => Promise<void>;
450
- }
451
- declare function stopKnowledgeSystem(ks: KnowledgeSystem): Promise<void>;
452
-
453
- /**
454
- * Make-Meaning Service
455
- *
456
- * Provides a clean interface:
457
- * const makeMeaning = await startMakeMeaning(project, config, eventBus, logger);
458
- */
459
-
460
- interface MakeMeaningService {
461
- knowledgeSystem: KnowledgeSystem;
462
- jobQueue: JobQueue;
463
- stop: () => Promise<void>;
464
- }
465
- declare function startMakeMeaning(project: SemiontProject, config: MakeMeaningConfig, eventBus: EventBus, logger: Logger, options?: {
466
- skipRebuild?: boolean;
467
- }): Promise<MakeMeaningService>;
468
-
469
- /**
470
- * LocalTransport — `ITransport` for an in-process `KnowledgeSystem`.
471
- *
472
- * Bus-ownership pattern (see `docs/protocol/TRANSPORT-CONTRACT.md`):
473
- * - The caller owns a make-meaning `EventBus` and passes it to both
474
- * `startMakeMeaning` and `LocalTransport` so the transport can publish
475
- * directly onto the bus the `KnowledgeSystem` actors are listening on.
476
- * - `SemiontClient` constructs its own `clientBus` and calls
477
- * `bridgeInto(clientBus)` during construction. `LocalTransport`
478
- * subscribes to every `BRIDGED_CHANNELS` entry on the make-meaning bus
479
- * and forwards each onto `clientBus`.
480
- * - The bus reference flows client → transport, never the other way.
481
- *
482
- * LocalTransport implements `ITransport` only. Auth, admin, and exchange
483
- * (`IBackendOperations`) are HTTP-shaped concepts that don't apply
484
- * in-process — local mode runs as a single host-process identity supplied
485
- * at construction, with no token/credential lifecycle. A `SemiontClient`
486
- * built over this transport has no `.auth` / `.admin` namespaces.
487
- */
488
-
489
- interface LocalTransportConfig {
490
- /**
491
- * The in-process knowledge system. Lifetime is owned by the caller —
492
- * `dispose()` on this transport does not stop the KnowledgeSystem.
493
- */
494
- knowledgeSystem: KnowledgeSystem;
495
- /**
496
- * The make-meaning `EventBus`. Must be the same instance passed to
497
- * `startMakeMeaning` so that emits land on the bus KnowledgeSystem
498
- * actors are subscribed to.
499
- */
500
- eventBus: EventBus;
501
- /**
502
- * Host-process identity. Stamped onto every emit as `_userId`, mirroring
503
- * the gateway-injection convention used by `HttpTransport` (where the
504
- * `/bus/emit` gateway reads the JWT subject and injects `_userId`).
505
- * Handlers downstream trust nothing else.
506
- */
507
- userId: UserDID;
508
- /**
509
- * Cosmetic base URL for diagnostics and URL composition. Defaults to
510
- * `local://in-process`. Local code never makes outgoing HTTP requests
511
- * with it.
512
- */
513
- baseUrl?: BaseUrl;
514
- }
515
- declare class LocalTransport implements ITransport {
516
- readonly baseUrl: BaseUrl;
517
- readonly state$: BehaviorSubject<ConnectionState>;
518
- private readonly errorsSubject;
519
- /**
520
- * Stream of `SemiontError` instances surfaced from transport-mediated
521
- * round-trips (typed-wire methods on this transport that fail). The
522
- * in-process implementation does not currently surface errors through
523
- * this stream — most failures here originate inside the make-meaning
524
- * actors and surface through bus channels (correlation-ID failures via
525
- * `busRequest`). The Subject exists to satisfy the `ITransport`
526
- * contract; future expansion (e.g. transport-level guard failures)
527
- * can publish into it.
528
- */
529
- readonly errors$: Observable<SemiontError>;
530
- private readonly bus;
531
- private readonly userId;
532
- private readonly bridges;
533
- private readonly bridgeSubs;
534
- private disposed;
535
- constructor(cfg: LocalTransportConfig);
536
- emit<K extends keyof EventMap>(channel: K, payload: EventMap[K], resourceScope?: ResourceId): Promise<void>;
537
- on<K extends keyof EventMap>(channel: K, handler: (payload: EventMap[K]) => void): () => void;
538
- stream<K extends keyof EventMap>(channel: K): Observable<EventMap[K]>;
539
- subscribeToResource(_resourceId: ResourceId): () => void;
540
- bridgeInto(bus: EventBus): void;
541
- dispose(): void;
542
- }
543
-
544
- /**
545
- * LocalContentTransport — `IContentTransport` for an in-process
546
- * `KnowledgeSystem`.
547
- *
548
- * Reads go straight to `kb.views` (resource lookup) + `kb.content`
549
- * (byte retrieval). No network, no auth — local mode runs as a single
550
- * host-process identity.
551
- *
552
- * `putBinary` is intentionally not implemented in Phase 2: in-process
553
- * resource creation is exercised through bus emits (mark/yield
554
- * namespaces), not multipart upload. If a future caller needs raw
555
- * binary upload from a local context, wire it through the same
556
- * resource-creation pipeline the HTTP `/resources` handler uses.
557
- */
558
-
559
- declare class LocalContentTransport implements IContentTransport {
560
- private readonly ks;
561
- constructor(ks: KnowledgeSystem);
562
- putBinary(_request: PutBinaryRequest, _options?: PutBinaryOptions): Promise<{
563
- resourceId: ResourceId;
564
- }>;
565
- getBinary(resourceId: ResourceId, options?: {
566
- accept?: ContentFormat$1 | string;
567
- auth?: AccessToken;
568
- }): Promise<{
569
- data: ArrayBuffer;
570
- contentType: string;
571
- }>;
572
- getBinaryStream(resourceId: ResourceId, options?: {
573
- accept?: ContentFormat$1 | string;
574
- auth?: AccessToken;
575
- }): Promise<{
576
- stream: ReadableStream<Uint8Array>;
577
- contentType: string;
578
- }>;
579
- private loadBinary;
580
- dispose(): void;
581
- }
582
-
583
- /**
584
- * Handles `mark:create-request` — the bus command for creating an annotation.
585
- *
586
- * Flow:
587
- * 1. Assemble the W3C annotation from the request using the injected user DID.
588
- * 2. Emit `mark:create` with the correlationId threaded through.
589
- * 3. Stower picks up `mark:create`, appends to the event store (threading
590
- * correlationId into event metadata), and publishes `mark:added` on the
591
- * core EventBus.
592
- * 4. This handler subscribes to `mark:added` and `mark:create-failed`,
593
- * matches by correlationId, and emits `mark:create-ok` / `mark:create-failed`
594
- * to the caller only after persistence has actually completed.
595
- *
596
- * This is a deferred-ack pattern: the result event attests that Stower has
597
- * persisted the annotation, not merely that the command was well-formed.
598
- */
599
- declare function registerAnnotationAssemblyHandler(eventBus: EventBus, parentLogger: Logger): void;
600
-
601
- interface Gatherer {
602
- generateAnnotationSummary(annId: AnnotationId, resId: ResourceId): Promise<Record<string, unknown>>;
603
- }
604
- declare function registerAnnotationLookupHandlers(eventBus: EventBus, kb: KnowledgeBase, gatherer: Gatherer, parentLogger: Logger): void;
605
-
606
- /**
607
- * Handles `bind:update-body` — the Bind flow's authoritative "apply body
608
- * operations to an annotation" command. Bind remains a first-class flow
609
- * despite delegating persistence to Mark — the semantic distinction (Bind =
610
- * reference linking, Mark = annotation CRUD) is meaningful at the UX and
611
- * agent-reasoning layers even when the downstream storage event is shared.
612
- *
613
- * Flow:
614
- * 1. Receive bind:update-body with correlationId.
615
- * 2. Forward to mark:update-body with correlationId threaded through.
616
- * 3. Stower persists (via EventStore.appendEvent) and publishes mark:body-updated
617
- * with correlationId in metadata.
618
- * 4. This handler subscribes to mark:body-updated and mark:body-update-failed,
619
- * matches by correlationId, and emits bind:body-updated / bind:body-update-failed
620
- * so the caller learns the real outcome — not an optimistic ack.
621
- */
622
- declare function registerBindUpdateBodyHandler(eventBus: EventBus, parentLogger: Logger): void;
623
-
624
- declare function registerJobCommandHandlers(eventBus: EventBus, jobQueue: JobQueue, project: SemiontProject, parentLogger: Logger): void;
625
-
626
- /**
627
- * Bus command handlers — pure bus-event translators that bridge the
628
- * "request" channels callers emit (`mark:create-request`, `bind:update-body`,
629
- * `job:create`, `browse:annotation-context-requested`,
630
- * `gather:summary-requested`) to the underlying make-meaning pipeline
631
- * (Stower, Browser, Gatherer, JobQueue).
632
- *
633
- * These ran in `apps/backend` historically because the HTTP gateway was
634
- * the only consumer that needed them. They are not HTTP-specific — moving
635
- * them here means `LocalTransport` consumers (and any future transport)
636
- * get the same contract automatically.
637
- */
638
-
639
- /**
640
- * Register all bus command handlers on the make-meaning EventBus. Called
641
- * during `startMakeMeaning` after the JobQueue and KnowledgeSystem exist.
642
- */
643
- declare function registerBusHandlers(eventBus: EventBus, knowledgeSystem: KnowledgeSystem, jobQueue: JobQueue, project: SemiontProject, logger: Logger): void;
644
-
645
- /**
646
- * Entity Types Bootstrap
647
- *
648
- * On startup, seeds the KB with DEFAULT_ENTITY_TYPES by emitting
649
- * frame:add-entity-type for each missing type. Reads the __system__ event
650
- * stream (the durable source of truth in .semiont/events/) to determine
651
- * which types already exist.
652
- *
653
- * Idempotent: safe to call on every startup. Only emits events for types
654
- * not already in the log.
655
- *
656
- * Future: evolve toward a migration-based model where a `system:bootstrapped`
657
- * sentinel event records that first-time init completed, and `system:migrated`
658
- * events record schema version upgrades (e.g., adding new default entity types
659
- * in a future release). For now, scanning the small __system__ stream is simple
660
- * and correct.
661
- */
662
-
663
- /**
664
- * Bootstrap entity types if any are missing from the event log.
665
- * Reads the __system__ stream to find existing frame:entity-type-added events,
666
- * then emits only the missing ones.
667
- */
668
- declare function bootstrapEntityTypes(eventBus: EventBus, eventStore: EventStore, logger?: Logger): Promise<void>;
669
-
670
- /**
671
- * Entity Types Projection Reader
672
- *
673
- * Reads entity types from the view storage projection file.
674
- * This file is maintained by ViewMaterializer in response to entitytype.added events.
675
- */
676
-
677
- /**
678
- * Read entity types from view storage projection
679
- */
680
- declare function readEntityTypesProjection(project: SemiontProject): Promise<string[]>;
681
-
682
- /**
683
- * SmelterActorStateUnit — domain-event fan-in for the Smelter worker.
684
- *
685
- * Subscribes to the six smelter-relevant channels on a shared bus and
686
- * exposes them as a single typed `events$` stream. Transport-neutral —
687
- * the caller passes a `WorkerBus` (HTTP `ActorStateUnit` today, an in-process
688
- * bus shim if/when one exists). The state unit does not own the bus and does
689
- * not dispose it.
690
- *
691
- * `start()` widens the bus's channel-subscription set to include the
692
- * smelter channels. On HTTP this extends the SSE subscription URL;
693
- * on an in-process bus this is a no-op (the underlying `EventBus`
694
- * already delivers every emit).
695
- */
696
-
697
- interface SmelterEvent {
698
- type: string;
699
- resourceId?: string;
700
- payload: Record<string, unknown>;
701
- }
702
- interface SmelterActorStateUnitOptions {
703
- bus: WorkerBus;
704
- }
705
- interface SmelterActorStateUnit extends StateUnit {
706
- events$: Observable<SmelterEvent>;
707
- emit(channel: string, payload: Record<string, unknown>): Promise<void>;
708
- start(): void;
709
- }
710
- declare function createSmelterActorStateUnit(options: SmelterActorStateUnitOptions): SmelterActorStateUnit;
711
-
712
- /**
713
- * Exchange Format Manifest Types
714
- *
715
- * Defines the metadata structures for backup archives.
716
- * The manifest is the first entry in an archive and describes its contents.
717
- */
718
- declare const BACKUP_FORMAT: "semiont-backup";
719
- declare const FORMAT_VERSION = 1;
720
- interface BackupManifestHeader {
721
- format: typeof BACKUP_FORMAT;
722
- version: number;
723
- exportedAt: string;
724
- sourceUrl: string;
725
- stats: {
726
- streams: number;
727
- events: number;
728
- blobs: number;
729
- contentBytes: number;
730
- };
731
- }
732
- interface BackupStreamSummary {
733
- stream: string;
734
- eventCount: number;
735
- }
736
- declare const LINKED_DATA_FORMAT: "semiont-linked-data";
737
- interface LinkedDataManifest {
738
- '@context': Record<string, string>;
739
- '@type': string;
740
- 'semiont:format': typeof LINKED_DATA_FORMAT;
741
- 'semiont:version': number;
742
- 'dct:created': string;
743
- 'prov:wasGeneratedBy': {
744
- '@type': string;
745
- 'prov:used': string;
746
- };
747
- 'semiont:entityTypes': string[];
748
- 'void:entities': number;
749
- }
750
- declare function isBackupManifest(obj: unknown): obj is BackupManifestHeader;
751
- declare function validateManifestVersion(version: number): void;
752
-
753
- /**
754
- * Backup Exporter
755
- *
756
- * Produces a lossless tar.gz archive of the system of record:
757
- * - Event log (all streams, JSONL format)
758
- * - Content store (content-addressed blobs)
759
- *
760
- * Reads events via EventStore and content via RepresentationStore.
761
- * The archive can restore a complete knowledge base.
762
- */
763
-
764
- /** Subset of EventStore used by the backup exporter. */
765
- interface BackupEventStoreReader {
766
- log: {
767
- storage: {
768
- getAllResourceIds(): Promise<ResourceId[]>;
769
- };
770
- getEvents(resourceId: ResourceId): Promise<StoredEvent[]>;
771
- };
772
- }
773
- /** Subset of WorkingTreeStore used by the backup exporter. */
774
- interface BackupContentReader {
775
- retrieve(storageUri: string): Promise<Buffer>;
776
- }
777
- interface BackupExporterOptions {
778
- eventStore: BackupEventStoreReader;
779
- content: BackupContentReader;
780
- sourceUrl: string;
781
- logger?: Logger;
782
- }
783
- /**
784
- * Export a full backup of the knowledge base to a tar.gz stream.
785
- *
786
- * Archive structure:
787
- * .semiont/manifest.jsonl - Format metadata + per-stream checksums
788
- * .semiont/events/__system__.jsonl - System events
789
- * .semiont/events/{resourceId}.jsonl - Per-resource events
790
- * {checksum}.{ext} - Content blobs (root level)
791
- */
792
- declare function exportBackup(options: BackupExporterOptions, output: Writable): Promise<BackupManifestHeader>;
793
-
794
- /**
795
- * Event Replay
796
- *
797
- * Replays parsed JSONL event streams through the EventBus.
798
- * Each domain event is translated to the corresponding command event
799
- * (e.g. yield:created → yield:create), emitted, and the result
800
- * event is awaited before proceeding (backpressure).
801
- *
802
- * Content blobs are resolved lazily via a lookup function so that
803
- * the caller controls memory strategy (streaming, on-disk, etc.).
804
- */
805
-
806
- /**
807
- * Resolves a content blob by its checksum.
808
- * Returned by the caller so replay doesn't dictate memory strategy.
809
- */
810
- type ContentBlobResolver = (checksum: string) => Buffer | undefined;
811
- interface ReplayStats {
812
- eventsReplayed: number;
813
- resourcesCreated: number;
814
- annotationsCreated: number;
815
- entityTypesAdded: number;
816
- }
817
-
818
- /**
819
- * Backup Importer
820
- *
821
- * Restores a knowledge base from a backup tar.gz archive.
822
- * Replays events through the EventBus → Stower pipeline so all
823
- * derived state (materialized views, graph) rebuilds naturally.
824
- *
825
- * Accepts a Readable stream so callers can pipe directly from disk
826
- * or network without buffering the entire archive first.
827
- * Content blobs are resolved lazily via a closure over the parsed
828
- * tar entries, avoiding a separate copy of all blob data in memory.
829
- */
830
-
831
- interface BackupImporterOptions {
832
- eventBus: EventBus;
833
- contentStore: WorkingTreeStore;
834
- logger?: Logger;
835
- }
836
- interface BackupImportResult {
837
- manifest: BackupManifestHeader;
838
- stats: ReplayStats;
839
- }
840
- /**
841
- * Import a backup archive by replaying events through the EventBus.
842
- *
843
- * Flow:
844
- * 1. Stream and decompress tar.gz entries
845
- * 2. Parse .semiont/manifest.jsonl → validate format
846
- * 3. Build blob resolver over root-level content entries
847
- * 4. Replay .semiont/events/__system__.jsonl (entity types)
848
- * 5. Replay each .semiont/events/{resourceId}.jsonl (resources, annotations)
849
- *
850
- * Events flow: importer → EventBus → Stower → EventStore + Views
851
- */
852
- declare function importBackup(archive: Readable, options: BackupImporterOptions): Promise<BackupImportResult>;
853
-
854
- /**
855
- * Linked Data Exporter
856
- *
857
- * Produces a JSON-LD tar.gz archive from the current state of the knowledge base.
858
- * Reads materialized views (not the event log) for a fast, current-state export.
859
- *
860
- * Archive structure:
861
- * .semiont/manifest.jsonld - JSON-LD manifest with format metadata
862
- * .semiont/resources/{resourceId}.jsonld - One JSON-LD document per resource
863
- * {checksum}.{ext} - Content blobs (root level)
864
- */
865
-
866
- /** Subset of ViewStorage used by the linked-data exporter. */
867
- interface LinkedDataViewReader {
868
- getAll(): Promise<Array<{
869
- resource: ResourceDescriptor;
870
- annotations: {
871
- annotations: Annotation[];
872
- };
873
- }>>;
874
- }
875
- /** Subset of WorkingTreeStore used by the linked-data exporter. */
876
- interface LinkedDataContentReader {
877
- retrieve(storageUri: string): Promise<Buffer>;
878
- }
879
- interface LinkedDataExporterOptions {
880
- views: LinkedDataViewReader;
881
- content: LinkedDataContentReader;
882
- sourceUrl: string;
883
- entityTypes: string[];
884
- includeArchived?: boolean;
885
- logger?: Logger;
886
- }
887
- /**
888
- * Export the knowledge base as a JSON-LD tar.gz archive.
889
- */
890
- declare function exportLinkedData(options: LinkedDataExporterOptions, output: Writable): Promise<LinkedDataManifest>;
891
-
892
- /**
893
- * Linked Data Importer
894
- *
895
- * Creates resources from a JSON-LD tar.gz archive exported by the linked-data exporter.
896
- * Unlike the backup importer, this is lossy — new resources are created (new IDs),
897
- * no event history is preserved. Entity types are restored from the manifest.
898
- *
899
- * Parses .semiont/manifest.jsonld for format validation and entity types,
900
- * then processes each .semiont/resources/{resourceId}.jsonld to create
901
- * resources and annotations via the EventBus → Stower pipeline.
902
- */
903
-
904
- interface LinkedDataImporterOptions {
905
- eventBus: EventBus;
906
- contentStore: WorkingTreeStore;
907
- userId: UserId;
908
- logger?: Logger;
909
- }
910
- interface LinkedDataImportResult {
911
- manifest: LinkedDataManifest;
912
- resourcesCreated: number;
913
- annotationsCreated: number;
914
- entityTypesAdded: number;
915
- }
916
- /**
917
- * Import a JSON-LD archive by creating resources through the EventBus.
918
- *
919
- * Flow:
920
- * 1. Stream and decompress tar.gz entries
921
- * 2. Parse .semiont/manifest.jsonld → validate format
922
- * 3. Build blob resolver over root-level content entries
923
- * 4. Add entity types from manifest via frame:add-entity-type
924
- * 5. For each .semiont/resources/{id}.jsonld:
925
- * a. Parse JSON-LD document
926
- * b. Resolve content blob by checksum from representations
927
- * c. Emit yield:create → await yield:created
928
- * d. For each annotation: emit mark:create → await mark:created
929
- */
930
- declare function importLinkedData(archive: Readable, options: LinkedDataImporterOptions): Promise<LinkedDataImportResult>;
931
-
932
- /**
933
- * Resource Operations
934
- *
935
- * Business logic for resource operations. All writes go through the EventBus
936
- * — the Stower actor subscribes and handles persistence.
937
- *
938
- * For create: emits yield:create, awaits yield:created / yield:create-failed.
939
- */
940
-
941
- type ContentFormat = components['schemas']['ContentFormat'];
942
- type Agent$1 = components['schemas']['Agent'];
943
- interface CreateResourceInput {
944
- name: string;
945
- storageUri: string;
946
- contentChecksum: string;
947
- byteSize: number;
948
- format: ContentFormat;
949
- language?: string;
950
- entityTypes?: string[];
951
- creationMethod?: CreationMethod;
952
- /** Provenance for AI-generated resources: source resource + annotation. */
953
- generatedFrom?: {
954
- resourceId?: string;
955
- annotationId?: string;
956
- };
957
- generationPrompt?: string;
958
- generator?: Agent$1 | Agent$1[];
959
- isDraft?: boolean;
960
- }
961
- declare class ResourceOperations {
962
- /**
963
- * Create a new resource via EventBus → Stower
964
- */
965
- static createResource(input: CreateResourceInput, userId: UserId, eventBus: EventBus): Promise<ResourceId>;
966
- }
967
-
968
- /**
969
- * Annotation Operations
970
- *
971
- * Business logic for annotation CRUD operations. All writes go through the
972
- * EventBus — the Stower actor subscribes and handles persistence.
973
- *
974
- * In-process callers pass a `UserId` to these operations; the
975
- * EventBus emits stamp it onto the gateway-injection field `_userId`,
976
- * matching the wire-side convention so Stower handlers see one shape
977
- * regardless of where the command originated.
978
- */
979
-
980
- type Agent = components['schemas']['Agent'];
981
-
982
- type CreateAnnotationRequest = components['schemas']['CreateAnnotationRequest'];
983
- type UpdateAnnotationBodyRequest = components['schemas']['UpdateAnnotationBodyRequest'];
984
- interface CreateAnnotationResult {
985
- annotation: Annotation;
986
- }
987
- interface UpdateAnnotationBodyResult {
988
- annotation: Annotation;
989
- }
990
- declare class AnnotationOperations {
991
- /**
992
- * Create a new annotation via EventBus → Stower
993
- */
994
- static createAnnotation(request: CreateAnnotationRequest, userId: UserId, creator: Agent, eventBus: EventBus): Promise<CreateAnnotationResult>;
995
- /**
996
- * Update annotation body via EventBus → Stower
997
- */
998
- static updateAnnotationBody(id: string, request: UpdateAnnotationBodyRequest, userId: UserId, eventBus: EventBus, kb: KnowledgeBase): Promise<UpdateAnnotationBodyResult>;
999
- /**
1000
- * Delete an annotation via EventBus → Stower
1001
- */
1002
- static deleteAnnotation(id: string, resourceIdStr: string, userId: UserId, eventBus: EventBus, kb: KnowledgeBase, logger?: Logger): Promise<void>;
1003
- }
1004
-
1005
- /**
1006
- * Resource Context
1007
- *
1008
- * Assembles resource context from view storage and content store
1009
- * Does NOT touch the graph - graph queries go through GraphContext
1010
- */
1011
-
1012
- interface ListResourcesFilters {
1013
- search?: string;
1014
- archived?: boolean;
1015
- }
1016
- declare class ResourceContext {
1017
- /**
1018
- * Get resource metadata from view storage
1019
- */
1020
- static getResourceMetadata(resourceId: ResourceId, kb: KnowledgeBase): Promise<ResourceDescriptor | null>;
1021
- /**
1022
- * List resources, optionally filtered.
1023
- *
1024
- * When `search` is set, delegates to `kb.graph.searchResources`, which runs
1025
- * the name match in the graph engine instead of scanning every view in JS.
1026
- * The graph result is then narrowed by `archived` if requested.
1027
- *
1028
- * When `search` is unset, falls back to scanning all materialized views.
1029
- * (TODO: also push the listing path through the graph for large KBs.)
1030
- */
1031
- static listResources(filters: ListResourcesFilters | undefined, kb: KnowledgeBase): Promise<ResourceDescriptor[]>;
1032
- private static sortByDateDesc;
1033
- /**
1034
- * Add content previews to resources (for search results)
1035
- * Retrieves and decodes the first 200 characters of each resource's primary representation
1036
- */
1037
- static addContentPreviews(resources: ResourceDescriptor[], kb: KnowledgeBase): Promise<Array<ResourceDescriptor & {
1038
- content: string;
1039
- }>>;
1040
- /**
1041
- * Get full content for a resource
1042
- * Retrieves and decodes the primary representation
1043
- */
1044
- static getResourceContent(resource: ResourceDescriptor, kb: KnowledgeBase): Promise<string | undefined>;
1045
- }
1046
-
1047
- /**
1048
- * Annotation Context
1049
- *
1050
- * Assembles annotation context from view storage and content store.
1051
- * Provides methods for:
1052
- * - Getting resource annotations
1053
- * - Building LLM context for annotations
1054
- * - Extracting annotation text context
1055
- * - Generating AI summaries
1056
- */
1057
-
1058
- type AnnotationLLMContextResponse = components['schemas']['AnnotationLLMContextResponse'];
1059
-
1060
- type AnnotationContextResponse = components['schemas']['AnnotationContextResponse'];
1061
- type ContextualSummaryResponse = components['schemas']['ContextualSummaryResponse'];
1062
- interface BuildContextOptions {
1063
- includeSourceContext?: boolean;
1064
- includeTargetContext?: boolean;
1065
- contextWindow?: number;
1066
- }
1067
- declare class AnnotationContext {
1068
- /**
1069
- * Build LLM context for an annotation
1070
- *
1071
- * @param annotationId - Bare annotation ID
1072
- * @param resourceId - Source resource ID
1073
- * @param kb - Knowledge base stores
1074
- * @param options - Context building options
1075
- * @param inferenceClient - Optional inference client for target context summary
1076
- * @returns Rich context for LLM processing
1077
- * @throws Error if annotation or resource not found
1078
- */
1079
- static buildLLMContext(annotationId: AnnotationId, resourceId: ResourceId, kb: KnowledgeBase, options?: BuildContextOptions, inferenceClient?: InferenceClient, logger?: Logger, embeddingProvider?: EmbeddingProvider): Promise<AnnotationLLMContextResponse>;
1080
- /**
1081
- * Get resource annotations from view storage (fast path)
1082
- * Throws if view missing
1083
- */
1084
- static getResourceAnnotations(resourceId: ResourceId, kb: KnowledgeBase): Promise<ResourceAnnotations>;
1085
- /**
1086
- * Get all annotations
1087
- * @returns Array of all annotation objects
1088
- */
1089
- static getAllAnnotations(resourceId: ResourceId, kb: KnowledgeBase): Promise<Annotation[]>;
1090
- /**
1091
- * Enrich reference annotations with resolved document names
1092
- * Adds _resolvedDocumentName property to annotations that link to documents
1093
- * @private
1094
- */
1095
- private static enrichResolvedReferences;
1096
- /**
1097
- * Get resource stats (version info)
1098
- * @returns Version and timestamp info for the annotations
1099
- */
1100
- static getResourceStats(resourceId: ResourceId, kb: KnowledgeBase): Promise<{
1101
- resourceId: ResourceId;
1102
- version: number;
1103
- updatedAt: string;
1104
- }>;
1105
- /**
1106
- * Check if resource exists in view storage
1107
- */
1108
- static resourceExists(resourceId: ResourceId, kb: KnowledgeBase): Promise<boolean>;
1109
- /**
1110
- * Get a single annotation by ID
1111
- * O(1) lookup using resource ID to access view storage
1112
- */
1113
- static getAnnotation(annotationId: AnnotationId, resourceId: ResourceId, kb: KnowledgeBase): Promise<Annotation | null>;
1114
- /**
1115
- * List annotations with optional filtering
1116
- * @param filters - Optional filters like resourceId and type
1117
- * @throws Error if resourceId not provided (cross-resource queries not supported in view storage)
1118
- */
1119
- static listAnnotations(filters: {
1120
- resourceId?: ResourceId;
1121
- type?: AnnotationCategory;
1122
- } | undefined, kb: KnowledgeBase): Promise<Annotation[]>;
1123
- /**
1124
- * Get annotation context (selected text with surrounding context)
1125
- */
1126
- static getAnnotationContext(annotationId: AnnotationId, resourceId: ResourceId, contextBefore: number, contextAfter: number, kb: KnowledgeBase): Promise<AnnotationContextResponse>;
1127
- /**
1128
- * Generate AI summary of annotation in context
1129
- */
1130
- static generateAnnotationSummary(annotationId: AnnotationId, resourceId: ResourceId, kb: KnowledgeBase, inferenceClient: InferenceClient): Promise<ContextualSummaryResponse>;
1131
- /**
1132
- * Get resource content as string
1133
- */
1134
- private static getResourceContent;
1135
- /**
1136
- * Extract annotation context from resource content
1137
- */
1138
- private static extractAnnotationContext;
1139
- /**
1140
- * Generate LLM summary of annotation in context
1141
- * Creates inference client per-request (HTTP handler context)
1142
- */
1143
- private static generateSummary;
1144
- }
1145
-
1146
- /**
1147
- * Graph Context
1148
- *
1149
- * Provides graph database operations for resources and annotations.
1150
- * All methods require graph traversal - must use graph database.
1151
- */
1152
-
1153
- interface GraphNode {
1154
- id: string;
1155
- type: string;
1156
- label: string;
1157
- metadata: {
1158
- entityTypes: string[];
1159
- };
1160
- }
1161
- interface GraphEdge {
1162
- source: string;
1163
- target: string;
1164
- type: string;
1165
- metadata: Record<string, unknown>;
1166
- }
1167
- interface GraphRepresentation {
1168
- nodes: GraphNode[];
1169
- edges: GraphEdge[];
1170
- }
1171
- declare class GraphContext {
1172
- /**
1173
- * Get all resources referencing this resource (backlinks)
1174
- * Requires graph traversal - must use graph database
1175
- */
1176
- static getBacklinks(resourceId: ResourceId, kb: KnowledgeBase): Promise<Annotation[]>;
1177
- /**
1178
- * Find shortest path between two resources
1179
- * Requires graph traversal - must use graph database
1180
- */
1181
- static findPath(fromResourceId: ResourceId, toResourceId: ResourceId, kb: KnowledgeBase, maxDepth?: number): Promise<GraphPath[]>;
1182
- /**
1183
- * Get resource connections (graph edges)
1184
- * Requires graph traversal - must use graph database
1185
- */
1186
- static getResourceConnections(resourceId: ResourceId, kb: KnowledgeBase): Promise<GraphConnection[]>;
1187
- /**
1188
- * Search resources by name (cross-resource query)
1189
- * Requires full-text search - must use graph database
1190
- */
1191
- static searchResources(query: string, kb: KnowledgeBase, limit?: number): Promise<ResourceDescriptor[]>;
1192
- /**
1193
- * Build graph representation with nodes and edges for a resource and its connections
1194
- * Retrieves connections from graph and builds visualization-ready structure
1195
- */
1196
- static buildGraphRepresentation(resourceId: ResourceId, maxRelated: number, kb: KnowledgeBase): Promise<GraphRepresentation>;
1197
- }
1198
-
1199
- /**
1200
- * LLM Context
1201
- *
1202
- * Builds comprehensive context for LLM processing of resources
1203
- * Orchestrates: ResourceContext, GraphContext, AnnotationContext, and generation functions
1204
- */
1205
-
1206
- type ResourceLLMContextResponse = components['schemas']['ResourceLLMContextResponse'];
1207
- interface LLMContextOptions {
1208
- depth: number;
1209
- maxResources: number;
1210
- includeContent: boolean;
1211
- includeSummary: boolean;
1212
- }
1213
- declare class LLMContext {
1214
- /**
1215
- * Get comprehensive LLM context for a resource
1216
- * Includes: main resource, related resources, annotations, graph, content, summary, references
1217
- */
1218
- static getResourceContext(resourceId: ResourceId, options: LLMContextOptions, kb: KnowledgeBase, inferenceClient: InferenceClient): Promise<ResourceLLMContextResponse>;
1219
- }
1220
-
1221
- /**
1222
- * Resource Generation Functions
1223
- *
1224
- * Application-specific resource generation logic:
1225
- * - Resource summary generation
1226
- * - Reference suggestion generation
1227
- *
1228
- * NOTE: generateResourceFromTopic lives in @semiont/jobs (canonical location)
1229
- * because make-meaning depends on jobs, not vice versa.
1230
- */
1231
-
1232
- /**
1233
- * Generate an intelligent summary for a resource
1234
- */
1235
- declare function generateResourceSummary(resourceName: string, content: string, entityTypes: string[], client: InferenceClient): Promise<string>;
1236
- /**
1237
- * Generate smart suggestions for a reference
1238
- */
1239
- declare function generateReferenceSuggestions(referenceTitle: string, client: InferenceClient, entityType?: string, currentContent?: string): Promise<string[] | null>;
1240
-
1241
- declare const PACKAGE_NAME = "@semiont/make-meaning";
1242
- declare const VERSION = "0.1.0";
1243
-
1244
- export { AnnotationContext, AnnotationOperations, BACKUP_FORMAT, type BackupContentReader, type BackupEventStoreReader, type BackupExporterOptions, type BackupImportResult, type BackupImporterOptions, type BackupManifestHeader, type BackupStreamSummary, Browser, type BuildContextOptions, CloneTokenManager, type ContentBlobResolver, type CreateAnnotationResult, type CreateResourceInput, type CreateResourceResult, FORMAT_VERSION, Gatherer$1 as Gatherer, GraphContext, type GraphEdge, type GraphNode, type GraphRepresentation, type KnowledgeBase, type KnowledgeSystem, LLMContext, type LLMContextOptions, type LinkedDataContentReader, type LinkedDataExporterOptions, type LinkedDataImportResult, type LinkedDataImporterOptions, type LinkedDataViewReader, type ListResourcesFilters, LocalContentTransport, LocalTransport, type LocalTransportConfig, type MakeMeaningConfig, type MakeMeaningService, Matcher, PACKAGE_NAME, type ReplayStats, ResourceContext, ResourceOperations, type SmelterActorStateUnit, type SmelterActorStateUnitOptions, type SmelterEvent, Stower, type UpdateAnnotationBodyResult, VERSION, bootstrapEntityTypes, createKnowledgeBase, createSmelterActorStateUnit, exportBackup, exportLinkedData, generateReferenceSuggestions, generateResourceSummary, importBackup, importLinkedData, isBackupManifest, readEntityTypesProjection, registerAnnotationAssemblyHandler, registerAnnotationLookupHandlers, registerBindUpdateBodyHandler, registerBusHandlers, registerJobCommandHandlers, startMakeMeaning, stopKnowledgeSystem, validateManifestVersion };
1
+ export { startMakeMeaning } from './service';
2
+ export type { MakeMeaningService, MakeMeaningConfig } from './service';
3
+ export type { KnowledgeSystem } from './knowledge-system';
4
+ export { stopKnowledgeSystem } from './knowledge-system';
5
+ export { LocalTransport, type LocalTransportConfig } from './local-transport';
6
+ export { LocalContentTransport } from './local-content-transport';
7
+ export { registerBusHandlers, registerAnnotationAssemblyHandler, registerAnnotationLookupHandlers, registerBindUpdateBodyHandler, registerJobCommandHandlers, } from './handlers';
8
+ export { bootstrapEntityTypes } from './bootstrap/entity-types';
9
+ export { readEntityTypesProjection } from './views/entity-types-reader';
10
+ export { createKnowledgeBase } from './knowledge-base';
11
+ export type { KnowledgeBase } from './knowledge-base';
12
+ export { Gatherer } from './gatherer';
13
+ export { Matcher } from './matcher';
14
+ export { Stower } from './stower';
15
+ export type { CreateResourceResult } from './stower';
16
+ export { Browser } from './browser';
17
+ export { CloneTokenManager } from './clone-token-manager';
18
+ export { createSmelterActorStateUnit, type SmelterActorStateUnit, type SmelterActorStateUnitOptions, type SmelterEvent, } from './smelter-actor-state-unit';
19
+ export * from './exchange';
20
+ export { ResourceOperations } from './resource-operations';
21
+ export type { CreateResourceInput } from './resource-operations';
22
+ export { assembleAnnotation, applyBodyOperations } from './annotation-assembly';
23
+ export type { AssembledAnnotation } from './annotation-assembly';
24
+ export { AnnotationOperations } from './annotation-operations';
25
+ export type { CreateAnnotationResult, UpdateAnnotationBodyResult } from './annotation-operations';
26
+ export { ResourceContext } from './resource-context';
27
+ export type { ListResourcesFilters } from './resource-context';
28
+ export { AnnotationContext } from './annotation-context';
29
+ export type { BuildContextOptions } from './annotation-context';
30
+ export { GraphContext } from './graph-context';
31
+ export type { GraphNode, GraphEdge, GraphRepresentation } from './graph-context';
32
+ export { LLMContext } from './llm-context';
33
+ export type { LLMContextOptions } from './llm-context';
34
+ export { generateResourceSummary, generateReferenceSuggestions, } from './generation/resource-generation';
35
+ export declare const PACKAGE_NAME = "@semiont/make-meaning";
36
+ export declare const VERSION = "0.1.0";
37
+ //# sourceMappingURL=index.d.ts.map