@ipab/cli 0.1.0-rc.11 → 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 (95) hide show
  1. package/README.md +15 -10
  2. package/dist/authoring.d.ts +6 -2
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +65 -18
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/builtins/skill.ipab.car +0 -0
  7. package/dist/cli.d.ts +2 -1
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +854 -179
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config-secret.js +1 -1
  12. package/dist/config-secret.js.map +1 -1
  13. package/dist/daemon-ui.d.ts +1 -0
  14. package/dist/daemon-ui.d.ts.map +1 -1
  15. package/dist/daemon-ui.js +2 -0
  16. package/dist/daemon-ui.js.map +1 -1
  17. package/dist/history.d.ts +3 -1
  18. package/dist/history.d.ts.map +1 -1
  19. package/dist/history.js +16 -1
  20. package/dist/history.js.map +1 -1
  21. package/dist/kubo-topology.d.ts +2 -0
  22. package/dist/kubo-topology.d.ts.map +1 -1
  23. package/dist/kubo-topology.js +17 -20
  24. package/dist/kubo-topology.js.map +1 -1
  25. package/dist/kubo.d.ts +5 -3
  26. package/dist/kubo.d.ts.map +1 -1
  27. package/dist/kubo.js +83 -13
  28. package/dist/kubo.js.map +1 -1
  29. package/dist/name-reference.d.ts +8 -0
  30. package/dist/name-reference.d.ts.map +1 -0
  31. package/dist/name-reference.js +63 -0
  32. package/dist/name-reference.js.map +1 -0
  33. package/dist/pivot-rpc.d.ts +37 -2
  34. package/dist/pivot-rpc.d.ts.map +1 -1
  35. package/dist/pivot-rpc.js +188 -8
  36. package/dist/pivot-rpc.js.map +1 -1
  37. package/dist/search-index.d.ts.map +1 -1
  38. package/dist/search-index.js +1 -0
  39. package/dist/search-index.js.map +1 -1
  40. package/dist/skill-definition.d.ts +9 -0
  41. package/dist/skill-definition.d.ts.map +1 -1
  42. package/dist/skill-definition.js +26 -2
  43. package/dist/skill-definition.js.map +1 -1
  44. package/dist/skill-source.d.ts +1 -0
  45. package/dist/skill-source.d.ts.map +1 -1
  46. package/dist/skill-source.js +10 -4
  47. package/dist/skill-source.js.map +1 -1
  48. package/dist/skills.d.ts +8 -2
  49. package/dist/skills.d.ts.map +1 -1
  50. package/dist/skills.js +31 -2
  51. package/dist/skills.js.map +1 -1
  52. package/dist/swarm-fs-core.d.ts +217 -0
  53. package/dist/swarm-fs-core.d.ts.map +1 -0
  54. package/dist/swarm-fs-core.js +885 -0
  55. package/dist/swarm-fs-core.js.map +1 -0
  56. package/dist/swarm-fs-path.d.ts +17 -0
  57. package/dist/swarm-fs-path.d.ts.map +1 -0
  58. package/dist/swarm-fs-path.js +46 -0
  59. package/dist/swarm-fs-path.js.map +1 -0
  60. package/dist/swarm-fs.d.ts +9 -0
  61. package/dist/swarm-fs.d.ts.map +1 -0
  62. package/dist/swarm-fs.js +21 -0
  63. package/dist/swarm-fs.js.map +1 -0
  64. package/dist/swarm-observations.d.ts +6 -0
  65. package/dist/swarm-observations.d.ts.map +1 -1
  66. package/dist/swarm-observations.js +28 -8
  67. package/dist/swarm-observations.js.map +1 -1
  68. package/dist/swarm.d.ts +124 -17
  69. package/dist/swarm.d.ts.map +1 -1
  70. package/dist/swarm.js +1085 -450
  71. package/dist/swarm.js.map +1 -1
  72. package/dist/unixfs-tree.d.ts +55 -0
  73. package/dist/unixfs-tree.d.ts.map +1 -1
  74. package/dist/unixfs-tree.js +361 -2
  75. package/dist/unixfs-tree.js.map +1 -1
  76. package/package.json +5 -5
  77. package/src/authoring.ts +88 -28
  78. package/src/cli.ts +1142 -267
  79. package/src/config-secret.ts +1 -1
  80. package/src/daemon-ui.ts +3 -0
  81. package/src/history.ts +26 -1
  82. package/src/kubo-topology.ts +25 -22
  83. package/src/kubo.ts +127 -9
  84. package/src/name-reference.ts +91 -0
  85. package/src/pivot-rpc.ts +272 -14
  86. package/src/search-index.ts +1 -0
  87. package/src/skill-definition.ts +45 -3
  88. package/src/skill-source.ts +10 -4
  89. package/src/skills.ts +43 -2
  90. package/src/swarm-fs-core.ts +1461 -0
  91. package/src/swarm-fs-path.ts +68 -0
  92. package/src/swarm-fs.ts +104 -0
  93. package/src/swarm-observations.ts +40 -14
  94. package/src/swarm.ts +1538 -656
  95. 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
22
  import { LOCAL_SWARM_ALIAS, LOCAL_SWARM_URL, isLocalSwarm, isReservedLocalHost, 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";
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));
@@ -195,7 +204,7 @@ async function ensureLocalSwarm(context) {
195
204
  const skill = await seedSkillSource();
196
205
  for (const [cid, data] of skill.blocks)
197
206
  await context.store.put(CID.parse(cid), data);
198
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
207
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
199
208
  let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
200
209
  templatePath: "ipab/templates",
201
210
  registryPath: "ipab/registry",
@@ -703,7 +712,7 @@ export async function swarmMembers(context, url, refresh = false) {
703
712
  local: observationSummary(observations.local),
704
713
  };
705
714
  }
