@ternent/ledger 0.1.7 → 0.2.0-alpha.1

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.
@@ -0,0 +1,189 @@
1
+ import { BaseIdentityCapability, PublicIdentity, PublicIdentity as PublicIdentity$1 } from "@ternent/identity";
2
+ type Json = null | boolean | string | number | Json[] | {
3
+ [key: string]: Json;
4
+ };
5
+ type JsonObject = {
6
+ [key: string]: Json;
7
+ };
8
+ type CommitId = `commit:${string}`;
9
+ type EntryId = `entry:${string}`;
10
+ type Relationship = "equal" | "ahead" | "behind" | "diverged" | "unrelated";
11
+ type VerificationReport = {
12
+ integrity: "valid" | "invalid" | "unsupported";
13
+ documentId: CommitId | null;
14
+ head: CommitId | null;
15
+ checkedCommits: number;
16
+ checkedEntries: number;
17
+ findings: readonly HistoryError[];
18
+ };
19
+ type HistoryError = {
20
+ code: string;
21
+ phase: string;
22
+ message: string;
23
+ path?: string;
24
+ commitId?: string;
25
+ entryId?: string;
26
+ details?: Readonly<JsonObject>;
27
+ };
28
+ type Result<T, E = HistoryError> = {
29
+ ok: true;
30
+ value: T;
31
+ } | {
32
+ ok: false;
33
+ error: E;
34
+ };
35
+ declare const ok: <T>(value: T) => Result<T>;
36
+ declare const error: (code: string, phase: string, path?: string) => HistoryError;
37
+ declare class Fault extends Error {
38
+ readonly finding: HistoryError;
39
+ constructor(finding: HistoryError);
40
+ }
41
+ declare function fail(code: string, phase?: string, path?: string): never;
42
+ declare function caught(cause: unknown, fallback: string, phase: string): HistoryError;
43
+ declare function attempt<T>(body: () => T, fallback?: string, phase?: string): Result<T>;
44
+ declare function concat(a: Uint8Array, b: Uint8Array): Uint8Array;
45
+ declare function signatureMessage(subject: LedgerCommitSubject, depth?: number): Uint8Array;
46
+ declare function identifier(subject: LedgerEntrySubject, kind: "entry", depth?: number): EntryId;
47
+ declare function identifier(subject: LedgerCommitSubject, kind: "commit", depth?: number): CommitId;
48
+ declare function inspectProtocol(bytes: Uint8Array, options?: {
49
+ limits?: Partial<LedgerLimits>;
50
+ }): Promise<{
51
+ report: VerificationReport;
52
+ snapshot?: LedgerSnapshot;
53
+ untrustedHistory: readonly LedgerSnapshot["commits"][number][];
54
+ }>;
55
+ declare function verifyDocument(bytes: Uint8Array, options?: {
56
+ limits?: Partial<LedgerLimits>;
57
+ }): Promise<VerificationReport>;
58
+ declare function compareSnapshots(a: Uint8Array, b: Uint8Array, options?: {
59
+ limits?: Partial<LedgerLimits>;
60
+ }): Promise<Result<Relationship>>;
61
+ declare const inspectLedger: typeof inspectProtocol;
62
+ declare const ledgerSignatureMessage: typeof signatureMessage;
63
+ declare const verifyLedger: typeof verifyDocument;
64
+ declare const compareLedgers: typeof compareSnapshots;
65
+ /** Ordered records from a verified snapshot; traversal does not itself establish trust. */
66
+ declare function orderedEntries(snapshot: LedgerSnapshot): Generator<{
67
+ commit: LedgerCommitRecord;
68
+ entry: LedgerEntryRecord;
69
+ }, void, unknown>;
70
+ declare function hashLedgerEntry(subject: LedgerEntrySubject): Result<`entry:${string}`, HistoryError>;
71
+ declare function hashLedgerCommit(subject: LedgerCommitSubject): Result<`commit:${string}`, HistoryError>;
72
+ declare const utf8: TextEncoder;
73
+ declare const text: TextDecoder;
74
+ declare function unicode(value: string): boolean;
75
+ declare function encodeJson(input: unknown, maxDepth?: number): Uint8Array;
76
+ declare function canonicalize(value: unknown): Result<Uint8Array>;
77
+ declare function parseJson(bytes: Uint8Array, maxDepth?: number, maxBytes?: number): Json;
78
+ declare function freeze<T>(value: T): T;
79
+ declare function detached<T>(value: T): T;
80
+ declare function nonce(): string;
81
+ type LedgerSigner = Pick<BaseIdentityCapability, "publicIdentity" | "sign">;
82
+ type LedgerPayload = {
83
+ type: "plain";
84
+ data: Json;
85
+ };
86
+ type LedgerEntrySubject = {
87
+ version: 1;
88
+ parent: CommitId | null;
89
+ nonce: string;
90
+ kind: string;
91
+ author: string;
92
+ authoredAt: string;
93
+ meta: JsonObject | null;
94
+ payload: LedgerPayload;
95
+ };
96
+ type LedgerEntryRecord = {
97
+ id: EntryId;
98
+ subject: LedgerEntrySubject;
99
+ };
100
+ type LedgerCommitSubject = {
101
+ version: 1;
102
+ suite: "ledger-ed25519-v1";
103
+ parent: CommitId | null;
104
+ nonce: string;
105
+ signer: PublicIdentity;
106
+ committedAt: string;
107
+ entryIds: EntryId[];
108
+ metadata: JsonObject | null;
109
+ };
110
+ type LedgerCommitRecord = {
111
+ id: CommitId;
112
+ subject: LedgerCommitSubject;
113
+ signature: string;
114
+ };
115
+ type LedgerSnapshot = {
116
+ format: "ledger";
117
+ version: 1;
118
+ documentId: CommitId;
119
+ head: CommitId;
120
+ commits: LedgerCommitRecord[];
121
+ entries: LedgerEntryRecord[];
122
+ };
123
+ type LedgerLimits = {
124
+ maxBytes: number;
125
+ maxCommits: number;
126
+ maxEntries: number;
127
+ maxDepth: number;
128
+ maxMetadataBytes: number;
129
+ maxPayloadBytes: number;
130
+ };
131
+ type LedgerAppendInput = {
132
+ kind: string;
133
+ payload?: Json;
134
+ meta?: JsonObject;
135
+ nonce?: string;
136
+ };
137
+ type LedgerReplayEntry = LedgerEntrySubject & {
138
+ entryId: EntryId;
139
+ commitId: CommitId | null;
140
+ committed: boolean;
141
+ };
142
+ type LedgerProjector<P> = (projection: P, entry: Readonly<LedgerReplayEntry>) => P;
143
+ type LedgerOptions = {
144
+ signer?: LedgerSigner;
145
+ limits?: Partial<LedgerLimits>;
146
+ now?: () => string;
147
+ };
148
+ type CreateLedgerConfig<P> = LedgerOptions & {
149
+ initialProjection: P;
150
+ projector: LedgerProjector<P>;
151
+ };
152
+ type LedgerState<P> = {
153
+ container: LedgerSnapshot | null;
154
+ staged: readonly LedgerEntryRecord[];
155
+ projection: P;
156
+ verification: VerificationReport | null;
157
+ };
158
+ type LedgerInstance<P> = {
159
+ create(input?: {
160
+ metadata?: JsonObject;
161
+ entries?: readonly LedgerAppendInput[];
162
+ }): Promise<void>;
163
+ load(snapshot: LedgerSnapshot | Uint8Array): Promise<void>;
164
+ import(snapshot: LedgerSnapshot | Uint8Array): Promise<void>;
165
+ append(input: LedgerAppendInput): Promise<{
166
+ entry: LedgerEntryRecord;
167
+ stagedCount: number;
168
+ }>;
169
+ appendMany(inputs: readonly LedgerAppendInput[]): Promise<readonly LedgerEntryRecord[]>;
170
+ commit(input?: {
171
+ metadata?: JsonObject;
172
+ }): Promise<{
173
+ commit: LedgerCommitRecord;
174
+ committedEntries: readonly LedgerEntryRecord[];
175
+ committedEntryIds: readonly EntryId[];
176
+ }>;
177
+ replay(options?: {
178
+ includeStaged?: boolean;
179
+ }): Promise<P>;
180
+ recompute(): Promise<P>;
181
+ verify(): Promise<VerificationReport>;
182
+ export(): Promise<LedgerSnapshot>;
183
+ getState(): Readonly<LedgerState<P>>;
184
+ subscribe(listener: (state: Readonly<LedgerState<P>>) => void): () => void;
185
+ clearStaged(): Promise<void>;
186
+ destroy(): Promise<void>;
187
+ };
188
+ export { identifier as A, Result as B, unicode as C, concat as D, compareSnapshots as E, signatureMessage as F, ok as G, caught as H, verifyDocument as I, Json as J, CommitId as K, verifyLedger as L, inspectProtocol as M, ledgerSignatureMessage as N, hashLedgerCommit as O, orderedEntries as P, VerificationReport as Q, Fault as R, text as S, compareLedgers as T, error as U, attempt as V, fail as W, PublicIdentity$1 as X, JsonObject as Y, Relationship as Z, detached as _, LedgerEntryRecord as a, encodeJson as b, LedgerLimits as c, LedgerProjector as d, LedgerReplayEntry as f, nonce as g, LedgerState as h, LedgerCommitSubject as i, inspectLedger as j, hashLedgerEntry as k, LedgerOptions as l, LedgerSnapshot as m, LedgerAppendInput as n, LedgerEntrySubject as o, LedgerSigner as p, EntryId as q, LedgerCommitRecord as r, LedgerInstance as s, CreateLedgerConfig as t, LedgerPayload as u, freeze as v, utf8 as w, parseJson as x, canonicalize as y, HistoryError as z };
189
+ //# sourceMappingURL=types-CR2908aA.d.ts.map
package/package.json CHANGED
@@ -1,48 +1,53 @@
1
1
  {
2
2
  "name": "@ternent/ledger",
3
- "version": "0.1.7",
4
- "description": "Append-only state engine for Concord",
3
+ "version": "0.2.0-alpha.1",
4
+ "description": "Standalone signed append-only logs with staging, commits, verification and replay",
5
5
  "license": "ISC",
6
- "type": "module",
7
- "sideEffects": false,
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/ternent/core.git",
9
+ "directory": "packages/ledger"
10
+ },
8
11
  "files": [
9
12
  "dist",
10
- "SPEC.md"
13
+ "README.md"
11
14
  ],
