@fangorn-network/sdk 2026.9.22-dev → 2026.10.19-dev

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 (89) hide show
  1. package/README.md +177 -192
  2. package/lib/cli/cli.d.ts +0 -0
  3. package/lib/cli/cli.js +165 -194
  4. package/lib/config.d.ts +32 -27
  5. package/lib/config.js +17 -7
  6. package/lib/contracts/app-registry/abi.d.ts +1033 -277
  7. package/lib/contracts/app-registry/abi.js +1214 -335
  8. package/lib/contracts/app-registry/index.d.ts +105 -65
  9. package/lib/contracts/app-registry/index.js +182 -175
  10. package/lib/contracts/data-registry/abi.d.ts +166 -187
  11. package/lib/contracts/data-registry/abi.js +207 -237
  12. package/lib/contracts/data-registry/index.d.ts +4 -151
  13. package/lib/contracts/data-registry/index.js +5 -279
  14. package/lib/contracts/index.d.ts +6 -7
  15. package/lib/contracts/index.js +6 -8
  16. package/lib/contracts/logs.d.ts +4 -1
  17. package/lib/contracts/logs.js +9 -2
  18. package/lib/contracts/membership-registry/abi.d.ts +1145 -0
  19. package/lib/contracts/membership-registry/abi.js +1333 -0
  20. package/lib/contracts/membership-registry/index.d.ts +79 -0
  21. package/lib/contracts/membership-registry/index.js +104 -0
  22. package/lib/contracts/types.d.ts +3 -1
  23. package/lib/contracts/types.js +3 -1
  24. package/lib/contracts/write.d.ts +34 -2
  25. package/lib/contracts/write.js +48 -1
  26. package/lib/crypto/encryption.js +4 -4
  27. package/lib/engine/car.d.ts +2 -2
  28. package/lib/engine/car.js +10 -5
  29. package/lib/engine/index.d.ts +99 -143
  30. package/lib/engine/index.js +156 -295
  31. package/lib/engine/records.d.ts +110 -0
  32. package/lib/engine/records.js +165 -0
  33. package/lib/engine/test-helpers.d.ts +7 -14
  34. package/lib/engine/test-helpers.js +7 -18
  35. package/lib/fangorn.d.ts +129 -156
  36. package/lib/fangorn.js +250 -250
  37. package/lib/feed.d.ts +7 -4
  38. package/lib/feed.js +4 -1
  39. package/lib/index.d.ts +9 -9
  40. package/lib/index.js +8 -9
  41. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  42. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  43. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  44. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  45. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  46. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  47. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  48. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  49. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  50. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  51. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  52. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  53. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  54. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  55. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  56. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  57. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  58. package/lib/node_modules/chai/index.js +2874 -0
  59. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  60. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  61. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  62. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  63. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  64. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  65. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  66. package/lib/providers/storage/signed-url.d.ts +16 -6
  67. package/lib/providers/storage/signed-url.js +20 -8
  68. package/lib/registry.d.ts +116 -0
  69. package/lib/registry.js +182 -0
  70. package/lib/test/mem-registry.d.ts +51 -0
  71. package/lib/test/mem-registry.js +107 -0
  72. package/lib/test/sdk-suite.d.ts +13 -0
  73. package/lib/test/sdk-suite.js +226 -0
  74. package/lib/test/testbed.d.ts +16411 -61
  75. package/lib/test/testbed.js +190 -84
  76. package/lib/types/index.d.ts +13 -11
  77. package/package.json +89 -73
  78. package/lib/contracts/data-registry/test.d.ts +0 -1
  79. package/lib/contracts/data-registry/test.js +0 -1
  80. package/lib/contracts/settlement-registry/abi.d.ts +0 -466
  81. package/lib/contracts/settlement-registry/abi.js +0 -535
  82. package/lib/contracts/settlement-registry/index.d.ts +0 -163
  83. package/lib/contracts/settlement-registry/index.js +0 -264
  84. package/lib/contracts/subscription-registry/abi.d.ts +0 -179
  85. package/lib/contracts/subscription-registry/abi.js +0 -195
  86. package/lib/contracts/subscription-registry/index.d.ts +0 -59
  87. package/lib/contracts/subscription-registry/index.js +0 -116
  88. package/lib/engine/graph.d.ts +0 -70
  89. package/lib/engine/graph.js +0 -73
package/lib/fangorn.js CHANGED
@@ -1,19 +1,18 @@
1
- import { DEFAULT_APP, FangornConfig, toAppId } from "./config.js";
1
+ import { FangornConfig, nonBlank, toAppId } from "./config.js";
2
2
  import { SignedUrlBackend } from "./providers/storage/signed-url.js";
3
3
  import { PinataBackend } from "./providers/storage/pinata.js";
4
- import { FangornEngine, MetagraphRegistry, assertValidNamespace, rootHexFromCid } from "./engine/index.js";
5
4
  import { AppRegistryClient } from "./contracts/app-registry/index.js";
6
- import { DataRegistryClient, subspaceId } from "./contracts/data-registry/index.js";
7
- import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
8
- import { SubscriptionRegistryClient } from "./contracts/subscription-registry/index.js";
5
+ import { MembershipRegistryClient } from "./contracts/membership-registry/index.js";
9
6
  import "./contracts/index.js";
7
+ import { ChainRegistry, ZERO_HEAD, repoExcluded } from "./registry.js";
8
+ import { FangornEngine, SchemaRegistry, assertValidRepoName, rootHexFromCid } from "./engine/index.js";
10
9
  import { AppFeed } from "./feed.js";