706
- export async function swarmNetworking(context, url, config, directory) {
715
+ export async function swarmNetworking(context, url, config, directory, currentHeadCid) {
707
716
  rejectLocalSwarm(url, "swarm networking");
708
717
  directory ??= (await inspection(context, url)).directory;
709
718
  const { account, local } = await localObservations(context, url, config);
@@ -755,6 +764,10 @@ export async function swarmNetworking(context, url, config, directory) {
755
764
  : actual.length
756
765
  ? "relay"
757
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;
758
771
  return {
759
772
  publicKey: member.publicKey,
760
773
  name: profile.name,
@@ -782,6 +795,22 @@ export async function swarmNetworking(context, url, config, directory) {
782
795
  freshness,
783
796
  addresses: actual.map((entry) => entry.address),
784
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
+ },
785
814
  };
786
815
  }),
787
816
  };
@@ -795,19 +824,28 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
795
824
  stopAtBundle: true,
796
825
  });
797
826
  const templatePrefix = `${meta.templatePath}/`;
798
- const skillPrefix = meta.skillPath ? `${meta.skillPath}/` : undefined;
827
+ const globalSkillPrefix = meta.skillPath
828
+ ? `${meta.skillPath}/global/`
829
+ : undefined;
830
+ const typeSkillPrefix = meta.skillPath
831
+ ? `${meta.skillPath}/types/`
832
+ : undefined;
799
833
  const registryPrefix = `${meta.registryPath}/`;
800
834
  let templates = 0;
801
- let skills = 0;
835
+ let globalSkills = 0;
836
+ let typeSkills = 0;
802
837
  let registrations = 0;
803
838
  for (const entry of walked.entries) {
804
839
  if (entry.name.startsWith(templatePrefix))
805
840
  templates++;
806
- else if (skillPrefix && entry.name.startsWith(skillPrefix))
807
- skills++;
841
+ else if (globalSkillPrefix && entry.name.startsWith(globalSkillPrefix))
842
+ globalSkills++;
843
+ else if (typeSkillPrefix && entry.name.startsWith(typeSkillPrefix))
844
+ typeSkills++;
808
845
  else if (entry.name.startsWith(registryPrefix))
809
846
  registrations++;
810
847
  }
848
+ const skills = globalSkills + typeSkills;
811
849
  return {
812
850
  mode: "local",
813
851
  configUrl: LOCAL_SWARM_URL,
@@ -827,6 +865,8 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
827
865
  names: walked.entries.length,
828
866
  templates,
829
867
  skills,
868
+ globalSkills,
869
+ typeSkills,
830
870
  registrations,
831
871
  },
832
872
  networking: {
@@ -863,7 +903,7 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
863
903
  status: "unavailable",
864
904
  error: "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
865
905
  },
866
- networking: await swarmNetworking(context, url, config, directory),
906
+ networking: await swarmNetworking(context, url, config, directory, head.root),
867
907
  };
868
908
  }
869
909
  function accountProfileLocation(context, publicKey) {
@@ -1307,6 +1347,7 @@ async function privateSource(context, record, signal, candidates) {
1307
1347
  source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
1308
1348
  };
1309
1349
  }
1350
+ const pivotReadinessRefreshIntervalMs = 45_000;
1310
1351
  export async function swarmDaemon(context, signal, synchronize) {
1311
1352
  const lock = await privateDirectory(context.stateDir, "swarm-daemon");
1312
1353
  await withPrivateLock(lock, async () => {
@@ -1390,7 +1431,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1390
1431
  : "unknown",
1391
1432
  running: Boolean(session?.running),
1392
1433
  receiptRpc: {
1393
- active: Boolean(session?.pivotServer),
1434
+ active: Boolean(session?.pivotServer?.listening),
1394
1435
  protocol: pivotReceiptProtocol,
1395
1436
  epoch: session?.pivotServer?.epoch ?? null,
1396
1437
  headId: session?.pivotServer?.headId ?? null,
@@ -1492,6 +1533,23 @@ export async function swarmDaemon(context, signal, synchronize) {
1492
1533
  error: "No connection snapshot collected.",
1493
1534
  peers: [],
1494
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
+ : {}),
1495
1553
  };
1496
1554
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1497
1555
  };
@@ -1530,6 +1588,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1530
1588
  };
1531
1589
  sessions.set(url, session);
1532
1590
  }
1591
+ let pivotListenerVerified = false;
1533
1592
  try {
1534
1593
  if (session.record?.config && context.pivot === undefined) {
1535
1594
  const self = session.record.config.members.find((member) => member.publicKey === session.record.account);
@@ -1570,6 +1629,22 @@ export async function swarmDaemon(context, signal, synchronize) {
1570
1629
  }
1571
1630
  if (!session.node)
1572
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
+ }
1573
1648
  let healthy = 0;
1574
1649
  await boundedMap([...session.candidates.active()], async ([id, addresses]) => {
1575
1650
  let success = false;
@@ -1591,8 +1666,8 @@ export async function swarmDaemon(context, signal, synchronize) {
1591
1666
  }
1592
1667
  });
1593
1668
  session.healthy = healthy;
1594
- // Startup-captured relay/bootstrap options must be removed immediately
1595
- // 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.
1596
1671
  const record = session.record;
1597
1672
  const self = record.config.members.find((member) => member.publicKey === record.account);
1598
1673
  const desired = memberPeers(self.peerId, session.candidates.active(), []);
@@ -1604,52 +1679,138 @@ export async function swarmDaemon(context, signal, synchronize) {
1604
1679
  });