12
- "publishConfig": {
13
- "access": "public"
14
- },
15
- "main": "dist/index.js",
16
- "module": "dist/index.js",
17
- "types": "dist/index.d.ts",
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "main": "./dist/index.js",
18
+ "module": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
18
20
  "exports": {
19
21
  ".": {
20
22
  "types": "./dist/index.d.ts",
21
- "import": "./dist/index.js",
22
- "default": "./dist/index.js"
23
+ "import": "./dist/index.js"
23
24
  },
24
- "./browser": {
25
- "types": "./dist/index.d.ts",
26
- "import": "./dist/browser.js",
27
- "default": "./dist/browser.js"
25
+ "./protocol": {
26
+ "types": "./dist/protocol/index.d.ts",
27
+ "import": "./dist/protocol/index.js"
28
28
  }
29
29
  },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
30
33
  "dependencies": {
31
- "@ternent/armour": "0.1.5",
32
- "@ternent/concord-protocol": "0.1.1",
33
- "@ternent/identity": "0.3.1",
34
- "@ternent/seal-cli": "0.3.9"
34
+ "@noble/hashes": "2.4.0",
35
+ "@ternent/identity": "^0.6.0-alpha.1"
35
36
  },
36
37
  "devDependencies": {
37
- "@types/node": "^24.3.0",
38
- "typescript": "^5.6.3",
39
- "vite": "^4.5.3",
40
- "vite-plugin-dts": "^1.7.3",
41
- "vitest": "^1.6.0"
38
+ "typescript": "npm:@typescript/typescript6@6.0.2",
39
+ "vite-plus": "1.7.0"
40
+ },
41
+ "engines": {
42
+ "node": ">=22.18.0"
42
43
  },
43
44
  "scripts": {
44
- "build:browser": "pnpm --filter @ternent/rage build && vite build -c vite.browser.config.ts",
45
- "build": "pnpm --filter @ternent/rage build && vite build && vite build -c vite.browser.config.ts",
46
- "test": "pnpm --filter @ternent/rage build && vitest run"
45
+ "fmt:check": "vp fmt --check .",
46
+ "lint": "vp lint --type-aware .",
47
+ "typecheck": "tsc6 --noEmit -p tsconfig.json",
48
+ "test": "vp test run",
49
+ "build": "vp pack",
50
+ "check:artifact": "publint --strict --pack false",
51
+ "check": "pnpm --filter @ternent/ledger... run build && pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run check:artifact"
47
52
  }
48
53
  }