11
10
  import { createPublicClient, createWalletClient, http } from "viem";
12
11
  import { privateKeyToAccount } from "viem/accounts";
13
12
  import { CID } from "multiformats/cid";
14
13
 
15
14
  //#region src/fangorn.ts
16
- const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
15
+ const ZERO_BYTES32 = ZERO_HEAD;
17
16
  const NS_CACHE_MAX = 256;
18
17
  function walletSigner(walletClient) {
19
18
  const account = walletClient.account;
@@ -26,21 +25,24 @@ function walletSigner(walletClient) {
26
25
  })
27
26
  };
28
27
  }
29
- function resolveStorage(storage, walletClient, config) {
28
+ function resolveStorage(storage, walletClient, config, getAppId) {
30
29
  if (!storage) return void 0;
30
+ if ("backend" in storage) return storage.backend;
31
31
  if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
32
- if ("signedUrl" in storage) return new SignedUrlBackend(storage.signedUrl.workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway);
33
- throw new Error(`Invalid storage config: must be { pinata: … } or { signedUrl: … }, got ${JSON.stringify(storage)}`);
32
+ if ("signedUrl" in storage) return new SignedUrlBackend(storage.signedUrl.workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway, getAppId);
33
+ throw new Error(`Invalid storage config: must be { pinata: … }, { signedUrl: … } or { backend: … }, got ${JSON.stringify(storage)}`);
34
34
  }
35
35
  /** The A2A extension a Fangorn app's agent card carries: it names the app the card speaks for. */
36
36
  const FANGORN_APP_EXTENSION = "https://fangorn.network/a2a/app/v1";
37
37
  var Fangorn = class Fangorn {
38
38
  ctx;
39
39
  _engine = null;
40
- _metagraph = new MetagraphRegistry();
40
+ _schemas = new SchemaRegistry();
41
41
  _feed = null;
42
+ _apps = null;
43
+ _membership = null;
42
44
  /**
43
- * The namespace cache
45
+ * The repo cache
44
46
  * Insertion order = LRU order
45
47
  */
46
48
  nsCache = /* @__PURE__ */ new Map();
@@ -49,11 +51,12 @@ var Fangorn = class Fangorn {
49
51
  }
50
52
  get engine() {
51
53
  if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
52
- this._engine ??= new FangornEngine(this.ctx.metadataStorage, this._metagraph, this.ctx.dataRegistry);
54
+ this._engine ??= new FangornEngine(this.ctx.metadataStorage, this._schemas, this.ctx.registry);
53
55
  return this._engine;
54
56
  }
55
- get metagraph() {
56
- return this._metagraph;
57
+ /** Per-repo record schemas. Unregistered types are accepted as-is. */
58
+ get schemas() {
59
+ return this._schemas;
57
60
  }
58
61
  /**
59
62
  * Static creation of a new Fangorn client
@@ -63,100 +66,64 @@ var Fangorn = class Fangorn {
63
66
  */
64
67
  static create(options) {
65
68
  if (!options.privateKey && !options.walletClient) throw new Error("Either privateKey or walletClient must be provided");
66
- const resolvedConfig = options.config ?? FangornConfig;
69
+ const config = options.config ?? FangornConfig;
67
70
  const walletClient = options.walletClient ?? createWalletClient({
68
71
  account: privateKeyToAccount(options.privateKey ?? "0x0"),
69
- chain: resolvedConfig.chain,
70
- transport: http(resolvedConfig.rpcUrl)
72
+ chain: config.chain,
73
+ transport: http(config.rpcUrl)
71
74
  });
72
- const metadataStorage = resolveStorage(options.storage, walletClient, resolvedConfig);
73
- const domain = options.domain ?? new URL(resolvedConfig.rpcUrl).hostname;
74
- const publicClient = createPublicClient({ transport: http(resolvedConfig.rpcUrl) });
75
- const appId = toAppId(options.appId ?? DEFAULT_APP);
76
- return new Fangorn({
77
- walletClient,
78
- metadataStorage,
79
- domain,
80
- dataRegistry: new DataRegistryClient(resolvedConfig.dataRegistryContractAddress, appId, publicClient, walletClient),
81
- appRegistry: new AppRegistryClient(resolvedConfig.appRegistryContractAddress, appId, publicClient, walletClient),
82
- subscriptionRegistry: new SubscriptionRegistryClient(resolvedConfig.subscriptionRegistryContractAddress, publicClient, walletClient),
83
- settlementRegistry: new SettlementRegistryClient(resolvedConfig.settlementRegistryContractAddress, publicClient, walletClient),
84
- config: resolvedConfig
75
+ const publicClient = createPublicClient({
76
+ chain: config.chain,
77
+ transport: http(config.rpcUrl)
85
78
  });
79
+ const chosenApp = nonBlank(options.appId);
80
+ const ctx = {
81
+ config,
82
+ walletClient,
83
+ publicClient,
84
+ appId: chosenApp ? toAppId(chosenApp) : void 0,
85
+ metadataStorage: void 0,
86
+ registry: options.registry ?? new ChainRegistry(config, publicClient, walletClient)
87
+ };
88
+ ctx.metadataStorage = resolveStorage(options.storage, walletClient, config, () => ctx.appId);
89
+ return new Fangorn(ctx);
86
90
  }
87
91
  /**
88
- * Resets a namespace's onchain state root to zero.
89
- * TODO: also unpin all data
90
- * Use at your own risk.
91
- */
92
- async reset(namespace) {
93
- const registry = this.getDataRegistry();
94
- const currentRoot = await registry.getNamespaceHead(this.getAddress(), namespace);
95
- await registry.commitStateRoot(namespace, currentRoot, ZERO_BYTES32);
96
- }
97
- /**
98
- * TODO: this isn't really needed here, it's cosmetic
99
- * instead, what if we moved this to a new paradigm where...
100
- *
101
- * each app registers as an ERC-8004 agent with the validation registry
102
- * pointing to these rules essentially?
103
- *
104
- *
105
- * Register permissive (no required fields) schemas for every tag/relation a
106
- * staged graph uses, unless the caller has already registered stricter rules
107
- * via `this.metagraph` directly — schema ids are free-form tags by default.
92
+ * Empties a repo: one commit of the empty state on top of the head. History
93
+ * stays (a head never goes back to zero), and so do the old records: the new
94
+ * head still names them as history.
108
95
  */
109
- registerPermissiveSchemas(repoName, vertices, edges) {
110
- const tagOf = /* @__PURE__ */ new Map();
111
- for (const v of vertices) {
112
- tagOf.set(v.id, v.tag);
113
- if (!this.metagraph.hasVertexSchema(repoName, v.tag)) this.metagraph.registerVertex(repoName, {
114
- id: v.tag,
115
- requiredFields: []
116
- });
117
- }
118
- for (const e of edges) {
119
- const sourceTag = tagOf.get(e.from);
120
- const targetTag = tagOf.get(e.to);
121
- if (!sourceTag || !targetTag) continue;
122
- if (!this.metagraph.hasEdgeSchema(repoName, sourceTag, e.rel, targetTag)) this.metagraph.registerEdge(repoName, {
123
- sourceSchema: sourceTag,
124
- relation: e.rel,
125
- targetSchema: targetTag
126
- });
127
- }
96
+ async reset(repo) {
97
+ const publisher = this.getAddress();
98
+ const head = await this.engine.resolveHeadCommit(publisher, repo);
99
+ const { commitCid } = await this.createCommit({
100
+ repo,
101
+ base: head,
102
+ records: [],
103
+ message: `Reset ${repo}`,
104
+ replace: true
105
+ });
106
+ return this.engine.pushCommit(publisher, repo, commitCid);
128
107
  }
129
- /** Stage a graph into one commit on top of `base` (engine shapes adapted from CLI shapes). */
108
+ /** Stage records into one commit on top of `base`. */
130
109
  createCommit(opts) {
131
- this.registerPermissiveSchemas(opts.namespace, opts.vertices, opts.edges);
132
110
  return this.engine.createCommit({
133
- namespace: opts.namespace,
134
- base: opts.base,
135
- vertices: opts.vertices.map((v) => {
136
- const safePayload = v.payload && typeof v.payload === "object" && !Array.isArray(v.payload) ? v.payload : { value: v.payload };
137
- return {
138
- id: v.id,
139
- schemaId: v.tag,
140
- payload: safePayload
141
- };
142
- }),
143
- edges: opts.edges.map((e) => ({
144
- relation: e.rel,
145
- from: e.from,
146
- to: e.to
147
- })),
148
- message: opts.message,
149
- replace: opts.replace
111
+ ...opts,
112
+ records: opts.records.map((r) => ({
113
+ id: r.id,
114
+ type: r.type,
115
+ payload: r.payload && typeof r.payload === "object" && !Array.isArray(r.payload) ? r.payload : { value: r.payload }
116
+ }))
150
117
  });
151
118
  }
152
119
  /**
153
- * Allocates a namespace in the publisher's root map.
154
- * A no-op (no on-chain tx) if the namespace is already initialized.
120
+ * Allocates a repo in the publisher's root map.
121
+ * A no-op (no on-chain tx) if the repo is already initialized.
155
122
  */
156
123
  async initRepo(repoName) {
157
- assertValidNamespace(repoName);
124
+ assertValidRepoName(repoName);
158
125
  const publisher = this.getAddress();
159
- if (await this.engine.namespaceExists(repoName, publisher)) return {
126
+ if (await this.engine.repoExists(publisher, repoName)) return {
160
127
  cid: void 0,
161
128
  commitCid: void 0,
162
129
  txHash: void 0,
@@ -164,10 +131,9 @@ var Fangorn = class Fangorn {
164
131
  };
165
132
  const head = await this.engine.resolveHeadCommit(publisher, repoName);
166
133
  const { commitCid } = await this.createCommit({
167
- namespace: repoName,
134
+ repo: repoName,
168
135
  base: head,
169
- vertices: [],
170
- edges: [],
136
+ records: [],
171
137
  message: `Initialize repository workspace: ${repoName}`
172
138
  });
173
139
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
@@ -179,78 +145,80 @@ var Fangorn = class Fangorn {
179
145
  };
180
146
  }
181
147
  /**
182
- * Stage one vertex and settle it on-chain in a single shot.
148
+ * Put one record and settle it on-chain in a single shot. `id` defaults to
149
+ * a random one, so repeated calls add records; pass an id to update one.
183
150
  */
184
- async upload(repoName, payload, schemaId) {
151
+ async upload(repoName, payload, type, id) {
185
152
  const publisher = this.getAddress();
186
153
  const head = await this.engine.resolveHeadCommit(publisher, repoName);
187
154
  if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
188
- const { commitCid, vertexCids } = await this.createCommit({
189
- namespace: repoName,
155
+ const { commitCid, recordCids } = await this.createCommit({
156
+ repo: repoName,
190
157
  base: head,
191
- vertices: [{
192
- id: "v0",
193
- tag: schemaId,
158
+ records: [{
159
+ id,
160
+ type,
194
161
  payload
195
162
  }],
196
- edges: [],
197
- message: `Upload to namespace ${repoName} under schema ${schemaId}`
163
+ message: `Upload to repo ${repoName} as type ${type}`
198
164
  });
199
165
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
166
+ const [[recordId, payloadCid]] = Object.entries(recordCids);
200
167
  return {
201
- payloadCid: vertexCids.v0,
168
+ id: recordId,
169
+ payloadCid,
202
170
  commitCid: commitCid.toString(),
203
171
  txHash
204
172
  };
205
173
  }
206
174
  /**
207
- * Stages many vertices (and optionally edges between them) under one publisher
208
- * root, instead of one tx per vertex. The whole graph is built in memory and
209
- * persisted as ONE CAR upload plus one commit block, then settled in a single
210
- * fast-forward tx. Edges reference vertices by the caller-supplied local `id`.
175
+ * Puts many records (and deletes some, by id) under one repo in a
176
+ * single commit, instead of one tx per record. Built in memory and persisted
177
+ * as ONE CAR upload plus one commit block, then settled in a single
178
+ * fast-forward tx. Relations are records too: give them `src`/`dst` `Ref`s.
211
179
  */
212
- async uploadBatch(repoName, vertices, edges = []) {
213
- assertValidNamespace(repoName);
214
- if (vertices.length === 0 && edges.length === 0) throw new Error("uploadBatch requires at least one vertex or edge");
180
+ async uploadBatch(repoName, records, deletes = []) {
181
+ assertValidRepoName(repoName);
182
+ if (records.length === 0 && deletes.length === 0) throw new Error("uploadBatch requires at least one record or delete");
215
183
  const publisher = this.getAddress();
216
184
  const head = await this.engine.resolveHeadCommit(publisher, repoName);
217
185
  if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
218
- const { commitCid, vertexCids } = await this.createCommit({
219
- namespace: repoName,
186
+ const { commitCid, recordCids } = await this.createCommit({
187
+ repo: repoName,
220
188
  base: head,
221
- vertices,
222
- edges,
223
- message: `Batch upload to namespace ${repoName}`
189
+ records,
190
+ deletes,
191
+ message: `Batch upload to repo ${repoName}`
224
192
  });
225
193
  const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
226
194
  return {
227
195
  commitCid: commitCid.toString(),
228
196
  txHash,
229
- vertexCids
197
+ recordCids
230
198
  };
231
199
  }
232
200
  /**
233
- * Build a new commit (no on-chain tx) that stages vertices/edges into
234
- * `namespace` on top of `parent` (a commit CID string, or undefined for a
201
+ * Build a new commit (no on-chain tx) that puts/deletes records in
202
+ * `repo` on top of `parent` (a commit CID string, or undefined for a
235
203
  * root commit). The commit and its CAR are uploaded to storage, so a later
236
204
  * `push` — even in a separate process — can settle it.
237
205
  */
238
206
  async commit(opts) {
239
- assertValidNamespace(opts.namespace);
207
+ assertValidRepoName(opts.repo);
240
208
  const parentCid = opts.parent ? CID.parse(opts.parent) : null;
241
- const { commitCid, root, vertexCids } = await this.createCommit({
242
- namespace: opts.namespace,
209
+ const { commitCid, root, recordCids } = await this.createCommit({
210
+ repo: opts.repo,
243
211
  base: parentCid,
244
- vertices: opts.vertices ?? [],
245
- edges: opts.edges ?? [],
212
+ records: opts.records ?? [],
213
+ deletes: opts.deletes,
246
214
  message: opts.message,
247
215
  replace: opts.replace
248
216
  });
249
217
  return {
250
218
  commitCid: commitCid.toString(),
251
- parents: parentCid ? [parentCid.toString()] : [],
219
+ parent: parentCid?.toString() ?? null,
252
220
  root: root.toString(),
253
- vertexCids
221
+ recordCids
254
222
  };
255
223
  }
256
224
  /**
@@ -267,14 +235,17 @@ var Fangorn = class Fangorn {
267
235
  * in IPFS, not a corrupted timeline.
268
236
  */
269
237
  async prepareCommit(opts) {
270
- assertValidNamespace(opts.namespace);
271
- const registry = this.getDataRegistry();
272
- const oldRoot = await registry.getNamespaceHead(opts.owner, opts.namespace);
273
- const { commitCid, vertexCids } = await this.createCommit({
274
- namespace: opts.namespace,
238
+ assertValidRepoName(opts.repo);
239
+ const registry = this.ctx.registry;
240
+ const oldRoot = await registry.head({
241
+ publisher: opts.owner,
242
+ repo: opts.repo
243
+ });
244
+ const { commitCid, recordCids } = await this.createCommit({
245
+ repo: opts.repo,
275
246
  base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
276
- vertices: opts.vertices ?? [],
277
- edges: opts.edges ?? [],
247
+ records: opts.records ?? [],
248
+ deletes: opts.deletes,
278
249
  message: opts.message,
279
250
  replace: opts.replace
280
251
  });
@@ -284,46 +255,52 @@ var Fangorn = class Fangorn {
284
255
  oldRoot,
285
256
  newRoot,
286
257
  staged: {
287
- vertices: opts.vertices?.length ?? 0,
288
- edges: opts.edges?.length ?? 0
258
+ records: opts.records?.length ?? 0,
259
+ deletes: opts.deletes?.length ?? 0
289
260
  },
290
- tx: await registry.prepareCommitStateRoot(opts.owner, opts.namespace, oldRoot, newRoot),
291
- vertexCids
261
+ tx: await registry.prepareUpdate(opts.owner, opts.repo, oldRoot, newRoot),
262
+ recordCids
292
263
  };
293
264
  }
294
265
  /**
295
- * Settle a local commit as the on-chain head of `namespace` (fast-forward
296
- * unless `force`). Each namespace has its own timeline, so pushes to
297
- * different namespaces never contend for the same compare-and-swap.
266
+ * Settle a local commit as the on-chain head of `repo`. Its parent must be
267
+ * the current head (see `FangornEngine.pushCommit`). Each repo has its own
268
+ * timeline, so pushes to different repos never contend.
298
269
  */
299
- async push(namespace, commitCid, opts) {
300
- const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), namespace, CID.parse(commitCid), opts);
270
+ async push(repo, commitCid) {
271
+ const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), repo, CID.parse(commitCid));
301
272
  return {
302
273
  txHash,
303
274
  onChainTip: onChainTip.toString()
304
275
  };
305
276
  }
306
- /** The owner's current on-chain tip for a namespace, or null if they have none. */
307
- async onChainTip(owner, namespace) {
308
- const cid = await this.engine.resolveHeadCommit(owner, namespace);
277
+ /** The owner's current on-chain tip for a repo, or null if they have none. */
278
+ async onChainTip(owner, repo) {
279
+ const cid = await this.engine.resolveHeadCommit(owner, repo);
309
280
  return cid ? cid.toString() : null;
310
281
  }
311
282
  /**
312
- * A publisher's namespace contents, cached against its on-chain tip.
283
+ * A publisher's repo as this client presents it, cached against its tip:
284
+ * the publisher's latest head, or, under an app, nothing unless the app
285
+ * presents the publisher (provides its storage) and excludes neither it nor
286
+ * the repo.
313
287
  *
314
- * Reading a namespace walks the pail tree from the root — many sequential
315
- * gateway fetches. The tip is one cheap contract read and only moves on
316
- * publish, so it doubles as the cache key: no TTL to tune, no invalidation
317
- * to remember after a settle, and never stale.
288
+ * Reading a repo walks its whole record tree from the root. The tip is one
289
+ * cheap contract read and only moves on publish, so it doubles as the cache
290
+ * key: no TTL to tune, no invalidation to remember after a settle, and never
291
+ * stale.
318
292
  *
319
- * LRU-bounded so an always-on process can't accumulate every namespace it
293
+ * LRU-bounded so an always-on process can't accumulate every repo it
320
294
  * ever touched. The durable copy is on-chain — an evicted entry re-walks.
321
295
  * ponytail: fixed entry count, not byte-aware; switch to a size budget if a
322
- * few huge namespaces blow memory before the count cap bites.
296
+ * few huge repos blow memory before the count cap bites.
323
297
  */
324
- async readNamespace(owner, namespace) {
325
- const key = `${owner.toLowerCase()}/${namespace}`;
326
- const tip = await this.onChainTip(owner, namespace);
298
+ async readRepo(owner, repo) {
299
+ const key = `${owner.toLowerCase()}/${repo}`;
300
+ const tip = await this.presentedTip({
301
+ publisher: owner,
302
+ repo
303
+ });
327
304
  const hit = this.nsCache.get(key);
328
305
  if (hit?.tip === tip) {
329
306
  this.nsCache.delete(key);
@@ -332,7 +309,7 @@ var Fangorn = class Fangorn {
332
309
  }
333
310
  const entry = {
334
311
  tip,
335
- contents: await this.engine.listNamespace(namespace, owner)
312
+ contents: await this.engine.listAt(tip ? CID.parse(tip) : null)
336
313
  };
337
314
  this.nsCache.delete(key);
338
315
  this.nsCache.set(key, entry);
@@ -342,34 +319,49 @@ var Fangorn = class Fangorn {
342
319
  }
343
320
  return entry;
344
321
  }
322
+ /** The commit this client presents of a repo, or null for none (see `readRepo`). */
323
+ async presentedTip(ref) {
324
+ const app = this.ctx.appId;
325
+ const registry = this.ctx.registry;
326
+ if (app && !await this.presentsRepo(app, ref)) return null;
327
+ const head = await registry.head(ref);
328
+ return head === ZERO_BYTES32 ? null : this.engine.commitCidFromRootHex(head);
329
+ }
330
+ /** Does `app` present `ref`: it presents the publisher, and excludes neither it nor the repo? */
331
+ async presentsRepo(app, ref) {
332
+ const registry = this.ctx.registry;
333
+ const [presents, excluded] = await Promise.all([registry.presents(app, ref.publisher), repoExcluded(registry, app, ref)]);
334
+ return presents && !excluded;
335
+ }
345
336
  /**
346
- * Every (publisher, namespace) pair that has ever committed under this app,
347
- * at its latest root — the app's directory, from ONE `getLogs`.
337
+ * Every (publisher, repo) this client's app presents, at its latest head, less
338
+ * what it excludes — the app's directory, from ONE `getLogs` over the update
339
+ * log, kept to the publishers the app presents.
348
340
  *
349
- * This is what cross-publisher discovery looks like now: the registry already
350
- * indexes `app_id`, so the commit log IS the index. No per-publisher fan-out,
351
- * no separate registration sweep, no central list — and unlike a publisher
352
- * roster it only surfaces publishers with actual content.
353
- *
354
- * Namespaces come back as `subspaceId` (the hash), not the name, because the
355
- * event never carries the name — recovering it costs one content fetch per
356
- * entry. Pass `namespace` when you know the name you're after (the usual
357
- * case: an app with one well-known namespace) and the filter is applied
358
- * on-chain instead.
341
+ * ponytail: reads every publisher's updates and drops non-members, so it costs
342
+ * what the network writes, not what the app holds. Filter on-chain by the
343
+ * app's members (a `publisher` topic list) once that is too slow.
344
+ * Narrow it with `repo` (every publisher's `docs`) or `owner`, filtered on-chain.
359
345
  */
360
- async appNamespaces(opts = {}) {
361
- const logs = await this.getDataRegistry().getStateCommittedLogs({
346
+ async appRepos(opts = {}) {
347
+ const app = this.requireApp("appRepos");
348
+ const entries = await this.ctx.registry.log({
362
349
  publisher: opts.owner,
363
- namespace: opts.namespace
364
- }, opts.fromBlock ?? 0n);
350
+ repo: opts.repo
351
+ }, opts.fromBlock ?? this.ctx.config.appRegistryFromBlock);
365
352
  const latest = /* @__PURE__ */ new Map();
366
- for (const log of logs) latest.set(log.namespaceKey, {
367
- owner: log.publisher,
368
- subspaceId: log.subspaceId,
369
- root: log.newRoot,
370
- blockNumber: log.blockNumber
353
+ for (const e of entries) latest.set(`${e.publisher.toLowerCase()}/${e.repo}`, {
354
+ owner: e.publisher,
355
+ repo: e.repo,
356
+ root: e.head,
357
+ blockNumber: e.t
371
358
  });
372
- return [...latest.values()];
359
+ const all = [...latest.values()];
360
+ const kept = await Promise.all(all.map((d) => this.presentsRepo(app, {
361
+ publisher: d.owner,
362
+ repo: d.repo
363
+ })));
364
+ return all.filter((_, i) => kept[i]);
373
365
  }
374
366
  /**
375
367
  * Resolve an app from its agent card URL alone, and prove the card speaks for it.
@@ -391,8 +383,8 @@ var Fangorn = class Fangorn {
391
383
  const p = ext.params ?? {};
392
384
  if (typeof p.appId !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(p.appId)) throw new Error(`agent card ${cardUrl}: appId is not a 32-byte hex string`);
393
385
  if (typeof p.fromBlock !== "string" || !/^\d+$/.test(p.fromBlock)) throw new Error(`agent card ${cardUrl}: fromBlock is not a decimal block number`);
394
- const namespaces = p.namespaces ?? [];
395
- if (!Array.isArray(namespaces) || !namespaces.every((n) => typeof n === "string")) throw new Error(`agent card ${cardUrl}: namespaces is not a list of strings`);
386
+ const repos = p.repos ?? p.namespaces ?? [];
387
+ if (!Array.isArray(repos) || !repos.every((n) => typeof n === "string")) throw new Error(`agent card ${cardUrl}: repos is not a list of strings`);
396
388
  const apps = this.getAppRegistry();
397
389
  if (p.chainId !== this.ctx.config.caip2 || typeof p.appRegistry !== "string" || p.appRegistry.toLowerCase() !== apps.getAddress().toLowerCase()) throw new Error(`agent card ${cardUrl} is for chain ${String(p.chainId)} / AppRegistry ${String(p.appRegistry)}, not this client's`);
398
390
  const appId = p.appId;
@@ -402,7 +394,7 @@ var Fangorn = class Fangorn {
402
394
  card,
403
395
  appId,
404
396
  fromBlock: BigInt(p.fromBlock),
405
- namespaces
397
+ repos
406
398
  };
407
399
  }
408
400
  /**
@@ -421,26 +413,26 @@ var Fangorn = class Fangorn {
421
413
  async *log(head, max) {
422
414
  for await (const { cid, commit } of this.engine.walkParents(CID.parse(head), max)) yield {
423
415
  cid: cid.toString(),
424
- parents: commit.parents.map((c) => c.toString()),
425
- timestamp: commit.timestamp,
416
+ parent: commit.parent?.toString() ?? null,
417
+ epoch: commit.epoch,
426
418
  message: commit.message,
427
419
  root: commit.root.toString()
428
420
  };
429
421
  }
430
- /** Show a commit and what it changed vs. its first parent. */
422
+ /** Show a commit and what it changed vs. its parent. */
431
423
  async show(commitCid) {
432
424
  return this.engine.diffCommit(CID.parse(commitCid));
433
425
  }
434
426
  /**
435
- * Lists every vertex and edge currently committed under a namespace, resolved
427
+ * Lists every record currently committed under a repo, resolved
436
428
  * from the publisher's on-chain root — useful for verifying what actually
437
429
  * made it into the repository, as opposed to what a given call staged.
438
430
  */
439
- async inspectNamespace(repoName) {
440
- return this.engine.listNamespace(repoName, this.getAddress());
431
+ async inspectRepo(repoName) {
432
+ return this.engine.listRepo(this.getAddress(), repoName);
441
433
  }
442
434
  /**
443
- * Stream changes to one publisher's namespace. Optionally replays from
435
+ * Stream changes to one publisher's repo. Optionally replays from
444
436
  * `fromBlock` first (resume cursor), then watches live until the `signal`
445
437
  * aborts. Each yielded change carries `blockNumber` — persist it to resume
446
438
  * exactly where you left off.
@@ -448,25 +440,26 @@ var Fangorn = class Fangorn {
448
440
  subscribe(opts) {
449
441
  return this.streamCommits({
450
442
  publisher: opts.owner ?? this.getAddress(),
451
- namespace: opts.namespace
443
+ repo: opts.repo
452
444
  }, opts);
453
445
  }
454
446
  /**
455
- * Stream changes across the *whole app* — every publisher, every namespace.
456
- * The app-level feed: one topic filter on `app_id`, no per-publisher fan-out
457
- * and no global root to keep in sync. Narrow it with `namespace` (every
458
- * publisher's `docs`) or `owner` (one publisher's whole app footprint).
447
+ * Stream changes across the *whole app* — every repo of every publisher it
448
+ * presents, less its exclusions. Narrow it with `repo` (every publisher's `docs`) or
449
+ * `owner` (one publisher's whole app footprint). With no app, every update by
450
+ * anyone: a firehose.
459
451
  */
460
452
  subscribeApp(opts = {}) {
461
453
  return this.streamCommits({
462
454
  publisher: opts.owner,
463
- namespace: opts.namespace
455
+ repo: opts.repo
464
456
  }, opts);
465
457
  }
466
458
  /** Shared catch-up-then-live loop behind `subscribe` and `subscribeApp`. */
467
459
  async *streamCommits(filter, opts) {
468
- const registry = this.getDataRegistry();
460
+ const registry = this.ctx.registry;
469
461
  const seen = /* @__PURE__ */ new Set();
462
+ const lastHead = /* @__PURE__ */ new Map();
470
463
  const buffer = [];
471
464
  let wake = null;
472
465
  const subState = {
@@ -478,7 +471,7 @@ var Fangorn = class Fangorn {
478
471
  wake = null;
479
472
  w?.();
480
473
  };
481
- const unwatch = registry.watchStateCommitted(filter, (log) => {
474
+ const unwatch = registry.watch(filter, (log) => {
482
475
  buffer.push(log);
483
476
  signal();
484
477
  }, (err) => {
@@ -491,10 +484,10 @@ var Fangorn = class Fangorn {
491
484
  };
492
485
  opts.signal?.addEventListener("abort", onAbort);
493
486
  try {
494
- if (opts.fromBlock !== void 0) for (const log of await registry.getStateCommittedLogs(filter, opts.fromBlock)) {
495
- if (seen.has(log.logId)) continue;
496
- seen.add(log.logId);
497
- const change = await this.toNamespaceChange(log);
487
+ if (opts.fromBlock !== void 0) for (const log of await registry.log(filter, opts.fromBlock)) {
488
+ if (seen.has(log.id)) continue;
489
+ seen.add(log.id);
490
+ const change = await this.toRepoChange(log, lastHead);
498
491
  if (change) yield change;
499
492
  }
500
493
  while (!subState.stopped) {
@@ -507,9 +500,9 @@ var Fangorn = class Fangorn {
507
500
  }
508
501
  const log = buffer.shift();
509
502
  if (!log) continue;
510
- if (seen.has(log.logId)) continue;
511
- seen.add(log.logId);
512
- const change = await this.toNamespaceChange(log);
503
+ if (seen.has(log.id)) continue;
504
+ seen.add(log.id);
505
+ const change = await this.toRepoChange(log, lastHead);
513
506
  if (change) yield change;
514
507
  }
515
508
  } finally {
@@ -518,77 +511,84 @@ var Fangorn = class Fangorn {
518
511
  }
519
512
  }
520
513
  /**
521
- * Resolve a raw `StateCommitted` log into a namespace change, or null if the
522
- * namespace slice was untouched.
514
+ * Resolve a log entry into a repo change, or null if nothing presented
515
+ * changed: the repo slice was untouched, or the app excludes it.
523
516
  *
524
- * The event carries `keccak256(namespace)`, never the name, so the name comes
525
- * from the commit's own root map — and must hash back to the subspace the
526
- * commit was published into, or the publisher settled a commit for one
527
- * namespace against another's timeline.
517
+ * The commit itself names its repo, which must be the one the entry was
518
+ * logged under, or the publisher settled a commit for one repo against
519
+ * another's timeline.
520
+ *
521
+ * The diff runs from the last head this stream saw for the repo, not from
522
+ * the entry's parent. If an entry was dropped (an RPC that left out a log),
523
+ * the two differ, and diffing from the entry's parent would skip what the
524
+ * dropped entry changed.
528
525
  */
529
- async toNamespaceChange(log) {
530
- const namespace = await this.engine.namespaceOf(log.newRoot);
531
- if (subspaceId(namespace) !== log.subspaceId) throw new Error(`commit ${log.newRoot} declares namespace "${namespace}", which does not match the subspace it was committed to (${log.subspaceId})`);
532
- const diff = await this.engine.namespaceDiff(log.oldRoot === ZERO_BYTES32 ? null : log.oldRoot, log.newRoot, namespace);
533
- if (!(diff.addedVertices.length || diff.removedVertexCids.length || diff.addedEdges.length || diff.removedEdges.length)) return null;
526
+ async toRepoChange(log, lastHead) {
527
+ const declared = await this.engine.repoOf(log.head);
528
+ if (declared !== log.repo) throw new Error(`commit ${log.head} declares repo "${declared}", which does not match the repo it was committed to ("${log.repo}")`);
529
+ const ref = {
530
+ publisher: log.publisher,
531
+ repo: log.repo
532
+ };
533
+ if (this.ctx.appId && !await this.presentsRepo(this.ctx.appId, ref)) return null;
534
+ const key = `${log.publisher.toLowerCase()}/${log.repo}`;
535
+ const oldRoot = lastHead.get(key) ?? log.parent;
536
+ lastHead.set(key, log.head);
537
+ const diff = await this.engine.repoDiff(oldRoot === ZERO_BYTES32 ? null : oldRoot, log.head);
538
+ if (!diff.puts.length && !diff.deletes.length) return null;
534
539
  return {
535
- namespace,
540
+ repo: log.repo,
536
541
  owner: log.publisher,
537
- commitCid: this.engine.commitCidFromRootHex(log.newRoot),
538
- oldRoot: log.oldRoot,
539
- newRoot: log.newRoot,
540
- blockNumber: log.blockNumber,
542
+ commitCid: this.engine.commitCidFromRootHex(log.head),
543
+ oldRoot,
544
+ newRoot: log.head,
545
+ blockNumber: log.t,
541
546
  ...diff
542
547
  };
543
548
  }
544
549
  getConfig() {
545
550
  return this.ctx.config;
546
551
  }
547
- getDataRegistry() {
548
- return this.ctx.dataRegistry;
552
+ /** Heads, membership, exclusions and logs: the registry of WHITEPAPER_1 §3.2. */
553
+ getRegistry() {
554
+ return this.ctx.registry;
549
555
  }
550
556
  /**
551
- * Apps, their publisher terms, and per-app membership.
552
- *
553
- * `commitStateRoot` cross-calls this contract, so joining the app here is a
554
- * precondition for publishing under it — `registerForApp()` before
555
- * `commit()`, or the commit reverts `NotRegisteredForApp`.
557
+ * App management: claiming an app (its storage subscription), terms,
558
+ * invitations and membership, the agent card, and the protocol admin's powers.
559
+ * The owner accepts a publisher (`acceptPublisher()`); from then its uploads
560
+ * bill the app's subscription, and the app presents its repos.
556
561
  */
557
562
  getAppRegistry() {
558
- return this.ctx.appRegistry;
559
- }
560
- /**
561
- * The publisher-side storage paywall. Per-wallet, not per-app: one
562
- * subscription covers everything this publisher writes, under every app.
563
- */
564
- getSubscriptionRegistry() {
565
- return this.ctx.subscriptionRegistry;
563
+ this._apps ??= new AppRegistryClient(this.ctx.config.appRegistryContractAddress, this.ctx.appId, this.ctx.publicClient, this.ctx.walletClient);
564
+ return this._apps;
566
565
  }
567
- /**
568
- * The consumer-side pay-then-read rail. Resources are keyed by owner+uid, so
569
- * this client is app-agnostic too.
570
- */
571
- getSettlementRegistry() {
572
- return this.ctx.settlementRegistry;
566
+ getMembershipRegistry() {
567
+ this._membership ??= new MembershipRegistryClient(this.ctx.config.membershipRegistryContractAddress, this.ctx.publicClient, this.ctx.walletClient);
568
+ return this._membership;
573
569
  }
574
- /** The app (global namespace) this client publishes and reads under. */
570
+ /** The app this client reads and publishes under, or undefined for none. */
575
571
  getAppId() {
576
- return this.ctx.dataRegistry.getAppId();
572
+ return this.ctx.appId;
573
+ }
574
+ requireApp(what) {
575
+ if (!this.ctx.appId) throw new Error(`${what} needs an app: pass \`appId\` to Fangorn.create() or call setAppId()`);
576
+ return this.ctx.appId;
577
577
  }
578
578
  /**
579
579
  * Point this client at a different app — by name (`"my-app"`) or by app id —
580
- * without rebuilding it. The app id prefixes every namespace key, so every
581
- * read, publish and subscription after this call lands in the new app.
580
+ * or at none, without rebuilding it. Every read, publish and subscription
581
+ * after this call is in the new context.
582
582
  *
583
- * Namespace reads are dropped from the cache (its keys are app-agnostic) and
583
+ * Repo reads are dropped from the cache (its keys are app-agnostic) and
584
584
  * the shared `appFeed` is released: a feed watches one app's commit stream, so
585
585
  * the next `appFeed()` opens a fresh subscription. Generators already running
586
586
  * from `subscribe`/`subscribeApp` keep their original filter until aborted.
587
587
  */
588
588
  setAppId(nameOrId) {
589
- const appId = toAppId(nameOrId);
590
- this.ctx.dataRegistry.setAppId(appId);
591
- this.ctx.appRegistry.setAppId(appId);
589
+ const chosen = nonBlank(nameOrId);
590
+ this.ctx.appId = chosen ? toAppId(chosen) : void 0;
591
+ this._apps?.setAppId(this.ctx.appId);
592
592
  this.nsCache.clear();
593
593
  this._feed = null;
594
594
  }
@@ -602,7 +602,7 @@ var Fangorn = class Fangorn {
602
602
  * picks up the new backend.
603
603
  */
604
604
  setStorage(storage) {
605
- this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
605
+ this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config, () => this.ctx.appId);
606
606
  this._engine = null;
607
607
  }
608
608
  getWalletClient() {