1605
1680
  session.selected = new Set(desired.map(({ ID }) => ID));
1606
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);
1607
1700
  if (session.pivot) {
1608
1701
  if (!session.pivotServer ||
1702
+ !session.pivotServer.server.listening ||
1609
1703
  session.pivotServer.nodeApi !== session.node.api ||
1610
1704
  session.pivotServer.epoch !== record.config.epoch ||
1611
1705
  session.pivotServer.headId !== record.config.headId) {
1612
1706
  await stopPivotServer(session);
1613
1707
  const pivotNode = session.node;
1614
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
+ },
1615
1723
  receipt: (receiptRequest, requestSignal) => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal),
1616
1724
  search: (params) => withState(session.context, (state) => queryLocalSearchIndex(state, url, params)),
1617
1725
  ...(context.diagnostic
1618
1726
  ? { diagnostic: context.diagnostic }
1619
1727
  : {}),
1620
- }, session.context.fetch);
1728
+ }, session.context.fetch, signal);
1621
1729
  session.pivotServer = {
1622
1730
  server: mounted,
1623
1731
  nodeApi: session.node.api,
1624
1732
  epoch: record.config.epoch,
1625
1733
  headId: record.config.headId,
1734
+ listening: true,
1626
1735
  };
1627
1736
  }
1628
- 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;
1629
1745
  }
1630
1746
  else {
1631
1747
  await stopPivotServer(session);
1632
1748
  }
1633
- try {
1634
- const peers = await nodeConnections(session.node, signal);
1635
- session.connections = {
1636
- observedAt: Date.now(),
1637
- error: null,
1638
- peers,
1639
- };
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
+ });
1640
1774
  }
1641
- catch (cause) {
1642
- signal.throwIfAborted();
1643
- session.connections = {
1644
- observedAt: session.connections?.observedAt ?? null,
1645
- error: message(cause).slice(0, 2048),
1646
- peers: session.connections?.peers ?? [],
1647
- };
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
+ }
1648
1807
  }
1649
1808
  }
1650
1809
  catch (cause) {
1651
1810
  if (signal.aborted)
1652
1811
  return;
1812
+ if (!pivotListenerVerified && session.pivotServer)
1813
+ session.pivotServer.listening = false;
1653
1814
  session.error = message(cause);
1654
1815
  session.nextDiscovery = 0;
1655
1816
  emitDiagnostic(`[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`);
@@ -1925,13 +2086,12 @@ async function boundPointer(context, configUrl, record) {
1925
2086
  writeWithReceipt: (receipt) => client(context, c.service).writeWithReceipt(c.scopeId, record.config.headId, receipt),
1926
2087
  };
1927
2088
  }
