@ipab/cli 0.1.0-rc.10 → 0.1.0-rc.12

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 (118) hide show
  1. package/README.md +24 -11
  2. package/dist/authoring.d.ts +7 -0
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +85 -5
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/builtins/skill.ipab.car +0 -0
  7. package/dist/builtins/template.bundle-viewer.car +0 -0
  8. package/dist/builtins/template.check.car +0 -0
  9. package/dist/builtins/template.node.car +0 -0
  10. package/dist/builtins/template.web-app.car +0 -0
  11. package/dist/bundled-skills.d.ts +1 -1
  12. package/dist/cli.d.ts +2 -1
  13. package/dist/cli.d.ts.map +1 -1
  14. package/dist/cli.js +904 -183
  15. package/dist/cli.js.map +1 -1
  16. package/dist/config-secret.js +1 -1
  17. package/dist/config-secret.js.map +1 -1
  18. package/dist/config.d.ts +4 -0
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +17 -2
  21. package/dist/config.js.map +1 -1
  22. package/dist/daemon-ui.d.ts +1 -0
  23. package/dist/daemon-ui.d.ts.map +1 -1
  24. package/dist/daemon-ui.js +2 -0
  25. package/dist/daemon-ui.js.map +1 -1
  26. package/dist/doctor.d.ts.map +1 -1
  27. package/dist/doctor.js +7 -3
  28. package/dist/doctor.js.map +1 -1
  29. package/dist/get.d.ts.map +1 -1
  30. package/dist/get.js +1 -1
  31. package/dist/get.js.map +1 -1
  32. package/dist/history.d.ts +3 -1
  33. package/dist/history.d.ts.map +1 -1
  34. package/dist/history.js +16 -1
  35. package/dist/history.js.map +1 -1
  36. package/dist/kubo-topology.d.ts +2 -0
  37. package/dist/kubo-topology.d.ts.map +1 -1
  38. package/dist/kubo-topology.js +17 -20
  39. package/dist/kubo-topology.js.map +1 -1
  40. package/dist/kubo.d.ts +5 -3
  41. package/dist/kubo.d.ts.map +1 -1
  42. package/dist/kubo.js +83 -13
  43. package/dist/kubo.js.map +1 -1
  44. package/dist/name-reference.d.ts +8 -0
  45. package/dist/name-reference.d.ts.map +1 -0
  46. package/dist/name-reference.js +63 -0
  47. package/dist/name-reference.js.map +1 -0
  48. package/dist/pivot-rpc.d.ts +37 -2
  49. package/dist/pivot-rpc.d.ts.map +1 -1
  50. package/dist/pivot-rpc.js +188 -8
  51. package/dist/pivot-rpc.js.map +1 -1
  52. package/dist/search-index.d.ts.map +1 -1
  53. package/dist/search-index.js +1 -0
  54. package/dist/search-index.js.map +1 -1
  55. package/dist/skill-definition.d.ts +9 -0
  56. package/dist/skill-definition.d.ts.map +1 -1
  57. package/dist/skill-definition.js +26 -2
  58. package/dist/skill-definition.js.map +1 -1
  59. package/dist/skill-source.d.ts +1 -0
  60. package/dist/skill-source.d.ts.map +1 -1
  61. package/dist/skill-source.js +10 -4
  62. package/dist/skill-source.js.map +1 -1
  63. package/dist/skills.d.ts +9 -3
  64. package/dist/skills.d.ts.map +1 -1
  65. package/dist/skills.js +31 -2
  66. package/dist/skills.js.map +1 -1
  67. package/dist/state.d.ts +20 -0
  68. package/dist/state.d.ts.map +1 -1
  69. package/dist/state.js +87 -3
  70. package/dist/state.js.map +1 -1
  71. package/dist/swarm-fs-core.d.ts +217 -0
  72. package/dist/swarm-fs-core.d.ts.map +1 -0
  73. package/dist/swarm-fs-core.js +885 -0
  74. package/dist/swarm-fs-core.js.map +1 -0
  75. package/dist/swarm-fs-path.d.ts +17 -0
  76. package/dist/swarm-fs-path.d.ts.map +1 -0
  77. package/dist/swarm-fs-path.js +46 -0
  78. package/dist/swarm-fs-path.js.map +1 -0
  79. package/dist/swarm-fs.d.ts +9 -0
  80. package/dist/swarm-fs.d.ts.map +1 -0
  81. package/dist/swarm-fs.js +21 -0
  82. package/dist/swarm-fs.js.map +1 -0
  83. package/dist/swarm-observations.d.ts +6 -0
  84. package/dist/swarm-observations.d.ts.map +1 -1
  85. package/dist/swarm-observations.js +28 -8
  86. package/dist/swarm-observations.js.map +1 -1
  87. package/dist/swarm.d.ts +192 -17
  88. package/dist/swarm.d.ts.map +1 -1
  89. package/dist/swarm.js +1360 -442
  90. package/dist/swarm.js.map +1 -1
  91. package/dist/unixfs-tree.d.ts +55 -0
  92. package/dist/unixfs-tree.d.ts.map +1 -1
  93. package/dist/unixfs-tree.js +361 -2
  94. package/dist/unixfs-tree.js.map +1 -1
  95. package/package.json +5 -5
  96. package/src/authoring.ts +125 -8
  97. package/src/cli.ts +1215 -281
  98. package/src/config-secret.ts +1 -1
  99. package/src/config.ts +20 -2
  100. package/src/daemon-ui.ts +3 -0
  101. package/src/doctor.ts +12 -2
  102. package/src/get.ts +2 -1
  103. package/src/history.ts +26 -1
  104. package/src/kubo-topology.ts +25 -22
  105. package/src/kubo.ts +127 -9
  106. package/src/name-reference.ts +91 -0
  107. package/src/pivot-rpc.ts +272 -14
  108. package/src/search-index.ts +1 -0
  109. package/src/skill-definition.ts +45 -3
  110. package/src/skill-source.ts +10 -4
  111. package/src/skills.ts +43 -2
  112. package/src/state.ts +117 -2
  113. package/src/swarm-fs-core.ts +1461 -0
  114. package/src/swarm-fs-path.ts +68 -0
  115. package/src/swarm-fs.ts +104 -0
  116. package/src/swarm-observations.ts +40 -14
  117. package/src/swarm.ts +1950 -727
  118. package/src/unixfs-tree.ts +447 -2
package/dist/swarm.js CHANGED
@@ -16,21 +16,25 @@ import { ContentError, GatewayReadError, IpfsStore } from "@ipab/ipfs-store";
16
16
  import { ScopeClient, ScopeApiError, RESOURCE_ID_PATTERN, issueScopeCertificate, signScopeWriteReceipt, uniqueId, verifyScopeCertificate, valueCid, parseVariableUpdate, } from "@ipab/bundle/pointer/scope";
17
17
  import { canonicalService, isCanonicalPublicKey, POINTER_ID_PATTERN, } from "@ipab/bundle/pointer/protocol";
18
18
  import { importPrivateKeyPkcs8, importPublicKeyRaw, keyId, signEd25519, verifyEd25519, } from "@ipab/bundle/pointer/crypto";
19
- import { HostError, object, message } from "./errors.js";
19
+ import { HostError, object, message, syntax } from "./errors.js";
20
20
  import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
21
21
  import { nodeError } from "./authoring.js";
22
- import { swarmUrl as canonicalSwarmUrl } from "./config.js";
23
- import { bundleJson, contentCar, provideContent, provideShallowContent, } from "./content-provider.js";
24
- import { deleteUnixfsPath, listUnixfsDirectory, resolveUnixfsPath, setUnixfsPath, walkUnixfsNames, } from "./unixfs-tree.js";
22
+ import { LOCAL_SWARM_ALIAS, LOCAL_SWARM_URL, isLocalSwarm, isReservedLocalHost, swarmUrl as canonicalSwarmUrl, } from "./config.js";
23
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
24
+ import { setUnixfsPath, walkUnixfsNames, } from "./unixfs-tree.js";
25
+ import { assertWritableSwarmFsPath, createSwarmFs, isV7Snapshot, listSubtreeNames, normalizeSwarmFsPath, resolveSnapshotName, v7RootSkipFiles, } from "./swarm-fs-core.js";
26
+ export { isV7Snapshot, listSubtreeNames, resolveSnapshotName, v7RootSkipFiles, };
25
27
  import { parsePublicationPins, pinPublication, } from "./pivot-service.js";
26
- import { mountPivotServer, parsePivotReceiptRequest, requestPivotReceiptOverP2p, signPivotReceiptRequest, verifyPivotReceiptRequest, } from "./pivot-rpc.js";
28
+ import { ensurePivotListener, mountPivotServer, parsePivotReplicateRequest, pivotReadinessOverP2p, parsePivotReceiptRequest, requestPivotReceiptOverP2p, signPivotReceiptRequest, signPivotReplicateRequest, verifyPivotReplicateRequest, verifyPivotReceiptRequest, } from "./pivot-rpc.js";
27
29
  import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
28
- import { bytes, relativePath } from "./space.js";
30
+ import { bytes } from "./space.js";
31
+ import { formalName, parseNameReference, formatNameReference, templateName, } from "./name-reference.js";
32
+ export { formalName, parseNameReference, formatNameReference, templateName, } from "./name-reference.js";
29
33
  import { appSchemaCid } from "./app-definition.js";
30
34
  import { State, createAssociation, exactCid, } from "./state.js";
31
35
  import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from "./swarm-files.js";
