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