@ipab/cli 0.1.0-rc.5 → 0.1.0-rc.7

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 (157) hide show
  1. package/README.md +128 -22
  2. package/dist/app-authoring.d.ts +5 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +4 -1
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-templates.d.ts +0 -1
  7. package/dist/app-templates.d.ts.map +1 -1
  8. package/dist/app-templates.js +6 -45
  9. package/dist/app-templates.js.map +1 -1
  10. package/dist/builtins/skill.ipab.car +0 -0
  11. package/dist/builtins/template.bundle-viewer.car +0 -0
  12. package/dist/builtins/template.check.car +0 -0
  13. package/dist/builtins/template.node.car +0 -0
  14. package/dist/builtins/template.web-app.car +0 -0
  15. package/dist/builtins.d.ts.map +1 -1
  16. package/dist/builtins.js +1 -39
  17. package/dist/builtins.js.map +1 -1
  18. package/dist/cli.d.ts +4 -1
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +934 -336
  21. package/dist/cli.js.map +1 -1
  22. package/dist/content-provider.d.ts +1 -1
  23. package/dist/content-provider.d.ts.map +1 -1
  24. package/dist/content-provider.js +4 -3
  25. package/dist/content-provider.js.map +1 -1
  26. package/dist/context.d.ts +16 -1
  27. package/dist/context.d.ts.map +1 -1
  28. package/dist/context.js +20 -10
  29. package/dist/context.js.map +1 -1
  30. package/dist/doctor.d.ts +29 -0
  31. package/dist/doctor.d.ts.map +1 -0
  32. package/dist/doctor.js +576 -0
  33. package/dist/doctor.js.map +1 -0
  34. package/dist/identity.d.ts +1 -1
  35. package/dist/identity.d.ts.map +1 -1
  36. package/dist/identity.js +9 -9
  37. package/dist/identity.js.map +1 -1
  38. package/dist/ipc.d.ts +2 -2
  39. package/dist/ipc.d.ts.map +1 -1
  40. package/dist/ipc.js +44 -12
  41. package/dist/ipc.js.map +1 -1
  42. package/dist/kubo-install.d.ts +18 -1
  43. package/dist/kubo-install.d.ts.map +1 -1
  44. package/dist/kubo-install.js +424 -61
  45. package/dist/kubo-install.js.map +1 -1
  46. package/dist/kubo-release.d.ts +19 -0
  47. package/dist/kubo-release.d.ts.map +1 -1
  48. package/dist/kubo-release.js +164 -0
  49. package/dist/kubo-release.js.map +1 -1
  50. package/dist/kubo.d.ts +1 -0
  51. package/dist/kubo.d.ts.map +1 -1
  52. package/dist/kubo.js +102 -96
  53. package/dist/kubo.js.map +1 -1
  54. package/dist/pins.d.ts +15 -17
  55. package/dist/pins.d.ts.map +1 -1
  56. package/dist/pins.js +144 -106
  57. package/dist/pins.js.map +1 -1
  58. package/dist/publish-source.d.ts +3 -0
  59. package/dist/publish-source.d.ts.map +1 -0
  60. package/dist/publish-source.js +85 -0
  61. package/dist/publish-source.js.map +1 -0
  62. package/dist/runtime.d.ts.map +1 -1
  63. package/dist/runtime.js +6 -5
  64. package/dist/runtime.js.map +1 -1
  65. package/dist/skill-definition.d.ts +6 -0
  66. package/dist/skill-definition.d.ts.map +1 -0
  67. package/dist/skill-definition.js +38 -0
  68. package/dist/skill-definition.js.map +1 -0
  69. package/dist/skill-source.d.ts +5 -0
  70. package/dist/skill-source.d.ts.map +1 -0
  71. package/dist/skill-source.js +12 -0
  72. package/dist/skill-source.js.map +1 -0
  73. package/dist/skills.d.ts +84 -0
  74. package/dist/skills.d.ts.map +1 -0
  75. package/dist/skills.js +736 -0
  76. package/dist/skills.js.map +1 -0
  77. package/dist/space.d.ts +15 -2
  78. package/dist/space.d.ts.map +1 -1
  79. package/dist/space.js +153 -3
  80. package/dist/space.js.map +1 -1
  81. package/dist/state-storage-windows.js +1 -1
  82. package/dist/state-storage.d.ts +3 -1
  83. package/dist/state-storage.d.ts.map +1 -1
  84. package/dist/state-storage.js +38 -7
  85. package/dist/state-storage.js.map +1 -1
  86. package/dist/state.d.ts +40 -6
  87. package/dist/state.d.ts.map +1 -1
  88. package/dist/state.js +208 -82
  89. package/dist/state.js.map +1 -1
  90. package/dist/swarm-envelope.d.ts +1 -0
  91. package/dist/swarm-envelope.d.ts.map +1 -1
  92. package/dist/swarm-envelope.js +12 -0
  93. package/dist/swarm-envelope.js.map +1 -1
  94. package/dist/swarm-files.d.ts +1 -1
  95. package/dist/swarm-files.d.ts.map +1 -1
  96. package/dist/swarm-files.js +2 -2
  97. package/dist/swarm-files.js.map +1 -1
  98. package/dist/swarm-meta.d.ts +17 -0
  99. package/dist/swarm-meta.d.ts.map +1 -0
  100. package/dist/swarm-meta.js +96 -0
  101. package/dist/swarm-meta.js.map +1 -0
  102. package/dist/swarm.d.ts +117 -8
  103. package/dist/swarm.d.ts.map +1 -1
  104. package/dist/swarm.js +1275 -131
  105. package/dist/swarm.js.map +1 -1
  106. package/dist/template-paths.d.ts +7 -0
  107. package/dist/template-paths.d.ts.map +1 -0
  108. package/dist/template-paths.js +23 -0
  109. package/dist/template-paths.js.map +1 -0
  110. package/dist/template-presentation.d.ts +20 -0
  111. package/dist/template-presentation.d.ts.map +1 -0
  112. package/dist/template-presentation.js +133 -0
  113. package/dist/template-presentation.js.map +1 -0
  114. package/dist/template-source.d.ts +2 -1
  115. package/dist/template-source.d.ts.map +1 -1
  116. package/dist/template-source.js +7 -1
  117. package/dist/template-source.js.map +1 -1
  118. package/dist/templates.d.ts +11 -0
  119. package/dist/templates.d.ts.map +1 -0
  120. package/dist/templates.js +53 -0
  121. package/dist/templates.js.map +1 -0
  122. package/package.json +7 -6
  123. package/src/app-authoring.ts +18 -2
  124. package/src/app-templates.ts +8 -72
  125. package/src/builtins.ts +2 -48
  126. package/src/cli.ts +1154 -387
  127. package/src/content-provider.ts +4 -2
  128. package/src/context.ts +45 -10
  129. package/src/doctor.ts +902 -0
  130. package/src/identity.ts +10 -10
  131. package/src/ipc.ts +63 -10
  132. package/src/kubo-install.ts +562 -78
  133. package/src/kubo-release.ts +213 -0
  134. package/src/kubo.ts +134 -106
  135. package/src/pins.ts +188 -126
  136. package/src/publish-source.ts +103 -0
  137. package/src/runtime.ts +6 -5
  138. package/src/skill-definition.ts +53 -0
  139. package/src/skill-source.ts +15 -0
  140. package/src/skills.ts +1005 -0
  141. package/src/space.ts +214 -5
  142. package/src/state-storage-windows.ts +1 -1
  143. package/src/state-storage.ts +53 -7
  144. package/src/state.ts +357 -98
  145. package/src/swarm-envelope.ts +14 -0
  146. package/src/swarm-files.ts +2 -1
  147. package/src/swarm-meta.ts +109 -0
  148. package/src/swarm.ts +1877 -175
  149. package/src/template-paths.ts +43 -0
  150. package/src/template-presentation.ts +151 -0
  151. package/src/template-source.ts +9 -2
  152. package/src/templates.ts +77 -0
  153. package/dist/setup.d.ts +0 -8
  154. package/dist/setup.d.ts.map +0 -1
  155. package/dist/setup.js +0 -27
  156. package/dist/setup.js.map +0 -1
  157. package/src/setup.ts +0 -34
package/dist/swarm.js CHANGED
@@ -1,31 +1,87 @@
1
- import { lstat, open, readFile } from "node:fs/promises";
1
+ import { createReadStream } from "node:fs";
2
+ import { lstat, mkdir, open } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
2
5
  import { createHash, randomBytes } from "node:crypto";
3
6
  import { stringify } from "yaml";
4
7
  import { CarBlockIterator } from "@ipld/car/iterator";
5
8
  import * as dagCbor from "@ipld/dag-cbor";
6
9
  import { CID } from "multiformats/cid";
7
10
  import { sha256 } from "multiformats/hashes/sha2";
8
- import { encodeSchema, openBundle } from "@ipab/bundle";
11
+ import { ContentBundleError, encodeSchema, openBundle, } from "@ipab/bundle";
9
12
  import { encodeBundleCar, memoryTree, streamChunks, } from "@ipab/bundle-builder";
10
13
  import { ContentError } from "@ipab/ipfs-store";
11
14
  import { ScopeClient, ScopeApiError, RESOURCE_ID_PATTERN, issueScopeCertificate, uniqueId, verifyScopeCertificate, valueCid, } from "@ipab/bundle/pointer/scope";
12
15
  import { canonicalService, isCanonicalPublicKey, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
13
16
  import { importPrivateKeyPkcs8, importPublicKeyRaw, keyId, signEd25519, verifyEd25519, } from "@ipab/bundle/pointer/crypto";
14
17
  import { HostError, object, message } from "./errors.js";
15
- import { accountIdentity } from "./identity.js";
18
+ import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
19
+ import { nodeError } from "./authoring.js";
16
20
  import { swarmUrl as canonicalSwarmUrl } from "./config.js";
17
- import { bundleJson, provideContent } from "./content-provider.js";
21
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
22
+ import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
18
23
  import { bytes, relativePath } from "./space.js";
19
24
  import { appSchemaCid } from "./app-definition.js";
20
- import { State } from "./state.js";
25
+ import { State, createAssociation, exactCid, } from "./state.js";
21
26
  import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
22
- import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, } from "./swarm-envelope.js";
27
+ import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
23
28
  import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
24
29
  import { memberPeers } from "./kubo-peering.js";
30
+ import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
31
+ import { inspectTemplate, templatePublicationSource } from "./templates.js";
32
+ import { seedSkillSource } from "./skill-source.js";
33
+ import { skillIdentity, skillSchema } from "./skill-definition.js";
34
+ import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmStateType, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
25
35
  async function contextIdentity(context, initialize = false) {
26
36
  context.identity ??= await accountIdentity(context.env, initialize);
27
37
  return context.identity;
28
38
  }
39
+ export async function inspectLocalMembership(input, account) {
40
+ const value = object(input, "local membership");
41
+ if (typeof value.configUrl !== "string" ||
42
+ !isCanonicalPublicKey(value.owner) ||
43
+ !isCanonicalPublicKey(value.account) ||
44
+ value.account !== account)
45
+ throw new HostError("Stored membership is inconsistent with HOME identity.");
46
+ const configUrl = canonicalSwarmUrl(value.configUrl);
47
+ if (configUrl !== value.configUrl)
48
+ throw new HostError("Noncanonical membership URL.");
49
+ const encryption = object(value.encryption, "encryption identity");
50
+ if (typeof encryption.privateKey !== "string" ||
51
+ typeof encryption.publicKey !== "string")
52
+ throw new HostError("Invalid encryption identity.");
53
+ validateEncryptionIdentity({
54
+ privateKey: encryption.privateKey,
55
+ publicKey: encryption.publicKey,
56
+ });
57
+ const request = value.request === undefined
58
+ ? undefined
59
+ : await verifyRequest(value.request);
60
+ if (request &&
61
+ (request.configUrl !== configUrl ||
62
+ request.member !== account ||
63
+ request.owner !== value.owner ||
64
+ request.encryptionKey !== encryption.publicKey))
65
+ throw new HostError("Stored Request binding mismatch.");
66
+ const config = value.config === undefined
67
+ ? undefined
68
+ : parseOrganization(value.config, configUrl);
69
+ if (config && config.owner !== value.owner)
70
+ throw new HostError("Stored Owner binding mismatch.");
71
+ let peer = request?.peerId;
72
+ if (value.secret !== undefined) {
73
+ if (!config)
74
+ throw new HostError("Stored secret has no configuration binding.");
75
+ const member = config.members.find((member) => member.publicKey === account);
76
+ if (!member)
77
+ throw new HostError("Stored membership lacks its member binding.");
78
+ const record = value;
79
+ await validateMembershipSecret(record, config, member);
80
+ peer = member.peerId;
81
+ }
82
+ const c = coordinates(configUrl);
83
+ return { configUrl, scope: nodeScope(c.service, c.scopeId), peer };
84
+ }
29
85
  const cidField = { type: "string", minLength: 1, maxLength: 128 };
