-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.d.ts
More file actions
4074 lines (3607 loc) · 129 KB
/
index.d.ts
File metadata and controls
4074 lines (3607 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @git-stunts/git-warp - A graph database where every node is a Git commit pointing to the Empty Tree.
*/
/**
* Causality tracking for distributed CRDT systems.
* Maps each writer ID to the highest observed operation counter.
*/
export class VersionVector {
static empty(): VersionVector;
static from(source: VersionVector | Map<string, number> | Record<string, number>): VersionVector;
get(writerId: string): number | undefined;
set(writerId: string, counter: number): this;
has(writerId: string): boolean;
get size(): number;
keys(): IterableIterator<string>;
values(): IterableIterator<number>;
entries(): IterableIterator<[string, number]>;
[Symbol.iterator](): IterableIterator<[string, number]>;
increment(writerId: string): { writerId: string; counter: number };
merge(other: VersionVector): VersionVector;
descends(other: VersionVector): boolean;
contains(dot: { writerId: string; counter: number }): boolean;
clone(): VersionVector;
equals(other: VersionVector): boolean;
}
/**
* Result of a ping health check.
*/
export interface PingResult {
/** Whether the ping succeeded */
ok: boolean;
/** Latency in milliseconds */
latencyMs: number;
}
/**
* Health status of a repository component.
*/
export interface RepositoryHealth {
/** Repository status */
status: 'healthy' | 'unhealthy';
/** Ping latency in milliseconds */
latencyMs: number;
}
/**
* Health status of the index component.
*/
export interface IndexHealth {
/** Index status */
status: 'healthy' | 'degraded' | 'unhealthy';
/** Whether an index is loaded */
loaded: boolean;
/** Number of shards (if loaded) */
shardCount?: number;
}
/**
* Complete health check result.
*/
export interface HealthResult {
/** Overall health status */
status: 'healthy' | 'degraded' | 'unhealthy';
/** Component health breakdown */
components: {
/** Repository health */
repository: RepositoryHealth;
/** Index health */
index: IndexHealth;
};
/** ISO timestamp if result is cached */
cachedAt?: string;
}
/**
* Health status constants.
*/
export const HealthStatus: {
readonly HEALTHY: 'healthy';
readonly DEGRADED: 'degraded';
readonly UNHEALTHY: 'unhealthy';
};
/**
* Options for creating a new graph node.
*/
export interface CreateNodeOptions {
/** The node's message/data */
message: string;
/** Array of parent commit SHAs */
parents?: string[];
/** Whether to GPG-sign the commit */
sign?: boolean;
}
/**
* Specification for a node to be created in bulk.
* Parents can include placeholder references like '$0', '$1' to reference
* nodes created earlier in the same batch (by their array index).
*/
export interface BulkNodeSpec {
/** The node's message/data */
message: string;
/** Array of parent commit SHAs or placeholder references ('$0', '$1', etc.) */
parents?: string[];
}
/**
* Options for listing nodes.
*/
export interface ListNodesOptions {
/** Git ref to start from (HEAD, branch, SHA) */
ref: string;
/** Maximum nodes to return (default: 50) */
limit?: number;
}
/**
* Options for iterating nodes.
*/
export interface IterateNodesOptions {
/** Git ref to start from */
ref: string;
/** Maximum nodes to yield (default: 1000000) */
limit?: number;
/** Optional AbortSignal for cancellation support */
signal?: AbortSignal;
}
/**
* Options for rebuilding the index.
*/
export interface RebuildOptions {
/** Maximum nodes to process (default: 10000000, max: 10000000) */
limit?: number;
/** Enable streaming mode with this memory threshold in bytes */
maxMemoryBytes?: number;
/** Optional AbortSignal for cancellation support */
signal?: AbortSignal;
/** Callback invoked on each flush (streaming mode only) */
onFlush?: (info: { flushedBytes: number; totalFlushedBytes: number; flushCount: number }) => void;
/** Callback invoked periodically during processing */
onProgress?: (info: { processedNodes: number; currentMemoryBytes: number | null }) => void;
}
/**
* Options for loading a previously built index.
*/
export interface LoadOptions {
/** Enable strict integrity verification (fail-closed). Default: true */
strict?: boolean;
/** Frontier to compare for staleness (maps writer IDs to their current tip SHAs) */
currentFrontier?: Map<string, string>;
/** Auto-rebuild when a stale index is detected. Requires rebuildRef. Default: false */
autoRebuild?: boolean;
/** Git ref to rebuild from when autoRebuild is true */
rebuildRef?: string;
}
/**
* Direction for graph traversal.
*/
export type TraversalDirection = 'forward' | 'reverse';
/**
* Node yielded during graph traversal.
*/
export interface TraversalNode {
/** The node's SHA */
sha: string;
/** Distance from start node */
depth: number;
/** SHA of the node that led to this one, or null for start */
parent: string | null;
}
/**
* Result of a path-finding operation.
*/
export interface PathResult {
/** Whether a path was found */
found: boolean;
/** Array of SHAs from source to target (empty if not found) */
path: string[];
/** Path length (-1 if not found) */
length: number;
}
/**
* Snapshot of a node passed into query predicates.
*/
export interface QueryNodeSnapshot {
id: string;
props: Record<string, unknown>;
edgesOut: Array<{ label: string; to: string }>;
edgesIn: Array<{ label: string; from: string }>;
}
/**
* Query result (standard).
*/
export interface QueryResultV1 {
stateHash: string;
nodes: Array<{
id?: string;
props?: Record<string, unknown>;
}>;
}
/**
* Aggregation specification for query results.
*/
export interface AggregateSpec {
/** Count matched nodes */
count?: boolean;
/** Sum a numeric property (dot-notation path, e.g. 'props.total') */
sum?: string;
/** Average a numeric property */
avg?: string;
/** Minimum of a numeric property */
min?: string;
/** Maximum of a numeric property */
max?: string;
}
/**
* Result of an aggregate query.
*/
export interface AggregateResult {
stateHash: string;
count?: number;
sum?: number;
avg?: number;
min?: number;
max?: number;
}
/**
* Depth option for multi-hop traversal.
*/
export interface HopOptions {
/** Number of hops or [min, max] range. Default: [1, 1] (single hop). */
depth?: number | [number, number];
}
/**
* Fluent query builder.
*/
export class QueryBuilder {
match(pattern: string | string[]): QueryBuilder;
where(fn: ((node: QueryNodeSnapshot) => boolean) | Record<string, unknown>): QueryBuilder;
outgoing(label?: string, options?: HopOptions): QueryBuilder;
incoming(label?: string, options?: HopOptions): QueryBuilder;
select(fields?: Array<'id' | 'props'>): QueryBuilder;
aggregate(spec: AggregateSpec): QueryBuilder;
run(): Promise<QueryResultV1 | AggregateResult>;
}
/**
* Logical graph traversal module.
*/
export interface TraverseFacadeOptions {
maxDepth?: number;
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
}
/** Edge weight function for weighted traversal algorithms. */
export type EdgeWeightFn = (from: string, to: string, label: string) => number | Promise<number>;
/** Node weight function for weighted traversal algorithms. */
export type NodeWeightFn = (nodeId: string) => number | Promise<number>;
/** Selector for weighted cost traversal mode — supply either an edge or node weight function, not both. */
export type WeightedCostSelector =
| { weightFn?: EdgeWeightFn; nodeWeightFn?: never }
| { nodeWeightFn?: NodeWeightFn; weightFn?: never };
/** @deprecated Traversal facade that delegates to GraphTraversal. Use GraphTraversal directly. */
export interface LogicalTraversal {
bfs(start: string, options?: TraverseFacadeOptions): Promise<string[]>;
dfs(start: string, options?: TraverseFacadeOptions): Promise<string[]>;
shortestPath(from: string, to: string, options?: TraverseFacadeOptions): Promise<{ found: boolean; path: string[]; length: number }>;
connectedComponent(start: string, options?: {
maxDepth?: number;
labelFilter?: string | string[];
}): Promise<string[]>;
isReachable(from: string, to: string, options?: TraverseFacadeOptions & {
signal?: AbortSignal;
}): Promise<{ reachable: boolean }>;
weightedShortestPath(from: string, to: string, options?: WeightedCostSelector & {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
signal?: AbortSignal;
}): Promise<{ path: string[]; totalCost: number }>;
aStarSearch(from: string, to: string, options?: WeightedCostSelector & {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
heuristicFn?: (nodeId: string, goalId: string) => number;
signal?: AbortSignal;
}): Promise<{ path: string[]; totalCost: number; nodesExplored: number }>;
bidirectionalAStar(from: string, to: string, options?: WeightedCostSelector & {
labelFilter?: string | string[];
forwardHeuristic?: (nodeId: string, goalId: string) => number;
backwardHeuristic?: (nodeId: string, goalId: string) => number;
signal?: AbortSignal;
}): Promise<{ path: string[]; totalCost: number; nodesExplored: number }>;
topologicalSort(start: string | string[], options?: {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
throwOnCycle?: boolean;
signal?: AbortSignal;
}): Promise<{ sorted: string[]; hasCycle: boolean }>;
commonAncestors(nodes: string[], options?: {
maxDepth?: number;
labelFilter?: string | string[];
maxResults?: number;
signal?: AbortSignal;
}): Promise<{ ancestors: string[] }>;
weightedLongestPath(from: string, to: string, options?: WeightedCostSelector & {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
signal?: AbortSignal;
}): Promise<{ path: string[]; totalCost: number }>;
levels(start: string | string[], options?: {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
signal?: AbortSignal;
}): Promise<{ levels: Map<string, number>; maxLevel: number }>;
transitiveReduction(start: string | string[], options?: {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
signal?: AbortSignal;
}): Promise<{ edges: Array<{ from: string; to: string; label: string }>; removed: number }>;
transitiveClosure(start: string | string[], options?: {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
maxEdges?: number;
signal?: AbortSignal;
}): Promise<{ edges: Array<{ from: string; to: string }> }>;
transitiveClosureStream(start: string | string[], options?: {
dir?: 'out' | 'in' | 'both';
labelFilter?: string | string[];
maxEdges?: number;
signal?: AbortSignal;
}): AsyncGenerator<{ from: string; to: string }, void, unknown>;
rootAncestors(start: string, options?: {
labelFilter?: string | string[];
maxDepth?: number;
signal?: AbortSignal;
}): Promise<{ roots: string[] }>;
}
/**
* Options for BFS/DFS traversal.
*/
export interface TraversalOptions {
/** Starting node SHA */
start: string;
/** Maximum nodes to visit (default: 100000) */
maxNodes?: number;
/** Maximum depth to traverse (default: 1000) */
maxDepth?: number;
/** Traversal direction (default: 'forward') */
direction?: TraversalDirection;
}
/**
* Options for ancestor/descendant traversal.
*/
export interface AncestorOptions {
/** Starting node SHA */
sha: string;
/** Maximum nodes to visit (default: 100000) */
maxNodes?: number;
/** Maximum depth to traverse (default: 1000) */
maxDepth?: number;
}
/**
* Options for path-finding operations.
*/
export interface PathOptions {
/** Source node SHA */
from: string;
/** Target node SHA */
to: string;
/** Maximum search depth (default: 1000) */
maxDepth?: number;
/** Maximum nodes to visit */
maxNodes?: number;
}
/**
* Options for finding common ancestors.
*/
export interface CommonAncestorsOptions {
/** Array of node SHAs */
shas: string[];
/** Maximum ancestors to return (default: 100) */
maxResults?: number;
/** Maximum depth to search (default: 1000) */
maxDepth?: number;
}
/**
* Options for topological sort.
*/
export interface TopologicalSortOptions {
/** Starting node SHA */
start: string;
/** Maximum nodes to yield (default: 100000) */
maxNodes?: number;
/** Direction determines dependency order (default: 'forward') */
direction?: TraversalDirection;
/** If true, throws TraversalError when cycle detected (default: false) */
throwOnCycle?: boolean;
}
/**
* Immutable entity representing a graph node.
*/
export class GraphNode {
/** Commit SHA */
readonly sha: string;
/** Author name */
readonly author: string | undefined;
/** Commit date */
readonly date: string | undefined;
/** Node message/data */
readonly message: string;
/** Array of parent SHAs */
readonly parents: readonly string[];
constructor(data: {
sha: string;
message: string;
author?: string;
date?: string;
parents?: string[];
});
}
/**
* Port interface for graph persistence operations.
* @abstract
*/
/**
* Full commit metadata returned by getNodeInfo.
*/
export interface NodeInfo {
/** Commit SHA */
sha: string;
/** Commit message */
message: string;
/** Author name */
author: string;
/** Commit date */
date: string;
/** Parent commit SHAs */
parents: string[];
}
/** Abstract port for Git persistence operations (commits, refs, blobs, trees). */
export abstract class GraphPersistencePort {
/** The empty tree SHA */
abstract get emptyTree(): string;
abstract commitNode(options: CreateNodeOptions): Promise<string>;
abstract showNode(sha: string): Promise<string>;
/** Gets full commit metadata for a node */
abstract getNodeInfo(sha: string): Promise<NodeInfo>;
abstract logNodesStream(options: ListNodesOptions & { format: string }): Promise<AsyncIterable<Uint8Array | string>>;
abstract logNodes(options: ListNodesOptions & { format: string }): Promise<string>;
/** Pings the repository to verify accessibility */
abstract ping(): Promise<PingResult>;
/** Counts nodes reachable from a ref without loading them into memory */
abstract countNodes(ref: string): Promise<number>;
/** Checks if a node exists by SHA */
nodeExists(sha: string): Promise<boolean>;
}
/**
* Port interface for index storage operations.
* @abstract
*/
export abstract class IndexStoragePort {
/** Writes a blob and returns its OID */
abstract writeBlob(content: Uint8Array | string): Promise<string>;
/** Writes a tree from entries and returns its OID */
abstract writeTree(entries: string[]): Promise<string>;
/** Reads a blob by OID */
abstract readBlob(oid: string): Promise<Uint8Array>;
/** Reads a tree and returns a map of path to blob OID */
abstract readTreeOids(treeOid: string): Promise<Record<string, string>>;
/** Updates a ref to point to an OID */
abstract updateRef(ref: string, oid: string): Promise<void>;
/** Reads the OID a ref points to */
abstract readRef(ref: string): Promise<string | null>;
}
/**
* Log levels in order of severity.
*/
export const LogLevel: {
readonly DEBUG: 0;
readonly INFO: 1;
readonly WARN: 2;
readonly ERROR: 3;
readonly SILENT: 4;
};
/** Numeric log level value (0=debug, 1=info, 2=warn, 3=error, 4=silent). */
export type LogLevelValue = 0 | 1 | 2 | 3 | 4;
/**
* Port interface for cryptographic operations.
* @abstract
*/
export abstract class CryptoPort {
/** Computes a hash digest of the given data */
abstract hash(algorithm: string, data: string | Uint8Array): Promise<string>;
/** Computes an HMAC of the given data */
abstract hmac(algorithm: string, key: string | Uint8Array, data: string | Uint8Array): Promise<Uint8Array>;
/** Constant-time comparison of two byte arrays */
abstract timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
}
/**
* Port interface for time-related operations.
* @abstract
*/
export abstract class ClockPort {
/** Returns a high-resolution timestamp in milliseconds */
abstract now(): number;
/** Returns the current wall-clock time as an ISO string */
abstract timestamp(): string;
}
/**
* Unified clock adapter supporting both Node.js and global performance APIs.
*
* Use the static factory methods for common cases:
* - `ClockAdapter.node()` -- Node.js `perf_hooks.performance`
* - `ClockAdapter.global()` -- `globalThis.performance` (Bun/Deno/browsers)
*/
export class ClockAdapter extends ClockPort {
constructor(options?: { performanceImpl?: Performance });
static node(): ClockAdapter;
static global(): ClockAdapter;
now(): number;
timestamp(): string;
}
/**
* Port interface for seek materialization cache operations.
*
* Implementations store serialized WarpStateV5 snapshots keyed by
* (ceiling, frontier) tuples for near-instant restoration of
* previously-visited ticks during seek exploration.
*
* @abstract
*/
export abstract class SeekCachePort {
/** Retrieves a cached state buffer by key, or null on miss. */
abstract get(key: string): Promise<{ buffer: Uint8Array; indexTreeOid?: string } | null>;
/** Stores a state buffer under the given key. */
abstract set(key: string, buffer: Uint8Array, options?: { indexTreeOid?: string }): Promise<void>;
/** Checks whether a key exists in the cache index. */
abstract has(key: string): Promise<boolean>;
/** Lists all keys currently in the cache index. */
abstract keys(): Promise<string[]>;
/** Removes a single entry from the cache. */
abstract delete(key: string): Promise<boolean>;
/** Removes all entries from the cache. */
abstract clear(): Promise<void>;
}
/**
* Port interface for content blob storage operations.
* Abstracts how large binary content is stored and retrieved.
* @abstract
*/
export abstract class BlobStoragePort {
/** Stores content and returns a storage identifier (e.g. CAS tree OID). */
abstract store(content: Uint8Array | string, options?: { slug?: string; mime?: string | null; size?: number | null }): Promise<string>;
/** Retrieves content by its storage identifier. */
abstract retrieve(oid: string): Promise<Uint8Array>;
/** Stores content from a streaming source and returns a storage identifier. */
abstract storeStream(source: AsyncIterable<Uint8Array>, options?: { slug?: string; mime?: string | null; size?: number | null }): Promise<string>;
/** Retrieves content as an async iterable of chunks. */
abstract retrieveStream(oid: string): AsyncIterable<Uint8Array>;
}
/**
* In-memory blob storage adapter for browser and test paths.
* Content-addressed Map-based storage implementing BlobStoragePort.
*/
export class InMemoryBlobStorageAdapter extends BlobStoragePort {
store(content: Uint8Array | string, options?: { slug?: string; mime?: string | null; size?: number | null }): Promise<string>;
retrieve(oid: string): Promise<Uint8Array>;
storeStream(source: AsyncIterable<Uint8Array>, options?: { slug?: string; mime?: string | null; size?: number | null }): Promise<string>;
retrieveStream(oid: string): AsyncIterable<Uint8Array>;
}
/**
* Port interface for structured logging operations.
* @abstract
*/
export abstract class LoggerPort {
/** Log a debug-level message */
abstract debug(message: string, context?: Record<string, unknown>): void;
/** Log an info-level message */
abstract info(message: string, context?: Record<string, unknown>): void;
/** Log a warning-level message */
abstract warn(message: string, context?: Record<string, unknown>): void;
/** Log an error-level message */
abstract error(message: string, context?: Record<string, unknown>): void;
/** Create a child logger with additional base context */
abstract child(context: Record<string, unknown>): LoggerPort;
}
/**
* No-operation logger adapter.
* Discards all log messages. Zero overhead.
*/
export class NoOpLogger extends LoggerPort {
debug(message: string, context?: Record<string, unknown>): void;
info(message: string, context?: Record<string, unknown>): void;
warn(message: string, context?: Record<string, unknown>): void;
error(message: string, context?: Record<string, unknown>): void;
child(context: Record<string, unknown>): NoOpLogger;
}
/**
* Console logger adapter with structured JSON output.
* Supports log level filtering, timestamps, and child loggers.
*/
export class ConsoleLogger extends LoggerPort {
constructor(options?: {
/** Minimum log level to output (default: LogLevel.INFO) */
level?: LogLevelValue | 'debug' | 'info' | 'warn' | 'error' | 'silent';
/** Base context for all log entries */
context?: Record<string, unknown>;
/** Custom timestamp function (defaults to ISO string) */
timestampFn?: () => string;
});
debug(message: string, context?: Record<string, unknown>): void;
info(message: string, context?: Record<string, unknown>): void;
warn(message: string, context?: Record<string, unknown>): void;
error(message: string, context?: Record<string, unknown>): void;
child(context: Record<string, unknown>): ConsoleLogger;
}
/**
* Git plumbing interface (from @git-stunts/plumbing).
*/
export interface GitPlumbing {
readonly emptyTree: string;
execute(options: { args: string[]; input?: string | Uint8Array }): Promise<string>;
executeStream(options: { args: string[] }): Promise<AsyncIterable<Uint8Array> & { collect(opts?: { asString?: boolean }): Promise<Uint8Array | string> }>;
}
/**
* In-memory persistence adapter for fast unit/integration tests.
*
* Implements the same GraphPersistencePort contract as GitGraphAdapter
* but stores all data in Maps — no real Git I/O required.
*/
export class InMemoryGraphAdapter extends GraphPersistencePort {
constructor(options?: {
author?: string;
clock?: { now: () => number };
hash?: (data: Uint8Array) => string;
});
get emptyTree(): string;
commitNode(options: CreateNodeOptions): Promise<string>;
showNode(sha: string): Promise<string>;
getNodeInfo(sha: string): Promise<NodeInfo>;
logNodesStream(options: ListNodesOptions & { format: string }): Promise<AsyncIterable<Uint8Array | string>>;
logNodes(options: ListNodesOptions & { format: string }): Promise<string>;
ping(): Promise<PingResult>;
countNodes(ref: string): Promise<number>;
}
/**
* Implementation of GraphPersistencePort and IndexStoragePort using GitPlumbing.
*/
export class GitGraphAdapter extends GraphPersistencePort implements IndexStoragePort {
constructor(options: { plumbing: GitPlumbing });
get emptyTree(): string;
commitNode(options: CreateNodeOptions): Promise<string>;
showNode(sha: string): Promise<string>;
getNodeInfo(sha: string): Promise<NodeInfo>;
logNodesStream(options: ListNodesOptions & { format: string }): Promise<AsyncIterable<Uint8Array | string>>;
logNodes(options: ListNodesOptions & { format: string }): Promise<string>;
writeBlob(content: Uint8Array | string): Promise<string>;
writeTree(entries: string[]): Promise<string>;
readTree(treeOid: string): Promise<Record<string, Uint8Array>>;
readTreeOids(treeOid: string): Promise<Record<string, string>>;
readBlob(oid: string): Promise<Uint8Array>;
updateRef(ref: string, oid: string): Promise<void>;
readRef(ref: string): Promise<string | null>;
deleteRef(ref: string): Promise<void>;
/** Checks if a node (commit) exists in the repository */
nodeExists(sha: string): Promise<boolean>;
ping(): Promise<PingResult>;
/** Counts nodes reachable from a ref without loading them into memory */
countNodes(ref: string): Promise<number>;
/** Reads a git config value */
configGet(key: string): Promise<string | null>;
/** Sets a git config value */
configSet(key: string, value: string): Promise<void>;
}
/**
* Node.js crypto adapter implementing CryptoPort.
*
* Uses Node.js built-in crypto module for hash and HMAC operations.
*/
export class NodeCryptoAdapter extends CryptoPort {
constructor();
hash(algorithm: string, data: string | Uint8Array): Promise<string>;
hmac(algorithm: string, key: string | Uint8Array, data: string | Uint8Array): Promise<Uint8Array>;
timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
}
/**
* Web Crypto API adapter implementing CryptoPort.
*
* Uses the standard Web Crypto API (globalThis.crypto.subtle) which is
* available in browsers, Deno, Bun, and Node.js 20+.
*/
export class WebCryptoAdapter extends CryptoPort {
constructor(options?: { subtle?: SubtleCrypto });
hash(algorithm: string, data: string | Uint8Array): Promise<string>;
hmac(algorithm: string, key: string | Uint8Array, data: string | Uint8Array): Promise<Uint8Array>;
timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean;
}
/**
* Port interface for HTTP server operations.
* @abstract
*/
export abstract class HttpServerPort {
abstract createServer(requestHandler: (request: {
method: string;
url: string;
headers: Record<string, string>;
body?: Uint8Array;
}) => Promise<{ status?: number; headers?: Record<string, string>; body?: string | Uint8Array }>): {
listen(port: number, callback?: (err?: Error | null) => void): void;
listen(port: number, host: string, callback?: (err?: Error | null) => void): void;
close(callback?: (err?: Error | null) => void): void;
address(): { address: string; port: number; family: string } | null;
};
}
/**
* Bun HTTP adapter implementing HttpServerPort.
*
* Uses globalThis.Bun.serve() to create an HTTP server.
*/
export class BunHttpAdapter extends HttpServerPort {
constructor(options?: { logger?: { error: (msg: string, ...args: unknown[]) => void } });
createServer(requestHandler: (request: {
method: string;
url: string;
headers: Record<string, string>;
body?: Uint8Array;
}) => Promise<{ status?: number; headers?: Record<string, string>; body?: string | Uint8Array }>): {
listen(port: number, callback?: (err?: Error | null) => void): void;
listen(port: number, host: string, callback?: (err?: Error | null) => void): void;
close(callback?: (err?: Error | null) => void): void;
address(): { address: string; port: number; family: string } | null;
};
}
/**
* Deno HTTP adapter implementing HttpServerPort.
*
* Uses globalThis.Deno.serve() (Deno 1.35+) to create an HTTP server.
*/
export class DenoHttpAdapter extends HttpServerPort {
constructor(options?: { logger?: { error: (msg: string, ...args: unknown[]) => void } });
createServer(requestHandler: (request: {
method: string;
url: string;
headers: Record<string, string>;
body?: Uint8Array;
}) => Promise<{ status?: number; headers?: Record<string, string>; body?: string | Uint8Array }>): {
listen(port: number, callback?: (err?: Error | null) => void): void;
listen(port: number, host: string, callback?: (err?: Error | null) => void): void;
close(callback?: (err?: Error | null) => void): void;
address(): { address: string; port: number; family: string } | null;
};
}
/**
* Builder for constructing bitmap indexes in memory.
*
* Pure domain class with no infrastructure dependencies.
*/
export class BitmapIndexBuilder {
/** SHA to numeric ID mappings */
readonly shaToId: Map<string, number>;
/** Numeric ID to SHA mappings */
readonly idToSha: string[];
constructor();
/** Registers a node and returns its numeric ID */
registerNode(sha: string): number;
/** Adds a directed edge from source to target */
addEdge(srcSha: string, tgtSha: string): void;
/** Serializes the index to a tree structure of buffers */
serialize(options?: { frontier?: Map<string, string> }): Promise<Record<string, Uint8Array>>;
}
/**
* Builder for constructing bitmap indexes from materialized WARP state.
*
* This builder creates adjacency indexes from WarpStateV5.edgeAlive OR-Set,
* NOT from Git commit DAG topology.
*/
export class WarpStateIndexBuilder {
constructor(options?: { crypto?: CryptoPort });
/**
* Builds an index from materialized WARP state.
*/
buildFromState(state: WarpStateV5): { builder: BitmapIndexBuilder; stats: { nodes: number; edges: number } };
/**
* Serializes the index to a tree structure of buffers.
*/
serialize(): Promise<Record<string, Uint8Array>>;
}
/**
* Builds a bitmap index from materialized WARP state.
*
* Convenience function that creates a WarpStateIndexBuilder, builds from state,
* and returns the serialized tree and stats.
*/
export function buildWarpStateIndex(state: WarpStateV5, options?: { crypto?: CryptoPort }): Promise<{ tree: Record<string, Uint8Array>; stats: { nodes: number; edges: number } }>;
/**
* Computes a deterministic hash of a WarpStateV5 state.
*
* Uses canonical serialization to ensure the same state always produces
* the same hash regardless of property iteration order.
*/
export function computeStateHashV5(state: WarpStateV5, options?: { crypto?: CryptoPort; codec?: unknown }): Promise<string | null>;
/**
* Projects a materialized WarpStateV5 into its visible graph projection.
*
* This is the stable substrate helper for higher layers that need to inspect
* materialized strand or coordinate state without depending on OR-Set
* internals.
*/
export function projectStateV5(state: WarpStateV5): VisibleStateProjectionV5;
/**
* Creates a substrate-generic reader over a materialized WarpStateV5.
*
* The reader exposes stable node/edge/property helpers plus entity-local node
* inspection without requiring callers to understand reducer internals.
*/
export function createStateReaderV5(state: WarpStateV5): VisibleStateReaderV5;
/**
* Compares two materialized WarpStateV5 snapshots using only their visible
* substrate truth.
*/
export function compareVisibleStateV5(
leftState: WarpStateV5,
rightState: WarpStateV5,
options?: { targetId?: string | null },
): VisibleStateComparisonV5;
/**
* Normalizes a substrate-generic visible-state scope. Current v1 scope
* supports include/exclude node-id prefixes; dependent edges and properties
* follow node visibility.
*/
export function normalizeVisibleStateScopeV1(
scope: unknown,
field?: string,
): VisibleStateScopeV1 | null;
/**
* Projects a materialized WarpStateV5 down to the visible subset admitted by
* a normalized visible-state scope.
*/
export function scopeMaterializedStateV5(
state: WarpStateV5,
scope?: VisibleStateScopeV1 | null,
): WarpStateV5;
/**
* Exports the exact deterministic substrate fact hashed by a coordinate
* comparison digest as a JSON-safe envelope for higher-layer storage.
*/
export function exportCoordinateComparisonFact(
comparison: CoordinateComparisonV1,
): CoordinateComparisonFactExportV1;
/**
* Exports the exact deterministic substrate fact hashed by a coordinate
* transfer-plan digest as a JSON-safe envelope without raw attachment bytes.
*/
export function exportCoordinateTransferPlanFact(
transferPlan: CoordinateTransferPlanV1,
): CoordinateTransferPlanFactExportV1;
/**
* Service for querying a loaded bitmap index.
*
* Provides O(1) lookups via lazy-loaded sharded bitmap data.
*/
export class BitmapIndexReader {
constructor(options: {
storage: IndexStoragePort;
/** If true, throw on validation failures; if false, log and return empty (default: false) */
strict?: boolean;
/** Logger for structured logging (default: NoOpLogger) */
logger?: LoggerPort;
/** CryptoPort instance for checksum verification. When not provided, checksum validation is skipped. */
crypto?: CryptoPort;
});
/**
* Configures the reader with shard OID mappings for lazy loading.
*
* The shardOids object maps shard filenames to their Git blob OIDs:
* - `meta_XX.json` - SHA→ID mappings for nodes with SHA prefix XX
* - `shards_fwd_XX.json` - Forward edge bitmaps (parent→children)
* - `shards_rev_XX.json` - Reverse edge bitmaps (child→parents)
*
* @example
* reader.setup({
* 'meta_ab.json': 'a1b2c3d4e5f6...',
* 'shards_fwd_ab.json': '1234567890ab...',
* 'shards_rev_ab.json': 'abcdef123456...'
* });
*/
setup(shardOids: Record<string, string>): void;
/** Looks up the numeric ID for a SHA */
lookupId(sha: string): Promise<number | undefined>;
/** Gets parent SHAs for a node (O(1) via reverse bitmap) */
getParents(sha: string): Promise<string[]>;
/** Gets child SHAs for a node (O(1) via forward bitmap) */
getChildren(sha: string): Promise<string[]>;
}
/**
* Service for building and loading the bitmap index from the graph.
*/
export class IndexRebuildService {
constructor(options: {
/** Graph service providing iterateNodes() for walking the graph */
graphService: { iterateNodes(options: IterateNodesOptions): AsyncGenerator<GraphNode, void, unknown> };
storage: IndexStoragePort;
/** Logger for structured logging (default: NoOpLogger) */
logger?: LoggerPort;
});
/**
* Rebuilds the bitmap index by walking the graph from a ref.
*
* **Memory**: O(N) where N is nodes. ~150-200MB for 1M nodes.
* **Time**: O(N) single pass.
*/
rebuild(ref: string, options?: RebuildOptions): Promise<string>;
/**
* Loads a previously built index from a tree OID.
*
* **Memory**: Lazy loading - O(1) initial, shards loaded on demand.
*/
load(treeOid: string, options?: LoadOptions): Promise<BitmapIndexReader>;
}
/**
* Service for performing health checks on the graph system.
*
* Follows hexagonal architecture by depending on ports, not adapters.
* Provides K8s-style probes (liveness vs readiness) and detailed component health.
*/
export class HealthCheckService {