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