package/SPEC.md DELETED
@@ -1,304 +0,0 @@
1
- # `@ternent/ledger` v2 Specification
2
-
3
- ## 1. Purpose
4
-
5
- `@ternent/ledger` is the append-only truth engine beneath Concord.
6
-
7
- It owns:
8
-
9
- - staged and committed truth
10
- - entry authoring
11
- - signed commit authoring
12
- - deterministic replay
13
- - verification of commit linkage, commit proofs, entry proofs, and payload hashes
14
- - persistence of committed truth plus staged truth
15
-
16
- It does not own:
17
-
18
- - app-domain command APIs
19
- - framework runtime behavior
20
- - storage authority
21
- - mutable CRUD semantics
22
-
23
- ## 2. Architectural thesis
24
-
25
- The corrected Ledger model is:
26
-
27
- - entries are units of meaning
28
- - commits are the primary authored integrity boundary
29
- - commits are signed
30
- - each commit references the previous commit id
31
- - chain integrity is carried by signed commits plus parent linkage
32
- - staged and committed truth remain explicit
33
-
34
- Entry-level authenticity is not sufficient to define the integrity of the full ledger history.
35
- Entries carry meaning. Signed commits carry authored history integrity.
36
-
37
- ## 3. Layering
38
-
39
- - `@ternent/concord-protocol` owns deterministic canonicalization and commit-chain traversal helpers
40
- - `@ternent/ledger` owns staged/committed truth, signed commits, replay, and verification
41
- - `@ternent/concord` owns command ergonomics and plugin projection above Ledger
42
-
43
- ## 4. Truth model
44
-
45
- ### 4.1 Container
46
-
47
- ```ts
48
- type LedgerContainer = {
49
- format: "concord-ledger";
50
- version: "1";
51
- commits: Record<string, LedgerCommitRecord>;
52
- entries: Record<string, LedgerEntryRecord>;
53
- head: string;
54
- };
55
- ```
56
-
57
- The container exposes committed truth only.
58
- Staged truth is held separately.
59
-
60
- ### 4.2 Entry record
61
-
62
- ```ts
63
- type LedgerEntryRecord = {
64
- entryId: string;
65
- kind: string;
66
- authoredAt: string;
67
- author: string;
68
- meta: Record<string, unknown> | null;
69
- payload: LedgerPayloadRecord;
70
- seal: SealProof;
71
- };
72
- ```
73
-
74
- Entries are the smallest unit of meaning.
75
- They may carry plaintext or encrypted payloads.
76
- They may be individually sealed.
77
-
78
- ### 4.3 Commit record
79
-
80
- ```ts
81
- type LedgerCommitRecord = {
82
- commitId: string;
83
- parentCommitId: string | null;
84
- committedAt: string;
85
- metadata: Record<string, unknown> | null;
86
- entryIds: string[];
87
- seal: SealProof;
88
- };
89
- ```
90
-
91
- Commits are first-class authored records.
92
- They are signed records, not unsigned grouping metadata.
93
-
94
- ## 5. Signed commit model
95
-
96
- ### 5.1 Unsigned commit subject
97
-
98
- Ledger must centralize construction of the unsigned commit subject.
99
-
100
- The unsigned commit subject includes:
101
-
102
- - `parentCommitId`
103
- - `committedAt`
104
- - `metadata`
105
- - ordered `entryIds`
106
-
107
- It excludes:
108
-
109
- - `commitId`
110
- - `seal`
111
- - any circular self-reference
112
-
113
- ### 5.2 Commit id derivation and signing
114
-
115
- Commit creation must follow this order:
116
-
117
- 1. build the canonical unsigned commit subject
118
- 2. derive `commitId` from that unsigned canonical subject
119
- 3. sign the same unsigned canonical subject bytes
120
- 4. attach the resulting proof as `seal`
121
-
122
- Commit proof bytes must never participate in commit id derivation.
123
-
124
- ## 6. Append and commit behavior
125
-
126
- ### 6.1 Append
127
-
128
- ```ts
129
- append(input: LedgerAppendInput): Promise<LedgerAppendResult>;
130
- appendMany(inputs: LedgerAppendInput[]): Promise<LedgerAppendResult[]>;
131
- ```
132
-
133
- Append stages fully formed `LedgerEntryRecord` values.
134
-
135
- Append does not mutate committed history.
136
-
137
- ### 6.2 Commit
138
-
139
- ```ts
140
- type LedgerCommitInput = {
141
- metadata?: Record<string, unknown>;
142
- };
143
-
144
- type LedgerCommitResult = {
145
- commit: LedgerCommitRecord;
146
- committedEntries: LedgerEntryRecord[];
147
- committedEntryIds: string[];
148
- };
149
- ```
150
-
151
- Rules:
152
-
153
- - `commit()` fails when no staged entries exist
154
- - staged entries are grouped in deterministic staged order
155
- - the new commit signs the unsigned commit subject
156
- - the committed chain advances only after successful signed commit creation
157
- - staged entries clear only after commit success
158
-
159
- ## 7. Replay
160
-
161
- ```ts
162
- replay(options?: LedgerReplayOptions): Promise<P>;
163
- ```
164
-
165
- Replay order is:
166
-
167
- 1. committed commits in chain order
168
- 2. committed entries in commit order
169
- 3. staged entries last for the in-memory working view
170
-
171
- Replay produces derived projection only.
172
- Projection is never persisted as truth.
173
-
174
- ## 8. Verification
175
-
176
- ```ts
177
- type LedgerVerificationResult = {
178
- valid: boolean;
179
- committedHistoryValid: boolean;
180
- commitChainValid: boolean;
181
- commitProofsValid: boolean;
182
- entriesValid: boolean;
183
- entryProofsValid: boolean;
184
- payloadHashesValid: boolean;
185
- proofsValid: boolean;
186
- invalidCommitIds: string[];
187
- invalidEntryIds: string[];
188
- };
189
- ```
190
-
191
- Verification must validate:
192
-
193
- - committed container structure
194
- - commit-chain linkage
195
- - commit id derivation from unsigned commit subjects
196
- - commit proof validity against unsigned commit subject bytes
197
- - entry id derivation
198
- - entry proof validity
199
- - encrypted payload hashes when present
200
-
201
- `commitChainValid` remains a structural diagnostic about commit linkage and commit id derivation.
202
- `committedHistoryValid` is the strict integrity boundary for the reachable committed document.
203
-
204
- `committedHistoryValid` is true only if:
205
-
206
- - reachable commit linkage is valid
207
- - reachable commit proofs are valid
208
- - all entries referenced by reachable commits are present and valid
209
- - all encrypted payload hashes for reachable committed entries are valid
210
-
211
- `valid` must equal `committedHistoryValid`.
212
-
213
- That means any invalid committed byte in reachable history makes the entire document globally invalid, even though verification still reports a precise local breakdown through the other fields.
214
-
215
- The combined `proofsValid` field is the conjunction of commit-proof and entry-proof validity.
216
-
217
- ## 9. Public API
218
-
219
- ```ts
220
- type LedgerInstance<P> = {
221
- create(params?: CreateLedgerParams): Promise<void>;
222
- load(container: LedgerContainer): Promise<void>;
223
- loadFromStorage(): Promise<boolean>;
224
-
225
- append(input: LedgerAppendInput): Promise<LedgerAppendResult>;
226
- appendMany(inputs: LedgerAppendInput[]): Promise<LedgerAppendResult[]>;
227
- commit(input?: LedgerCommitInput): Promise<LedgerCommitResult>;
228
-
229
- replay(options?: LedgerReplayOptions): Promise<P>;
230
- recompute(): Promise<P>;
231
- verify(options?: LedgerVerifyOptions): Promise<LedgerVerificationResult>;
232
-
233
- export(): Promise<LedgerContainer>;
234
- import(container: LedgerContainer): Promise<void>;
235
-
236
- getState(): Readonly<LedgerState<P>>;
237
- subscribe(listener: (state: Readonly<LedgerState<P>>) => void): () => void;
238
- clearStaged(): Promise<void>;
239
- destroy(): Promise<void>;
240
- };
241
- ```
242
-
243
- ## 10. State and persistence
244
-
245
- ```ts
246
- type LedgerState<P> = {
247
- container: LedgerContainer | null;
248
- staged: LedgerEntryRecord[];
249
- projection: P;
250
- verification: LedgerVerificationSnapshot | null;
251
- };
252
- ```
253
-
254
- Storage persists:
255
-
256
- - committed container
257
- - staged entries
258
-
259
- Storage does not persist:
260
-
261
- - projection
262
- - signer or decryptor capability context
263
- - verification caches as authority
264
-
265
- ## 11. Example lifecycle
266
-
267
- ```ts
268
- await ledger.create({
269
- metadata: {
270
- surface: "workspace",
271
- },
272
- });
273
-
274
- await ledger.append({
275
- kind: "todo.item.created",
276
- payload: { id: "todo_123", title: "Buy milk" },
277
- });
278
-
279
- await ledger.append({
280
- kind: "todo.item.renamed",
281
- payload: { id: "todo_123", title: "Buy oat milk" },
282
- });
283
-
284
- await ledger.commit({
285
- metadata: {
286
- message: "Create and refine first todo",
287
- },
288
- });
289
-
290
- const projection = await ledger.replay();
291
- const verification = await ledger.verify();
292
- const exported = await ledger.export();
293
- ```
294
-
295
- ## 12. Acceptance criteria
296
-
297
- Ledger is correct when:
298
-
299
- - commit ids derive from unsigned commit subjects only
300
- - commit proofs validate against those same unsigned commit subject bytes
301
- - tampering with parent linkage or commit content fails verification
302
- - staged entries remain uncommitted until explicit commit
303
- - replay order remains committed history first, staged truth last
304
- - exported ledgers show signed commit records as the authored chain boundary