1928
- async function writeNamesHead(context, url, head, root, cid) {
2089
+ export async function writeNamesHead(context, url, head, root, cid) {
1929
2090
  if (isLocalSwarm(url)) {
1930
- await head.write(root, cid, uniqueId());
1931
- return;
2091
+ return head.write(root, cid, uniqueId());
1932
2092
  }
1933
2093
  const lock = await privateDirectory(await directory(context), `state-pin-${createHash("sha256").update(url).digest("hex")}`);
1934
- await withPrivateLock(lock, async () => {
2094
+ return withPrivateLock(lock, async () => {
1935
2095
  if (context.confirmPublication) {
1936
2096
  try {
1937
2097
  await context.confirmPublication(url, root);
@@ -1939,8 +2099,7 @@ async function writeNamesHead(context, url, head, root, cid) {
1939
2099
  catch (cause) {
1940
2100
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1941
2101
  }
1942
- await head.write(root, cid, uniqueId());
1943
- return;
2102
+ return head.write(root, cid, uniqueId());
1944
2103
  }
1945
2104
  const idempotencyKey = uniqueId();
1946
2105
  let receipt;
@@ -1951,10 +2110,9 @@ async function writeNamesHead(context, url, head, root, cid) {
1951
2110
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1952
2111
  }
1953
2112
  if (receipt === null) {
1954
- await head.write(root, cid, idempotencyKey);
1955
- return;
2113
+ return head.write(root, cid, idempotencyKey);
1956
2114
  }
1957
- await head.writeWithReceipt(receipt);
2115
+ return head.writeWithReceipt(receipt);
1958
2116
  });
1959
2117
  }
1960
2118
  async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKey) {
@@ -2176,16 +2334,275 @@ export async function syncPivotPublications(context, url, signal) {
2176
2334
  }
2177
2335
  const source = context.store.withLocalSource(kuboSource(node, peers, context.diagnostic));
2178
2336
  try {
2337
+ if (CID.parse(head.root).code === dagPb.code)
2338
+ await pinPublication(source, [head.root], node, signal, context.fetch);
2179
2339
  await readSnapshot(source, head.root, url);
2180
2340
  const roots = CID.parse(head.root).code === dagPb.code
2181
2341
  ? [head.root]
2182
2342
  : await frozenPublicationClosure(source, head.root);
2183
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;
2350
+ }
2351
+ finally {
2352
+ await source.close();
2353
+ }
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;
2184
2478
  }
2185
2479
  finally {
2186
2480
  await source.close();
2187
2481
  }
2188
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
+ }
2189
2606
  export async function typedJson(store, cid, type) {
2190
2607
  const { bundle, value } = await bundleJson(store, cid);
2191
2608
  if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
@@ -2263,46 +2680,6 @@ async function writeV7RootBundle(store, configuration, configUrl) {
2263
2680
  });
2264
2681
  return jsonBundle(store, swarmRootType, value);
2265
2682
  }
2266
- function isV7Snapshot(snapshot) {
2267
- return snapshot.stateBundle?.unixfsRoot?.version === 7;
2268
- }
2269
- function v7RootSkipFiles(snapshot) {
2270
- const root = snapshot.stateBundle?.unixfsRoot;
2271
- if (!root)
2272
- return new Set();
2273
- return new Set([".bundle.yaml", root.typeFile, root.entryFile]);
2274
- }
2275
- async function resolveSnapshotName(store, snapshot, name) {
2276
- if (isV7Snapshot(snapshot))
2277
- return resolveUnixfsPath(store, CID.parse(snapshot.stateBundle.cid), name);
2278
- return Object.hasOwn(snapshot.names, name) ? snapshot.names[name] : undefined;
2279
- }
2280
- async function listSubtreeNames(store, snapshot, prefix, flatOnly = false) {
2281
- if (isV7Snapshot(snapshot)) {
2282
- const dirCid = await resolveUnixfsPath(store, CID.parse(snapshot.stateBundle.cid), prefix);
2283
- if (!dirCid)
2284
- return [];
2285
- if (flatOnly) {
2286
- const entries = await listUnixfsDirectory(store, dirCid);
2287
- return [...entries.entries()]
2288
- .map(([child, cid]) => ({ name: `${prefix}/${child}`, cid }))
2289
- .sort((a, b) => a.name.localeCompare(b.name));
2290
- }
2291
- const walked = await walkUnixfsNames(store, dirCid, {
2292
- prefix,
2293
- stopAtBundle: true,
2294
- });
2295
- return walked.entries.map((entry) => ({
2296
- name: entry.name,
2297
- cid: CID.parse(entry.targetCid),
2298
- }));
2299
- }
2300
- const needle = `${prefix}/`;
2301
- return Object.entries(snapshot.names)
2302
- .filter(([name]) => name.startsWith(needle))
2303
- .map(([name, cid]) => ({ name, cid }))
2304
- .sort((a, b) => a.name.localeCompare(b.name));
2305
- }
2306
2683
  async function readV7Root(store, cid) {
2307
2684
  const canonical = cid.toV1();
2308
2685
  const rootKey = canonical.toString();
@@ -2528,7 +2905,7 @@ async function publication(store, state, previous, writer) {
2528
2905
  await store.put(cid, data);
2529
2906
  return cid.toString();
2530
2907
  }
2531
- function missingContent(cause) {
2908
+ export function missingContent(cause) {
2532
2909
  let failure = cause;
2533
2910
  for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2534
2911
  failure = failure.cause;
@@ -2807,7 +3184,7 @@ function headerProjection(header) {
2807
3184
  throw new HostError("A verified account projection is required.");
2808
3185
  return header.projection;
2809
3186
  }
2810
- async function localHeader(context, url) {
3187
+ export async function localHeader(context, url) {
2811
3188
  if (isLocalSwarm(url))
2812
3189
  return { header: await readLocalSwarmHeader(context), account: "local" };
2813
3190
  if (context.forceRefresh)
@@ -2845,7 +3222,7 @@ async function localHeader(context, url) {
2845
3222
  }
2846
3223
  // SharedContent invokes this source only after a genuine local ENOENT. Its
2847
3224
  // store is not replaced from inside its own pending read (which would deadlock).
2848
- async function lazyPrivateSource(context, url, account, basis) {
3225
+ export async function lazyPrivateSource(context, url, account, basis) {
2849
3226
  rejectLocalSwarm(url, "private Kubo networking");
2850
3227
  const finishPrevious = context.finishRead;
2851
3228
  delete context.finishRead;
@@ -2971,7 +3348,7 @@ export async function createSwarm(context, options = {}) {
2971
3348
  const skill = await seedSkillSource();
2972
3349
  for (const [cid, data] of skill.blocks)
2973
3350
  await context.store.put(CID.parse(cid), data);
2974
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
3351
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
2975
3352
  let root;
2976
3353
  if (record.stateVersion === 7) {
2977
3354
  let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
@@ -3803,60 +4180,6 @@ export async function resumeRemoval(context, url) {
3803
4180
  }
3804
4181
  });
3805
4182
  }
3806
- export function formalName(name) {
3807
- relativePath(name);
3808
- if (name.length > 256 || name.startsWith("builtin:"))
3809
- throw new HostError("Invalid formal Name.");
3810
- return name;
3811
- }
3812
- function decodeNameComponent(value, part) {
3813
- try {
3814
- return decodeURIComponent(value);
3815
- }
3816
- catch {
3817
- throw new HostError(`Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`);
3818
- }
3819
- }
3820
- export function parseNameReference(reference) {
3821
- if (/^name:/i.test(reference))
3822
- throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
3823
- if (!/^ipab:/i.test(reference))
3824
- return undefined;
3825
- if (/^ipab:\/\/https?:\/\//i.test(reference))
3826
- 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.");
3827
- const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
3828
- if (!match)
3829
- throw new HostError("Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.");
3830
- const authority = decodeNameComponent(match[1], "authority");
3831
- if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
3832
- if (!/^https?:\/\//i.test(authority))
3833
- throw new HostError("Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.");
3834
- canonicalSwarmUrl(authority);
3835
- }
3836
- if (/[?#\s]/.test(match[2]))
3837
- throw new HostError("Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.");
3838
- const segments = match[2].split("/").map((segment) => {
3839
- const decoded = decodeNameComponent(segment, "path");
3840
- if (/[/\\]/.test(decoded))
3841
- throw new HostError("Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.");
3842
- return decoded;
3843
- });
3844
- try {
3845
- return {
3846
- ...(authority ? { swarm: authority } : {}),
3847
- name: match[2] === "" ? "" : formalName(segments.join("/")),
3848
- };
3849
- }
3850
- catch (error) {
3851
- if (!(error instanceof HostError))
3852
- throw error;
3853
- 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);
3854
- }
3855
- }
3856
- export function formatNameReference(swarm, name) {
3857
- const segment = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
3858
- return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
3859
- }
3860
4183
  export async function resolveReference(context, reference, swarm, local, raw = false, mode = "active") {
3861
4184
  const shared = parseNameReference(reference);
3862
4185
  let source;
@@ -3919,7 +4242,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
3919
4242
  return headContentFailure(context, source.configUrl, source.header.config, source.header.head, cause);
3920
4243
  }
3921
4244
  }
3922
- async function artifactValue(store, targetCid, protect) {
4245
+ export async function artifactValue(store, targetCid, protect) {
3923
4246
  let cid = targetCid;
3924
4247
  const visited = new Set();
3925
4248
  for (let depth = 0;; depth++) {
@@ -4306,11 +4629,55 @@ function metaCid(snapshot) {
4306
4629
  function hasMeta(snapshot) {
4307
4630
  return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
4308
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
+ }
4309
4675
  export async function swarmSkills(context, configUrl, requested, owner) {
4310
- const warm = await localHeader(context, configUrl);
4311
- if (warm && !warm.header.localSourceReady)
4312
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4313
- 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
+ });
4314
4681
  const roots = new Set();
4315
4682
  const protect = async (cid) => {
4316
4683
  roots.add(cid);
@@ -4319,29 +4686,24 @@ export async function swarmSkills(context, configUrl, requested, owner) {
4319
4686
  await context.store.confirmRetained(owner, values);
4320
4687
  };
4321
4688
  for (let attempt = 0;; attempt++) {
4322
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
4323
- header = await swarmHeader(context, configUrl, true);
4324
- continue;
4325
- }
4326
- if (hasMeta(header.snapshot)) {
4327
- if (isV7Snapshot(header.snapshot)) {
4689
+ if (hasMeta(ctx.snapshot)) {
4690
+ if (ctx.isV7) {
4328
4691
  if (context.store.supportsRetention) {
4329
- const rootId = metaCid(header.snapshot);
4692
+ const rootId = metaCid(ctx.snapshot);
4330
4693
  await context.store.retainDirect(owner, [rootId]);
4331
4694
  await context.store.confirmDirectRetained(owner, [rootId]);
4332
4695
  }
4333
4696
  }
4334
4697
  else {
4335
- await protect(metaCid(header.snapshot));
4698
+ await protect(metaCid(ctx.snapshot));
4336
4699
  }
4337
4700
  }
4338
- const meta = await swarmMeta(context, header);
4701
+ const meta = await swarmMeta(context, ctx.header);
4339
4702
  if (!meta.skillPath)
4340
- throw new HostError(header.snapshot.stateBundle
4341
- ? "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."
4342
- : `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.`);
4343
- const prefix = `${meta.skillPath}/`;
4344
- 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);
4345
4707
  for (const { cid: target } of entries)
4346
4708
  roots.add(target.toString());
4347
4709
  await context.store.registerOwnerAsync(owner, [...roots]);
@@ -4349,52 +4711,357 @@ export async function swarmSkills(context, configUrl, requested, owner) {
4349
4711
  const identities = new Set();
4350
4712
  for (const { name, cid: target } of entries) {
4351
4713
  if (name.slice(prefix.length).includes("/"))
4352
- throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
4714
+ throw new HostError(`Skill Name "${name}" must be flat under ${globalDir}.`);
4353
4715
  const cid = await artifactValue(context.store, target.toString(), protect);
4354
4716
  const bundle = await openBundle(CID.parse(cid), {
4355
4717
  resolveCid: (key) => context.store.block.get(key.toString()),
4356
4718
  });
4357
4719
  if (bundle.schemaKey !== skillSchema.cid.toString())
4358
4720
  throw new HostError(`Name "${name}" is not an exact Skill type Bundle.`);
4359
- const identity = await skillIdentity(bundle);
4360
- if (identities.has(identity))
4361
- throw new HostError(`Duplicate Skill installation name "${identity}" in this Swarm.`);
4362
- identities.add(identity);
4363
- 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
+ });
4364
4731
  }
4365
4732
  const missing = requested.filter((reference) => !result.some((skill) => skill.name === reference || skill.identity === reference));
4366
- if (missing.length && !attempt && header.source === "cache") {
4367
- 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
+ });
4368
4738
  continue;
4369
4739
  }
4370
4740
  if (missing.length)
4371
- 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(", ")}.`);
4372
4742
  return result;
4373
4743
  }
4374
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
+ }
4375
5030
  export async function resolveTemplateSelector(context, selector, configUrl) {
4376
5031
  formalName(selector);
4377
- const warm = await localHeader(context, configUrl);
4378
- if (warm && !warm.header.localSourceReady)
4379
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4380
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
4381
- if (!hasMeta(header.snapshot) && header.source === "cache")
4382
- header = await swarmHeader(context, configUrl, true);
4383
- for (let attempt = 0;; attempt++) {
4384
- const meta = await swarmMeta(context, header);
4385
- const name = formalName(`${meta.templatePath}/${selector}`);
4386
- const target = await resolveSnapshotName(context.store, header.snapshot, name);
4387
- if (target)
4388
- return artifactValue(context.store, target.toString());
4389
- if (attempt || header.source !== "cache")
4390
- throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
4391
- 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;
4392
5056
  }
4393
- }
4394
- export function templateName(name) {
4395
- if (name.includes(":"))
4396
- throw new HostError("Template NAME must be a safe relative Name, not a URI.");
4397
- 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.`);
4398
5065
  }
4399
5066
  async function templateEntry(context, configUrl, header, selector) {
4400
5067
  const meta = await swarmMeta(context, header);
@@ -4414,19 +5081,55 @@ async function templateEntry(context, configUrl, header, selector) {
4414
5081
  ...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
4415
5082
  };
4416
5083
  }
4417
- async function retainDaemonRoots(store, owner, roots) {
5084
+ async function retainDaemonRoots(store, owner, roots, signal) {
4418
5085
  const unique = [...new Set(roots)];
5086
+ const options = signal ? [{ signal }] : [];
4419
5087
  if (!store.supportsRetention) {
4420
5088
  for (const root of unique)
4421
- await store.prepare(root);
5089
+ await store.prepare(root, ...options);
4422
5090
  return;
4423
5091
  }
4424
- await store.recoverOwner(owner, []);
5092
+ await store.recoverOwner(owner, [], ...options);
4425
5093
  if (unique.length) {
4426
- await store.retain(owner, unique);
4427
- await store.confirmRetained(owner, unique);
5094
+ await store.retain(owner, unique, ...options);
5095
+ await store.confirmRetained(owner, unique, ...options);
5096
+ }
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
+ }
4428
5130
  }
4429
- await store.reconcile(owner, unique);
5131
+ await retainDaemonRoots(context.store, owner, roots);
5132
+ return entries.length;
4430
5133
  }
4431
5134
  export async function syncSwarmTemplates(context, configUrl, header) {
4432
5135
  if (!hasMeta(header.snapshot))
@@ -4488,13 +5191,17 @@ export async function syncSwarmRegistry(context, configUrl, header) {
4488
5191
  export async function syncPivotReplicationAndIndex(context, configUrl, header, signal) {
4489
5192
  if (!context.pivot || !isV7Snapshot(header.snapshot))
4490
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) {
4491
5198
  const headCid = CID.parse(header.stateCid).toV1().toString();
4492
5199
  const previousHead = withState(context, (state) => state.searchIndexState(configUrl)?.headCid ?? null);
4493
5200
  if (context.node) {
4494
5201
  await pinAdd(context.node, headCid, true, signal);
4495
5202
  }
4496
5203
  const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
4497
- await retainDaemonRoots(context.store, owner, [headCid]);
5204
+ await retainDaemonRoots(context.store, owner, [headCid], signal);
4498
5205
  await withStateAsync(context, (state) => indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
4499
5206
  skipRootFiles: v7RootSkipFiles(header.snapshot),
4500
5207
  ...(signal ? { signal } : {}),
@@ -4506,39 +5213,32 @@ export async function syncPivotReplicationAndIndex(context, configUrl, header, s
4506
5213
  export async function swarmTemplates(context, configUrl, selector) {
4507
5214
  if (selector !== undefined)
4508
5215
  templateName(selector);
4509
- const warm = await localHeader(context, configUrl);
4510
- if (warm && !warm.header.localSourceReady)
4511
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4512
- let header = warm?.header ??
4513
- (await swarmHeader(context, configUrl, undefined, "local-first"));
4514
- for (let attempt = 0;; attempt++) {
4515
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
4516
- header = await swarmHeader(context, configUrl, true, "local-first");
4517
- continue;
4518
- }
4519
- const meta = await swarmMeta(context, header);
4520
- const name = selector === undefined
4521
- ? undefined
4522
- : formalName(`${meta.templatePath}/${selector}`);
4523
- if (name &&
4524
- !(await resolveSnapshotName(context.store, header.snapshot, name)) &&
4525
- header.source === "cache" &&
4526
- !attempt) {
4527
- header = await swarmHeader(context, configUrl, true, "local-first");
4528
- continue;
4529
- }
4530
- const selectors = selector === undefined
4531
- ? (await listSubtreeNames(context.store, header.snapshot, meta.templatePath, false)).map((entry) => entry.name.slice(meta.templatePath.length + 1))
4532
- : [selector];
4533
- const items = [];
4534
- for (const item of selectors)
4535
- items.push(await templateEntry(context, configUrl, header, item));
4536
- return items;
4537
- }
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;
4538
5238
  }
4539
5239
  export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
4540
5240
  templateName(selector);
4541
- await pointer(context, configUrl);
5241
+ await swarmFsTransport.pointer(context, configUrl);
4542
5242
  const content = await templatePublicationSource(source, context.store);
4543
5243
  const details = await inspectTemplate(context.store, content);
4544
5244
  let location;
@@ -4568,57 +5268,44 @@ export async function setSwarmTemplate(context, configUrl, selector, source, exp
4568
5268
  export async function removeSwarmTemplate(context, configUrl, selector, expect) {
4569
5269
  templateName(selector);
4570
5270
  const expected = exactCid(expect);
4571
- const head = await pointer(context, configUrl);
4572
5271
  let basis;
4573
- for (let attempt = 0; attempt < 8; attempt++) {
4574
- const currentHead = await head.read();
4575
- const current = await readSnapshot(context.store, currentHead.root, configUrl);
4576
- const meta = await swarmMeta(context, { snapshot: current });
4577
- const name = formalName(`${meta.templatePath}/${selector}`);
4578
- if (basis !== undefined && basis !== name)
4579
- throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
4580
- basis = name;
4581
- const old = (await resolveSnapshotName(context.store, current, name))?.toString();
4582
- if (!old)
4583
- throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
4584
- if (old !== expected)
4585
- throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
4586
- let next;
4587
- if (isV7Snapshot(current)) {
4588
- next = await prepareV7PathDelete(context, configUrl, current, name);
4589
- }
4590
- else {
4591
- const names = { ...current.names };
4592
- delete names[name];
4593
- next = await prepareNamesPublication(context, configUrl, current, names, []);
4594
- }
4595
- try {
4596
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
4597
- }
4598
- catch (cause) {
4599
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4600
- throw cause;
4601
- if (cause instanceof ScopeApiError && cause.status === 412)
4602
- continue;
4603
- throw new HostError(`Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4604
- }
4605
- try {
4606
- await swarmHeader(context, configUrl, true);
4607
- }
4608
- catch (cause) {
4609
- throw new HostError(`Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
4610
- }
4611
- return {
4612
- swarm: configUrl,
4613
- templatePath: meta.templatePath,
4614
- metaCid: metaCid(current),
4615
- selector,
4616
- name,
4617
- reference: formatNameReference(configUrl, name),
4618
- targetCid: old,
4619
- };
4620
- }
4621
- 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;
4622
5309
  }
4623
5310
  async function registryAssociations(context, header) {
4624
5311
  assertNamesRegistry(header.snapshot);
@@ -4637,18 +5324,13 @@ async function registryAssociations(context, header) {
4637
5324
  return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
4638
5325
  }
4639
5326
  export async function swarmRegistrations(context, configUrl) {
4640
- let header = await swarmHeader(context, configUrl);
4641
- if (!hasMeta(header.snapshot) && header.source === "cache")
4642
- header = await swarmHeader(context, configUrl, true);
4643
- 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);
4644
5332
  }
4645
5333
  export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
4646
- const warm = mode === "local-first" ? await localHeader(context, configUrl) : undefined;
4647
- if (warm && !warm.header.localSourceReady)
4648
- await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
4649
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
4650
- if (!hasMeta(header.snapshot) && header.source === "cache")
4651
- header = await swarmHeader(context, configUrl, true);
4652
5334
  const findAssociation = async (current) => {
4653
5335
  if (isV7Snapshot(current.snapshot)) {
4654
5336
  const meta = await swarmMeta(context, current);
@@ -4659,54 +5341,25 @@ export async function swarmAssociation(context, configUrl, schemaCid, mode = "ac
4659
5341
  }
4660
5342
  return (await registryAssociations(context, current)).find((item) => item.schemaCid === schemaCid);
4661
5343
  };
4662
- let association = await findAssociation(header);
4663
- if (!association && header.source === "cache") {
4664
- header = await swarmHeader(context, configUrl, true);
4665
- association = await findAssociation(header);
4666
- }
4667
- return association;
4668
- }
4669
- async function prepareV7PathSet(context, configUrl, current, name, targetCid, roots, retainedRoots) {
4670
- const { newRootCid, createdDirCids } = await setUnixfsPath(context.store, CID.parse(current.stateBundle.cid), name, targetCid);
4671
- if (isLocalSwarm(configUrl))
4672
- return newRootCid.toString();
4673
- const recursiveRoots = [...new Set(roots)];
4674
- const retainedRecursive = [...new Set(retainedRoots ?? roots)];
4675
- await provideShallowContent(context.store, {
4676
- directBlocks: createdDirCids,
4677
- recursiveRoots,
4678
- retainedDirect: createdDirCids,
4679
- retainedRecursive,
4680
- endpoint: context.node.api,
4681
- ...(context.fetch ? { fetcher: context.fetch } : {}),
4682
- authorizationToken: context.node.auth,
4683
- owner: `publication:${newRootCid.toString()}`,
4684
- });
4685
- withState(context, (state) => {
4686
- state.invalidateSwarmHeader(configUrl);
4687
- });
4688
- return newRootCid.toString();
4689
- }
4690
- async function prepareV7PathDelete(context, configUrl, current, name) {
4691
- const { newRootCid, createdDirCids } = await deleteUnixfsPath(context.store, CID.parse(current.stateBundle.cid), name);
4692
- if (isLocalSwarm(configUrl))
4693
- return newRootCid.toString();
4694
- await provideShallowContent(context.store, {
4695
- directBlocks: createdDirCids,
4696
- recursiveRoots: [],
4697
- retainedDirect: createdDirCids,
4698
- retainedRecursive: [],
4699
- endpoint: context.node.api,
4700
- ...(context.fetch ? { fetcher: context.fetch } : {}),
4701
- authorizationToken: context.node.auth,
4702
- owner: `publication:${newRootCid.toString()}`,
4703
- });
4704
- withState(context, (state) => {
4705
- 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
+ },
4706
5357
  });
4707
- return newRootCid.toString();
5358
+ return ctx.header === cachedHeader
5359
+ ? cachedResult
5360
+ : findAssociation(ctx.header);
4708
5361
  }
4709
- async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
5362
+ export async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
4710
5363
  const identity = await contextIdentity(context);
4711
5364
  const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), undefined, identity.publicKey);
4712
5365
  await provideContent(context.store, [...new Set([next, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...(retainedRoots ?? roots)])]);
@@ -4716,7 +5369,7 @@ async function prepareNamesPublication(context, configUrl, current, names, roots
4716
5369
  return next;
4717
5370
  }
4718
5371
  async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
4719
- const head = await pointer(context, configUrl);
5372
+ await swarmFsTransport.pointer(context, configUrl);
4720
5373
  if (association) {
4721
5374
  const app = await openBundle(CID.parse(association.appCid), {
4722
5375
  resolveCid: (cid) => context.store.block.get(cid.toString()),
@@ -4727,49 +5380,43 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
4727
5380
  const roots = association
4728
5381
  ? await dependencies(context.store, association.appCid)
4729
5382
  : new Set();
4730
- for (let attempt = 0; attempt < 8; attempt++) {
4731
- const currentHead = await head.read();
4732
- const current = await readSnapshot(context.store, currentHead.root, configUrl);
4733
- assertNamesRegistry(current);
4734
- const meta = await swarmMeta(context, { snapshot: current });
4735
- const name = formalName(`${meta.registryPath}/${schemaCid}`);
4736
- const oldCid = (await resolveSnapshotName(context.store, current, name))?.toString();
4737
- if (association) {
4738
- if (oldCid === association.appCid)
4739
- return;
4740
- if (oldCid && !replace)
4741
- throw new HostError("Schema has another association; use --replace.");
4742
- }
4743
- else if (!oldCid) {
4744
- throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
4745
- }
4746
- let next;
4747
- if (isV7Snapshot(current)) {
4748
- next = association
4749
- ? await prepareV7PathSet(context, configUrl, current, name, CID.parse(association.appCid), roots)
4750
- : await prepareV7PathDelete(context, configUrl, current, name);
4751
- }
4752
- else {
4753
- const names = { ...current.names };
4754
- if (association)
4755
- names[name] = CID.parse(association.appCid);
4756
- else
4757
- delete names[name];
4758
- next = await prepareNamesPublication(context, configUrl, current, names, roots);
4759
- }
4760
- try {
4761
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
4762
- return;
4763
- }
4764
- catch (cause) {
4765
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4766
- throw cause;
4767
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
4768
- throw new HostError(`Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4769
- continue;
4770
- }
4771
- }
4772
- 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
+ });
4773
5420
  }
4774
5421
  export async function setSwarmAssociation(context, configUrl, value, replace = false) {
4775
5422
  if (value.argv.length !== 1 || value.argv[0] !== "%")
@@ -4880,41 +5527,31 @@ export async function unpublish(context, options) {
4880
5527
  throw new HostError("Unpublish requires a selected Swarm configuration URL or alias.");
4881
5528
  const name = formalName(options.name);
4882
5529
  const expected = exactCid(options.expect);
4883
- const head = await pointer(context, options.swarm);
4884
- for (let attempt = 0; attempt < 8; attempt++) {
4885
- const currentHead = await head.read();
4886
- const current = await readSnapshot(context.store, currentHead.root, options.swarm);
4887
- const old = (await resolveSnapshotName(context.store, current, name))?.toString();
4888
- if (!old)
4889
- throw new HostError(`Name "${name}" is missing; nothing was removed.`);
4890
- if (old !== expected)
4891
- throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
4892
- let next;
4893
- if (isV7Snapshot(current)) {
4894
- next = await prepareV7PathDelete(context, options.swarm, current, name);
4895
- }
4896
- else {
4897
- const names = { ...current.names };
4898
- delete names[name];
4899
- next = await prepareNamesPublication(context, options.swarm, current, names, []);
4900
- }
4901
- try {
4902
- await head.write(next, currentHead.cid, uniqueId());
4903
- }
4904
- catch (cause) {
4905
- if (cause instanceof ScopeApiError && cause.status === 412)
4906
- continue;
4907
- throw new HostError(`Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4908
- }
4909
- try {
4910
- await swarmHeader(context, options.swarm, true);
4911
- }
4912
- catch (cause) {
4913
- throw new HostError(`Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
4914
- }
4915
- return { name, targetCid: old };
4916
- }
4917
- 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;
4918
5555
  }
4919
5556
  export async function publish(context, content, options) {
4920
5557
  return publishContent(context, content, options);
@@ -4922,7 +5559,7 @@ export async function publish(context, content, options) {
4922
5559
  async function publishContent(context, content, options, nameForSnapshot) {
4923
5560
  if (!options.swarm)
4924
5561
  throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
4925
- const head = await pointer(context, options.swarm);
5562
+ await swarmFsTransport.pointer(context, options.swarm);
4926
5563
  const roots = await dependencies(context.store, content);
4927
5564
  const currentRoots = [...(await currentDependencies(context.store, content))];
4928
5565
  await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
@@ -4947,45 +5584,43 @@ async function publishContent(context, content, options, nameForSnapshot) {
4947
5584
  timestamp: new Date().toISOString(),
4948
5585
  });
4949
5586
  roots.add(candidate);
4950
- if (expected)
4951
- 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)
4952
5592
  roots.add(root);
4953
- for (let attempt = 0; attempt < 8; attempt++) {
4954
- const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root, options.swarm);
4955
- if (nameForSnapshot) {
4956
- name = await nameForSnapshot(current);
4957
- if (resolvedName !== undefined && resolvedName !== name)
4958
- throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
4959
- resolvedName = name;
4960
- }
4961
- const existing = (await resolveSnapshotName(context.store, current, name))?.toString();
4962
- if (existing !== expected)
4963
- 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");
4964
- const retained = [
4965
- candidate,
4966
- ...(expected ? await dependencies(context.store, expected) : []),
4967
- ];
4968
- const next = isV7Snapshot(current)
4969
- ? await prepareV7PathSet(context, options.swarm, current, name, CID.parse(candidate), roots, retained)
4970
- : await prepareNamesPublication(context, options.swarm, current, { ...current.names, [name]: CID.parse(candidate) }, roots, retained);
4971
- try {
4972
- await writeNamesHead(context, options.swarm, head, next, currentHead.cid);
4973
- }
4974
- catch (cause) {
4975
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
4976
- throw cause;
4977
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
4978
- throw new HostError(`HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
4979
- continue;
4980
- }
4981
- try {
4982
- await swarmHeader(context, options.swarm, true);
4983
- }
4984
- catch (cause) {
4985
- 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");
4986
- }
4987
- return candidate;
4988
- }
4989
- 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;
4990
5625
  }
4991
5626
  //# sourceMappingURL=swarm.js.map