32
36
  import { openApproval, openApprovalV2, sealApprovalV2, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
33
- import { checkCachedNode, kuboSource, peerId, pinAdd, pinRm, prepareNode, startNode, stopNode, probePeer, nodeConnections, validateAddress, } from "./kubo.js";
37
+ import { checkCachedNode, kuboSource, nodeReady, peerId, pinAdd, isRecursivelyPinned, pinRm, prepareNode, startNode, stopNode, probePeer, nodeConnections, validateAddress, } from "./kubo.js";
34
38
  import { memberPeers } from "./kubo-peering.js";
35
39
  import { PivotCandidates } from "./kubo-topology.js";
36
40
  import { indexV7UnixfsSwarm, queryLocalSearchIndex, validateSearchParams, } from "./search-index.js";
@@ -40,7 +44,7 @@ import { networkingBinding, pivotLocalStatus, readNetworkingSnapshot, writeNetwo
40
44
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
41
45
  import { inspectTemplate, templatePublicationSource } from "./templates.js";
42
46
  import { seedSkillSource } from "./skill-source.js";
43
- import { skillIdentity, skillSchema } from "./skill-definition.js";
47
+ import { inspectSkillBundle, skillSchema } from "./skill-definition.js";
44
48
  import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmRootType, parseSwarmRootState, isSwarmRootSchema, swarmStateType, previousSwarmStateType, previousSwarmStateSchema, parseSwarmState, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
45
49
  function memberIsPivot(config, member, profile) {
46
50
  return config.v === 3
@@ -139,6 +143,11 @@ function withState(context, operation) {
139
143
  state.close();
140
144
  }
141
145
  }
146
+ export function invalidateSwarmHeader(context, configUrl) {
147
+ withState(context, (state) => {
148
+ state.invalidateSwarmHeader(configUrl);
149
+ });
150
+ }
142
151
  export { canonicalSwarmUrl };
143
152
  function coordinates(configUrl) {
144
153
  const url = new URL(canonicalSwarmUrl(configUrl));
@@ -162,7 +171,139 @@ async function local(context, configUrl) {
162
171
  async function saveLocal(context, membership) {
163
172
  await writePrivate(await directory(context), localName(membership.configUrl), membership);
164
173
  }
174
+ export const LOCAL_SWARM_HOLD_OWNER = "local-swarm-head";
175
+ const LOCAL_SWARM_NAME = "Local";
176
+ const LOCAL_SWARM_DESCRIPTION = "Built-in single-machine Swarm";
177
+ const LOCAL_SWARM_ORG = {
178
+ v: 3,
179
+ scopeId: "0000000000000000",
180
+ owner: "local",
181
+ name: LOCAL_SWARM_NAME,
182
+ description: LOCAL_SWARM_DESCRIPTION,
183
+ headId: "0000000000000000",
184
+ epoch: 1,
185
+ bootstrap: [],
186
+ members: [],
187
+ };
188
+ function rejectLocalSwarm(url, action) {
189
+ if (isLocalSwarm(url) || isReservedLocalHost(url)) {
190
+ throw new HostError(`The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support ${action}.`);
191
+ }
192
+ }
193
+ async function ensureLocalSwarm(context) {
194
+ const existing = withState(context, (state) => state.localSwarmHead());
195
+ if (existing)
196
+ return existing;
197
+ const names = {};
198
+ for (const selector of seedTemplateNames) {
199
+ const template = await seedTemplateSource(selector);
200
+ for (const [cid, data] of template.blocks)
201
+ await context.store.put(CID.parse(cid), data);
202
+ names[`ipab/templates/${selector}`] = CID.parse(template.cid);
203
+ }
204
+ const skill = await seedSkillSource();
205
+ for (const [cid, data] of skill.blocks)
206
+ await context.store.put(CID.parse(cid), data);
207
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
208
+ let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
209
+ templatePath: "ipab/templates",
210
+ registryPath: "ipab/registry",
211
+ skillPath: "ipab/skills",
212
+ }, LOCAL_SWARM_URL));
213
+ for (const [path, targetCid] of Object.entries(names)) {
214
+ currentRoot = (await setUnixfsPath(context.store, currentRoot, path, targetCid)).newRootCid;
215
+ }
216
+ const root = currentRoot.toString();
217
+ const valCid = await valueCid({ root });
218
+ const now = new Date().toISOString();
219
+ if (context.store.supportsRetention) {
220
+ await context.store.retain(LOCAL_SWARM_HOLD_OWNER, [root]);
221
+ await context.store.confirmRetained(LOCAL_SWARM_HOLD_OWNER, [root]);
222
+ }
223
+ const { record, inserted } = withState(context, (state) => state.initLocalSwarmHead({
224
+ headCid: root,
225
+ valueCid: valCid,
226
+ createdAt: now,
227
+ updatedAt: now,
228
+ }));
229
+ if (context.store.supportsRetention) {
230
+ if (!inserted && record.headCid !== root) {
231
+ await context.store.retain(LOCAL_SWARM_HOLD_OWNER, [record.headCid]);
232
+ await context.store.confirmRetained(LOCAL_SWARM_HOLD_OWNER, [
233
+ record.headCid,
234
+ ]);
235
+ }
236
+ await context.store.reconcile(LOCAL_SWARM_HOLD_OWNER, [record.headCid]);
237
+ }
238
+ return record;
239
+ }
240
+ async function readLocalSwarmHeader(context) {
241
+ const record = await ensureLocalSwarm(context);
242
+ const content = await readHeaderSnapshot(context.store, record.headCid, LOCAL_SWARM_URL);
243
+ const head = {
244
+ value: { root: record.headCid },
245
+ cid: record.valueCid,
246
+ root: record.headCid,
247
+ etag: `"${record.valueCid}"`,
248
+ };
249
+ const header = {
250
+ head,
251
+ ...content,
252
+ config: LOCAL_SWARM_ORG,
253
+ source: "cache",
254
+ verifiedAt: record.updatedAt,
255
+ localSourceReady: true,
256
+ };
257
+ await refreshNamePins(context, LOCAL_SWARM_URL, header);
258
+ return header;
259
+ }
260
+ function localSwarmPointer(context) {
261
+ return {
262
+ read: async () => {
263
+ const record = await ensureLocalSwarm(context);
264
+ return {
265
+ value: { root: record.headCid },
266
+ cid: record.valueCid,
267
+ root: record.headCid,
268
+ etag: `"${record.valueCid}"`,
269
+ };
270
+ },
271
+ write: async (root, expectedCid) => {
272
+ const valCid = await valueCid({ root });
273
+ const now = new Date().toISOString();
274
+ if (context.store.supportsRetention) {
275
+ await context.store.retain(LOCAL_SWARM_HOLD_OWNER, [root]);
276
+ await context.store.confirmRetained(LOCAL_SWARM_HOLD_OWNER, [root]);
277
+ }
278
+ const swapped = withState(context, (state) => state.compareAndSwapLocalSwarmHead(expectedCid, {
279
+ headCid: root,
280
+ valueCid: valCid,
281
+ updatedAt: now,
282
+ }));
283
+ if (!swapped) {
284
+ const current = withState(context, (state) => state.localSwarmHead());
285
+ if (context.store.supportsRetention && current) {
286
+ await context.store
287
+ .reconcile(LOCAL_SWARM_HOLD_OWNER, [current.headCid])
288
+ .catch(() => { });
289
+ }
290
+ throw new ScopeApiError(412, "cas_conflict", "Local Swarm HEAD changed concurrently; retry against the latest snapshot.", undefined);
291
+ }
292
+ if (context.store.supportsRetention) {
293
+ await context.store.reconcile(LOCAL_SWARM_HOLD_OWNER, [root]);
294
+ }
295
+ return {
296
+ value: { root },
297
+ cid: valCid,
298
+ };
299
+ },
300
+ writeWithReceipt: () => Promise.reject(new HostError(`The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support Pivot receipt writes.`)),
301
+ };
302
+ }
165
303
  function client(context, service, identity, secret) {
304
+ if (isReservedLocalHost(service)) {
305
+ throw new HostError(`Refusing network request to reserved .invalid host (${service}) for the built-in "${LOCAL_SWARM_ALIAS}" Swarm.`);
306
+ }
166
307
  return new ScopeClient({
167
308
  service,
168
309
  ...(identity
@@ -519,6 +660,36 @@ async function inspection(context, url, refresh = false) {
519
660
  };
520
661
  }
521
662
  export async function swarmMembers(context, url, refresh = false) {
663
+ if (isLocalSwarm(url)) {
664
+ const headRecord = withState(context, (state) => state.localSwarmHead());
665
+ return {
666
+ mode: "local",
667
+ configUrl: LOCAL_SWARM_URL,
668
+ members: [
669
+ {
670
+ publicKey: "local",
671
+ role: "owner",
672
+ name: "Local user",
673
+ description: "Single-machine built-in Swarm user",
674
+ pivot: false,
675
+ localStatus: null,
676
+ peerId: "",
677
+ updatedAt: headRecord?.updatedAt ?? "",
678
+ },
679
+ ],
680
+ cache: {
681
+ source: "cache",
682
+ freshness: "current",
683
+ updatedAt: headRecord?.updatedAt ?? new Date().toISOString(),
684
+ },
685
+ local: {
686
+ status: "unavailable",
687
+ updatedAt: null,
688
+ verifiedAt: null,
689
+ error: null,
690
+ },
691
+ };
692
+ }
522
693
  const { config, directory, cache } = await inspection(context, url, refresh);
523
694
  const observations = await localObservations(context, url, config);
524
695
  const members = directory.map(({ member, profile }) => {
@@ -541,7 +712,8 @@ export async function swarmMembers(context, url, refresh = false) {
541
712
  local: observationSummary(observations.local),
542
713
  };
543
714
  }
544
- export async function swarmNetworking(context, url, config, directory) {
715
+ export async function swarmNetworking(context, url, config, directory, currentHeadCid) {
716
+ rejectLocalSwarm(url, "swarm networking");
545
717
  directory ??= (await inspection(context, url)).directory;
546
718
  const { account, local } = await localObservations(context, url, config);
547
719
  const saved = local.snapshot?.connections;
@@ -592,6 +764,10 @@ export async function swarmNetworking(context, url, config, directory) {
592
764
  : actual.length
593
765
  ? "relay"
594
766
  : "disconnected";
767
+ const readiness = local.snapshot?.readiness?.[member.peerId];
768
+ const readinessCurrent = local.status === "current" &&
769
+ readiness &&
770
+ Date.now() - readiness.observedAt <= 90_000;
595
771
  return {
596
772
  publicKey: member.publicKey,
597
773
  name: profile.name,
@@ -619,11 +795,97 @@ export async function swarmNetworking(context, url, config, directory) {
619
795
  freshness,
620
796
  addresses: actual.map((entry) => entry.address),
621
797
  },
798
+ readiness: {
799
+ status: !readinessCurrent
800
+ ? "unknown"
801
+ : !readiness.status
802
+ ? "unreachable"
803
+ : readiness.status.ready &&
804
+ readiness.status.headCid === currentHeadCid
805
+ ? "ready"
806
+ : "not-ready",
807
+ observedAt: readiness
808
+ ? new Date(readiness.observedAt).toISOString()
809
+ : null,
810
+ headCid: readiness?.status?.headCid ?? null,
811
+ indexedHeadCid: readiness?.status?.indexedHeadCid ?? null,
812
+ error: readiness?.error ?? readiness?.status?.syncError ?? null,
813
+ },
622
814
  };
623
815
  }),
624
816
  };
625
817
  }
626
818
  export async function inspectSwarmStatus(context, url, refresh = false) {
819
+ if (isLocalSwarm(url)) {
820
+ const header = await readLocalSwarmHeader(context);
821
+ const meta = await swarmMeta(context, header);
822
+ const walked = await walkUnixfsNames(context.store, CID.parse(header.stateCid), {
823
+ skipRootFiles: v7RootSkipFiles(header.snapshot),
824
+ stopAtBundle: true,
825
+ });
826
+ const templatePrefix = `${meta.templatePath}/`;
827
+ const globalSkillPrefix = meta.skillPath
828
+ ? `${meta.skillPath}/global/`
829
+ : undefined;
830
+ const typeSkillPrefix = meta.skillPath
831
+ ? `${meta.skillPath}/types/`
832
+ : undefined;
833
+ const registryPrefix = `${meta.registryPath}/`;
834
+ let templates = 0;
835
+ let globalSkills = 0;
836
+ let typeSkills = 0;
837
+ let registrations = 0;
838
+ for (const entry of walked.entries) {
839
+ if (entry.name.startsWith(templatePrefix))
840
+ templates++;
841
+ else if (globalSkillPrefix && entry.name.startsWith(globalSkillPrefix))
842
+ globalSkills++;
843
+ else if (typeSkillPrefix && entry.name.startsWith(typeSkillPrefix))
844
+ typeSkills++;
845
+ else if (entry.name.startsWith(registryPrefix))
846
+ registrations++;
847
+ }
848
+ const skills = globalSkills + typeSkills;
849
+ return {
850
+ mode: "local",
851
+ configUrl: LOCAL_SWARM_URL,
852
+ config: LOCAL_SWARM_ORG,
853
+ head: header.head,
854
+ lastWriter: null,
855
+ cache: {
856
+ source: "cache",
857
+ freshness: "current",
858
+ updatedAt: header.verifiedAt,
859
+ },
860
+ state: {
861
+ status: "available",
862
+ error: null,
863
+ },
864
+ local: {
865
+ names: walked.entries.length,
866
+ templates,
867
+ skills,
868
+ globalSkills,
869
+ typeSkills,
870
+ registrations,
871
+ },
872
+ networking: {
873
+ daemon: {
874
+ status: "unavailable",
875
+ updatedAt: null,
876
+ verifiedAt: null,
877
+ error: null,
878
+ },
879
+ connections: {
880
+ observedAt: null,
881
+ error: null,
882
+ peers: [],
883
+ freshness: "unavailable",
884
+ },
885
+ pivots: [],
886
+ },
887
+ };
888
+ }
627
889
  const { config, directory, head, cache } = await inspection(context, url, refresh);
628
890
  const writer = directory.find(({ member }) => member.publicKey === head.update?.subject);
629
891
  return {
@@ -641,7 +903,7 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
641
903
  status: "unavailable",
642
904
  error: "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
643
905
  },
644
- networking: await swarmNetworking(context, url, config, directory),
906
+ networking: await swarmNetworking(context, url, config, directory, head.root),
645
907
  };
646
908
  }
647
909
  function accountProfileLocation(context, publicKey) {
@@ -808,6 +1070,7 @@ export async function updateAccountProfile(context, changes) {
808
1070
  return { profile, localPersisted: true, swarms };
809
1071
  }
810
1072
  async function fetchConfig(context, configUrl, signal) {
1073
+ rejectLocalSwarm(configUrl, "remote configuration fetch");
811
1074
  const c = coordinates(configUrl), api = client(context, c.service);
812
1075
  const options = signal ? { signal } : {};
813
1076
  const [variable, scope] = await Promise.all([
@@ -956,6 +1219,7 @@ async function validateMembershipSecret(record, config, member) {
956
1219
  }
957
1220
  }
958
1221
  async function privateSource(context, record, signal, candidates) {
1222
+ rejectLocalSwarm(record.configUrl, "private Kubo networking");
959
1223
  const config = record.config, secret = record.secret;
960
1224
  const identity = await contextIdentity(context);
961
1225
  const self = config.members.find((member) => member.publicKey === identity.publicKey);
@@ -1083,6 +1347,7 @@ async function privateSource(context, record, signal, candidates) {
1083
1347
  source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
1084
1348
  };
1085
1349
  }
1350
+ const pivotReadinessRefreshIntervalMs = 45_000;
1086
1351
  export async function swarmDaemon(context, signal, synchronize) {
1087
1352
  const lock = await privateDirectory(context.stateDir, "swarm-daemon");
1088
1353
  await withPrivateLock(lock, async () => {
@@ -1166,7 +1431,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1166
1431
  : "unknown",
1167
1432
  running: Boolean(session?.running),
1168
1433
  receiptRpc: {
1169
- active: Boolean(session?.pivotServer),
1434
+ active: Boolean(session?.pivotServer?.listening),
1170
1435
  protocol: pivotReceiptProtocol,
1171
1436
  epoch: session?.pivotServer?.epoch ?? null,
1172
1437
  headId: session?.pivotServer?.headId ?? null,
@@ -1268,6 +1533,23 @@ export async function swarmDaemon(context, signal, synchronize) {
1268
1533
  error: "No connection snapshot collected.",
1269
1534
  peers: [],
1270
1535
  },
1536
+ ...(session.context.pivotReadiness
1537
+ ? {
1538
+ readiness: Object.fromEntries(Object.entries(session.context.pivotReadiness).map(([peerId, value]) => [
1539
+ peerId,
1540
+ {
1541
+ ...value,
1542
+ error: redact(value.error, session),
1543
+ status: value.status
1544
+ ? {
1545
+ ...value.status,
1546
+ syncError: redact(value.status.syncError, session),
1547
+ }
1548
+ : null,
1549
+ },
1550
+ ])),
1551
+ }
1552
+ : {}),
1271
1553
  };
1272
1554
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1273
1555
  };
@@ -1306,6 +1588,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1306
1588
  };
1307
1589
  sessions.set(url, session);
1308
1590
  }
1591
+ let pivotListenerVerified = false;
1309
1592
  try {
1310
1593
  if (session.record?.config && context.pivot === undefined) {
1311
1594
  const self = session.record.config.members.find((member) => member.publicKey === session.record.account);
@@ -1346,6 +1629,22 @@ export async function swarmDaemon(context, signal, synchronize) {
1346
1629
  }
1347
1630
  if (!session.node)
1348
1631
  return;
1632
+ const currentRecord = session.record;
1633
+ const currentSelf = currentRecord.config.members.find((member) => member.publicKey === currentRecord.account);
1634
+ if (!(await nodeReady(session.node, signal, session.context.fetch))) {
1635
+ if (session.pivotServer)
1636
+ session.pivotServer.listening = false;
1637
+ const currentDesired = memberPeers(currentSelf.peerId, session.candidates.active(), []);
1638
+ session.node = await startNode(context.stateDir, nodeScope(coordinates(url).service, currentRecord.config.scopeId), currentRecord.secret.swarmKey, currentRecord.config.epoch, context.listen, {
1639
+ self: currentSelf.peerId,
1640
+ pivot: session.pivot ?? false,
1641
+ peers: currentDesired,
1642
+ signal,
1643
+ });
1644
+ session.selected = new Set(currentDesired.map(({ ID }) => ID));
1645
+ session.context.node = session.node;
1646
+ emitDiagnostic(`[${url}] Managed Kubo was offline; restarted before probing peers.`);
1647
+ }
1349
1648
  let healthy = 0;
1350
1649
  await boundedMap([...session.candidates.active()], async ([id, addresses]) => {
1351
1650
  let success = false;
@@ -1367,8 +1666,8 @@ export async function swarmDaemon(context, signal, synchronize) {
1367
1666
  }
1368
1667
  });
1369
1668
  session.healthy = healthy;
1370
- // Startup-captured relay/bootstrap options must be removed immediately
1371
- // when a candidate enters cooldown, not merely changed through config RPC.
1669
+ // Reconcile active Pivot Bootstrap candidates via live Kubo RPC
1670
+ // without restarting the daemon unless startup-only config changed.
1372
1671
  const record = session.record;
1373
1672
  const self = record.config.members.find((member) => member.publicKey === record.account);
1374
1673
  const desired = memberPeers(self.peerId, session.candidates.active(), []);
@@ -1380,52 +1679,138 @@ export async function swarmDaemon(context, signal, synchronize) {
1380
1679
  });
1381
1680
  session.selected = new Set(desired.map(({ ID }) => ID));
1382
1681
  session.context.node = session.node;
1682
+ try {
1683
+ const peers = await nodeConnections(session.node, signal);
1684
+ session.connections = {
1685
+ observedAt: Date.now(),
1686
+ error: null,
1687
+ peers,
1688
+ };
1689
+ }
1690
+ catch (cause) {
1691
+ signal.throwIfAborted();
1692
+ session.connections = {
1693
+ observedAt: session.connections?.observedAt ?? null,
1694
+ error: message(cause).slice(0, 2048),
1695
+ peers: session.connections?.peers ?? [],
1696
+ };
1697
+ }
1698
+ // Persist connectivity before potentially slow content acquisition.
1699
+ await persist(url, session, true);
1383
1700
  if (session.pivot) {
1384
1701
  if (!session.pivotServer ||
1702
+ !session.pivotServer.server.listening ||
1385
1703
  session.pivotServer.nodeApi !== session.node.api ||
1386
1704
  session.pivotServer.epoch !== record.config.epoch ||
1387
1705
  session.pivotServer.headId !== record.config.headId) {
1388
1706
  await stopPivotServer(session);
1389
1707
  const pivotNode = session.node;
1390
1708
  const mounted = await mountPivotServer(pivotNode, {
1709
+ status: (requestSignal) => pivotStatus({ ...session.context, node: pivotNode }, url, requestSignal),
1710
+ replicate: async (request, requestSignal) => {
1711
+ const requestContext = {
1712
+ ...session.context,
1713
+ node: pivotNode,
1714
+ };
1715
+ try {
1716
+ return await handlePivotReplicateRequest(requestContext, url, request, requestSignal);
1717
+ }
1718
+ finally {
1719
+ session.context.pivotSyncError =
1720
+ requestContext.pivotSyncError ?? null;
1721
+ }
1722
+ },
1391
1723
  receipt: (receiptRequest, requestSignal) => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal),
1392
1724
  search: (params) => withState(session.context, (state) => queryLocalSearchIndex(state, url, params)),
1393
1725
  ...(context.diagnostic
1394
1726
  ? { diagnostic: context.diagnostic }
1395
1727
  : {}),
1396
- }, session.context.fetch);
1728
+ }, session.context.fetch, signal);
1397
1729
  session.pivotServer = {
1398
1730
  server: mounted,
1399
1731
  nodeApi: session.node.api,
1400
1732
  epoch: record.config.epoch,
1401
1733
  headId: record.config.headId,
1734
+ listening: true,
1402
1735
  };
1403
1736
  }
1404
- await syncPivotPublications(session.context, url, signal);
1737
+ else {
1738
+ const remounted = await ensurePivotListener(session.node, session.pivotServer.server.address, signal, session.context.fetch);
1739
+ session.pivotServer.listening = true;
1740
+ if (remounted) {
1741
+ emitDiagnostic(`[${url}] Re-mounted Pivot P2P listener ${pivotReceiptProtocol} -> ${session.pivotServer.server.address}.`);
1742
+ }
1743
+ }
1744
+ pivotListenerVerified = true;
1405
1745
  }
1406
1746
  else {
1407
1747
  await stopPivotServer(session);
1408
1748
  }
1409
- try {
1410
- const peers = await nodeConnections(session.node, signal);
1411
- session.connections = {
1412
- observedAt: Date.now(),
1413
- error: null,
1414
- peers,
1415
- };
1749
+ const now = Date.now();
1750
+ const replicationIntervalMs = (context.syncInterval ?? 60) * 1000;
1751
+ const knownRemotePivots = session.candidates.observations();
1752
+ const online = new Set([
1753
+ ...[...knownRemotePivots]
1754
+ .filter(([, value]) => value.probe === "success")
1755
+ .map(([peerId]) => peerId),
1756
+ ...session.connections.peers.map((peer) => peer.peerId),
1757
+ ]);
1758
+ const remoteOnline = [...online].filter((peerId) => peerId !== session.node.peerId);
1759
+ const onlineRemotePivots = remoteOnline.filter((peerId) => knownRemotePivots.has(peerId));
1760
+ const remoteReadinessDue = onlineRemotePivots.some((peerId) => {
1761
+ const entry = session.context.pivotReadiness?.[peerId];
1762
+ return (!entry ||
1763
+ now - entry.observedAt >= pivotReadinessRefreshIntervalMs);
1764
+ });
1765
+ const replicationDue = now >= (session.nextReplication ?? 0);
1766
+ if ((onlineRemotePivots.length > 0 &&
1767
+ (remoteReadinessDue || replicationDue)) ||
1768
+ (remoteOnline.length > 0 && replicationDue)) {
1769
+ session.nextReplication = now + replicationIntervalMs;
1770
+ await replicateSwarm(session.context, url, signal, {
1771
+ automatic: true,
1772
+ onlinePeers: online,
1773
+ });
1416
1774
  }
1417
- catch (cause) {
1418
- signal.throwIfAborted();
1419
- session.connections = {
1420
- observedAt: session.connections?.observedAt ?? null,
1421
- error: message(cause).slice(0, 2048),
1422
- peers: session.connections?.peers ?? [],
1423
- };
1775
+ if (session.pivot) {
1776
+ const pivotSyncDue = now >= (session.nextPivotSync ?? 0);
1777
+ const selfReadiness = session.context.pivotReadiness?.[session.node.peerId];
1778
+ const selfReadinessDue = !selfReadiness ||
1779
+ now - selfReadiness.observedAt >=
1780
+ pivotReadinessRefreshIntervalMs;
1781
+ if (pivotSyncDue) {
1782
+ session.nextPivotSync = now + replicationIntervalMs;
1783
+ try {
1784
+ await syncPivotPublications(session.context, url, signal);
1785
+ }
1786
+ finally {
1787
+ if (!signal.aborted) {
1788
+ const status = await pivotStatus(session.context, url, signal);
1789
+ session.context.pivotReadiness ??= {};
1790
+ session.context.pivotReadiness[session.node.peerId] = {
1791
+ observedAt: Date.now(),
1792
+ status,
1793
+ error: null,
1794
+ };
1795
+ }
1796
+ }
1797
+ }
1798
+ else if (selfReadinessDue) {
1799
+ const status = await pivotStatus(session.context, url, signal);
1800
+ session.context.pivotReadiness ??= {};
1801
+ session.context.pivotReadiness[session.node.peerId] = {
1802
+ observedAt: Date.now(),
1803
+ status,
1804
+ error: null,
1805
+ };
1806
+ }
1424
1807
  }
1425
1808
  }
1426
1809
  catch (cause) {
1427
1810
  if (signal.aborted)
1428
1811
  return;
1812
+ if (!pivotListenerVerified && session.pivotServer)
1813
+ session.pivotServer.listening = false;
1429
1814
  session.error = message(cause);
1430
1815
  session.nextDiscovery = 0;
1431
1816
  emitDiagnostic(`[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`);
@@ -1567,6 +1952,7 @@ async function localForRead(context, configUrl) {
1567
1952
  return record;
1568
1953
  }
1569
1954
  async function approvedMembership(context, configUrl, signal) {
1955
+ rejectLocalSwarm(configUrl, "remote membership");
1570
1956
  const record = await localForRead(context, configUrl);
1571
1957
  const { config } = await fetchConfig(context, configUrl, signal);
1572
1958
  if (config.owner !== record.owner)
@@ -1630,6 +2016,7 @@ async function refresh(context, configUrl) {
1630
2016
  return record;
1631
2017
  }
1632
2018
  async function readyMembership(context, configUrl) {
2019
+ rejectLocalSwarm(configUrl, "remote membership");
1633
2020
  const record = await localForRead(context, configUrl);
1634
2021
  if (!record.config || !record.secret)
1635
2022
  return refresh(context, configUrl);
@@ -1664,6 +2051,8 @@ function headValue(head) {
1664
2051
  };
1665
2052
  }
1666
2053
  export async function pointer(context, configUrl) {
2054
+ if (isLocalSwarm(configUrl))
2055
+ return localSwarmPointer(context);
1667
2056
  return boundPointer(context, configUrl, await readyMembership(context, configUrl));
1668
2057
  }
1669
2058
  async function boundPointer(context, configUrl, record) {
@@ -1697,9 +2086,12 @@ async function boundPointer(context, configUrl, record) {
1697
2086
  writeWithReceipt: (receipt) => client(context, c.service).writeWithReceipt(c.scopeId, record.config.headId, receipt),
1698
2087
  };
1699
2088
  }
1700
- async function writeNamesHead(context, url, head, root, cid) {
2089
+ export async function writeNamesHead(context, url, head, root, cid) {
2090
+ if (isLocalSwarm(url)) {
2091
+ return head.write(root, cid, uniqueId());
2092
+ }
1701
2093
  const lock = await privateDirectory(await directory(context), `state-pin-${createHash("sha256").update(url).digest("hex")}`);
1702
- await withPrivateLock(lock, async () => {
2094
+ return withPrivateLock(lock, async () => {
1703
2095
  if (context.confirmPublication) {
1704
2096
  try {
1705
2097
  await context.confirmPublication(url, root);
@@ -1707,8 +2099,7 @@ async function writeNamesHead(context, url, head, root, cid) {
1707
2099
  catch (cause) {
1708
2100
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1709
2101
  }
1710
- await head.write(root, cid, uniqueId());
1711
- return;
2102
+ return head.write(root, cid, uniqueId());
1712
2103
  }
1713
2104
  const idempotencyKey = uniqueId();
1714
2105
  let receipt;
@@ -1718,7 +2109,10 @@ async function writeNamesHead(context, url, head, root, cid) {
1718
2109
  catch (cause) {
1719
2110
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1720
2111
  }
1721
- await head.writeWithReceipt(receipt);
2112
+ if (receipt === null) {
2113
+ return head.write(root, cid, idempotencyKey);
2114
+ }
2115
+ return head.writeWithReceipt(receipt);
1722
2116
  });
1723
2117
  }
1724
2118
  async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKey) {
@@ -1730,8 +2124,15 @@ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKe
1730
2124
  if (!pivots.length)
1731
2125
  throw new HostError("No Pivot nodes are declared. Declare an independent member with swarm profile --pivot true before publishing; HEAD was not changed.");
1732
2126
  const remote = pivots.filter(({ member }) => member.publicKey !== record.account);
1733
- if (!remote.length)
2127
+ if (!remote.length) {
2128
+ if (members.length === 1 &&
2129
+ members[0].member.publicKey === record.account &&
2130
+ record.account === config.owner) {
2131
+ context.diagnostic?.(`[${url}] Solo self-Pivot Swarm detected; publishing ${root} directly without remote Pivot receipt.`);
2132
+ return null;
2133
+ }
1734
2134
  throw new HostError("Publication requires an independent Pivot node. Declare another member with swarm profile --pivot true; HEAD was not changed.");
2135
+ }
1735
2136
  const authorized = remote.filter(({ member }) => member.publicKey === config.owner ||
1736
2137
  (config.v === 3
1737
2138
  ? member.role === "pivot"
@@ -1784,6 +2185,7 @@ async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKe
1784
2185
  throw new HostError(`No authorized independent Pivot issued a HEAD write receipt for publication ${root} (${errors.join("; ")}); HEAD was not changed.`);
1785
2186
  }
1786
2187
  export async function handlePivotReceiptRequest(context, url, input, signal) {
2188
+ rejectLocalSwarm(url, "Pivot receipt RPC");
1787
2189
  const request = parsePivotReceiptRequest(input);
1788
2190
  const record = await approvedMembership(context, url, signal);
1789
2191
  const config = record.config;
@@ -1899,6 +2301,7 @@ async function hasLocalBlock(store, cid) {
1899
2301
  }
1900
2302
  }
1901
2303
  export async function syncPivotPublications(context, url, signal) {
2304
+ rejectLocalSwarm(url, "Pivot publication sync");
1902
2305
  if (context.pivot === false)
1903
2306
  return;
1904
2307
  const record = await approvedMembership(context, url, signal);
@@ -1931,16 +2334,275 @@ export async function syncPivotPublications(context, url, signal) {
1931
2334
  }
1932
2335
  const source = context.store.withLocalSource(kuboSource(node, peers, context.diagnostic));
1933
2336
  try {
2337
+ if (CID.parse(head.root).code === dagPb.code)
2338
+ await pinPublication(source, [head.root], node, signal, context.fetch);
1934
2339
  await readSnapshot(source, head.root, url);
1935
2340
  const roots = CID.parse(head.root).code === dagPb.code
1936
2341
  ? [head.root]
1937
2342
  : await frozenPublicationClosure(source, head.root);
1938
2343
  await pinPublication(source, roots, node, signal, context.fetch);
2344
+ await finishPivotReplication(context, url, record, head, source, signal);
2345
+ context.pivotSyncError = null;
2346
+ }
2347
+ catch (cause) {
2348
+ context.pivotSyncError = message(cause).slice(0, 2048);
2349
+ throw cause;
1939
2350
  }
1940
2351
  finally {
1941
2352
  await source.close();
1942
2353
  }
1943
2354
  }
2355
+ async function localHeadClosure(context, headCid, signal, url) {
2356
+ const local = context.store.supportsRetention
2357
+ ? new IpfsStore({
2358
+ dataDir: context.store.configuration.dataDir,
2359
+ limits: context.store.limits,
2360
+ })
2361
+ : context.store;
2362
+ try {
2363
+ await local.prepare(headCid, { signal });
2364
+ if (url)
2365
+ await readSnapshot(local, headCid, url);
2366
+ if (CID.parse(headCid).code !== dagPb.code) {
2367
+ for (const root of await frozenPublicationClosure(local, headCid))
2368
+ await local.prepare(root, { signal });
2369
+ }
2370
+ return true;
2371
+ }
2372
+ catch (cause) {
2373
+ signal.throwIfAborted();
2374
+ if (missingContent(cause))
2375
+ return false;
2376
+ throw cause;
2377
+ }
2378
+ finally {
2379
+ if (local !== context.store)
2380
+ await local.close();
2381
+ }
2382
+ }
2383
+ export async function pivotStatus(context, url, signal) {
2384
+ rejectLocalSwarm(url, "Pivot status");
2385
+ const record = await approvedMembership(context, url, signal);
2386
+ const c = coordinates(url);
2387
+ const head = headValue(await client(context, c.service).read(c.scopeId, record.config.headId, {
2388
+ signal,
2389
+ }));
2390
+ const indexedHeadCid = withState(context, (state) => state.searchIndexState(url)?.headCid ?? null);
2391
+ const local = await localHeadClosure(context, head.root, signal, url);
2392
+ const pinned = local &&
2393
+ Boolean(context.node) &&
2394
+ (await isRecursivelyPinned(context.node, head.root, signal, context.fetch));
2395
+ const indexed = CID.parse(head.root).code !== dagPb.code || indexedHeadCid === head.root;
2396
+ return {
2397
+ v: 1,
2398
+ ready: pinned && indexed && !context.pivotSyncError,
2399
+ headCid: pinned ? head.root : null,
2400
+ indexedHeadCid,
2401
+ syncError: context.pivotSyncError ??
2402
+ (!pinned
2403
+ ? "Current HEAD is not fully replicated and recursively pinned."
2404
+ : !indexed
2405
+ ? "Current HEAD is not indexed."
2406
+ : null),
2407
+ };
2408
+ }
2409
+ async function finishPivotReplication(context, url, record, head, source, signal) {
2410
+ const snapshot = await readSnapshot(source, head.root, url);
2411
+ const roots = CID.parse(head.root).code === dagPb.code
2412
+ ? [head.root]
2413
+ : await frozenPublicationClosure(source, head.root);
2414
+ const owner = `daemon-pivot-root:${createHash("sha256").update(url).digest("hex")}`;
2415
+ await retainDaemonRoots(source, owner, roots, signal);
2416
+ const fresh = await approvedMembership(context, url, signal);
2417
+ const c = coordinates(url);
2418
+ const current = headValue(await client(context, c.service).read(c.scopeId, fresh.config.headId, {
2419
+ signal,
2420
+ }));
2421
+ if (fresh.config.epoch !== record.config.epoch ||
2422
+ fresh.config.headId !== record.config.headId ||
2423
+ current.root !== head.root)
2424
+ throw new HostError("HEAD or membership changed during replication; retry the current HEAD.");
2425
+ if (CID.parse(head.root).code === dagPb.code) {
2426
+ await syncPivotReplicationAndIndex({ ...context, pivot: true, store: source }, url, {
2427
+ head,
2428
+ snapshot,
2429
+ config: fresh.config,
2430
+ source: "network",
2431
+ verifiedAt: new Date().toISOString(),
2432
+ stateCid: head.root,
2433
+ }, signal);
2434
+ }
2435
+ }
2436
+ export async function handlePivotReplicateRequest(context, url, input, signal) {
2437
+ rejectLocalSwarm(url, "Pivot replicate");
2438
+ const request = parsePivotReplicateRequest(input);
2439
+ const record = await approvedMembership(context, url, signal);
2440
+ const c = coordinates(url);
2441
+ const config = record.config;
2442
+ if (request.service !== c.service ||
2443
+ request.scopeId !== c.scopeId ||
2444
+ request.headId !== config.headId ||
2445
+ request.epoch !== config.epoch)
2446
+ throw new HostError("Replicate request does not match the current Swarm configuration.");
2447
+ if (!config.members.some((member) => member.publicKey === request.member))
2448
+ throw new HostError("Replicate requester is not an approved Swarm member.", 1, "PIVOT_UNAUTHORIZED");
2449
+ await verifyPivotReplicateRequest(request);
2450
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId, { signal }));
2451
+ if (head.root !== request.headCid)
2452
+ throw new HostError("Replicate headCid must equal the current verified HEAD.");
2453
+ if (!context.node)
2454
+ throw new HostError("Replication requires an active Pivot node.");
2455
+ const status = await pivotStatus(context, url, signal);
2456
+ if (status.ready && status.headCid === head.root)
2457
+ return { ready: true, headCid: head.root };
2458
+ const source = context.store.withLocalSource(kuboSource(context.node, [], context.diagnostic));
2459
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(120_000)]);
2460
+ try {
2461
+ await pinPublication(source, [head.root], context.node, bounded, context.fetch);
2462
+ await finishPivotReplication(context, url, record, head, source, bounded);
2463
+ const fresh = await approvedMembership(context, url, bounded);
2464
+ const current = headValue(await client(context, c.service).read(c.scopeId, fresh.config.headId, {
2465
+ signal: bounded,
2466
+ }));
2467
+ if (!fresh.config.members.some((member) => member.publicKey === request.member) ||
2468
+ fresh.config.epoch !== config.epoch ||
2469
+ fresh.config.headId !== config.headId ||
2470
+ current.root !== head.root)
2471
+ throw new HostError("HEAD or requester membership changed during replication; retry.");
2472
+ context.pivotSyncError = null;
2473
+ return { ready: true, headCid: head.root };
2474
+ }
2475
+ catch (cause) {
2476
+ context.pivotSyncError = message(cause).slice(0, 2048);
2477
+ throw cause;
2478
+ }
2479
+ finally {
2480
+ await source.close();
2481
+ }
2482
+ }
2483
+ export async function replicateSwarm(context, url, signal = AbortSignal.timeout(180_000), options = {}) {
2484
+ const { automatic = false, onlinePeers } = options;
2485
+ rejectLocalSwarm(url, "swarm replicate");
2486
+ const record = await approvedMembership(context, url, signal);
2487
+ const c = coordinates(url);
2488
+ const config = record.config;
2489
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId, { signal }));
2490
+ const members = await memberDirectory(context, url, config);
2491
+ let targets = members.filter(({ member, profile }) => member.publicKey !== record.account &&
2492
+ memberIsPivot(config, member, profile) &&
2493
+ (!automatic || !onlinePeers || onlinePeers.has(member.peerId)));
2494
+ if (options.pivot !== undefined) {
2495
+ const selector = options.pivot;
2496
+ targets = targets.filter(({ member, profile }) => member.publicKey === selector ||
2497
+ member.peerId === selector ||
2498
+ profile.name === selector);
2499
+ if (targets.length !== 1)
2500
+ throw new HostError(`Pivot "${selector}" is ${targets.length ? "ambiguous; use its public key or PeerID" : "not a declared remote Pivot; run swarm members"}.`);
2501
+ }
2502
+ const results = [];
2503
+ if (!targets.length) {
2504
+ if (!automatic)
2505
+ throw new HostError("No remote Pivot is declared. Approve a Pivot and run its daemon first.");
2506
+ return { headCid: head.root, results };
2507
+ }
2508
+ const complete = await localHeadClosure(context, head.root, signal, url);
2509
+ if (!automatic && !complete)
2510
+ throw new HostError("This member does not hold the complete current HEAD locally; replication was not started.");
2511
+ if (!context.node) {
2512
+ if (automatic)
2513
+ throw new HostError("Automatic replication requires an active node.");
2514
+ await activate(context, record);
2515
+ }
2516
+ let provided = false;
2517
+ for (const { member, profile } of targets) {
2518
+ const options = {
2519
+ node: context.node,
2520
+ pivotPeerId: member.peerId,
2521
+ pivotAddresses: automatic ? [] : profile.addresses,
2522
+ signal,
2523
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
2524
+ };
2525
+ let reachable = false;
2526
+ try {
2527
+ if (!automatic)
2528
+ context.diagnostic?.(`Checking Pivot ${profile.name || member.peerId} readiness...`);
2529
+ const status = await pivotReadinessOverP2p(options);
2530
+ context.pivotReadiness ??= {};
2531
+ context.pivotReadiness[member.peerId] = {
2532
+ observedAt: Date.now(),
2533
+ status: "v" in status ? status : null,
2534
+ error: null,
2535
+ };
2536
+ reachable = true;
2537
+ if (status.ready && status.headCid === head.root) {
2538
+ results.push({ peerId: member.peerId, status: "ready" });
2539
+ if (automatic)
2540
+ continue;
2541
+ break;
2542
+ }
2543
+ if (!complete)
2544
+ continue;
2545
+ if (!provided) {
2546
+ await provideContent(context.store, [head.root], context.node.api, context.fetch, context.node.auth, [head.root], signal);
2547
+ provided = true;
2548
+ }
2549
+ const identity = await contextIdentity(context);
2550
+ const request = await signPivotReplicateRequest({
2551
+ service: c.service,
2552
+ scopeId: c.scopeId,
2553
+ headId: config.headId,
2554
+ epoch: config.epoch,
2555
+ headCid: head.root,
2556
+ member: identity.publicKey,
2557
+ }, identity.privateKey);
2558
+ context.diagnostic?.(`Replicating ${head.root} to Pivot ${profile.name || member.peerId}...`);
2559
+ await pivotReadinessOverP2p(options, request);
2560
+ context.pivotReadiness[member.peerId] = {
2561
+ observedAt: Date.now(),
2562
+ status: {
2563
+ v: 1,
2564
+ ready: true,
2565
+ headCid: head.root,
2566
+ indexedHeadCid: CID.parse(head.root).code === dagPb.code ? head.root : null,
2567
+ syncError: null,
2568
+ },
2569
+ error: null,
2570
+ };
2571
+ results.push({ peerId: member.peerId, status: "replicated" });
2572
+ break;
2573
+ }
2574
+ catch (cause) {
2575
+ signal.throwIfAborted();
2576
+ const error = message(cause);
2577
+ const reportError = !automatic || reachable;
2578
+ context.pivotReadiness ??= {};
2579
+ context.pivotReadiness[member.peerId] = {
2580
+ observedAt: Date.now(),
2581
+ status: reachable
2582
+ ? {
2583
+ v: 1,
2584
+ ready: false,
2585
+ headCid: null,
2586
+ indexedHeadCid: null,
2587
+ syncError: error.slice(0, 2048),
2588
+ }
2589
+ : null,
2590
+ error: reportError ? error.slice(0, 2048) : null,
2591
+ };
2592
+ if (reportError)
2593
+ context.diagnostic?.(`Pivot ${member.peerId} replication check failed: ${error}`);
2594
+ results.push({
2595
+ peerId: member.peerId,
2596
+ status: reachable ? "failed" : "unreachable",
2597
+ error,
2598
+ });
2599
+ }
2600
+ }
2601
+ if (!automatic &&
2602
+ !results.some((result) => result.status === "ready" || result.status === "replicated"))
2603
+ throw new HostError(`No Pivot confirmed current HEAD readiness: ${results.map((result) => result.error).join("; ")}`);
2604
+ return { headCid: head.root, results };
2605
+ }
1944
2606
  export async function typedJson(store, cid, type) {
1945
2607
  const { bundle, value } = await bundleJson(store, cid);
1946
2608
  if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
@@ -2018,46 +2680,6 @@ async function writeV7RootBundle(store, configuration, configUrl) {
2018
2680
  });
2019
2681
  return jsonBundle(store, swarmRootType, value);
2020
2682
  }
2021
- function isV7Snapshot(snapshot) {
2022
- return snapshot.stateBundle?.unixfsRoot?.version === 7;
2023
- }
2024
- function v7RootSkipFiles(snapshot) {
2025
- const root = snapshot.stateBundle?.unixfsRoot;
2026
- if (!root)
2027
- return new Set();
2028
- return new Set([".bundle.yaml", root.typeFile, root.entryFile]);
2029
- }
2030
- async function resolveSnapshotName(store, snapshot, name) {
2031
- if (isV7Snapshot(snapshot))
2032
- return resolveUnixfsPath(store, CID.parse(snapshot.stateBundle.cid), name);
2033
- return Object.hasOwn(snapshot.names, name) ? snapshot.names[name] : undefined;
2034
- }
2035
- async function listSubtreeNames(store, snapshot, prefix, flatOnly = false) {
2036
- if (isV7Snapshot(snapshot)) {
2037
- const dirCid = await resolveUnixfsPath(store, CID.parse(snapshot.stateBundle.cid), prefix);
2038
- if (!dirCid)
2039
- return [];
2040
- if (flatOnly) {
2041
- const entries = await listUnixfsDirectory(store, dirCid);
2042
- return [...entries.entries()]
2043
- .map(([child, cid]) => ({ name: `${prefix}/${child}`, cid }))
2044
- .sort((a, b) => a.name.localeCompare(b.name));
2045
- }
2046
- const walked = await walkUnixfsNames(store, dirCid, {
2047
- prefix,
2048
- stopAtBundle: true,
2049
- });
2050
- return walked.entries.map((entry) => ({
2051
- name: entry.name,
2052
- cid: CID.parse(entry.targetCid),
2053
- }));
2054
- }
2055
- const needle = `${prefix}/`;
2056
- return Object.entries(snapshot.names)
2057
- .filter(([name]) => name.startsWith(needle))
2058
- .map(([name, cid]) => ({ name, cid }))
2059
- .sort((a, b) => a.name.localeCompare(b.name));
2060
- }
2061
2683
  async function readV7Root(store, cid) {
2062
2684
  const canonical = cid.toV1();
2063
2685
  const rootKey = canonical.toString();
@@ -2283,7 +2905,7 @@ async function publication(store, state, previous, writer) {
2283
2905
  await store.put(cid, data);
2284
2906
  return cid.toString();
2285
2907
  }
2286
- function missingContent(cause) {
2908
+ export function missingContent(cause) {
2287
2909
  let failure = cause;
2288
2910
  for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2289
2911
  failure = failure.cause;
@@ -2333,6 +2955,8 @@ async function headContentFailure(context, configUrl, config, head, cause) {
2333
2955
  throw error;
2334
2956
  }
2335
2957
  export async function sharedSwarmStatus(context, configUrl) {
2958
+ if (isLocalSwarm(configUrl))
2959
+ return readLocalSwarmHeader(context);
2336
2960
  const { config } = await fetchConfig(context, configUrl);
2337
2961
  const c = coordinates(configUrl);
2338
2962
  const head = headValue(await client(context, c.service).read(c.scopeId, config.headId));
@@ -2384,6 +3008,8 @@ export async function swarmHeader(context, configUrl, force = context.forceRefre
2384
3008
  }
2385
3009
  async function readSwarmHeader(context, configUrl, force = context.forceRefresh ?? false, mode = "active") {
2386
3010
  canonicalSwarmUrl(configUrl);
3011
+ if (isLocalSwarm(configUrl))
3012
+ return readLocalSwarmHeader(context);
2387
3013
  let record = mode === "local-first"
2388
3014
  ? await approvedMembership(context, configUrl)
2389
3015
  : force
@@ -2558,7 +3184,9 @@ function headerProjection(header) {
2558
3184
  throw new HostError("A verified account projection is required.");
2559
3185
  return header.projection;
2560
3186
  }
2561
- async function localHeader(context, url) {
3187
+ export async function localHeader(context, url) {
3188
+ if (isLocalSwarm(url))
3189
+ return { header: await readLocalSwarmHeader(context), account: "local" };
2562
3190
  if (context.forceRefresh)
2563
3191
  return;
2564
3192
  canonicalSwarmUrl(url);
@@ -2594,7 +3222,8 @@ async function localHeader(context, url) {
2594
3222
  }
2595
3223
  // SharedContent invokes this source only after a genuine local ENOENT. Its
2596
3224
  // store is not replaced from inside its own pending read (which would deadlock).
2597
- async function lazyPrivateSource(context, url, account, basis) {
3225
+ export async function lazyPrivateSource(context, url, account, basis) {
3226
+ rejectLocalSwarm(url, "private Kubo networking");
2598
3227
  const finishPrevious = context.finishRead;
2599
3228
  delete context.finishRead;
2600
3229
  await finishPrevious?.();
@@ -2643,6 +3272,8 @@ async function lazyPrivateSource(context, url, account, basis) {
2643
3272
  };
2644
3273
  }
2645
3274
  export async function createSwarm(context, options = {}) {
3275
+ if (options.alias === LOCAL_SWARM_ALIAS)
3276
+ throw new HostError(`Swarm alias "${LOCAL_SWARM_ALIAS}" is reserved for the built-in local Swarm.`);
2646
3277
  if ((options.properties?.name.length ?? 0) > 256 ||
2647
3278
  (options.properties?.description.length ?? 0) > 2048 ||
2648
3279
  (options.addresses?.length ?? 0) > 16)
@@ -2717,7 +3348,7 @@ export async function createSwarm(context, options = {}) {
2717
3348
  const skill = await seedSkillSource();
2718
3349
  for (const [cid, data] of skill.blocks)
2719
3350
  await context.store.put(CID.parse(cid), data);
2720
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
3351
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
2721
3352
  let root;
2722
3353
  if (record.stateVersion === 7) {
2723
3354
  let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
@@ -2846,6 +3477,7 @@ const requestMessageV2 = (request) => JSON.stringify(["IPAB-REQUEST/2", request]
2846
3477
  const legacyRequestMessage = (request) => JSON.stringify(["IPAB-REQUEST/1", request]);
2847
3478
  const requestDigest = (request) => createHash("sha256").update(JSON.stringify(request)).digest("hex");
2848
3479
  export async function exportRequest(context, url, output) {
3480
+ rejectLocalSwarm(url, "swarm export");
2849
3481
  const record = await local(context, canonicalSwarmUrl(url));
2850
3482
  if (!record.request)
2851
3483
  throw new HostError("Owner membership has no Request.");
@@ -2860,6 +3492,7 @@ export async function exportRequest(context, url, output) {
2860
3492
  return record.request.member;
2861
3493
  }
2862
3494
  export async function requestMembership(context, url, options) {
3495
+ rejectLocalSwarm(url, "swarm request");
2863
3496
  if ("name" in options)
2864
3497
  throw new HostError("Set your account-wide name with ipab profile --name NAME; membership requests no longer embed display names.");
2865
3498
  const desiredRole = options.role ?? "ordinary";
@@ -3034,6 +3667,7 @@ export async function approveMembership(context, input, options = {}) {
3034
3667
  const request = typeof input === "string"
3035
3668
  ? await verifiedRequest(input)
3036
3669
  : await verifyRequest(input), url = request.configUrl;
3670
+ rejectLocalSwarm(url, "swarm approve");
3037
3671
  const dir = await directory(context);
3038
3672
  return withPrivateLock(dir, async () => {
3039
3673
  const { identity, record } = await ownerCheck(context, url);
@@ -3225,6 +3859,7 @@ export async function approveMembership(context, input, options = {}) {
3225
3859
  });
3226
3860
  }
3227
3861
  export async function grantPivotAuthority(context, url, memberPublicKey) {
3862
+ rejectLocalSwarm(url, "swarm pivot grant");
3228
3863
  if (!isCanonicalPublicKey(memberPublicKey))
3229
3864
  throw new HostError("Invalid member public key.");
3230
3865
  const dir = await directory(context);
@@ -3292,6 +3927,7 @@ export async function grantPivotAuthority(context, url, memberPublicKey) {
3292
3927
  });
3293
3928
  }
3294
3929
  export async function updateSwarm(context, url, changes) {
3930
+ rejectLocalSwarm(url, "swarm update");
3295
3931
  if ((changes.name?.length ?? 0) > 256 ||
3296
3932
  (changes.description?.length ?? 0) > 2048)
3297
3933
  throw new HostError("Organization name/description limit exceeded.");
@@ -3310,6 +3946,7 @@ export async function updateSwarm(context, url, changes) {
3310
3946
  };
3311
3947
  }
3312
3948
  export async function updateProfile(context, url, changes) {
3949
+ rejectLocalSwarm(url, "swarm profile");
3313
3950
  if ("name" in changes || "description" in changes)
3314
3951
  throw new HostError("Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.");
3315
3952
  if ((changes.addresses?.length ?? 0) > 16)
@@ -3357,6 +3994,7 @@ export async function updateProfile(context, url, changes) {
3357
3994
  return profile;
3358
3995
  }
3359
3996
  export async function removeMember(context, url, member) {
3997
+ rejectLocalSwarm(url, "swarm exclude");
3360
3998
  const dir = await directory(context);
3361
3999
  await withPrivateLock(dir, async () => {
3362
4000
  const { identity, record: membership } = await ownerCheck(context, url);
@@ -3380,6 +4018,7 @@ export async function removeMember(context, url, member) {
3380
4018
  await resumeRemoval(context, url);
3381
4019
  }
3382
4020
  export async function resumeRemoval(context, url) {
4021
+ rejectLocalSwarm(url, "swarm resume");
3383
4022
  const dir = await directory(context);
3384
4023
  return withPrivateLock(dir, async () => {
3385
4024
  const identity = await contextIdentity(context);
@@ -3541,60 +4180,6 @@ export async function resumeRemoval(context, url) {
3541
4180
  }
3542
4181
  });
3543
4182
  }
3544
- export function formalName(name) {
3545
- relativePath(name);
3546
- if (name.length > 256 || name.startsWith("builtin:"))
3547
- throw new HostError("Invalid formal Name.");
3548
- return name;
3549
- }
3550
- function decodeNameComponent(value, part) {
3551
- try {
3552
- return decodeURIComponent(value);
3553
- }
3554
- catch {
3555
- throw new HostError(`Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`);
3556
- }
3557
- }
3558
- export function parseNameReference(reference) {
3559
- if (/^name:/i.test(reference))
3560
- throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
3561
- if (!/^ipab:/i.test(reference))
3562
- return undefined;
3563
- if (/^ipab:\/\/https?:\/\//i.test(reference))
3564
- throw new HostError("Unencoded configuration URL in IPAB URI. Percent-encode the entire configuration URL and each Name path segment separately, or copy the reference from ipab search.");
3565
- const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
3566
- if (!match)
3567
- throw new HostError("Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.");
3568
- const authority = decodeNameComponent(match[1], "authority");
3569
- if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
3570
- if (!/^https?:\/\//i.test(authority))
3571
- throw new HostError("Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.");
3572
- canonicalSwarmUrl(authority);
3573
- }
3574
- if (/[?#\s]/.test(match[2]))
3575
- throw new HostError("Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.");
3576
- const segments = match[2].split("/").map((segment) => {
3577
- const decoded = decodeNameComponent(segment, "path");
3578
- if (/[/\\]/.test(decoded))
3579
- throw new HostError("Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.");
3580
- return decoded;
3581
- });
3582
- try {
3583
- return {
3584
- ...(authority ? { swarm: authority } : {}),
3585
- name: match[2] === "" ? "" : formalName(segments.join("/")),
3586
- };
3587
- }
3588
- catch (error) {
3589
- if (!(error instanceof HostError))
3590
- throw error;
3591
- throw new HostError("Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.", error.exitCode, error.code, error.phase);
3592
- }
3593
- }
3594
- export function formatNameReference(swarm, name) {
3595
- const segment = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
3596
- return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
3597
- }
3598
4183
  export async function resolveReference(context, reference, swarm, local, raw = false, mode = "active") {
3599
4184
  const shared = parseNameReference(reference);
3600
4185
  let source;
@@ -3632,7 +4217,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
3632
4217
  }
3633
4218
  };
3634
4219
  let link = await target();
3635
- if (!link && header.source === "cache") {
4220
+ if (!link && header.source === "cache" && !isLocalSwarm(selected)) {
3636
4221
  header = await swarmHeader(context, selected, true);
3637
4222
  link = await target();
3638
4223
  }
@@ -3643,7 +4228,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
3643
4228
  source = { configUrl: selected, header };
3644
4229
  }
3645
4230
  else {
3646
- if (swarm)
4231
+ if (swarm && !isLocalSwarm(swarm))
3647
4232
  await readyMembership(context, swarm);
3648
4233
  targetCid = local(reference);
3649
4234
  }
@@ -3657,7 +4242,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
3657
4242
  return headContentFailure(context, source.configUrl, source.header.config, source.header.head, cause);
3658
4243
  }
3659
4244
  }
3660
- async function artifactValue(store, targetCid, protect) {
4245
+ export async function artifactValue(store, targetCid, protect) {
3661
4246
  let cid = targetCid;
3662
4247
  const visited = new Set();
3663
4248
  for (let depth = 0;; depth++) {
@@ -3709,6 +4294,8 @@ export async function pinNameSubscription(context, reference, selected) {
3709
4294
  if (!selected || !missingContent(cause))
3710
4295
  throw cause;
3711
4296
  const swarm = withState(context, (state) => state.resolveSwarm(selected));
4297
+ if (isLocalSwarm(swarm))
4298
+ throw cause;
3712
4299
  await readyMembership(context, swarm);
3713
4300
  roots = [
3714
4301
  ...(await currentDependencies(context.store, canonical.reference)),
@@ -3950,7 +4537,22 @@ export async function searchNames(context, query, swarms, options = {}) {
3950
4537
  const header = (await localHeader(context, swarm.cid))?.header ??
3951
4538
  (await swarmHeader(context, swarm.cid, context.forceRefresh, "local-first"));
3952
4539
  if (isV7Snapshot(header.snapshot)) {
3953
- const response = await searchV7ViaPivot(context, swarm.cid, header, validated);
4540
+ let response;
4541
+ if (isLocalSwarm(swarm.cid)) {
4542
+ await withStateAsync(context, async (state) => {
4543
+ if (state.searchIndexState(LOCAL_SWARM_URL)?.headCid !==
4544
+ header.head.root) {
4545
+ await indexV7UnixfsSwarm(state, context.store, LOCAL_SWARM_URL, header.head.root, { skipRootFiles: v7RootSkipFiles(header.snapshot) });
4546
+ }
4547
+ });
4548
+ const localResponse = withState(context, (state) => queryLocalSearchIndex(state, LOCAL_SWARM_URL, validated));
4549
+ if (!localResponse)
4550
+ throw new HostError("Local Swarm search index is unavailable.");
4551
+ response = localResponse;
4552
+ }
4553
+ else {
4554
+ response = await searchV7ViaPivot(context, swarm.cid, header, validated);
4555
+ }
3954
4556
  searched.push({
3955
4557
  configUrl: swarm.cid,
3956
4558
  source: header.source,
@@ -4027,11 +4629,55 @@ function metaCid(snapshot) {
4027
4629
  function hasMeta(snapshot) {
4028
4630
  return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
4029
4631
  }
4632
+ export const swarmFsTransport = {
4633
+ pointer,
4634
+ writeNamesHead,
4635
+ readSnapshot,
4636
+ swarmHeader,
4637
+ localHeader,
4638
+ lazyPrivateSource,
4639
+ invalidateSwarmHeader,
4640
+ prepareNamesPublication,
4641
+ missingContent,
4642
+ };
4643
+ const swarmFs = createSwarmFs(swarmFsTransport);
4644
+ function missingSkillPathError(snapshot) {
4645
+ return new HostError(snapshot.stateBundle
4646
+ ? "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."
4647
+ : `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(snapshot)}. Upgrades never overwrite Meta.`);
4648
+ }
4649
+ function canonicalTypeSkillLeaf(name, leaf) {
4650
+ try {
4651
+ if (exactCid(leaf, true) === leaf)
4652
+ return leaf;
4653
+ }
4654
+ catch {
4655
+ // Fall through to typed error below.
4656
+ }
4657
+ throw new HostError(`Type Skill Name "${name}" must use a canonical schema CID.`);
4658
+ }
4659
+ async function inspectDirectTypeSkill(store, name, targetCid) {
4660
+ let bundle;
4661
+ try {
4662
+ bundle = await openBundle(CID.parse(targetCid), {
4663
+ resolveCid: (key) => store.block.get(key.toString()),
4664
+ });
4665
+ }
4666
+ catch (cause) {
4667
+ if (cause instanceof HostError)
4668
+ throw cause;
4669
+ throw new HostError(`Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
4670
+ }
4671
+ if (bundle.schemaKey !== skillSchema.cid.toString())
4672
+ throw new HostError(`Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
4673
+ return inspectSkillBundle(bundle);
4674
+ }
4030
4675
  export async function swarmSkills(context, configUrl, requested, owner) {
4031
- const warm = await localHeader(context, configUrl);
4032
- if (warm && !warm.header.localSourceReady)
4033
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4034
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
4676
+ let ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4677
+ mode: "active",
4678
+ preferLocalCache: true,
4679
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
4680
+ });
4035
4681
  const roots = new Set();
4036
4682
  const protect = async (cid) => {
4037
4683
  roots.add(cid);
@@ -4040,29 +4686,24 @@ export async function swarmSkills(context, configUrl, requested, owner) {
4040
4686
  await context.store.confirmRetained(owner, values);
4041
4687
  };
4042
4688
  for (let attempt = 0;; attempt++) {
4043
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
4044
- header = await swarmHeader(context, configUrl, true);
4045
- continue;
4046
- }
4047
- if (hasMeta(header.snapshot)) {
4048
- if (isV7Snapshot(header.snapshot)) {
4689
+ if (hasMeta(ctx.snapshot)) {
4690
+ if (ctx.isV7) {
4049
4691
  if (context.store.supportsRetention) {
4050
- const rootId = metaCid(header.snapshot);
4692
+ const rootId = metaCid(ctx.snapshot);
4051
4693
  await context.store.retainDirect(owner, [rootId]);
4052
4694
  await context.store.confirmDirectRetained(owner, [rootId]);
4053
4695
  }
4054
4696
  }
4055
4697
  else {
4056
- await protect(metaCid(header.snapshot));
4698
+ await protect(metaCid(ctx.snapshot));
4057
4699
  }
4058
4700
  }
4059
- const meta = await swarmMeta(context, header);
4701
+ const meta = await swarmMeta(context, ctx.header);
4060
4702
  if (!meta.skillPath)
4061
- throw new HostError(header.snapshot.stateBundle
4062
- ? "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."
4063
- : `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.`);
4064
- const prefix = `${meta.skillPath}/`;
4065
- const entries = await listSubtreeNames(context.store, header.snapshot, meta.skillPath, true);
4703
+ throw missingSkillPathError(ctx.snapshot);
4704
+ const globalDir = `${meta.skillPath}/global`;
4705
+ const prefix = `${globalDir}/`;
4706
+ const entries = await listSubtreeNames(context.store, ctx.snapshot, globalDir, false);
4066
4707
  for (const { cid: target } of entries)
4067
4708
  roots.add(target.toString());
4068
4709
  await context.store.registerOwnerAsync(owner, [...roots]);
@@ -4070,52 +4711,357 @@ export async function swarmSkills(context, configUrl, requested, owner) {
4070
4711
  const identities = new Set();
4071
4712
  for (const { name, cid: target } of entries) {
4072
4713
  if (name.slice(prefix.length).includes("/"))
4073
- throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
4714
+ throw new HostError(`Skill Name "${name}" must be flat under ${globalDir}.`);
4074
4715
  const cid = await artifactValue(context.store, target.toString(), protect);
4075
4716
  const bundle = await openBundle(CID.parse(cid), {
4076
4717
  resolveCid: (key) => context.store.block.get(key.toString()),
4077
4718
  });
4078
4719
  if (bundle.schemaKey !== skillSchema.cid.toString())
4079
4720
  throw new HostError(`Name "${name}" is not an exact Skill type Bundle.`);
4080
- const identity = await skillIdentity(bundle);
4081
- if (identities.has(identity))
4082
- throw new HostError(`Duplicate Skill installation name "${identity}" in this Swarm.`);
4083
- identities.add(identity);
4084
- result.push({ name, cid, identity });
4721
+ const metadata = await inspectSkillBundle(bundle);
4722
+ if (identities.has(metadata.name))
4723
+ throw new HostError(`Duplicate Skill installation name "${metadata.name}" in this Swarm.`);
4724
+ identities.add(metadata.name);
4725
+ result.push({
4726
+ name,
4727
+ cid,
4728
+ identity: metadata.name,
4729
+ description: metadata.description,
4730
+ });
4085
4731
  }
4086
4732
  const missing = requested.filter((reference) => !result.some((skill) => skill.name === reference || skill.identity === reference));
4087
- if (missing.length && !attempt && header.source === "cache") {
4088
- header = await swarmHeader(context, configUrl, true);
4733
+ if (missing.length && !attempt && ctx.source === "cache" && !ctx.isLocal) {
4734
+ ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4735
+ mode: "active",
4736
+ forceRefresh: true,
4737
+ });
4089
4738
  continue;
4090
4739
  }
4091
4740
  if (missing.length)
4092
- throw new HostError(`Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`);
4741
+ throw new HostError(`Skill identities or shared Names not found under ${globalDir}: ${missing.join(", ")}.`);
4093
4742
  return result;
4094
4743
  }
4095
4744
  }
4745
+ export async function swarmTypeSkills(context, configUrl, options = {}) {
4746
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4747
+ mode: options.mode ?? "local-first",
4748
+ ...(options.forceRefresh !== undefined
4749
+ ? { forceRefresh: options.forceRefresh }
4750
+ : {}),
4751
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
4752
+ });
4753
+ const roots = new Set();
4754
+ if (options.owner && hasMeta(ctx.snapshot)) {
4755
+ const rootId = metaCid(ctx.snapshot);
4756
+ if (ctx.isV7) {
4757
+ if (context.store.supportsRetention) {
4758
+ await context.store.retainDirect(options.owner, [rootId]);
4759
+ await context.store.confirmDirectRetained(options.owner, [rootId]);
4760
+ }
4761
+ }
4762
+ else {
4763
+ roots.add(rootId);
4764
+ await context.store.retain(options.owner, [...roots]);
4765
+ await context.store.confirmRetained(options.owner, [...roots]);
4766
+ }
4767
+ }
4768
+ const meta = await swarmMeta(context, ctx.header);
4769
+ if (!meta.skillPath)
4770
+ throw missingSkillPathError(ctx.snapshot);
4771
+ const typesDir = `${meta.skillPath}/types`;
4772
+ const prefix = `${typesDir}/`;
4773
+ const entries = await listSubtreeNames(context.store, ctx.snapshot, typesDir, false);
4774
+ if (options.owner) {
4775
+ for (const { cid: target } of entries)
4776
+ roots.add(target.toString());
4777
+ await context.store.registerOwnerAsync(options.owner, [...roots]);
4778
+ }
4779
+ const result = [];
4780
+ for (const { name, cid: target } of entries) {
4781
+ if (name.slice(prefix.length).includes("/"))
4782
+ throw new HostError(`Type Skill Name "${name}" must be flat under ${typesDir}.`);
4783
+ const leaf = name.slice(prefix.length);
4784
+ const schemaCid = canonicalTypeSkillLeaf(name, leaf);
4785
+ const targetCid = target.toString();
4786
+ const metadata = await inspectDirectTypeSkill(context.store, name, targetCid);
4787
+ result.push({
4788
+ name,
4789
+ schemaCid,
4790
+ cid: targetCid,
4791
+ identity: metadata.name,
4792
+ description: metadata.description,
4793
+ });
4794
+ }
4795
+ return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
4796
+ }
4797
+ export async function swarmTypeSkill(context, configUrl, schemaCid, options = {}) {
4798
+ const canonicalSchema = exactCid(schemaCid, true);
4799
+ let cachedHeader;
4800
+ let cachedName;
4801
+ let cachedTarget;
4802
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4803
+ mode: options.mode ?? "local-first",
4804
+ ...(options.forceRefresh !== undefined
4805
+ ? { forceRefresh: options.forceRefresh }
4806
+ : {}),
4807
+ shouldRefresh: async (current) => {
4808
+ if (!hasMeta(current.snapshot))
4809
+ return true;
4810
+ await current.ensureLocalSource();
4811
+ const meta = await swarmMeta(context, current.header);
4812
+ if (!meta.skillPath)
4813
+ return false;
4814
+ const name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
4815
+ const target = await resolveSnapshotName(context.store, current.snapshot, name);
4816
+ cachedHeader = current.header;
4817
+ cachedName = name;
4818
+ cachedTarget = target;
4819
+ return !target;
4820
+ },
4821
+ });
4822
+ let name;
4823
+ let target;
4824
+ if (ctx.header === cachedHeader && cachedName !== undefined) {
4825
+ name = cachedName;
4826
+ target = cachedTarget;
4827
+ }
4828
+ else {
4829
+ const meta = await swarmMeta(context, ctx.header);
4830
+ if (!meta.skillPath)
4831
+ throw missingSkillPathError(ctx.snapshot);
4832
+ name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
4833
+ try {
4834
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
4835
+ }
4836
+ catch (cause) {
4837
+ if (!missingContent(cause))
4838
+ throw cause;
4839
+ await ctx.ensureLocalSource();
4840
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
4841
+ }
4842
+ }
4843
+ if (!target)
4844
+ return undefined;
4845
+ const targetCid = target.toString();
4846
+ const metadata = await inspectDirectTypeSkill(context.store, name, targetCid);
4847
+ return {
4848
+ name,
4849
+ schemaCid: canonicalSchema,
4850
+ cid: targetCid,
4851
+ identity: metadata.name,
4852
+ description: metadata.description,
4853
+ };
4854
+ }
4855
+ export async function setSwarmSkill(context, configUrl, input) {
4856
+ if (!input.global && input.types.length === 0)
4857
+ syntax("skills set requires --global and/or at least one --type SCHEMA.");
4858
+ const skillCid = exactCid(input.skillCid);
4859
+ const canonicalTypes = [
4860
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
4861
+ ].sort((left, right) => left.localeCompare(right));
4862
+ let bundle;
4863
+ try {
4864
+ bundle = await openBundle(CID.parse(skillCid), {
4865
+ resolveCid: (key) => context.store.block.get(key.toString()),
4866
+ });
4867
+ }
4868
+ catch (cause) {
4869
+ if (cause instanceof HostError)
4870
+ throw cause;
4871
+ throw new HostError(`Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
4872
+ }
4873
+ if (bundle.schemaKey !== skillSchema.cid.toString())
4874
+ throw new HostError(`Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
4875
+ const metadata = await inspectSkillBundle(bundle);
4876
+ let expectedSkillPath;
4877
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
4878
+ allowLegacyNames: true,
4879
+ refreshAfterCommit: true,
4880
+ maxAttempts: 8,
4881
+ plan: async (planCtx) => {
4882
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
4883
+ if (!meta.skillPath)
4884
+ throw missingSkillPathError(planCtx.snapshot);
4885
+ if (expectedSkillPath !== undefined &&
4886
+ meta.skillPath !== expectedSkillPath)
4887
+ throw new HostError("Swarm skillPath changed concurrently; retry ipab skills set.", 3, "EDIT_CONFLICT", "publication");
4888
+ expectedSkillPath = meta.skillPath;
4889
+ const plannedTargets = [];
4890
+ if (input.global) {
4891
+ const path = formalName(`${meta.skillPath}/global/${metadata.name}`);
4892
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
4893
+ plannedTargets.push({ scope: "global", name: path });
4894
+ }
4895
+ for (const schemaCid of canonicalTypes) {
4896
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
4897
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
4898
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
4899
+ }
4900
+ const resolvedTargets = await Promise.all(plannedTargets.map(async (target) => ({
4901
+ ...target,
4902
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
4903
+ })));
4904
+ const conflicts = resolvedTargets.filter((target) => target.existing !== null && target.existing !== skillCid);
4905
+ if (conflicts.length > 0 && !input.replace)
4906
+ throw new HostError(`Skill target(s) already point to a different CID (${conflicts.map((target) => target.name).join(", ")}); use --replace to overwrite.`, 3, "EDIT_CONFLICT", "publication");
4907
+ const pending = resolvedTargets.filter((target) => target.existing !== skillCid);
4908
+ const targets = resolvedTargets.map((target) => ({
4909
+ scope: target.scope,
4910
+ name: target.name,
4911
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
4912
+ cid: skillCid,
4913
+ previousCid: target.existing,
4914
+ changed: target.existing !== skillCid,
4915
+ }));
4916
+ if (pending.length === 0)
4917
+ return {
4918
+ kind: "noop",
4919
+ result: { skillPath: meta.skillPath, targets },
4920
+ };
4921
+ const operations = pending.map((target) => ({
4922
+ op: "set",
4923
+ path: target.name,
4924
+ targetCid: CID.parse(skillCid),
4925
+ }));
4926
+ return {
4927
+ kind: "commit",
4928
+ operations,
4929
+ recursiveRoots: [skillCid],
4930
+ retainedRecursive: [skillCid],
4931
+ result: { skillPath: meta.skillPath, targets },
4932
+ };
4933
+ },
4934
+ messages: {
4935
+ unconfirmed: (cause) => `Skill association unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
4936
+ pinStale: (cause) => `Skill association committed, but HEAD/subscription refresh failed: ${message(cause)}.`,
4937
+ headBusy: () => "HEAD is busy; retry ipab skills set.",
4938
+ },
4939
+ });
4940
+ return {
4941
+ swarm: committed.swarm,
4942
+ skillPath: committed.result.skillPath,
4943
+ cid: skillCid,
4944
+ identity: metadata.name,
4945
+ description: metadata.description,
4946
+ headCid: committed.headCid,
4947
+ previousHeadCid: committed.previousHeadCid,
4948
+ rootCid: committed.rootCid,
4949
+ previousRootCid: committed.previousRootCid,
4950
+ changed: committed.changed,
4951
+ targets: committed.result.targets,
4952
+ };
4953
+ }
4954
+ export async function removeSwarmSkill(context, configUrl, input) {
4955
+ if (input.globalName === undefined && input.types.length === 0)
4956
+ syntax("skills remove requires --global NAME and/or at least one --type SCHEMA.");
4957
+ if (input.globalName !== undefined &&
4958
+ (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(input.globalName) ||
4959
+ input.globalName.length > 64))
4960
+ syntax(`Invalid global Skill name "${input.globalName}". Expected lowercase kebab-case (1..64 characters).`);
4961
+ const canonicalTypes = [
4962
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
4963
+ ].sort((left, right) => left.localeCompare(right));
4964
+ let expectedSkillPath;
4965
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
4966
+ allowLegacyNames: true,
4967
+ refreshAfterCommit: true,
4968
+ maxAttempts: 8,
4969
+ plan: async (planCtx) => {
4970
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
4971
+ if (!meta.skillPath)
4972
+ throw missingSkillPathError(planCtx.snapshot);
4973
+ if (expectedSkillPath !== undefined &&
4974
+ meta.skillPath !== expectedSkillPath)
4975
+ throw new HostError("Swarm skillPath changed concurrently; retry ipab skills remove.", 3, "EDIT_CONFLICT", "publication");
4976
+ expectedSkillPath = meta.skillPath;
4977
+ const plannedTargets = [];
4978
+ if (input.globalName !== undefined) {
4979
+ const path = formalName(`${meta.skillPath}/global/${input.globalName}`);
4980
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
4981
+ plannedTargets.push({ scope: "global", name: path });
4982
+ }
4983
+ for (const schemaCid of canonicalTypes) {
4984
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
4985
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
4986
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
4987
+ }
4988
+ const resolvedTargets = await Promise.all(plannedTargets.map(async (target) => ({
4989
+ ...target,
4990
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
4991
+ })));
4992
+ const missing = resolvedTargets.filter((target) => target.existing === null);
4993
+ if (missing.length > 0)
4994
+ throw new HostError(`Skill target(s) not found: ${missing.map((target) => target.name).join(", ")}.`, 1, "SKILL_NOT_FOUND", "state");
4995
+ const operations = resolvedTargets.map((target) => ({
4996
+ op: "delete",
4997
+ path: target.name,
4998
+ }));
4999
+ const removed = resolvedTargets.map((target) => ({
5000
+ scope: target.scope,
5001
+ name: target.name,
5002
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
5003
+ removedCid: target.existing,
5004
+ }));
5005
+ return {
5006
+ kind: "commit",
5007
+ operations,
5008
+ recursiveRoots: [],
5009
+ retainedRecursive: [],
5010
+ result: { skillPath: meta.skillPath, removed },
5011
+ };
5012
+ },
5013
+ messages: {
5014
+ unconfirmed: (cause) => `Skill removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5015
+ pinStale: (cause) => `Skill removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
5016
+ headBusy: () => "HEAD is busy; retry ipab skills remove.",
5017
+ },
5018
+ });
5019
+ return {
5020
+ swarm: committed.swarm,
5021
+ skillPath: committed.result.skillPath,
5022
+ headCid: committed.headCid,
5023
+ previousHeadCid: committed.previousHeadCid,
5024
+ rootCid: committed.rootCid,
5025
+ previousRootCid: committed.previousRootCid,
5026
+ changed: committed.changed,
5027
+ removed: committed.result.removed,
5028
+ };
5029
+ }
4096
5030
  export async function resolveTemplateSelector(context, selector, configUrl) {
4097
5031
  formalName(selector);
4098
- const warm = await localHeader(context, configUrl);
4099
- if (warm && !warm.header.localSourceReady)
4100
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4101
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
4102
- if (!hasMeta(header.snapshot) && header.source === "cache")
4103
- header = await swarmHeader(context, configUrl, true);
4104
- for (let attempt = 0;; attempt++) {
4105
- const meta = await swarmMeta(context, header);
4106
- const name = formalName(`${meta.templatePath}/${selector}`);
4107
- const target = await resolveSnapshotName(context.store, header.snapshot, name);
4108
- if (target)
4109
- return artifactValue(context.store, target.toString());
4110
- if (attempt || header.source !== "cache")
4111
- throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
4112
- header = await swarmHeader(context, configUrl, true);
5032
+ let cachedHeader;
5033
+ let cachedName;
5034
+ let cachedTarget;
5035
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5036
+ mode: "active",
5037
+ preferLocalCache: true,
5038
+ shouldRefresh: async (current) => {
5039
+ if (!hasMeta(current.snapshot))
5040
+ return true;
5041
+ await current.ensureLocalSource();
5042
+ const meta = await swarmMeta(context, current.header);
5043
+ const name = formalName(`${meta.templatePath}/${selector}`);
5044
+ const target = await resolveSnapshotName(context.store, current.snapshot, name);
5045
+ cachedHeader = current.header;
5046
+ cachedName = name;
5047
+ cachedTarget = target;
5048
+ return !target;
5049
+ },
5050
+ });
5051
+ let name;
5052
+ let target;
5053
+ if (ctx.header === cachedHeader) {
5054
+ name = cachedName;
5055
+ target = cachedTarget;
4113
5056
  }
4114
- }
4115
- export function templateName(name) {
4116
- if (name.includes(":"))
4117
- throw new HostError("Template NAME must be a safe relative Name, not a URI.");
4118
- return formalName(name);
5057
+ else {
5058
+ const meta = await swarmMeta(context, ctx.header);
5059
+ name = formalName(`${meta.templatePath}/${selector}`);
5060
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
5061
+ }
5062
+ if (target)
5063
+ return artifactValue(context.store, target.toString());
5064
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
4119
5065
  }
4120
5066
  async function templateEntry(context, configUrl, header, selector) {
4121
5067
  const meta = await swarmMeta(context, header);
@@ -4135,19 +5081,55 @@ async function templateEntry(context, configUrl, header, selector) {
4135
5081
  ...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
4136
5082
  };
4137
5083
  }
4138
- async function retainDaemonRoots(store, owner, roots) {
5084
+ async function retainDaemonRoots(store, owner, roots, signal) {
4139
5085
  const unique = [...new Set(roots)];
5086
+ const options = signal ? [{ signal }] : [];
4140
5087
  if (!store.supportsRetention) {
4141
5088
  for (const root of unique)
4142
- await store.prepare(root);
5089
+ await store.prepare(root, ...options);
4143
5090
  return;
4144
5091
  }
4145
- await store.recoverOwner(owner, []);
5092
+ await store.recoverOwner(owner, [], ...options);
4146
5093
  if (unique.length) {
4147
- await store.retain(owner, unique);
4148
- await store.confirmRetained(owner, unique);
5094
+ await store.retain(owner, unique, ...options);
5095
+ await store.confirmRetained(owner, unique, ...options);
4149
5096
  }
4150
- await store.reconcile(owner, unique);
5097
+ await store.reconcile(owner, unique, ...options);
5098
+ }
5099
+ export async function syncSwarmTypeSkills(context, configUrl, header) {
5100
+ if (!hasMeta(header.snapshot))
5101
+ return 0;
5102
+ const meta = await swarmMeta(context, header);
5103
+ if (!meta.skillPath)
5104
+ return 0;
5105
+ const typesDir = `${meta.skillPath}/types`;
5106
+ const prefix = `${typesDir}/`;
5107
+ const entries = await listSubtreeNames(context.store, header.snapshot, typesDir, false);
5108
+ const roots = [];
5109
+ for (const { name, cid: target } of entries) {
5110
+ if (name.slice(prefix.length).includes("/"))
5111
+ throw new HostError(`Type Skill Name "${name}" must be flat under ${typesDir}.`);
5112
+ const leaf = name.slice(prefix.length);
5113
+ canonicalTypeSkillLeaf(name, leaf);
5114
+ const targetCid = target.toString();
5115
+ await inspectDirectTypeSkill(context.store, name, targetCid);
5116
+ roots.push(targetCid);
5117
+ }
5118
+ const owner = `daemon-type-skills:${createHash("sha256").update(configUrl).digest("hex")}`;
5119
+ if (roots.length) {
5120
+ if (isV7Snapshot(header.snapshot)) {
5121
+ if (context.store.supportsRetention) {
5122
+ const rootId = metaCid(header.snapshot);
5123
+ await context.store.retainDirect(owner, [rootId]);
5124
+ await context.store.confirmDirectRetained(owner, [rootId]);
5125
+ }
5126
+ }
5127
+ else {
5128
+ roots.unshift(metaCid(header.snapshot));
5129
+ }
5130
+ }
5131
+ await retainDaemonRoots(context.store, owner, roots);
5132
+ return entries.length;
4151
5133
  }
4152
5134
  export async function syncSwarmTemplates(context, configUrl, header) {
4153
5135
  if (!hasMeta(header.snapshot))
@@ -4209,13 +5191,17 @@ export async function syncSwarmRegistry(context, configUrl, header) {
4209
5191
  export async function syncPivotReplicationAndIndex(context, configUrl, header, signal) {
4210
5192
  if (!context.pivot || !isV7Snapshot(header.snapshot))
4211
5193
  return;
5194
+ const lock = await privateDirectory(context.stateDir, `pivot-index-${createHash("sha256").update(configUrl).digest("hex")}`);
5195
+ return withPrivateLock(lock, () => updatePivotReplicationAndIndex(context, configUrl, header, signal), signal);
5196
+ }
5197
+ async function updatePivotReplicationAndIndex(context, configUrl, header, signal) {
4212
5198
  const headCid = CID.parse(header.stateCid).toV1().toString();
4213
5199
  const previousHead = withState(context, (state) => state.searchIndexState(configUrl)?.headCid ?? null);
4214
5200
  if (context.node) {
4215
5201
  await pinAdd(context.node, headCid, true, signal);
4216
5202
  }
4217
5203
  const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
4218
- await retainDaemonRoots(context.store, owner, [headCid]);
5204
+ await retainDaemonRoots(context.store, owner, [headCid], signal);
4219
5205
  await withStateAsync(context, (state) => indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
4220
5206
  skipRootFiles: v7RootSkipFiles(header.snapshot),
4221
5207
  ...(signal ? { signal } : {}),
@@ -4227,39 +5213,32 @@ export async function syncPivotReplicationAndIndex(context, configUrl, header, s
4227
5213
  export async function swarmTemplates(context, configUrl, selector) {
4228
5214
  if (selector !== undefined)
4229
5215
  templateName(selector);
4230
- const warm = await localHeader(context, configUrl);
4231
- if (warm && !warm.header.localSourceReady)
4232
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4233
- let header = warm?.header ??
4234
- (await swarmHeader(context, configUrl, undefined, "local-first"));
4235
- for (let attempt = 0;; attempt++) {
4236
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
4237
- header = await swarmHeader(context, configUrl, true, "local-first");
4238
- continue;
4239
- }
4240
- const meta = await swarmMeta(context, header);
4241
- const name = selector === undefined
4242
- ? undefined
4243
- : formalName(`${meta.templatePath}/${selector}`);
4244
- if (name &&
4245
- !(await resolveSnapshotName(context.store, header.snapshot, name)) &&
4246
- header.source === "cache" &&
4247
- !attempt) {
4248
- header = await swarmHeader(context, configUrl, true, "local-first");
4249
- continue;
4250
- }
4251
- const selectors = selector === undefined
4252
- ? (await listSubtreeNames(context.store, header.snapshot, meta.templatePath, false)).map((entry) => entry.name.slice(meta.templatePath.length + 1))
4253
- : [selector];
4254
- const items = [];
4255
- for (const item of selectors)
4256
- items.push(await templateEntry(context, configUrl, header, item));
4257
- return items;
4258
- }
5216
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5217
+ mode: "local-first",
5218
+ preferLocalCache: true,
5219
+ shouldRefresh: async (current) => {
5220
+ if (!hasMeta(current.snapshot))
5221
+ return true;
5222
+ if (selector === undefined)
5223
+ return false;
5224
+ await current.ensureLocalSource();
5225
+ const meta = await swarmMeta(context, current.header);
5226
+ const name = formalName(`${meta.templatePath}/${selector}`);
5227
+ return !(await resolveSnapshotName(context.store, current.snapshot, name));
5228
+ },
5229
+ });
5230
+ const meta = await swarmMeta(context, ctx.header);
5231
+ const selectors = selector === undefined
5232
+ ? (await listSubtreeNames(context.store, ctx.snapshot, meta.templatePath, false)).map((entry) => entry.name.slice(meta.templatePath.length + 1))
5233
+ : [selector];
5234
+ const items = [];
5235
+ for (const item of selectors)
5236
+ items.push(await templateEntry(context, configUrl, ctx.header, item));
5237
+ return items;
4259
5238
  }
4260
5239
  export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
4261
5240
  templateName(selector);
4262
- await pointer(context, configUrl);
5241
+ await swarmFsTransport.pointer(context, configUrl);
4263
5242
  const content = await templatePublicationSource(source, context.store);
4264
5243
  const details = await inspectTemplate(context.store, content);
4265
5244
  let location;
@@ -4289,57 +5268,44 @@ export async function setSwarmTemplate(context, configUrl, selector, source, exp
4289
5268
  export async function removeSwarmTemplate(context, configUrl, selector, expect) {
4290
5269
  templateName(selector);
4291
5270
  const expected = exactCid(expect);
4292
- const head = await pointer(context, configUrl);
4293
5271
  let basis;
4294
- for (let attempt = 0; attempt < 8; attempt++) {
4295
- const currentHead = await head.read();
4296
- const current = await readSnapshot(context.store, currentHead.root, configUrl);
4297
- const meta = await swarmMeta(context, { snapshot: current });
4298
- const name = formalName(`${meta.templatePath}/${selector}`);
4299
- if (basis !== undefined && basis !== name)
4300
- throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
4301
- basis = name;
4302
- const old = (await resolveSnapshotName(context.store, current, name))?.toString();
4303
- if (!old)
4304
- throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
4305
- if (old !== expected)
4306
- throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
4307
- let next;
4308
- if (isV7Snapshot(current)) {
4309
- next = await prepareV7PathDelete(context, configUrl, current, name);
4310
- }
4311
- else {
4312
- const names = { ...current.names };
4313
- delete names[name];
4314
- next = await prepareNamesPublication(context, configUrl, current, names, []);
4315
- }
4316
- try {
4317
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
4318
- }
4319
- catch (cause) {
4320
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4321
- throw cause;
4322
- if (cause instanceof ScopeApiError && cause.status === 412)
4323
- continue;
4324
- throw new HostError(`Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4325
- }
4326
- try {
4327
- await swarmHeader(context, configUrl, true);
4328
- }
4329
- catch (cause) {
4330
- throw new HostError(`Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
4331
- }
4332
- return {
4333
- swarm: configUrl,
4334
- templatePath: meta.templatePath,
4335
- metaCid: metaCid(current),
4336
- selector,
4337
- name,
4338
- reference: formatNameReference(configUrl, name),
4339
- targetCid: old,
4340
- };
4341
- }
4342
- throw new HostError("HEAD is busy; retry the template removal.");
5272
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
5273
+ allowLegacyNames: true,
5274
+ refreshAfterCommit: true,
5275
+ plan: async (planCtx) => {
5276
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
5277
+ const name = formalName(`${meta.templatePath}/${selector}`);
5278
+ if (basis !== undefined && basis !== name)
5279
+ throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
5280
+ basis = name;
5281
+ const old = (await planCtx.resolve(name))?.toString();
5282
+ if (!old)
5283
+ throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
5284
+ if (old !== expected)
5285
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
5286
+ return {
5287
+ kind: "commit",
5288
+ operations: [{ op: "delete", path: name }],
5289
+ recursiveRoots: [],
5290
+ retainedRecursive: [],
5291
+ result: {
5292
+ swarm: configUrl,
5293
+ templatePath: meta.templatePath,
5294
+ metaCid: metaCid(planCtx.snapshot),
5295
+ selector,
5296
+ name,
5297
+ reference: formatNameReference(configUrl, name),
5298
+ targetCid: old,
5299
+ },
5300
+ };
5301
+ },
5302
+ messages: {
5303
+ unconfirmed: (cause) => `Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5304
+ pinStale: (cause) => `Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
5305
+ headBusy: () => "HEAD is busy; retry the template removal.",
5306
+ },
5307
+ });
5308
+ return committed.result;
4343
5309
  }
4344
5310
  async function registryAssociations(context, header) {
4345
5311
  assertNamesRegistry(header.snapshot);
@@ -4358,18 +5324,13 @@ async function registryAssociations(context, header) {
4358
5324
  return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
4359
5325
  }
4360
5326
  export async function swarmRegistrations(context, configUrl) {
4361
- let header = await swarmHeader(context, configUrl);
4362
- if (!hasMeta(header.snapshot) && header.source === "cache")
4363
- header = await swarmHeader(context, configUrl, true);
4364
- return registryAssociations(context, header);
5327
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5328
+ mode: "active",
5329
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
5330
+ });
5331
+ return registryAssociations(context, ctx.header);
4365
5332
  }
4366
5333
  export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
4367
- const warm = mode === "local-first" ? await localHeader(context, configUrl) : undefined;
4368
- if (warm && !warm.header.localSourceReady)
4369
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4370
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
4371
- if (!hasMeta(header.snapshot) && header.source === "cache")
4372
- header = await swarmHeader(context, configUrl, true);
4373
5334
  const findAssociation = async (current) => {
4374
5335
  if (isV7Snapshot(current.snapshot)) {
4375
5336
  const meta = await swarmMeta(context, current);
@@ -4380,50 +5341,25 @@ export async function swarmAssociation(context, configUrl, schemaCid, mode = "ac
4380
5341
  }
4381
5342
  return (await registryAssociations(context, current)).find((item) => item.schemaCid === schemaCid);
4382
5343
  };
4383
- let association = await findAssociation(header);
4384
- if (!association && header.source === "cache") {
4385
- header = await swarmHeader(context, configUrl, true);
4386
- association = await findAssociation(header);
4387
- }
4388
- return association;
4389
- }
4390
- async function prepareV7PathSet(context, configUrl, current, name, targetCid, roots, retainedRoots) {
4391
- const { newRootCid, createdDirCids } = await setUnixfsPath(context.store, CID.parse(current.stateBundle.cid), name, targetCid);
4392
- const recursiveRoots = [...new Set(roots)];
4393
- const retainedRecursive = [...new Set(retainedRoots ?? roots)];
4394
- await provideShallowContent(context.store, {
4395
- directBlocks: createdDirCids,
4396
- recursiveRoots,
4397
- retainedDirect: createdDirCids,
4398
- retainedRecursive,
4399
- endpoint: context.node.api,
4400
- ...(context.fetch ? { fetcher: context.fetch } : {}),
4401
- authorizationToken: context.node.auth,
4402
- owner: `publication:${newRootCid.toString()}`,
4403
- });
4404
- withState(context, (state) => {
4405
- state.invalidateSwarmHeader(configUrl);
4406
- });
4407
- return newRootCid.toString();
4408
- }
4409
- async function prepareV7PathDelete(context, configUrl, current, name) {
4410
- const { newRootCid, createdDirCids } = await deleteUnixfsPath(context.store, CID.parse(current.stateBundle.cid), name);
4411
- await provideShallowContent(context.store, {
4412
- directBlocks: createdDirCids,
4413
- recursiveRoots: [],
4414
- retainedDirect: createdDirCids,
4415
- retainedRecursive: [],
4416
- endpoint: context.node.api,
4417
- ...(context.fetch ? { fetcher: context.fetch } : {}),
4418
- authorizationToken: context.node.auth,
4419
- owner: `publication:${newRootCid.toString()}`,
4420
- });
4421
- withState(context, (state) => {
4422
- state.invalidateSwarmHeader(configUrl);
5344
+ let cachedHeader;
5345
+ let cachedResult;
5346
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5347
+ mode: "active",
5348
+ preferLocalCache: mode === "local-first",
5349
+ shouldRefresh: async (current) => {
5350
+ if (!hasMeta(current.snapshot))
5351
+ return true;
5352
+ await current.ensureLocalSource();
5353
+ cachedHeader = current.header;
5354
+ cachedResult = await findAssociation(current.header);
5355
+ return !cachedResult;
5356
+ },
4423
5357
  });
4424
- return newRootCid.toString();
5358
+ return ctx.header === cachedHeader
5359
+ ? cachedResult
5360
+ : findAssociation(ctx.header);
4425
5361
  }
4426
- async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
5362
+ export async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
4427
5363
  const identity = await contextIdentity(context);
4428
5364
  const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), undefined, identity.publicKey);
4429
5365
  await provideContent(context.store, [...new Set([next, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...(retainedRoots ?? roots)])]);
@@ -4433,7 +5369,7 @@ async function prepareNamesPublication(context, configUrl, current, names, roots
4433
5369
  return next;
4434
5370
  }
4435
5371
  async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
4436
- const head = await pointer(context, configUrl);
5372
+ await swarmFsTransport.pointer(context, configUrl);
4437
5373
  if (association) {
4438
5374
  const app = await openBundle(CID.parse(association.appCid), {
4439
5375
  resolveCid: (cid) => context.store.block.get(cid.toString()),
@@ -4444,49 +5380,43 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
4444
5380
  const roots = association
4445
5381
  ? await dependencies(context.store, association.appCid)
4446
5382
  : new Set();
4447
- for (let attempt = 0; attempt < 8; attempt++) {
4448
- const currentHead = await head.read();
4449
- const current = await readSnapshot(context.store, currentHead.root, configUrl);
4450
- assertNamesRegistry(current);
4451
- const meta = await swarmMeta(context, { snapshot: current });
4452
- const name = formalName(`${meta.registryPath}/${schemaCid}`);
4453
- const oldCid = (await resolveSnapshotName(context.store, current, name))?.toString();
4454
- if (association) {
4455
- if (oldCid === association.appCid)
4456
- return;
4457
- if (oldCid && !replace)
4458
- throw new HostError("Schema has another association; use --replace.");
4459
- }
4460
- else if (!oldCid) {
4461
- throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
4462
- }
4463
- let next;
4464
- if (isV7Snapshot(current)) {
4465
- next = association
4466
- ? await prepareV7PathSet(context, configUrl, current, name, CID.parse(association.appCid), roots)
4467
- : await prepareV7PathDelete(context, configUrl, current, name);
4468
- }
4469
- else {
4470
- const names = { ...current.names };
4471
- if (association)
4472
- names[name] = CID.parse(association.appCid);
4473
- else
4474
- delete names[name];
4475
- next = await prepareNamesPublication(context, configUrl, current, names, roots);
4476
- }
4477
- try {
4478
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
4479
- return;
4480
- }
4481
- catch (cause) {
4482
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4483
- throw cause;
4484
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
4485
- throw new HostError(`Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4486
- continue;
4487
- }
4488
- }
4489
- throw new HostError(`HEAD is busy for ${configUrl}; retry the registry edit.`);
5383
+ await swarmFs.commitSwarmPaths(context, configUrl, {
5384
+ allowLegacyNames: true,
5385
+ refreshAfterCommit: false,
5386
+ plan: async (planCtx) => {
5387
+ assertNamesRegistry(planCtx.snapshot);
5388
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
5389
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
5390
+ const oldCid = (await planCtx.resolve(name))?.toString();
5391
+ if (association) {
5392
+ if (oldCid === association.appCid)
5393
+ return { kind: "noop", result: undefined };
5394
+ if (oldCid && !replace)
5395
+ throw new HostError("Schema has another association; use --replace.");
5396
+ return {
5397
+ kind: "commit",
5398
+ operations: [
5399
+ { op: "set", path: name, targetCid: CID.parse(association.appCid) },
5400
+ ],
5401
+ recursiveRoots: roots,
5402
+ result: undefined,
5403
+ };
5404
+ }
5405
+ if (!oldCid)
5406
+ throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
5407
+ return {
5408
+ kind: "commit",
5409
+ operations: [{ op: "delete", path: name }],
5410
+ recursiveRoots: [],
5411
+ retainedRecursive: [],
5412
+ result: undefined,
5413
+ };
5414
+ },
5415
+ messages: {
5416
+ unconfirmed: (cause, url) => `Registry publication unconfirmed for ${url}: ${message(cause)}. Inspect the Swarm registry before retry.`,
5417
+ headBusy: (url) => `HEAD is busy for ${url}; retry the registry edit.`,
5418
+ },
5419
+ });
4490
5420
  }
4491
5421
  export async function setSwarmAssociation(context, configUrl, value, replace = false) {
4492
5422
  if (value.argv.length !== 1 || value.argv[0] !== "%")
@@ -4597,41 +5527,31 @@ export async function unpublish(context, options) {
4597
5527
  throw new HostError("Unpublish requires a selected Swarm configuration URL or alias.");
4598
5528
  const name = formalName(options.name);
4599
5529
  const expected = exactCid(options.expect);
4600
- const head = await pointer(context, options.swarm);
4601
- for (let attempt = 0; attempt < 8; attempt++) {
4602
- const currentHead = await head.read();
4603
- const current = await readSnapshot(context.store, currentHead.root, options.swarm);
4604
- const old = (await resolveSnapshotName(context.store, current, name))?.toString();
4605
- if (!old)
4606
- throw new HostError(`Name "${name}" is missing; nothing was removed.`);
4607
- if (old !== expected)
4608
- throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
4609
- let next;
4610
- if (isV7Snapshot(current)) {
4611
- next = await prepareV7PathDelete(context, options.swarm, current, name);
4612
- }
4613
- else {
4614
- const names = { ...current.names };
4615
- delete names[name];
4616
- next = await prepareNamesPublication(context, options.swarm, current, names, []);
4617
- }
4618
- try {
4619
- await head.write(next, currentHead.cid, uniqueId());
4620
- }
4621
- catch (cause) {
4622
- if (cause instanceof ScopeApiError && cause.status === 412)
4623
- continue;
4624
- throw new HostError(`Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4625
- }
4626
- try {
4627
- await swarmHeader(context, options.swarm, true);
4628
- }
4629
- catch (cause) {
4630
- throw new HostError(`Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
4631
- }
4632
- return { name, targetCid: old };
4633
- }
4634
- throw new HostError("HEAD is busy; retry unpublish.");
5530
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
5531
+ allowLegacyNames: true,
5532
+ refreshAfterCommit: true,
5533
+ plan: async (planCtx) => {
5534
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
5535
+ const old = (await planCtx.resolve(name))?.toString();
5536
+ if (!old)
5537
+ throw new HostError(`Name "${name}" is missing; nothing was removed.`);
5538
+ if (old !== expected)
5539
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
5540
+ return {
5541
+ kind: "commit",
5542
+ operations: [{ op: "delete", path: name }],
5543
+ recursiveRoots: [],
5544
+ retainedRecursive: [],
5545
+ result: { name, targetCid: old },
5546
+ };
5547
+ },
5548
+ messages: {
5549
+ unconfirmed: (cause) => `Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5550
+ pinStale: (cause) => `Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
5551
+ headBusy: () => "HEAD is busy; retry unpublish.",
5552
+ },
5553
+ });
5554
+ return committed.result;
4635
5555
  }
4636
5556
  export async function publish(context, content, options) {
4637
5557
  return publishContent(context, content, options);
@@ -4639,7 +5559,7 @@ export async function publish(context, content, options) {
4639
5559
  async function publishContent(context, content, options, nameForSnapshot) {
4640
5560
  if (!options.swarm)
4641
5561
  throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
4642
- const head = await pointer(context, options.swarm);
5562
+ await swarmFsTransport.pointer(context, options.swarm);
4643
5563
  const roots = await dependencies(context.store, content);
4644
5564
  const currentRoots = [...(await currentDependencies(context.store, content))];
4645
5565
  await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
@@ -4664,45 +5584,43 @@ async function publishContent(context, content, options, nameForSnapshot) {
4664
5584
  timestamp: new Date().toISOString(),
4665
5585
  });
4666
5586
  roots.add(candidate);
4667
- if (expected)
4668
- for (const root of await dependencies(context.store, expected))
5587
+ const expectedDeps = expected
5588
+ ? await dependencies(context.store, expected)
5589
+ : undefined;
5590
+ if (expectedDeps)
5591
+ for (const root of expectedDeps)
4669
5592
  roots.add(root);
4670
- for (let attempt = 0; attempt < 8; attempt++) {
4671
- const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root, options.swarm);
4672
- if (nameForSnapshot) {
4673
- name = await nameForSnapshot(current);
4674
- if (resolvedName !== undefined && resolvedName !== name)
4675
- throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
4676
- resolvedName = name;
4677
- }
4678
- const existing = (await resolveSnapshotName(context.store, current, name))?.toString();
4679
- if (existing !== expected)
4680
- 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");
4681
- const retained = [
4682
- candidate,
4683
- ...(expected ? await dependencies(context.store, expected) : []),
4684
- ];
4685
- const next = isV7Snapshot(current)
4686
- ? await prepareV7PathSet(context, options.swarm, current, name, CID.parse(candidate), roots, retained)
4687
- : await prepareNamesPublication(context, options.swarm, current, { ...current.names, [name]: CID.parse(candidate) }, roots, retained);
4688
- try {
4689
- await writeNamesHead(context, options.swarm, head, next, currentHead.cid);
4690
- }
4691
- catch (cause) {
4692
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4693
- throw cause;
4694
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
4695
- throw new HostError(`HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4696
- continue;
4697
- }
4698
- try {
4699
- await swarmHeader(context, options.swarm, true);
4700
- }
4701
- catch (cause) {
4702
- 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");
4703
- }
4704
- return candidate;
4705
- }
4706
- throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
5593
+ const retained = [candidate, ...(expectedDeps ?? [])];
5594
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
5595
+ allowLegacyNames: true,
5596
+ refreshAfterCommit: true,
5597
+ plan: async (planCtx) => {
5598
+ if (nameForSnapshot) {
5599
+ name = await nameForSnapshot(planCtx.snapshot);
5600
+ if (resolvedName !== undefined && resolvedName !== name)
5601
+ throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
5602
+ resolvedName = name;
5603
+ }
5604
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
5605
+ const existing = (await planCtx.resolve(name))?.toString();
5606
+ if (existing !== expected)
5607
+ 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");
5608
+ return {
5609
+ kind: "commit",
5610
+ operations: [
5611
+ { op: "set", path: name, targetCid: CID.parse(candidate) },
5612
+ ],
5613
+ recursiveRoots: roots,
5614
+ retainedRecursive: retained,
5615
+ result: candidate,
5616
+ };
5617
+ },
5618
+ messages: {
5619
+ unconfirmed: (cause) => `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
5620
+ pinStale: (cause) => `Publication committed as ${candidate}, but its HEAD/subscription refresh failed: ${message(cause)}. Published content remains pinned; inspect HEAD and retry the affected Name pin.`,
5621
+ headBusy: () => `HEAD is busy; candidate ${candidate} remains retained.`,
5622
+ },
5623
+ });
5624
+ return committed.result;
4707
5625
  }
4708
5626
  //# sourceMappingURL=swarm.js.map