30
86
  export const artifactType = {
31
87
  contentType: "application/json",
@@ -94,7 +150,7 @@ function parseOrganization(value, configUrl) {
94
150
  const { scopeId } = coordinates(configUrl);
95
151
  if (Object.keys(data).sort().join() !==
96
152
  "bootstrap,description,epoch,headId,members,name,owner,scopeId,v" ||
97
- data.v !== 1 ||
153
+ (data.v !== 1 && data.v !== 2) ||
98
154
  data.scopeId !== scopeId ||
99
155
  !isCanonicalPublicKey(data.owner) ||
100
156
  typeof data.name !== "string" ||
@@ -110,14 +166,20 @@ function parseOrganization(value, configUrl) {
110
166
  data.bootstrap.length > 64 ||
111
167
  !Array.isArray(data.members) ||
112
168
  data.members.length < 1 ||
113
- data.members.length > 16)
169
+ data.members.length > 256)
114
170
  throw new HostError("Invalid Scope organization configuration.");
115
171
  const identities = new Set(), peers = new Set(), profiles = new Set();
116
172
  const members = [];
117
173
  for (const raw of data.members) {
118
174
  const member = object(raw, "member");
119
- if (Object.keys(member).sort().join() !==
175
+ if (Object.keys(member)
176
+ .filter((key) => key !== "memberId")
177
+ .sort()
178
+ .join() !==
120
179
  "approval,encryptionKey,peerId,profileId,publicKey,requestId" ||
180
+ (member.memberId !== undefined &&
181
+ (typeof member.memberId !== "string" ||
182
+ !RESOURCE_ID_PATTERN.test(member.memberId))) ||
121
183
  !isCanonicalPublicKey(member.publicKey) ||
122
184
  typeof member.encryptionKey !== "string" ||
123
185
  member.encryptionKey.length > 256 ||
@@ -134,6 +196,9 @@ function parseOrganization(value, configUrl) {
134
196
  peers.add(member.peerId);
135
197
  profiles.add(member.profileId);
136
198
  members.push({
199
+ ...(typeof member.memberId === "string"
200
+ ? { memberId: member.memberId }
201
+ : {}),
137
202
  publicKey: member.publicKey,
138
203
  encryptionKey: member.encryptionKey,
139
204
  peerId: member.peerId,
@@ -154,7 +219,7 @@ function parseOrganization(value, configUrl) {
154
219
  bootstrap.push(address);
155
220
  }
156
221
  return {
157
- v: 1,
222
+ v: data.v,
158
223
  scopeId,
159
224
  owner: data.owner,
160
225
  name: data.name,
@@ -167,9 +232,15 @@ function parseOrganization(value, configUrl) {
167
232
  }
168
233
  function parseProfile(value, expectedPeer) {
169
234
  const data = object(value, "member profile");
170
- if (Object.keys(data).sort().join() !== "addresses,name,updatedAt" ||
235
+ if (![
236
+ "addresses,name,updatedAt",
237
+ "addresses,description,name,updatedAt",
238
+ ].includes(Object.keys(data).sort().join()) ||
171
239
  typeof data.name !== "string" ||
172
240
  data.name.length > 256 ||
241
+ (data.description !== undefined &&
242
+ (typeof data.description !== "string" ||
243
+ data.description.length > 2048)) ||
173
244
  typeof data.updatedAt !== "string" ||
174
245
  !Number.isFinite(Date.parse(data.updatedAt)) ||
175
246
  !Array.isArray(data.addresses) ||
@@ -182,7 +253,191 @@ function parseProfile(value, expectedPeer) {
182
253
  validateAddress(address, expectedPeer);
183
254
  addresses.push(address);
184
255
  }
185
- return { name: data.name, addresses, updatedAt: data.updatedAt };
256
+ return {
257
+ name: data.name,
258
+ ...(typeof data.description === "string"
259
+ ? { description: data.description }
260
+ : {}),
261
+ addresses,
262
+ updatedAt: data.updatedAt,
263
+ };
264
+ }
265
+ export async function swarmMembers(context, url) {
266
+ const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
267
+ const c = coordinates(url), api = client(context, c.service);
268
+ const members = await boundedMap(config.members, async (member) => {
269
+ const profile = parseProfile((await api.read(c.scopeId, member.profileId)).value, member.peerId);
270
+ return {
271
+ publicKey: member.publicKey,
272
+ role: member.publicKey === config.owner ? "owner" : "member",
273
+ name: profile.name,
274
+ description: profile.description ?? "",
275
+ };
276
+ });
277
+ return { configUrl: url, members };
278
+ }
279
+ function accountProfileLocation(context, publicKey) {
280
+ return {
281
+ parent: join(resolve(context.env.HOME ?? context.env.USERPROFILE ?? homedir()), ".ipab"),
282
+ name: `${createHash("sha256").update(publicKey).digest("hex")}.json`,
283
+ };
284
+ }
285
+ async function storedAccountProfile(context) {
286
+ const identity = await contextIdentity(context);
287
+ const { parent, name } = accountProfileLocation(context, identity.publicKey);
288
+ try {
289
+ await lstat(join(parent, "profiles"));
290
+ }
291
+ catch (cause) {
292
+ if (nodeError(cause, "ENOENT"))
293
+ return undefined;
294
+ throw cause;
295
+ }
296
+ await protectedPath(parent, true);
297
+ await protectedPath(join(parent, "profiles"), true);
298
+ const value = await readPrivate(join(parent, "profiles"), name);
299
+ if (value === undefined)
300
+ return undefined;
301
+ const data = object(value, "account profile");
302
+ if (Object.keys(data).sort().join() !==
303
+ "description,name,publicKey,updatedAt" ||
304
+ data.publicKey !== identity.publicKey ||
305
+ typeof data.name !== "string" ||
306
+ data.name.length > 256 ||
307
+ typeof data.description !== "string" ||
308
+ data.description.length > 2048 ||
309
+ typeof data.updatedAt !== "string" ||
310
+ !Number.isFinite(Date.parse(data.updatedAt)))
311
+ throw new HostError("Invalid protected account profile; restore the existing profile file.");
312
+ return {
313
+ publicKey: identity.publicKey,
314
+ name: data.name,
315
+ description: data.description,
316
+ updatedAt: data.updatedAt,
317
+ };
318
+ }
319
+ async function accountProfileDirectory(context, publicKey) {
320
+ const { parent } = accountProfileLocation(context, publicKey);
321
+ try {
322
+ await lstat(parent);
323
+ }
324
+ catch (cause) {
325
+ if (!nodeError(cause, "ENOENT"))
326
+ throw cause;
327
+ await mkdir(parent, { mode: 0o700 });
328
+ await secureNew(parent, true);
329
+ }
330
+ await protectedPath(parent, true);
331
+ return privateDirectory(parent, "profiles");
332
+ }
333
+ async function initialAccountProfile(context, changes = {}) {
334
+ const identity = await contextIdentity(context);
335
+ if (changes.name !== undefined && changes.description !== undefined)
336
+ return {
337
+ publicKey: identity.publicKey,
338
+ name: changes.name,
339
+ description: changes.description,
340
+ updatedAt: null,
341
+ };
342
+ const legacy = [];
343
+ for (const entry of withState(context, (state) => state.swarms())) {
344
+ const { config } = await fetchConfig(context, entry.cid);
345
+ const self = config.members.find((member) => member.publicKey === identity.publicKey);
346
+ if (!self)
347
+ continue; // Pending requests have no public profile yet.
348
+ const c = coordinates(entry.cid);
349
+ legacy.push(parseProfile((await client(context, c.service).read(c.scopeId, self.profileId))
350
+ .value, self.peerId));
351
+ }
352
+ const field = (key) => {
353
+ if (changes[key] !== undefined)
354
+ return changes[key];
355
+ const values = new Set(legacy.map((profile) => profile[key] ?? ""));
356
+ if (values.size > 1)
357
+ throw new HostError(`Legacy Swarm profiles disagree on ${key}. Run ipab profile --${key} TEXT to choose your account-wide value; no profile has been saved.`);
358
+ return values.values().next().value ?? "";
359
+ };
360
+ return {
361
+ publicKey: identity.publicKey,
362
+ name: field("name"),
363
+ description: field("description"),
364
+ updatedAt: null,
365
+ };
366
+ }
367
+ export async function accountProfile(context) {
368
+ return ((await storedAccountProfile(context)) ??
369
+ (await initialAccountProfile(context)));
370
+ }
371
+ async function ensureAccountProfile(context, changes = {}) {
372
+ const identity = await contextIdentity(context);
373
+ const dir = await accountProfileDirectory(context, identity.publicKey);
374
+ return withPrivateLock(dir, async () => {
375
+ const existing = await storedAccountProfile(context);
376
+ if (existing &&
377
+ changes.name === undefined &&
378
+ changes.description === undefined)
379
+ return existing;
380
+ const profile = {
381
+ ...(existing ?? (await initialAccountProfile(context, changes))),
382
+ ...changes,
383
+ updatedAt: new Date().toISOString(),
384
+ };
385
+ await writePrivate(dir, accountProfileLocation(context, identity.publicKey).name, profile);
386
+ return profile;
387
+ });
388
+ }
389
+ async function syncAccountProfile(context, record, personal, fetched) {
390
+ const identity = await contextIdentity(context), c = coordinates(record.configUrl);
391
+ const self = record.config.members.find((member) => member.publicKey === identity.publicKey);
392
+ const api = client(context, c.service, identity, identity.publicKey === record.owner ? undefined : record.secret);
393
+ let existing = fetched;
394
+ if (!existing) {
395
+ const variable = await api.read(c.scopeId, self.profileId);
396
+ existing = {
397
+ profile: parseProfile(variable.value, self.peerId),
398
+ cid: variable.cid,
399
+ };
400
+ }
401
+ const old = existing.profile;
402
+ if (old.name === personal.name && old.description === personal.description)
403
+ return old;
404
+ const profile = {
405
+ ...old,
406
+ name: personal.name,
407
+ description: personal.description,
408
+ updatedAt: new Date().toISOString(),
409
+ };
410
+ await api.write(c.scopeId, self.profileId, profile, existing.cid, uniqueId());
411
+ return profile;
412
+ }
413
+ export async function updateAccountProfile(context, changes) {
414
+ if ((changes.name?.length ?? 0) > 256 ||
415
+ (changes.description?.length ?? 0) > 2048)
416
+ throw new HostError("Profile name/description limit exceeded.");
417
+ await contextIdentity(context, true);
418
+ let profile;
419
+ try {
420
+ profile = await ensureAccountProfile(context, changes);
421
+ }
422
+ catch (cause) {
423
+ throw new HostError(`Personal profile local persistence failed: ${message(cause)}. No Swarm synchronization was attempted.`);
424
+ }
425
+ const swarms = [];
426
+ for (const entry of withState(context, (state) => state.swarms())) {
427
+ try {
428
+ const record = await approvedMembership(context, entry.cid);
429
+ await syncAccountProfile(context, record, profile);
430
+ swarms.push({ configUrl: entry.cid, synchronized: true });
431
+ }
432
+ catch (cause) {
433
+ swarms.push({
434
+ configUrl: entry.cid,
435
+ synchronized: false,
436
+ error: message(cause),
437
+ });
438
+ }
439
+ }
440
+ return { profile, localPersisted: true, swarms };
186
441
  }
187
442
  async function fetchConfig(context, configUrl, signal) {
188
443
  const c = coordinates(configUrl), api = client(context, c.service);
@@ -191,10 +446,76 @@ async function fetchConfig(context, configUrl, signal) {
191
446
  api.read(c.scopeId, c.configId, options),
192
447
  api.send("GET", c.scopeId, "", undefined, options),
193
448
  ]);
194
- const config = parseOrganization(variable.value, configUrl);
195
- if (scope.owner !== config.owner)
449
+ const raw = object(variable.value, "organization configuration");
450
+ if (scope.owner !== raw.owner)
196
451
  throw new HostError("Organization Owner does not match the immutable Scope trust root.");
197
- return { config, variable };
452
+ if (raw.v === 2) {
453
+ if (!Array.isArray(raw.members) ||
454
+ raw.members.length < 1 ||
455
+ raw.members.length > 256)
456
+ throw new HostError("Invalid organization member directory.");
457
+ const ids = new Set(), identities = new Set();
458
+ const directory = raw.members.map((item) => {
459
+ const member = object(item, "member directory entry");
460
+ if (Object.keys(member).sort().join() !== "memberId,publicKey" ||
461
+ !isCanonicalPublicKey(member.publicKey) ||
462
+ typeof member.memberId !== "string" ||
463
+ !RESOURCE_ID_PATTERN.test(member.memberId) ||
464
+ ids.has(member.memberId) ||
465
+ identities.has(member.publicKey))
466
+ throw new HostError("Invalid or duplicate member directory entry.");
467
+ ids.add(member.memberId);
468
+ identities.add(member.publicKey);
469
+ return { publicKey: member.publicKey, memberId: member.memberId };
470
+ });
471
+ const members = await boundedMap(directory, async (entry) => {
472
+ const member = object((await api.read(c.scopeId, entry.memberId, options)).value, "member record");
473
+ if (member.publicKey !== entry.publicKey)
474
+ throw new HostError("Member record does not match its directory identity.");
475
+ return { ...member, memberId: entry.memberId };
476
+ });
477
+ return {
478
+ config: parseOrganization({ ...raw, members }, configUrl),
479
+ variable,
480
+ };
481
+ }
482
+ return { config: parseOrganization(raw, configUrl), variable };
483
+ }
484
+ async function boundedMap(items, operation) {
485
+ const results = [];
486
+ for (let offset = 0; offset < items.length; offset += 16) {
487
+ const batch = await Promise.allSettled(items.slice(offset, offset + 16).map(operation));
488
+ for (const result of batch) {
489
+ if (result.status === "rejected")
490
+ throw result.reason;
491
+ results.push(result.value);
492
+ }
493
+ }
494
+ return results;
495
+ }
496
+ function configValue(config) {
497
+ if (config.v === 1)
498
+ return config;
499
+ return {
500
+ ...config,
501
+ members: config.members.map((member) => {
502
+ if (!member.memberId)
503
+ throw new HostError("Member directory is missing its record ID.");
504
+ return { publicKey: member.publicKey, memberId: member.memberId };
505
+ }),
506
+ };
507
+ }
508
+ async function createMemberRecord(api, scopeId, member, key) {
509
+ const value = {
510
+ publicKey: member.publicKey,
511
+ encryptionKey: member.encryptionKey,
512
+ peerId: member.peerId,
513
+ profileId: member.profileId,
514
+ requestId: member.requestId,
515
+ approval: member.approval,
516
+ };
517
+ const created = await api.create(scopeId, value, key);
518
+ return { ...value, memberId: created.id };
198
519
  }
199
520
  function binding(configUrl, config, member) {
200
521
  return {
@@ -235,20 +556,22 @@ async function privateSource(context, record, signal) {
235
556
  await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, config.headId, identity.publicKey);
236
557
  await verifyScopeCertificate(secret.certificate, config.owner, c.service, c.scopeId, self.profileId, identity.publicKey);
237
558
  }
559
+ const personal = await storedAccountProfile(context);
238
560
  const addresses = new Map();
239
561
  const api = client(context, c.service);
240
562
  let selfProfile;
241
- const profiles = await Promise.allSettled(config.members.map((member) => api.read(c.scopeId, member.profileId, signal ? { signal } : {})));
563
+ const profiles = await boundedMap(config.members, (member) => api.read(c.scopeId, member.profileId, signal ? { signal } : {}));
242
564
  for (const [index, member] of config.members.entries()) {
243
- const result = profiles[index];
244
- if (result.status === "rejected")
245
- throw result.reason;
246
- const profile = result.value;
565
+ const profile = profiles[index];
247
566
  const value = parseProfile(profile.value, member.peerId);
248
567
  if (member.publicKey === identity.publicKey)
249
568
  selfProfile = { profile: value, cid: profile.cid };
250
569
  addresses.set(member.peerId, value.addresses);
251
570
  }
571
+ if (personal && selfProfile) {
572
+ selfProfile.profile = await syncAccountProfile(context, record, personal, selfProfile);
573
+ selfProfile.cid = await valueCid(selfProfile.profile);
574
+ }
252
575
  const desired = memberPeers(self.peerId, addresses, config.bootstrap);
253
576
  signal?.throwIfAborted();
254
577
  const node = await startNode(context.stateDir, nodeScope(c.service, config.scopeId), secret.swarmKey, config.epoch, context.listen, { self: self.peerId, peers: desired, ...(signal ? { signal } : {}) });
@@ -343,6 +666,11 @@ async function readyMembership(context, configUrl) {
343
666
  throw cause;
344
667
  }
345
668
  }
669
+ else {
670
+ const personal = await storedAccountProfile(context);
671
+ if (personal)
672
+ await syncAccountProfile(context, record, personal);
673
+ }
346
674
  return record;
347
675
  }
348
676
  function headValue(head) {
@@ -434,14 +762,93 @@ export async function jsonBundle(store, type, value) {
434
762
  await encoded.close();
435
763
  }
436
764
  }
765
+ async function writeStateBundle(store, configuration, targets) {
766
+ const meta = parseSwarmMeta(configuration);
767
+ const names = Object.fromEntries(Object.entries(targets).map(([name, cid]) => [
768
+ formalName(name),
769
+ cid.toString(),
770
+ ]));
771
+ return jsonBundle(store, meta.skillPath === undefined ? legacySwarmStateType : swarmStateType, { v: 5, ...meta, names });
772
+ }
437
773
  export async function writeSnapshot(store, snapshot) {
438
- const encoded = dagCbor.encode(snapshot), cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
439
- await store.put(cid, encoded);
440
- return cid.toString();
774
+ if (snapshot.stateBundle) {
775
+ if (Object.keys(snapshot.registrations ?? {}).length)
776
+ throw new HostError("State Bundles cannot contain legacy registrations.");
777
+ return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names);
778
+ }
779
+ const put = async (value) => {
780
+ const encoded = dagCbor.encode(value);
781
+ const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
782
+ await store.put(cid, encoded);
783
+ return cid;
784
+ };
785
+ const names = await put(snapshot.names);
786
+ if (Object.keys(snapshot.registrations ?? {}).length) {
787
+ const registrations = await put(snapshot.registrations);
788
+ return (await put({ v: 3, names, registrations })).toString();
789
+ }
790
+ return (await put({ v: 4, names })).toString();
791
+ }
792
+ async function readState(store, cid) {
793
+ if (cid.code !== dagCbor.code) {
794
+ const bundle = await openBundle(cid, {
795
+ resolveCid: (key) => store.block.get(key.toString()),
796
+ });
797
+ const type = bundle.schemaKey === legacySwarmStateSchema.cid.toString()
798
+ ? legacySwarmStateType
799
+ : swarmStateType;
800
+ const value = object(await typedJson(store, cid.toString(), type), "State Bundle");
801
+ if (value.v !== 5 ||
802
+ Object.keys(value).sort().join() !==
803
+ (type === legacySwarmStateType
804
+ ? "names,registryPath,templatePath,v"
805
+ : "names,registryPath,skillPath,templatePath,v"))
806
+ throw new HostError("Invalid State Bundle entry.");
807
+ const meta = parseSwarmMeta({
808
+ templatePath: value.templatePath,
809
+ registryPath: value.registryPath,
810
+ ...(type === legacySwarmStateType ? {} : { skillPath: value.skillPath }),
811
+ });
812
+ const names = Object.fromEntries(Object.entries(object(value.names, "Names")).map(([name, target]) => {
813
+ formalName(name);
814
+ if (typeof target !== "string" || exactCid(target) !== target)
815
+ throw new HostError("State Names require exact canonical CIDs.");
816
+ return [name, CID.parse(target)];
817
+ }));
818
+ return { v: 2, names, stateBundle: { meta, cid: cid.toString() } };
819
+ }
820
+ const data = await store.block.get(cid.toString());
821
+ const root = object(dagCbor.decode(data), "State");
822
+ if (root.v === 4) {
823
+ const names = CID.asCID(root.names);
824
+ if (!names || Object.keys(root).sort().join() !== "names,v")
825
+ throw new HostError("Invalid State Names root.");
826
+ return decodeSnapshot(dagCbor.encode({
827
+ v: 2,
828
+ names: dagCbor.decode(await store.block.get(names.toString())),
829
+ }));
830
+ }
831
+ if (root.v !== 3)
832
+ return decodeSnapshot(data);
833
+ const names = CID.asCID(root.names), registrations = CID.asCID(root.registrations);
834
+ if (!names ||
835
+ !registrations ||
836
+ Object.keys(root).sort().join() !== "names,registrations,v")
837
+ throw new HostError("Invalid State index roots.");
838
+ const [namesBlock, registrationsBlock] = await Promise.all([
839
+ store.block.get(names.toString()),
840
+ store.block.get(registrations.toString()),
841
+ ]);
842
+ return decodeSnapshot(dagCbor.encode({
843
+ v: 2,
844
+ names: dagCbor.decode(namesBlock),
845
+ registrations: dagCbor.decode(registrationsBlock),
846
+ }));
441
847
  }
442
848
  function decodeSnapshot(data) {
443
849
  const value = object(dagCbor.decode(data), "State"), names = object(value.names, "Names");
444
- if (value.v !== 2 || Object.keys(value).sort().join() !== "names,v")
850
+ if (value.v !== 2 ||
851
+ Object.keys(value).some((key) => !["v", "names", "registrations"].includes(key)))
445
852
  throw new HostError("Unsupported old State; rebuild the Swarm.");
446
853
  const links = [];
447
854
  for (const [name, link] of Object.entries(names)) {
@@ -451,11 +858,38 @@ function decodeSnapshot(data) {
451
858
  throw new HostError("Names must link CIDs.");
452
859
  links.push([name, cid]);
453
860
  }
454
- return { v: 2, names: Object.fromEntries(links) };
861
+ const registrations = {};
862
+ if (value.registrations !== undefined) {
863
+ for (const [schema, raw] of Object.entries(object(value.registrations, "Registrations"))) {
864
+ const item = object(raw, "Association");
865
+ const appCid = CID.asCID(item.appCid);
866
+ if (Object.keys(item).sort().join() !== "appCid,argv" ||
867
+ !appCid ||
868
+ !Array.isArray(item.argv) ||
869
+ !item.argv.every((argument) => typeof argument === "string"))
870
+ throw new HostError("Invalid shared Association.");
871
+ const association = createAssociation(schema, appCid.toString(), item.argv);
872
+ if (association.schemaCid !== schema)
873
+ throw new HostError("Shared Association requires a canonical type CID.");
874
+ registrations[schema] = { appCid, argv: association.argv };
875
+ }
876
+ }
877
+ return {
878
+ v: 2,
879
+ names: Object.fromEntries(links),
880
+ ...(value.registrations !== undefined ? { registrations } : {}),
881
+ };
455
882
  }
456
883
  export async function readSnapshot(store, root) {
457
884
  const publication = await readPublication(store, root);
458
- return decodeSnapshot(await store.block.get(publication.state.toString()));
885
+ return readState(store, publication.state);
886
+ }
887
+ async function readHeaderSnapshot(store, root) {
888
+ const publication = await readPublication(store, root);
889
+ return {
890
+ snapshot: await readState(store, publication.state),
891
+ stateCid: publication.state.toString(),
892
+ };
459
893
  }
460
894
  async function readPublication(store, root) {
461
895
  if (CID.parse(root).code !== dagCbor.code)
@@ -482,16 +916,22 @@ async function publication(store, state, previous) {
482
916
  await store.put(cid, data);
483
917
  return cid.toString();
484
918
  }
919
+ function missingContent(cause) {
920
+ let failure = cause;
921
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
922
+ failure = failure.cause;
923
+ return failure instanceof ContentError && failure.code === "missing_block";
924
+ }
485
925
  export async function sharedSwarmStatus(context, configUrl) {
486
926
  const { config } = await fetchConfig(context, configUrl);
487
927
  const c = coordinates(configUrl);
488
928
  const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
489
- let snapshot;
929
+ let content;
490
930
  try {
491
- snapshot = await readSnapshot(context.store, head.root);
931
+ content = await readHeaderSnapshot(context.store, head.root);
492
932
  }
493
933
  catch (cause) {
494
- if (!(cause instanceof ContentError) || cause.code !== "missing_block")
934
+ if (!missingContent(cause))
495
935
  throw cause;
496
936
  const registered = withState(context, (state) => state.swarms().some((entry) => entry.cid === configUrl));
497
937
  if (!registered)
@@ -499,51 +939,94 @@ export async function sharedSwarmStatus(context, configUrl) {
499
939
  context.diagnostic?.("Shared State is missing locally; connecting the registered Swarm content source.");
500
940
  return swarmHeader(context, configUrl, true);
501
941
  }
502
- return {
942
+ const header = {
503
943
  head,
504
- snapshot,
944
+ ...content,
505
945
  config,
506
946
  source: "network",
507
947
  verifiedAt: new Date().toISOString(),
508
948
  };
949
+ if (withState(context, (state) => state
950
+ .contentPins()
951
+ .some((pin) => pin.swarm === configUrl && pin.status !== "deleting"))) {
952
+ const record = await localForRead(context, configUrl);
953
+ await lazyPrivateSource(context, configUrl, record.account, config);
954
+ await refreshNamePins(context, configUrl, header);
955
+ }
956
+ return header;
957
+ }
958
+ export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
959
+ try {
960
+ return await readSwarmHeader(context, configUrl, force, mode);
961
+ }
962
+ catch (cause) {
963
+ withState(context, (state) => {
964
+ for (const pin of state.contentPins())
965
+ if (pin.swarm === configUrl && pin.status !== "deleting")
966
+ state.saveContentPin({
967
+ ...pin,
968
+ freshness: "stale",
969
+ error: message(cause),
970
+ });
971
+ });
972
+ throw cause;
973
+ }
509
974
  }
510
- export async function swarmHeader(context, configUrl, force = context.forceRefresh ?? false) {
975
+ async function readSwarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
511
976
  canonicalSwarmUrl(configUrl);
512
- let record = force
513
- ? await refresh(context, configUrl)
514
- : await readyMembership(context, configUrl);
515
- const cached = !force && cachedHeader(context, record);
516
- if (cached)
977
+ let record = mode === "local-first"
978
+ ? await approvedMembership(context, configUrl)
979
+ : force
980
+ ? await refresh(context, configUrl)
981
+ : await readyMembership(context, configUrl);
982
+ const cached = !force && (await cachedHeader(context, record));
983
+ if (cached) {
984
+ projectHeader(context, record, cached);
985
+ await refreshNamePins(context, configUrl, cached);
517
986
  return cached;
518
- let head = await (await boundPointer(context, configUrl, record)).read();
519
- let snapshot;
987
+ }
988
+ if (mode === "local-first") {
989
+ await saveLocal(context, record);
990
+ await lazyPrivateSource(context, configUrl, record.account, record.config);
991
+ }
992
+ const c = coordinates(configUrl);
993
+ let head = mode === "local-first"
994
+ ? headValue(await client(context, c.service).read(c.scopeId, record.config.headId))
995
+ : await (await boundPointer(context, configUrl, record)).read();
996
+ let content;
520
997
  try {
521
- snapshot = await readSnapshot(context.store, head.root);
998
+ content = await readHeaderSnapshot(context.store, head.root);
522
999
  }
523
- catch {
1000
+ catch (cause) {
1001
+ if (mode === "local-first")
1002
+ throw cause;
524
1003
  record = await refresh(context, configUrl);
525
1004
  head = await (await boundPointer(context, configUrl, record)).read();
526
- snapshot = await readSnapshot(context.store, head.root);
1005
+ content = await readHeaderSnapshot(context.store, head.root);
527
1006
  }
528
1007
  const current = await local(context, configUrl), verifiedAt = Date.now();
529
1008
  withState(context, (state) => {
530
1009
  state.saveSwarmHeader(record.account, configUrl, {
531
1010
  head,
532
- snapshot: Buffer.from(dagCbor.encode(snapshot)).toString("base64"),
1011
+ snapshot: Buffer.from(dagCbor.encode(content.snapshot)).toString("base64"),
1012
+ stateCid: content.stateCid,
533
1013
  verifiedAt,
534
1014
  headId: current.config.headId,
535
1015
  epoch: current.config.epoch,
536
1016
  });
537
1017
  });
538
- return {
1018
+ const header = {
539
1019
  head,
540
- snapshot,
1020
+ ...content,
541
1021
  config: current.config,
542
1022
  source: "network",
543
1023
  verifiedAt: new Date(verifiedAt).toISOString(),
544
1024
  };
1025
+ projectHeader(context, current, header);
1026
+ await refreshNamePins(context, configUrl, header);
1027
+ return header;
545
1028
  }
546
- function cachedHeader(context, record) {
1029
+ async function cachedHeader(context, record) {
547
1030
  const config = record.config;
548
1031
  if (!config || !record.secret)
549
1032
  return;
@@ -554,20 +1037,69 @@ function cachedHeader(context, record) {
554
1037
  (cached.epoch !== undefined && cached.epoch !== config.epoch) ||
555
1038
  !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
556
1039
  return;
1040
+ const cachedSnapshot = object(dagCbor.decode(Buffer.from(cached.snapshot, "base64")), "cached State");
1041
+ const { stateBundle, ...legacySnapshot } = cachedSnapshot;
1042
+ const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
1043
+ if (stateBundle !== undefined) {
1044
+ const data = object(stateBundle, "cached State Bundle");
1045
+ if (Object.keys(data).sort().join() !== "cid,meta" ||
1046
+ typeof data.cid !== "string" ||
1047
+ exactCid(data.cid) !== data.cid ||
1048
+ (cached.stateCid !== undefined && data.cid !== cached.stateCid))
1049
+ throw new HostError("Invalid cached State Bundle.");
1050
+ snapshot.stateBundle = { meta: parseSwarmMeta(data.meta), cid: data.cid };
1051
+ }
1052
+ let stateCid = cached.stateCid;
1053
+ if (!stateCid) {
1054
+ try {
1055
+ stateCid = (await readPublication(context.store, headValue(cached.head).root)).state.toString();
1056
+ }
1057
+ catch (cause) {
1058
+ if (cause instanceof ContentError && cause.code === "missing_block")
1059
+ return;
1060
+ throw cause;
1061
+ }
1062
+ }
557
1063
  return {
558
1064
  head: headValue(cached.head),
559
- snapshot: decodeSnapshot(Buffer.from(cached.snapshot, "base64")),
1065
+ snapshot,
1066
+ stateCid,
560
1067
  config,
561
1068
  source: "cache",
562
1069
  verifiedAt: new Date(cached.verifiedAt).toISOString(),
563
1070
  };
564
1071
  }
1072
+ function projectHeader(context, record, header) {
1073
+ const member = header.config.members.find((item) => item.publicKey === record.account);
1074
+ if (!member || record.owner !== header.config.owner)
1075
+ throw new HostError("Projection membership does not match the verified account.");
1076
+ const binding = {
1077
+ account: record.account,
1078
+ swarm: record.configUrl,
1079
+ stateCid: header.stateCid,
1080
+ root: header.head.root,
1081
+ valueCid: header.head.cid,
1082
+ verifiedAt: Date.parse(header.verifiedAt),
1083
+ headId: header.config.headId,
1084
+ epoch: header.config.epoch,
1085
+ membership: JSON.stringify({ owner: record.owner, member }),
1086
+ };
1087
+ withState(context, (state) => {
1088
+ state.projectSwarm(binding, header.snapshot.names, () => []);
1089
+ });
1090
+ header.projection = binding;
1091
+ }
1092
+ function headerProjection(header) {
1093
+ if (!header.projection)
1094
+ throw new HostError("A verified account projection is required.");
1095
+ return header.projection;
1096
+ }
565
1097
  async function localHeader(context, url) {
566
1098
  if (context.forceRefresh)
567
1099
  return;
568
1100
  canonicalSwarmUrl(url);
569
1101
  const record = await localForRead(context, url);
570
- const header = cachedHeader(context, record);
1102
+ const header = await cachedHeader(context, record);
571
1103
  if (!header)
572
1104
  return;
573
1105
  const config = parseOrganization(header.config, url);
@@ -583,11 +1115,22 @@ async function localHeader(context, url) {
583
1115
  await validateMembershipSecret(record, config, member);
584
1116
  const c = coordinates(url);
585
1117
  await checkCachedNode(context.stateDir, nodeScope(c.service, c.scopeId), config.epoch, member.peerId);
1118
+ projectHeader(context, record, header);
1119
+ if (withState(context, (state) => state
1120
+ .contentPins()
1121
+ .some((pin) => pin.swarm === url && pin.status !== "deleting"))) {
1122
+ await lazyPrivateSource(context, url, record.account, header.config);
1123
+ header.localSourceReady = true;
1124
+ await refreshNamePins(context, url, header);
1125
+ }
586
1126
  return { header, account: record.account };
587
1127
  }
588
1128
  // SharedContent invokes this source only after a genuine local ENOENT. Its
589
1129
  // store is not replaced from inside its own pending read (which would deadlock).
590
1130
  async function lazyPrivateSource(context, url, account, basis) {
1131
+ const finishPrevious = context.finishRead;
1132
+ delete context.finishRead;
1133
+ await finishPrevious?.();
591
1134
  const lifetime = new AbortController();
592
1135
  let pending;
593
1136
  const load = async (signal) => {
@@ -645,6 +1188,7 @@ export async function createSwarm(context, options = {}) {
645
1188
  (options.service && options.service !== service))
646
1189
  throw new HostError("Configure origin-bound pointers.service/apiKey before creating a Scope.");
647
1190
  const identity = await contextIdentity(context, true), op = options.resume ?? uniqueId(), dir = await directory(context);
1191
+ const personal = await ensureAccountProfile(context);
648
1192
  if (!POINTER_ID_PATTERN.test(op))
649
1193
  throw new HostError("Invalid creation resume ID.");
650
1194
  return withPrivateLock(dir, async () => {
@@ -668,6 +1212,7 @@ export async function createSwarm(context, options = {}) {
668
1212
  name: options.properties?.name ?? "",
669
1213
  description: options.properties?.description ?? "",
670
1214
  createdAt: new Date().toISOString(),
1215
+ personal: { name: personal.name, description: personal.description },
671
1216
  };
672
1217
  await writePrivate(dir, `creation-${op}.json`, record);
673
1218
  }
@@ -676,26 +1221,72 @@ export async function createSwarm(context, options = {}) {
676
1221
  const save = () => writePrivate(dir, `creation-${op}.json`, record);
677
1222
  const api = client(context, service, identity);
678
1223
  try {
1224
+ if (!record.seed) {
1225
+ if (record.headId)
1226
+ throw new HostError("Legacy creation has an unseeded HEAD. Preserve this recovery record and explicitly migrate the Swarm; it cannot complete as a newly seeded Swarm.");
1227
+ const names = {};
1228
+ for (const selector of seedTemplateNames) {
1229
+ const template = await seedTemplateSource(selector);
1230
+ for (const [cid, data] of template.blocks)
1231
+ await context.store.put(CID.parse(cid), data);
1232
+ names[`ipab/template/${selector}`] = CID.parse(template.cid);
1233
+ }
1234
+ const skill = await seedSkillSource();
1235
+ for (const [cid, data] of skill.blocks)
1236
+ await context.store.put(CID.parse(cid), data);
1237
+ names["ipab/skills/ipab"] = CID.parse(skill.cid);
1238
+ const root = await publication(context.store, await writeStateBundle(context.store, {
1239
+ templatePath: "ipab/template",
1240
+ registryPath: "ipab/registry",
1241
+ skillPath: "ipab/skills",
1242
+ }, names));
1243
+ const roots = await frozenPublicationClosure(context.store, root);
1244
+ record.seed = {
1245
+ root,
1246
+ roots,
1247
+ car: Buffer.from(await contentCar(context.store, roots)).toString("base64"),
1248
+ };
1249
+ await save();
1250
+ }
1251
+ const seedBytes = Buffer.from(record.seed.car, "base64");
1252
+ const seed = await CarBlockIterator.fromIterable(streamChunks(new Blob([seedBytes]).stream()));
1253
+ for await (const block of seed)
1254
+ await context.store.put(block.cid, block.bytes);
679
1255
  if (!record.scopeId) {
680
1256
  record.scopeId = (await api.createScope(`${op}.scope`)).id;
681
1257
  await save();
682
1258
  }
683
1259
  const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId), context.listen);
684
1260
  if (!record.headId) {
685
- const root = await publication(context.store, await writeSnapshot(context.store, { v: 2, names: {} }));
686
- record.headId = (await api.create(record.scopeId, { root }, `${op}.head`)).id;
1261
+ record.headId = (await api.create(record.scopeId, { root: record.seed.root }, `${op}.head`)).id;
687
1262
  await save();
688
1263
  }
689
1264
  if (!record.profileId) {
690
- const addresses = options.addresses ?? node.addresses;
691
- for (const address of addresses)
692
- validateAddress(address, node.peerId);
693
- record.profileId = (await api.create(record.scopeId, { name: record.name, addresses, updatedAt: record.createdAt }, `${op}.profile`)).id;
1265
+ if (!record.profile) {
1266
+ const addresses = options.addresses ?? node.addresses;
1267
+ for (const address of addresses)
1268
+ validateAddress(address, node.peerId);
1269
+ record.profile = {
1270
+ ...(record.personal ?? { name: record.name }),
1271
+ addresses,
1272
+ updatedAt: record.createdAt,
1273
+ };
1274
+ await save();
1275
+ }
1276
+ record.profileId = (await api.create(record.scopeId, record.profile, `${op}.profile`)).id;
694
1277
  await save();
695
1278
  }
696
1279
  if (!record.config) {
1280
+ const member = await createMemberRecord(api, record.scopeId, {
1281
+ publicKey: identity.publicKey,
1282
+ encryptionKey: record.encryption.publicKey,
1283
+ peerId: node.peerId,
1284
+ profileId: record.profileId,
1285
+ requestId: op,
1286
+ approval: null,
1287
+ }, `${op}.member`);
697
1288
  record.config = {
698
- v: 1,
1289
+ v: 2,
699
1290
  scopeId: record.scopeId,
700
1291
  owner: identity.publicKey,
701
1292
  name: record.name,
@@ -703,21 +1294,12 @@ export async function createSwarm(context, options = {}) {
703
1294
  headId: record.headId,
704
1295
  epoch: 1,
705
1296
  bootstrap: options.addresses ?? node.addresses,
706
- members: [
707
- {
708
- publicKey: identity.publicKey,
709
- encryptionKey: record.encryption.publicKey,
710
- peerId: node.peerId,
711
- profileId: record.profileId,
712
- requestId: op,
713
- approval: null,
714
- },
715
- ],
1297
+ members: [member],
716
1298
  };
717
1299
  await save();
718
1300
  }
719
1301
  if (!record.configId) {
720
- record.configId = (await api.create(record.scopeId, record.config, `${op}.config`)).id;
1302
+ record.configId = (await api.create(record.scopeId, configValue(record.config), `${op}.config`)).id;
721
1303
  await save();
722
1304
  }
723
1305
  const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
@@ -739,7 +1321,7 @@ export async function createSwarm(context, options = {}) {
739
1321
  await saveLocal(context, membership);
740
1322
  await activate(context, membership);
741
1323
  const head = await api.read(record.scopeId, record.headId);
742
- await provideContent(context.store, [headValue(head).root], context.node.api, context.fetch, context.node.auth);
1324
+ await provideContent(context.store, [...new Set([headValue(head).root, ...record.seed.roots])], context.node.api, context.fetch, context.node.auth);
743
1325
  withState(context, (state) => state.registerSwarm(configUrl, options.alias));
744
1326
  return configUrl;
745
1327
  }
@@ -764,13 +1346,12 @@ export async function exportRequest(context, url, output) {
764
1346
  return record.request.id;
765
1347
  }
766
1348
  export async function requestMembership(context, url, options) {
767
- if ((options.name?.length ?? 0) > 256)
768
- throw new HostError("Request name exceeds 256 characters.");
1349
+ if ("name" in options)
1350
+ throw new HostError("Set your account-wide name with ipab profile --name NAME before requesting membership.");
769
1351
  canonicalSwarmUrl(url);
770
1352
  const identity = await contextIdentity(context, true);
771
1353
  const { config } = await fetchConfig(context, url);
772
- if (options.ownerFingerprint !== (await keyId(config.owner)))
773
- throw new HostError(`Trusted Owner fingerprint required; observed ${await keyId(config.owner)}. Verify through an independent trusted channel.`);
1354
+ const personal = await ensureAccountProfile(context);
774
1355
  const dir = await directory(context);
775
1356
  await withPrivateLock(dir, async () => {
776
1357
  if (options.alias !== undefined)
@@ -795,7 +1376,7 @@ export async function requestMembership(context, url, options) {
795
1376
  configUrl: url,
796
1377
  scopeId: config.scopeId,
797
1378
  owner: config.owner,
798
- name: options.name ?? "",
1379
+ name: personal.name,
799
1380
  member: identity.publicKey,
800
1381
  encryptionKey: encryption.publicKey,
801
1382
  peerId: node.peerId,
@@ -818,14 +1399,42 @@ export async function requestMembership(context, url, options) {
818
1399
  });
819
1400
  withState(context, (state) => state.registerSwarm(url, options.alias));
820
1401
  });
821
- if (options.output)
822
- await exportRequest(context, url, options.output);
823
- return (await local(context, url)).request.id;
1402
+ const file = options.output === undefined ? undefined : resolve(options.output);
1403
+ if (file !== undefined)
1404
+ await exportRequest(context, url, file);
1405
+ const record = await local(context, url);
1406
+ return {
1407
+ requestId: record.request.id,
1408
+ ownerFingerprint: await keyId(record.owner),
1409
+ request: record.request,
1410
+ ...(file === undefined ? {} : { file }),
1411
+ };
824
1412
  }
825
1413
  export async function verifiedRequest(path) {
826
1414
  if ((await lstat(path)).size > 16 * 1024)
827
1415
  throw new HostError("Request file exceeds 16 KiB.");
828
- return verifyRequest(JSON.parse(await readFile(path, "utf8")));
1416
+ return verifiedRequestStream(createReadStream(path));
1417
+ }
1418
+ export async function verifiedRequestStream(input) {
1419
+ const chunks = [];
1420
+ let size = 0;
1421
+ for await (const chunk of input) {
1422
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
1423
+ size += bytes.byteLength;
1424
+ if (size > 16 * 1024)
1425
+ throw new HostError("Request input exceeds 16 KiB.");
1426
+ chunks.push(bytes);
1427
+ }
1428
+ let value;
1429
+ try {
1430
+ value = JSON.parse(Buffer.concat(chunks)
1431
+ .toString("utf8")
1432
+ .replace(/^\uFEFF/, ""));
1433
+ }
1434
+ catch (cause) {
1435
+ throw new HostError(`Invalid Request JSON: ${message(cause)}.`);
1436
+ }
1437
+ return verifyRequest(value);
829
1438
  }
830
1439
  async function verifyRequest(input) {
831
1440
  const fields = object(input, "Request");
@@ -940,6 +1549,7 @@ export async function approveMembership(context, input, options = {}) {
940
1549
  if (!operation.profileId)
941
1550
  operation.profileId = (await api.create(c.scopeId, {
942
1551
  name: request.name,
1552
+ description: "",
943
1553
  addresses: [],
944
1554
  updatedAt: operation.createdAt,
945
1555
  }, `${operation.operation}.profile`)).id;
@@ -956,14 +1566,15 @@ export async function approveMembership(context, input, options = {}) {
956
1566
  };
957
1567
  const config = {
958
1568
  ...fetched.config,
1569
+ v: 2,
959
1570
  members: fetched.config.members.filter((m) => m.publicKey !== request.member),
960
1571
  };
961
1572
  if (config.members.some((m) => m.peerId === request.peerId))
962
1573
  throw new HostError("PeerID is already assigned to another member.");
963
1574
  if (request.member === identity.publicKey)
964
1575
  throw new HostError("Owner cannot request member approval.");
965
- if (config.members.length >= 16)
966
- throw new HostError("Organization member limit is 16.");
1576
+ if (config.members.length >= 256)
1577
+ throw new HostError("Organization member limit is 256.");
967
1578
  const certificate = await issueScopeCertificate({
968
1579
  v: 1,
969
1580
  service: c.service,
@@ -977,9 +1588,17 @@ export async function approveMembership(context, input, options = {}) {
977
1588
  operation.baseline = fetched.variable.cid;
978
1589
  await save();
979
1590
  }
1591
+ if (operation.value.v === 2) {
1592
+ for (const member of operation.value.members) {
1593
+ if (!member.memberId) {
1594
+ Object.assign(member, await createMemberRecord(api, c.scopeId, member, `${operation.operation}.${member.publicKey}.member`));
1595
+ await save();
1596
+ }
1597
+ }
1598
+ }
980
1599
  const observed = await api.read(c.scopeId, c.configId);
981
- if (observed.cid !== (await valueCid(operation.value)))
982
- await api.write(c.scopeId, c.configId, operation.value, operation.baseline, `${operation.operation}.publish`);
1600
+ if (observed.cid !== (await valueCid(configValue(operation.value))))
1601
+ await api.write(c.scopeId, c.configId, configValue(operation.value), operation.baseline, `${operation.operation}.publish`);
983
1602
  operation.completed = true;
984
1603
  await save();
985
1604
  record.config = operation.value;
@@ -995,7 +1614,7 @@ export async function updateSwarm(context, url, changes) {
995
1614
  if (changes.name === undefined && changes.description === undefined)
996
1615
  throw new HostError("swarm update requires name or description.");
997
1616
  const fetched = await fetchConfig(context, url), config = { ...fetched.config, ...changes };
998
- const result = await client(context, c.service, identity).write(c.scopeId, c.configId, config, fetched.variable.cid, uniqueId());
1617
+ const result = await client(context, c.service, identity).write(c.scopeId, c.configId, configValue(config), fetched.variable.cid, uniqueId());
999
1618
  record.config = config;
1000
1619
  await saveLocal(context, record);
1001
1620
  return {
@@ -1006,10 +1625,12 @@ export async function updateSwarm(context, url, changes) {
1006
1625
  };
1007
1626
  }
1008
1627
  export async function updateProfile(context, url, changes) {
1009
- if (changes.name !== undefined && changes.name.length > 256)
1010
- throw new HostError("Profile name exceeds 256 characters.");
1628
+ if ("name" in changes || "description" in changes)
1629
+ throw new HostError("Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.");
1011
1630
  if ((changes.addresses?.length ?? 0) > 16)
1012
1631
  throw new HostError("Profile address limit is 16.");
1632
+ if (changes.addresses === undefined)
1633
+ throw new HostError("swarm profile requires --address MULTIADDR; use ipab profile to read personal data.");
1013
1634
  const record = await readyMembership(context, url), identity = await contextIdentity(context), c = coordinates(url);
1014
1635
  const member = record.config.members.find((m) => m.publicKey === identity.publicKey);
1015
1636
  for (const address of changes.addresses ?? [])
@@ -1088,6 +1709,7 @@ export async function resumeRemoval(context, url) {
1088
1709
  if (!record.nextConfig) {
1089
1710
  const config = {
1090
1711
  ...record.oldConfig,
1712
+ v: 2,
1091
1713
  headId: record.newHeadId,
1092
1714
  epoch: record.oldConfig.epoch + 1,
1093
1715
  members: structuredClone(record.oldConfig.members.filter((m) => m.publicKey !== record.member)),
@@ -1104,10 +1726,19 @@ export async function resumeRemoval(context, url) {
1104
1726
  write: [config.headId, member.profileId],
1105
1727
  }, await importPrivateKeyPkcs8(identity.privateKey));
1106
1728
  member.approval = await sealApproval(binding(url, config, member), { certificate, swarmKey: record.newKey }, identity);
1729
+ delete member.memberId;
1107
1730
  }
1108
1731
  record.nextConfig = config;
1109
1732
  await save();
1110
1733
  }
1734
+ if (record.nextConfig.v === 2) {
1735
+ for (const member of record.nextConfig.members) {
1736
+ if (!member.memberId) {
1737
+ Object.assign(member, await createMemberRecord(api, c.scopeId, member, `${record.operation}.${member.publicKey}.member`));
1738
+ await save();
1739
+ }
1740
+ }
1741
+ }
1111
1742
  const leaving = record.oldConfig.members.find((m) => m.publicKey === record.member);
1112
1743
  // Delete the profile before exposing the new configuration. Old HEAD stays readable until final cleanup.
1113
1744
  try {
@@ -1126,8 +1757,8 @@ export async function resumeRemoval(context, url) {
1126
1757
  }
1127
1758
  if (!record.published) {
1128
1759
  const observed = await api.read(c.scopeId, c.configId);
1129
- if (observed.cid !== (await valueCid(record.nextConfig)))
1130
- await api.write(c.scopeId, c.configId, record.nextConfig, record.configCid, `${record.operation}.config`);
1760
+ if (observed.cid !== (await valueCid(configValue(record.nextConfig))))
1761
+ await api.write(c.scopeId, c.configId, configValue(record.nextConfig), record.configCid, `${record.operation}.config`);
1131
1762
  record.published = true;
1132
1763
  await save();
1133
1764
  }
@@ -1144,6 +1775,23 @@ export async function resumeRemoval(context, url) {
1144
1775
  if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1145
1776
  throw cause;
1146
1777
  }
1778
+ for (const member of record.oldConfig.members) {
1779
+ if (member.memberId &&
1780
+ !record.nextConfig.members.some((next) => next.memberId === member.memberId)) {
1781
+ for (const action of ["freeze", "delete"]) {
1782
+ try {
1783
+ if (action === "freeze")
1784
+ await api.freeze(c.scopeId, member.memberId, `${record.operation}.${member.publicKey}.freeze`);
1785
+ else
1786
+ await api.delete(c.scopeId, member.memberId, `${record.operation}.${member.publicKey}.delete`);
1787
+ }
1788
+ catch (cause) {
1789
+ if (!(cause instanceof ScopeApiError) || cause.status !== 410)
1790
+ throw cause;
1791
+ }
1792
+ }
1793
+ }
1794
+ }
1147
1795
  record.completed = true;
1148
1796
  await save();
1149
1797
  withState(context, (state) => {
@@ -1231,7 +1879,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
1231
1879
  }
1232
1880
  if (!link)
1233
1881
  throw new HostError(`Formal Name "${shared.name}" was not found after refreshing HEAD.`);
1234
- if (warm && header === warm.header)
1882
+ if (warm && header === warm.header && !header.localSourceReady)
1235
1883
  await lazyPrivateSource(context, selected, warm.account, header.config);
1236
1884
  targetCid = link.toString();
1237
1885
  }
@@ -1240,22 +1888,149 @@ export async function resolveReference(context, reference, swarm, local, raw = f
1240
1888
  await readyMembership(context, swarm);
1241
1889
  targetCid = local(reference);
1242
1890
  }
1891
+ const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
1892
+ return { targetCid, cid };
1893
+ }
1894
+ async function artifactValue(store, targetCid, protect) {
1243
1895
  let cid = targetCid;
1244
1896
  const visited = new Set();
1245
- for (let depth = 0; !raw; depth++) {
1897
+ for (let depth = 0;; depth++) {
1246
1898
  if (depth >= 64 || visited.has(cid))
1247
1899
  throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
1248
1900
  visited.add(cid);
1901
+ await protect?.(cid);
1249
1902
  const bundle = await openBundle(CID.parse(cid), {
1250
- resolveCid: (cid) => context.store.block.get(cid.toString()),
1903
+ resolveCid: (cid) => store.block.get(cid.toString()),
1251
1904
  });
1252
1905
  if (bundle.schemaKey !== (await encodeSchema(artifactType)).cid.toString())
1253
1906
  break;
1254
- cid = CID.parse(parseArtifact(await typedJson(context.store, cid, artifactType)).value)
1907
+ cid = CID.parse(parseArtifact(await typedJson(store, cid, artifactType)).value)
1255
1908
  .toV1()
1256
1909
  .toString();
1257
1910
  }
1258
- return { targetCid, cid };
1911
+ return cid;
1912
+ }
1913
+ export function pinReference(state, reference, selected) {
1914
+ const shared = parseNameReference(reference);
1915
+ if (!shared)
1916
+ return { reference: exactCid(reference) };
1917
+ const swarm = shared.swarm ? state.resolveSwarm(shared.swarm) : selected;
1918
+ if (!swarm)
1919
+ throw new HostError("Pinning a shared Name requires --swarm or swarm use, or a Swarm authority in the IPAB URI.");
1920
+ return {
1921
+ reference: formatNameReference(swarm, shared.name),
1922
+ swarm,
1923
+ name: shared.name,
1924
+ };
1925
+ }
1926
+ export async function pinNameSubscription(context, reference, selected) {
1927
+ const canonical = withState(context, (state) => pinReference(state, reference, selected));
1928
+ if (!canonical.swarm || !canonical.name) {
1929
+ let roots;
1930
+ try {
1931
+ roots = [
1932
+ ...(await currentDependencies(context.store, canonical.reference)),
1933
+ ];
1934
+ }
1935
+ catch (cause) {
1936
+ if (!selected || !missingContent(cause))
1937
+ throw cause;
1938
+ const swarm = withState(context, (state) => state.resolveSwarm(selected));
1939
+ await readyMembership(context, swarm);
1940
+ roots = [
1941
+ ...(await currentDependencies(context.store, canonical.reference)),
1942
+ ];
1943
+ }
1944
+ return withStateAsync(context, (state) => pinCid(state, canonical.reference, context.store, roots));
1945
+ }
1946
+ const resolved = await resolveReference(context, canonical.reference, canonical.swarm, exactCid, false, "local-first");
1947
+ const roots = await currentDependencies(context.store, resolved.targetCid);
1948
+ const pin = withState(context, (state) => reservePin(state, canonical.reference, context.store.configuration, {
1949
+ swarm: canonical.swarm,
1950
+ name: canonical.name,
1951
+ }));
1952
+ return withStateAsync(context, (state) => retainPin(state, pin, context.store, { ...resolved, roots: [...roots] }));
1953
+ }
1954
+ async function withStateAsync(context, operation) {
1955
+ if (context.state)
1956
+ return operation(context.state);
1957
+ const state = new State(context.stateDir);
1958
+ try {
1959
+ return await operation(state);
1960
+ }
1961
+ finally {
1962
+ state.close();
1963
+ }
1964
+ }
1965
+ export async function refreshNamePins(context, url, header) {
1966
+ const pins = withState(context, (state) => state
1967
+ .contentPins()
1968
+ .filter((pin) => pin.swarm === url && pin.status !== "deleting"));
1969
+ const failures = [];
1970
+ for (const saved of pins) {
1971
+ const target = Object.hasOwn(header.snapshot.names, saved.name)
1972
+ ? header.snapshot.names[saved.name].toString()
1973
+ : undefined;
1974
+ if (!target) {
1975
+ withState(context, (state) => {
1976
+ failedPin(state, saved.reference, new Error("Shared Name is missing; keeping its last verified version."), true);
1977
+ });
1978
+ context.diagnostic?.(`Pin ${saved.reference} is missing; its last verified version remains retained.`);
1979
+ continue;
1980
+ }
1981
+ let claimed = false;
1982
+ try {
1983
+ // A cached HEAD can differ from the saved subscription after publication or a failed refresh.
1984
+ if (saved.targetCid === target &&
1985
+ saved.status === "ready" &&
1986
+ saved.freshness === "current")
1987
+ continue;
1988
+ const pin = withState(context, (state) => refreshPinClaim(state, saved));
1989
+ if (!pin)
1990
+ continue;
1991
+ claimed = true;
1992
+ const cid = await artifactValue(context.store, target);
1993
+ const roots = [...(await currentDependencies(context.store, target))];
1994
+ await withStateAsync(context, (state) => retainPin(state, pin, context.store, { cid, targetCid: target, roots }));
1995
+ }
1996
+ catch (cause) {
1997
+ if (claimed)
1998
+ withState(context, (state) => {
1999
+ failedPin(state, saved.reference, cause);
2000
+ });
2001
+ failures.push(`${saved.reference}: ${message(cause)}`);
2002
+ }
2003
+ }
2004
+ if (failures.length)
2005
+ throw new HostError(`Name subscription refresh failed; prior verified versions remain retained:\n${failures.join("\n")}`, 1, "PIN_STALE");
2006
+ }
2007
+ async function currentDependencies(store, root, found = new Set()) {
2008
+ if (found.has(root))
2009
+ return found;
2010
+ if (found.size >= 64)
2011
+ throw new HostError("Current pin dependency limit exceeded.");
2012
+ found.add(root);
2013
+ const bundle = await openBundle(CID.parse(root), {
2014
+ resolveCid: (cid) => store.block.get(cid.toString()),
2015
+ });
2016
+ if (bundle.schemaKey === (await encodeSchema(artifactType)).cid.toString()) {
2017
+ await currentDependencies(store, parseArtifact(await typedJson(store, root, artifactType)).value, found);
2018
+ }
2019
+ else if (bundle.schemaKey === appSchemaCid.toString()) {
2020
+ const app = object((await bundleJson(store, root)).value, "App");
2021
+ if (app.source) {
2022
+ const source = object(app.source, "source");
2023
+ if (typeof source.cid !== "string")
2024
+ throw new HostError("Invalid App source association.");
2025
+ await currentDependencies(store, source.cid, found);
2026
+ }
2027
+ }
2028
+ else if (isSwarmStateSchema(bundle.schemaKey)) {
2029
+ const snapshot = await readState(store, CID.parse(root));
2030
+ for (const target of Object.values(snapshot.names))
2031
+ await currentDependencies(store, target.toString(), found);
2032
+ }
2033
+ return found;
1259
2034
  }
1260
2035
  export async function searchNames(context, query, swarms) {
1261
2036
  if (!query ||
@@ -1266,7 +2041,7 @@ export async function searchNames(context, query, swarms) {
1266
2041
  const searched = [];
1267
2042
  for (const swarm of swarms) {
1268
2043
  const header = (await localHeader(context, swarm.cid))?.header ??
1269
- (await swarmHeader(context, swarm.cid));
2044
+ (await swarmHeader(context, swarm.cid, context.forceRefresh, "local-first"));
1270
2045
  searched.push({
1271
2046
  configUrl: swarm.cid,
1272
2047
  source: header.source,
@@ -1274,18 +2049,359 @@ export async function searchNames(context, query, swarms) {
1274
2049
  valueCid: header.head.cid,
1275
2050
  verifiedAt: header.verifiedAt,
1276
2051
  });
1277
- for (const name of Object.keys(header.snapshot.names).sort())
1278
- if (name.toLowerCase().includes(query.toLowerCase()))
1279
- matches.push({
1280
- swarm: swarm.cid,
1281
- alias: swarm.alias,
1282
- name,
1283
- reference: formatNameReference(swarm.cid, name),
1284
- targetCid: header.snapshot.names[name].toString(),
1285
- });
2052
+ for (const { name, targetCid } of withState(context, (state) => state.searchSwarmNames(headerProjection(header), query)))
2053
+ matches.push({
2054
+ swarm: swarm.cid,
2055
+ alias: swarm.alias,
2056
+ name,
2057
+ reference: formatNameReference(swarm.cid, name),
2058
+ targetCid,
2059
+ });
1286
2060
  }
1287
2061
  return { matches, swarms: searched };
1288
2062
  }
2063
+ function assertNamesRegistry(snapshot) {
2064
+ if (Object.keys(snapshot.registrations ?? {}).length)
2065
+ throw new HostError("Legacy shared registrations are inactive; per-association argv is unsupported and has not been dropped or migrated. Create a new seeded Swarm and explicitly register intended Apps there. Old Swarm content and history remain readable.");
2066
+ }
2067
+ export async function swarmMeta(context, header) {
2068
+ if (header.snapshot.stateBundle)
2069
+ return header.snapshot.stateBundle.meta;
2070
+ const cid = header.snapshot.names.ipab;
2071
+ if (!cid)
2072
+ throw new HostError('Swarm Meta Name "ipab" is missing. Create a new seeded Swarm or explicitly publish a typed Swarm Meta Bundle; existing Swarms are never automatically upgraded.');
2073
+ try {
2074
+ const bundle = await openBundle(cid, {
2075
+ resolveCid: (key) => context.store.block.get(key.toString()),
2076
+ });
2077
+ const type = bundle.schemaKey === legacySwarmMetaSchema.cid.toString()
2078
+ ? legacySwarmMetaType
2079
+ : swarmMetaType;
2080
+ return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
2081
+ }
2082
+ catch (cause) {
2083
+ throw new HostError(`Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`);
2084
+ }
2085
+ }
2086
+ function metaCid(snapshot) {
2087
+ return snapshot.stateBundle?.cid ?? snapshot.names.ipab.toString();
2088
+ }
2089
+ function hasMeta(snapshot) {
2090
+ return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
2091
+ }
2092
+ export async function swarmSkills(context, configUrl, requested, owner) {
2093
+ const warm = await localHeader(context, configUrl);
2094
+ if (warm && !warm.header.localSourceReady)
2095
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2096
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
2097
+ const roots = new Set();
2098
+ const protect = async (cid) => {
2099
+ roots.add(cid);
2100
+ const values = [...roots];
2101
+ context.store.registerOwner(owner, values);
2102
+ await context.store.retain(owner, values);
2103
+ await context.store.confirmRetained(owner, values);
2104
+ };
2105
+ for (let attempt = 0;; attempt++) {
2106
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
2107
+ header = await swarmHeader(context, configUrl, true);
2108
+ continue;
2109
+ }
2110
+ if (hasMeta(header.snapshot))
2111
+ await protect(metaCid(header.snapshot));
2112
+ const meta = await swarmMeta(context, header);
2113
+ if (!meta.skillPath)
2114
+ throw new HostError(header.snapshot.stateBundle
2115
+ ? "This Swarm uses the earlier exact State Bundle type without skillPath. There is no in-place root-configuration migration command. Create a new seeded Swarm and explicitly republish reviewed Names. Publishing a user Name ipab never overrides root configuration; upgrades never rewrite it."
2116
+ : `This Swarm uses the legacy exact Meta type without skillPath. Explicitly build and publish a new typed Meta Bundle with templatePath and registryPath preserved and skillPath chosen, then run ipab publish ipab META_SOURCE --expect ${metaCid(header.snapshot)}. Upgrades never overwrite Meta.`);
2117
+ const prefix = `${meta.skillPath}/`;
2118
+ const entries = Object.entries(header.snapshot.names).filter(([name]) => name.startsWith(prefix));
2119
+ for (const [, target] of entries)
2120
+ roots.add(target.toString());
2121
+ context.store.registerOwner(owner, [...roots]);
2122
+ const result = [];
2123
+ const identities = new Set();
2124
+ for (const [name, target] of entries.sort(([a], [b]) => a.localeCompare(b))) {
2125
+ if (name.slice(prefix.length).includes("/"))
2126
+ throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
2127
+ const cid = await artifactValue(context.store, target.toString(), protect);
2128
+ const bundle = await openBundle(CID.parse(cid), {
2129
+ resolveCid: (key) => context.store.block.get(key.toString()),
2130
+ });
2131
+ if (bundle.schemaKey !== skillSchema.cid.toString())
2132
+ throw new HostError(`Name "${name}" is not an exact Skill type Bundle.`);
2133
+ const identity = await skillIdentity(bundle);
2134
+ if (identities.has(identity))
2135
+ throw new HostError(`Duplicate Skill installation name "${identity}" in this Swarm.`);
2136
+ identities.add(identity);
2137
+ result.push({ name, cid, identity });
2138
+ }
2139
+ const missing = requested.filter((reference) => !result.some((skill) => skill.name === reference || skill.identity === reference));
2140
+ if (missing.length && !attempt && header.source === "cache") {
2141
+ header = await swarmHeader(context, configUrl, true);
2142
+ continue;
2143
+ }
2144
+ if (missing.length)
2145
+ throw new HostError(`Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`);
2146
+ return result;
2147
+ }
2148
+ }
2149
+ export async function resolveTemplateSelector(context, selector, configUrl) {
2150
+ formalName(selector);
2151
+ const warm = await localHeader(context, configUrl);
2152
+ if (warm && !warm.header.localSourceReady)
2153
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2154
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
2155
+ if (!hasMeta(header.snapshot) && header.source === "cache")
2156
+ header = await swarmHeader(context, configUrl, true);
2157
+ for (let attempt = 0;; attempt++) {
2158
+ const meta = await swarmMeta(context, header);
2159
+ const name = formalName(`${meta.templatePath}/${selector}`);
2160
+ const target = header.snapshot.names[name];
2161
+ if (target)
2162
+ return artifactValue(context.store, target.toString());
2163
+ if (attempt || header.source !== "cache")
2164
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
2165
+ header = await swarmHeader(context, configUrl, true);
2166
+ }
2167
+ }
2168
+ export function templateName(name) {
2169
+ if (name.includes(":"))
2170
+ throw new HostError("Template NAME must be a safe relative Name, not a URI.");
2171
+ return formalName(name);
2172
+ }
2173
+ async function templateEntry(context, configUrl, header, selector) {
2174
+ const meta = await swarmMeta(context, header);
2175
+ const name = formalName(`${meta.templatePath}/${templateName(selector)}`);
2176
+ const target = header.snapshot.names[name];
2177
+ if (!target)
2178
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
2179
+ const targetCid = target.toString();
2180
+ return {
2181
+ swarm: configUrl,
2182
+ templatePath: meta.templatePath,
2183
+ metaCid: metaCid(header.snapshot),
2184
+ name,
2185
+ selector,
2186
+ reference: formatNameReference(configUrl, name),
2187
+ targetCid,
2188
+ ...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
2189
+ };
2190
+ }
2191
+ export async function swarmTemplates(context, configUrl, selector) {
2192
+ if (selector !== undefined)
2193
+ templateName(selector);
2194
+ const warm = await localHeader(context, configUrl);
2195
+ if (warm && !warm.header.localSourceReady)
2196
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2197
+ let header = warm?.header ??
2198
+ (await swarmHeader(context, configUrl, undefined, "local-first"));
2199
+ for (let attempt = 0;; attempt++) {
2200
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
2201
+ header = await swarmHeader(context, configUrl, true, "local-first");
2202
+ continue;
2203
+ }
2204
+ const meta = await swarmMeta(context, header);
2205
+ const name = selector === undefined
2206
+ ? undefined
2207
+ : formalName(`${meta.templatePath}/${selector}`);
2208
+ if (name &&
2209
+ !header.snapshot.names[name] &&
2210
+ header.source === "cache" &&
2211
+ !attempt) {
2212
+ header = await swarmHeader(context, configUrl, true, "local-first");
2213
+ continue;
2214
+ }
2215
+ const selectors = selector === undefined
2216
+ ? Object.keys(header.snapshot.names)
2217
+ .filter((key) => key.startsWith(`${meta.templatePath}/`))
2218
+ .map((key) => key.slice(meta.templatePath.length + 1))
2219
+ .sort((a, b) => a.localeCompare(b))
2220
+ : [selector];
2221
+ const items = [];
2222
+ for (const item of selectors)
2223
+ items.push(await templateEntry(context, configUrl, header, item));
2224
+ return items;
2225
+ }
2226
+ }
2227
+ export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
2228
+ templateName(selector);
2229
+ await pointer(context, configUrl);
2230
+ const content = await templatePublicationSource(source, context.store);
2231
+ const details = await inspectTemplate(context.store, content);
2232
+ let location;
2233
+ const targetCid = await publishContent(context, content, {
2234
+ swarm: configUrl,
2235
+ name: selector,
2236
+ ...(expect === undefined ? {} : { expect }),
2237
+ }, async (current) => {
2238
+ const meta = await swarmMeta(context, { snapshot: current });
2239
+ const name = formalName(`${meta.templatePath}/${selector}`);
2240
+ location = {
2241
+ name,
2242
+ templatePath: meta.templatePath,
2243
+ metaCid: metaCid(current),
2244
+ };
2245
+ return name;
2246
+ });
2247
+ return {
2248
+ swarm: configUrl,
2249
+ ...location,
2250
+ selector,
2251
+ reference: formatNameReference(configUrl, location.name),
2252
+ targetCid,
2253
+ ...details,
2254
+ };
2255
+ }
2256
+ export async function removeSwarmTemplate(context, configUrl, selector, expect) {
2257
+ templateName(selector);
2258
+ const expected = exactCid(expect);
2259
+ const head = await pointer(context, configUrl);
2260
+ let basis;
2261
+ for (let attempt = 0; attempt < 8; attempt++) {
2262
+ const currentHead = await head.read();
2263
+ const current = await readSnapshot(context.store, currentHead.root);
2264
+ const meta = await swarmMeta(context, { snapshot: current });
2265
+ const name = formalName(`${meta.templatePath}/${selector}`);
2266
+ if (basis !== undefined && basis !== name)
2267
+ throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
2268
+ basis = name;
2269
+ const old = current.names[name]?.toString();
2270
+ if (!old)
2271
+ throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
2272
+ if (old !== expected)
2273
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
2274
+ const names = { ...current.names };
2275
+ delete names[name];
2276
+ const next = await prepareNamesPublication(context, configUrl, currentHead.root, current, names, []);
2277
+ try {
2278
+ await head.write(next, currentHead.cid, uniqueId());
2279
+ }
2280
+ catch (cause) {
2281
+ if (cause instanceof ScopeApiError && cause.status === 412)
2282
+ continue;
2283
+ throw new HostError(`Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
2284
+ }
2285
+ try {
2286
+ await swarmHeader(context, configUrl, true);
2287
+ }
2288
+ catch (cause) {
2289
+ throw new HostError(`Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
2290
+ }
2291
+ return {
2292
+ swarm: configUrl,
2293
+ templatePath: meta.templatePath,
2294
+ metaCid: metaCid(current),
2295
+ selector,
2296
+ name,
2297
+ reference: formatNameReference(configUrl, name),
2298
+ targetCid: old,
2299
+ };
2300
+ }
2301
+ throw new HostError("HEAD is busy; retry the template removal.");
2302
+ }
2303
+ async function registryAssociations(context, header) {
2304
+ assertNamesRegistry(header.snapshot);
2305
+ const meta = await swarmMeta(context, header);
2306
+ const prefix = `${meta.registryPath}/`;
2307
+ const result = [];
2308
+ for (const [name, cid] of Object.entries(header.snapshot.names)) {
2309
+ if (!name.startsWith(prefix))
2310
+ continue;
2311
+ const schemaCid = name.slice(prefix.length);
2312
+ if (exactCid(schemaCid, true) !== schemaCid)
2313
+ throw new HostError(`Registry Name "${name}" must end in an exact canonical type CID.`);
2314
+ result.push(createAssociation(schemaCid, cid.toString(), ["%"]));
2315
+ }
2316
+ return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
2317
+ }
2318
+ export async function swarmRegistrations(context, configUrl) {
2319
+ let header = await swarmHeader(context, configUrl);
2320
+ if (!hasMeta(header.snapshot) && header.source === "cache")
2321
+ header = await swarmHeader(context, configUrl, true);
2322
+ return registryAssociations(context, header);
2323
+ }
2324
+ export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
2325
+ const warm = mode === "local-first" ? await localHeader(context, configUrl) : undefined;
2326
+ if (warm && !warm.header.localSourceReady)
2327
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2328
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
2329
+ if (!hasMeta(header.snapshot) && header.source === "cache")
2330
+ header = await swarmHeader(context, configUrl, true);
2331
+ let association = (await registryAssociations(context, header)).find((item) => item.schemaCid === schemaCid);
2332
+ if (!association && header.source === "cache") {
2333
+ header = await swarmHeader(context, configUrl, true);
2334
+ association = (await registryAssociations(context, header)).find((item) => item.schemaCid === schemaCid);
2335
+ }
2336
+ return association;
2337
+ }
2338
+ async function prepareNamesPublication(context, configUrl, previousRoot, current, names, roots, retainedRoots) {
2339
+ const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }), previousRoot);
2340
+ const closure = await publicationClosure(context.store, next, false);
2341
+ await provideContent(context.store, [...new Set([...closure.provided, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...closure.nameTargets, ...(retainedRoots ?? roots)])]);
2342
+ withState(context, (state) => {
2343
+ state.invalidateSwarmHeader(configUrl);
2344
+ });
2345
+ return next;
2346
+ }
2347
+ async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
2348
+ const head = await pointer(context, configUrl);
2349
+ if (association) {
2350
+ const app = await openBundle(CID.parse(association.appCid), {
2351
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
2352
+ });
2353
+ if (app.schemaKey !== appSchemaCid.toString())
2354
+ throw new HostError("Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.");
2355
+ }
2356
+ const roots = association
2357
+ ? await dependencies(context.store, association.appCid)
2358
+ : new Set();
2359
+ for (let attempt = 0; attempt < 8; attempt++) {
2360
+ const currentHead = await head.read();
2361
+ const current = await readSnapshot(context.store, currentHead.root);
2362
+ assertNamesRegistry(current);
2363
+ const meta = await swarmMeta(context, { snapshot: current });
2364
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
2365
+ const oldCid = current.names[name]?.toString();
2366
+ if (association) {
2367
+ if (oldCid === association.appCid)
2368
+ return;
2369
+ if (oldCid && !replace)
2370
+ throw new HostError("Schema has another association; use --replace.");
2371
+ }
2372
+ else if (!oldCid) {
2373
+ throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
2374
+ }
2375
+ const names = { ...current.names };
2376
+ if (association)
2377
+ names[name] = CID.parse(association.appCid);
2378
+ else
2379
+ delete names[name];
2380
+ const next = await prepareNamesPublication(context, configUrl, currentHead.root, current, names, roots);
2381
+ try {
2382
+ await head.write(next, currentHead.cid, uniqueId());
2383
+ return;
2384
+ }
2385
+ catch (cause) {
2386
+ if (!(cause instanceof ScopeApiError) || cause.status !== 412)
2387
+ throw new HostError(`Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
2388
+ continue;
2389
+ }
2390
+ }
2391
+ throw new HostError(`HEAD is busy for ${configUrl}; retry the registry edit.`);
2392
+ }
2393
+ export async function setSwarmAssociation(context, configUrl, value, replace = false) {
2394
+ if (value.argv.length !== 1 || value.argv[0] !== "%")
2395
+ throw new HostError('Custom per-association argv is unsupported. Apps opened through the registry receive only the content CID (whole "%" argument); adapt the App or use ipab exec APP_CID ARGS.');
2396
+ const association = createAssociation(value.schemaCid, value.appCid, value.argv);
2397
+ await editSwarmAssociation(context, configUrl, association.schemaCid, association, replace);
2398
+ return association;
2399
+ }
2400
+ export async function removeSwarmAssociation(context, configUrl, schemaCid) {
2401
+ const schema = exactCid(schemaCid, true);
2402
+ await editSwarmAssociation(context, configUrl, schema, undefined, false);
2403
+ return schema;
2404
+ }
1289
2405
  async function dependencies(store, root, found = new Set()) {
1290
2406
  if (found.has(root))
1291
2407
  return found;
@@ -1310,49 +2426,71 @@ async function dependencies(store, root, found = new Set()) {
1310
2426
  await dependencies(store, source.cid, found);
1311
2427
  }
1312
2428
  }
2429
+ else if (isSwarmStateSchema(bundle.schemaKey)) {
2430
+ const snapshot = await readState(store, CID.parse(root));
2431
+ for (const target of Object.values(snapshot.names))
2432
+ await dependencies(store, target.toString(), found);
2433
+ }
1313
2434
  return found;
1314
2435
  }
1315
2436
  export async function frozenPublicationClosure(store, root) {
1316
- const publications = new Set(), content = new Set();
2437
+ return (await publicationClosure(store, root)).provided;
2438
+ }
2439
+ async function publicationClosure(store, root, includeDependencies = true) {
2440
+ const publications = new Set(), content = new Set(), nameTargets = new Set();
1317
2441
  let current = root;
1318
2442
  while (current !== undefined) {
1319
2443
  if (publications.has(current) || publications.size >= 256)
1320
2444
  throw new HostError("Frozen publication history exceeds limits or contains a cycle.");
1321
2445
  publications.add(current);
1322
2446
  const publication = await readPublication(store, current);
1323
- const snapshot = decodeSnapshot(await store.block.get(publication.state.toString()));
1324
- for (const target of Object.values(snapshot.names))
1325
- await dependencies(store, target.toString(), content);
2447
+ const snapshot = await readState(store, publication.state);
2448
+ for (const target of Object.values(snapshot.names)) {
2449
+ nameTargets.add(target.toString());
2450
+ if (includeDependencies)
2451
+ await dependencies(store, target.toString(), content);
2452
+ else
2453
+ content.add(target.toString());
2454
+ }
2455
+ if (includeDependencies)
2456
+ for (const association of Object.values(snapshot.registrations ?? {}))
2457
+ await dependencies(store, association.appCid.toString(), content);
1326
2458
  current = publication.previous?.toString();
1327
2459
  }
1328
- return [
1329
- root,
1330
- ...[...new Set([...publications, ...content])]
1331
- .filter((cid) => cid !== root)
1332
- .sort(),
1333
- ];
2460
+ return {
2461
+ nameTargets,
2462
+ provided: [
2463
+ root,
2464
+ ...[...new Set([...publications, ...content])]
2465
+ .filter((cid) => cid !== root)
2466
+ .sort(),
2467
+ ],
2468
+ };
1334
2469
  }
1335
2470
  export async function publish(context, content, options) {
2471
+ return publishContent(context, content, options);
2472
+ }
2473
+ async function publishContent(context, content, options, nameForSnapshot) {
1336
2474
  if (!options.swarm)
1337
2475
  throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
1338
2476
  const head = await pointer(context, options.swarm);
1339
2477
  const roots = await dependencies(context.store, content);
1340
- if (!options.name) {
1341
- if (options.expect || options.snapshot)
1342
- throw new HostError("--expect/--snapshot require --name.");
1343
- await head.read();
1344
- await provideContent(context.store, [...roots], context.node.api, context.fetch, context.node.auth);
1345
- return content;
1346
- }
1347
- const name = formalName(options.name);
2478
+ const currentRoots = [...(await currentDependencies(context.store, content))];
2479
+ await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
2480
+ let name = formalName(options.name);
2481
+ let resolvedName;
1348
2482
  if (options.snapshot && options.expect)
1349
2483
  throw new HostError("Snapshots cannot replace an occupied Name.");
1350
2484
  const expected = options.expect
1351
2485
  ? CID.parse(options.expect).toV1().toString()
1352
2486
  : undefined;
1353
- if (expected)
1354
- parseArtifact(await typedJson(context.store, expected, artifactType));
1355
- const candidate = options.snapshot
2487
+ const contentBundle = await openBundle(CID.parse(content), {
2488
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
2489
+ });
2490
+ const direct = contentBundle.schemaKey === appSchemaCid.toString() ||
2491
+ contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
2492
+ contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
2493
+ const candidate = options.snapshot || direct
1356
2494
  ? content
1357
2495
  : await jsonBundle(context.store, artifactType, {
1358
2496
  value: content,
@@ -1365,26 +2503,32 @@ export async function publish(context, content, options) {
1365
2503
  roots.add(root);
1366
2504
  for (let attempt = 0; attempt < 8; attempt++) {
1367
2505
  const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root);
2506
+ if (nameForSnapshot) {
2507
+ name = await nameForSnapshot(current);
2508
+ if (resolvedName !== undefined && resolvedName !== name)
2509
+ throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
2510
+ resolvedName = name;
2511
+ }
1368
2512
  if ((Object.hasOwn(current.names, name)
1369
2513
  ? current.names[name]?.toString()
1370
2514
  : undefined) !== expected)
1371
- throw new HostError(`Edit conflict for ${name}; candidate ${candidate} remains retained. Choose an explicit baseline.`, 3, "EDIT_CONFLICT", "publication");
1372
- const next = await publication(context.store, await writeSnapshot(context.store, {
1373
- ...current,
1374
- names: { ...current.names, [name]: CID.parse(candidate) },
1375
- }), currentHead.root);
1376
- await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth);
1377
- withState(context, (state) => {
1378
- state.invalidateSwarmHeader(options.swarm);
1379
- });
2515
+ throw new HostError(`Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_CID (the old Artifact CID when applicable); inspect the current Name before retrying.`, 3, "EDIT_CONFLICT", "publication");
2516
+ const next = await prepareNamesPublication(context, options.swarm, currentHead.root, current, { ...current.names, [name]: CID.parse(candidate) }, roots, expected ? await dependencies(context.store, expected) : []);
1380
2517
  try {
1381
2518
  await head.write(next, currentHead.cid, uniqueId());
1382
- return candidate;
1383
2519
  }
1384
2520
  catch (cause) {
1385
2521
  if (!(cause instanceof ScopeApiError) || cause.status !== 412)
1386
2522
  throw new HostError(`HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
2523
+ continue;
2524
+ }
2525
+ try {
2526
+ await swarmHeader(context, options.swarm, true);
2527
+ }
2528
+ catch (cause) {
2529
+ throw new HostError(`Publication committed as ${candidate}, but its HEAD/subscription refresh failed: ${message(cause)}. Published content remains pinned; inspect HEAD and retry the affected Name pin.`, 1, "PIN_STALE", "publication");
1387
2530
  }
2531
+ return candidate;
1388
2532
  }
1389
2533
  throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
1390
2534
  }