@ipab/cli 0.1.0-rc.11 → 0.1.0-rc.13

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 (151) 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-daemon.d.ts +14 -0
  8. package/dist/cli-daemon.d.ts.map +1 -0
  9. package/dist/cli-daemon.js +400 -0
  10. package/dist/cli-daemon.js.map +1 -0
  11. package/dist/cli.d.ts +2 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +1631 -1100
  14. package/dist/cli.js.map +1 -1
  15. package/dist/config-secret.js +1 -1
  16. package/dist/config-secret.js.map +1 -1
  17. package/dist/daemon-api.d.ts +80 -0
  18. package/dist/daemon-api.d.ts.map +1 -0
  19. package/dist/daemon-api.js +2411 -0
  20. package/dist/daemon-api.js.map +1 -0
  21. package/dist/daemon-client.d.ts +322 -0
  22. package/dist/daemon-client.d.ts.map +1 -0
  23. package/dist/daemon-client.js +400 -0
  24. package/dist/daemon-client.js.map +1 -0
  25. package/dist/daemon-protocol.d.ts +22 -0
  26. package/dist/daemon-protocol.d.ts.map +1 -0
  27. package/dist/daemon-protocol.js +39 -0
  28. package/dist/daemon-protocol.js.map +1 -0
  29. package/dist/daemon-telemetry.d.ts +86 -0
  30. package/dist/daemon-telemetry.d.ts.map +1 -0
  31. package/dist/daemon-telemetry.js +502 -0
  32. package/dist/daemon-telemetry.js.map +1 -0
  33. package/dist/daemon-ui.d.ts +69 -0
  34. package/dist/daemon-ui.d.ts.map +1 -1
  35. package/dist/daemon-ui.js +285 -4
  36. package/dist/daemon-ui.js.map +1 -1
  37. package/dist/daemon.d.ts +10 -0
  38. package/dist/daemon.d.ts.map +1 -1
  39. package/dist/daemon.js +289 -38
  40. package/dist/daemon.js.map +1 -1
  41. package/dist/history.d.ts +3 -1
  42. package/dist/history.d.ts.map +1 -1
  43. package/dist/history.js +16 -1
  44. package/dist/history.js.map +1 -1
  45. package/dist/identity.d.ts.map +1 -1
  46. package/dist/identity.js +7 -2
  47. package/dist/identity.js.map +1 -1
  48. package/dist/ipc.d.ts +19 -7
  49. package/dist/ipc.d.ts.map +1 -1
  50. package/dist/ipc.js +96 -70
  51. package/dist/ipc.js.map +1 -1
  52. package/dist/kubo-topology.d.ts +2 -0
  53. package/dist/kubo-topology.d.ts.map +1 -1
  54. package/dist/kubo-topology.js +17 -20
  55. package/dist/kubo-topology.js.map +1 -1
  56. package/dist/kubo.d.ts +5 -3
  57. package/dist/kubo.d.ts.map +1 -1
  58. package/dist/kubo.js +83 -13
  59. package/dist/kubo.js.map +1 -1
  60. package/dist/name-reference.d.ts +8 -0
  61. package/dist/name-reference.d.ts.map +1 -0
  62. package/dist/name-reference.js +63 -0
  63. package/dist/name-reference.js.map +1 -0
  64. package/dist/pins.d.ts.map +1 -1
  65. package/dist/pins.js +18 -3
  66. package/dist/pins.js.map +1 -1
  67. package/dist/pivot-rpc.d.ts +37 -2
  68. package/dist/pivot-rpc.d.ts.map +1 -1
  69. package/dist/pivot-rpc.js +188 -8
  70. package/dist/pivot-rpc.js.map +1 -1
  71. package/dist/search-index.d.ts.map +1 -1
  72. package/dist/search-index.js +1 -0
  73. package/dist/search-index.js.map +1 -1
  74. package/dist/skill-definition.d.ts +9 -0
  75. package/dist/skill-definition.d.ts.map +1 -1
  76. package/dist/skill-definition.js +26 -2
  77. package/dist/skill-definition.js.map +1 -1
  78. package/dist/skill-source.d.ts +1 -0
  79. package/dist/skill-source.d.ts.map +1 -1
  80. package/dist/skill-source.js +10 -4
  81. package/dist/skill-source.js.map +1 -1
  82. package/dist/skills.d.ts +8 -2
  83. package/dist/skills.d.ts.map +1 -1
  84. package/dist/skills.js +31 -2
  85. package/dist/skills.js.map +1 -1
  86. package/dist/state-storage.d.ts.map +1 -1
  87. package/dist/state-storage.js +2 -1
  88. package/dist/state-storage.js.map +1 -1
  89. package/dist/state.d.ts +1 -1
  90. package/dist/state.d.ts.map +1 -1
  91. package/dist/state.js +3 -2
  92. package/dist/state.js.map +1 -1
  93. package/dist/swarm-files.d.ts.map +1 -1
  94. package/dist/swarm-files.js +7 -2
  95. package/dist/swarm-files.js.map +1 -1
  96. package/dist/swarm-fs-core.d.ts +217 -0
  97. package/dist/swarm-fs-core.d.ts.map +1 -0
  98. package/dist/swarm-fs-core.js +885 -0
  99. package/dist/swarm-fs-core.js.map +1 -0
  100. package/dist/swarm-fs-path.d.ts +17 -0
  101. package/dist/swarm-fs-path.d.ts.map +1 -0
  102. package/dist/swarm-fs-path.js +46 -0
  103. package/dist/swarm-fs-path.js.map +1 -0
  104. package/dist/swarm-fs.d.ts +9 -0
  105. package/dist/swarm-fs.d.ts.map +1 -0
  106. package/dist/swarm-fs.js +21 -0
  107. package/dist/swarm-fs.js.map +1 -0
  108. package/dist/swarm-observations.d.ts +6 -0
  109. package/dist/swarm-observations.d.ts.map +1 -1
  110. package/dist/swarm-observations.js +28 -8
  111. package/dist/swarm-observations.js.map +1 -1
  112. package/dist/swarm.d.ts +134 -18
  113. package/dist/swarm.d.ts.map +1 -1
  114. package/dist/swarm.js +1293 -484
  115. package/dist/swarm.js.map +1 -1
  116. package/dist/unixfs-tree.d.ts +55 -0
  117. package/dist/unixfs-tree.d.ts.map +1 -1
  118. package/dist/unixfs-tree.js +361 -2
  119. package/dist/unixfs-tree.js.map +1 -1
  120. package/package.json +5 -5
  121. package/src/authoring.ts +88 -28
  122. package/src/cli-daemon.ts +482 -0
  123. package/src/cli.ts +2080 -1464
  124. package/src/config-secret.ts +1 -1
  125. package/src/daemon-api.ts +3148 -0
  126. package/src/daemon-client.ts +975 -0
  127. package/src/daemon-protocol.ts +61 -0
  128. package/src/daemon-telemetry.ts +656 -0
  129. package/src/daemon-ui.ts +364 -4
  130. package/src/daemon.ts +337 -43
  131. package/src/history.ts +26 -1
  132. package/src/identity.ts +10 -2
  133. package/src/ipc.ts +113 -79
  134. package/src/kubo-topology.ts +25 -22
  135. package/src/kubo.ts +127 -9
  136. package/src/name-reference.ts +91 -0
  137. package/src/pins.ts +23 -3
  138. package/src/pivot-rpc.ts +272 -14
  139. package/src/search-index.ts +1 -0
  140. package/src/skill-definition.ts +45 -3
  141. package/src/skill-source.ts +10 -4
  142. package/src/skills.ts +43 -2
  143. package/src/state-storage.ts +5 -1
  144. package/src/state.ts +3 -1
  145. package/src/swarm-files.ts +10 -2
  146. package/src/swarm-fs-core.ts +1461 -0
  147. package/src/swarm-fs-path.ts +68 -0
  148. package/src/swarm-fs.ts +104 -0
  149. package/src/swarm-observations.ts +40 -14
  150. package/src/swarm.ts +2149 -1033
  151. package/src/unixfs-tree.ts +447 -2
package/dist/swarm.js CHANGED
@@ -16,31 +16,36 @@ 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";
37
41
  import { queryRemotePivotSearch, rankPivotCandidates, } from "./search-service.js";
42
+ import { DaemonTelemetry, telemetryLogFilename } from "./daemon-telemetry.js";
38
43
  import { DaemonLogBuffer, emptySyncState, pivotReceiptProtocol, redactDaemonText, } from "./daemon-ui.js";
39
44
  import { networkingBinding, pivotLocalStatus, readNetworkingSnapshot, writeNetworkingSnapshot, networkingAccount, } from "./swarm-observations.js";
40
45
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
41
46
  import { inspectTemplate, templatePublicationSource } from "./templates.js";
42
47
  import { seedSkillSource } from "./skill-source.js";
43
- import { skillIdentity, skillSchema } from "./skill-definition.js";
48
+ import { inspectSkillBundle, skillSchema } from "./skill-definition.js";
44
49
  import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmRootType, parseSwarmRootState, isSwarmRootSchema, swarmStateType, previousSwarmStateType, previousSwarmStateSchema, parseSwarmState, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
45
50
  function memberIsPivot(config, member, profile) {
46
51
  return config.v === 3
@@ -128,6 +133,15 @@ export const artifactType = {
128
133
  },
129
134
  },
130
135
  };
136
+ function withSwarmLock(context, lockDir, action, signal) {
137
+ if (context.inProcessMutex) {
138
+ return context.inProcessMutex.run(lockDir, async () => {
139
+ signal?.throwIfAborted();
140
+ return action();
141
+ });
142
+ }
143
+ return withPrivateLock(lockDir, action, signal);
144
+ }
131
145
  function withState(context, operation) {
132
146
  if (context.state)
133
147
  return operation(context.state);
@@ -139,6 +153,11 @@ function withState(context, operation) {
139
153
  state.close();
140
154
  }
141
155
  }
156
+ export function invalidateSwarmHeader(context, configUrl) {
157
+ withState(context, (state) => {
158
+ state.invalidateSwarmHeader(configUrl);
159
+ });
160
+ }
142
161
  export { canonicalSwarmUrl };
143
162
  function coordinates(configUrl) {
144
163
  const url = new URL(canonicalSwarmUrl(configUrl));
@@ -195,7 +214,7 @@ async function ensureLocalSwarm(context) {
195
214
  const skill = await seedSkillSource();
196
215
  for (const [cid, data] of skill.blocks)
197
216
  await context.store.put(CID.parse(cid), data);
198
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
217
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
199
218
  let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
200
219
  templatePath: "ipab/templates",
201
220
  registryPath: "ipab/registry",
@@ -595,7 +614,7 @@ async function inspection(context, url, refresh = false) {
595
614
  ]);
596
615
  let snapshot;
597
616
  if (saved === undefined) {
598
- snapshot = await withPrivateLock(await privateDirectory(context.stateDir, "swarm-inspections"), async () => {
617
+ snapshot = await withSwarmLock(context, await privateDirectory(context.stateDir, "swarm-inspections"), async () => {
599
618
  const { config, variable } = await fetchConfig(context, url);
600
619
  const directory = await memberDirectory(context, url, config);
601
620
  const c = coordinates(url);
@@ -703,7 +722,7 @@ export async function swarmMembers(context, url, refresh = false) {
703
722
  local: observationSummary(observations.local),
704
723
  };
705
724
  }
706
- export async function swarmNetworking(context, url, config, directory) {
725
+ export async function swarmNetworking(context, url, config, directory, currentHeadCid) {
707
726
  rejectLocalSwarm(url, "swarm networking");
708
727
  directory ??= (await inspection(context, url)).directory;
709
728
  const { account, local } = await localObservations(context, url, config);
@@ -755,6 +774,10 @@ export async function swarmNetworking(context, url, config, directory) {
755
774
  : actual.length
756
775
  ? "relay"
757
776
  : "disconnected";
777
+ const readiness = local.snapshot?.readiness?.[member.peerId];
778
+ const readinessCurrent = local.status === "current" &&
779
+ readiness &&
780
+ Date.now() - readiness.observedAt <= 90_000;
758
781
  return {
759
782
  publicKey: member.publicKey,
760
783
  name: profile.name,
@@ -782,6 +805,22 @@ export async function swarmNetworking(context, url, config, directory) {
782
805
  freshness,
783
806
  addresses: actual.map((entry) => entry.address),
784
807
  },
808
+ readiness: {
809
+ status: !readinessCurrent
810
+ ? "unknown"
811
+ : !readiness.status
812
+ ? "unreachable"
813
+ : readiness.status.ready &&
814
+ readiness.status.headCid === currentHeadCid
815
+ ? "ready"
816
+ : "not-ready",
817
+ observedAt: readiness
818
+ ? new Date(readiness.observedAt).toISOString()
819
+ : null,
820
+ headCid: readiness?.status?.headCid ?? null,
821
+ indexedHeadCid: readiness?.status?.indexedHeadCid ?? null,
822
+ error: readiness?.error ?? readiness?.status?.syncError ?? null,
823
+ },
785
824
  };
786
825
  }),
787
826
  };
@@ -795,19 +834,28 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
795
834
  stopAtBundle: true,
796
835
  });
797
836
  const templatePrefix = `${meta.templatePath}/`;
798
- const skillPrefix = meta.skillPath ? `${meta.skillPath}/` : undefined;
837
+ const globalSkillPrefix = meta.skillPath
838
+ ? `${meta.skillPath}/global/`
839
+ : undefined;
840
+ const typeSkillPrefix = meta.skillPath
841
+ ? `${meta.skillPath}/types/`
842
+ : undefined;
799
843
  const registryPrefix = `${meta.registryPath}/`;
800
844
  let templates = 0;
801
- let skills = 0;
845
+ let globalSkills = 0;
846
+ let typeSkills = 0;
802
847
  let registrations = 0;
803
848
  for (const entry of walked.entries) {
804
849
  if (entry.name.startsWith(templatePrefix))
805
850
  templates++;
806
- else if (skillPrefix && entry.name.startsWith(skillPrefix))
807
- skills++;
851
+ else if (globalSkillPrefix && entry.name.startsWith(globalSkillPrefix))
852
+ globalSkills++;
853
+ else if (typeSkillPrefix && entry.name.startsWith(typeSkillPrefix))
854
+ typeSkills++;
808
855
  else if (entry.name.startsWith(registryPrefix))
809
856
  registrations++;
810
857
  }
858
+ const skills = globalSkills + typeSkills;
811
859
  return {
812
860
  mode: "local",
813
861
  configUrl: LOCAL_SWARM_URL,
@@ -827,6 +875,8 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
827
875
  names: walked.entries.length,
828
876
  templates,
829
877
  skills,
878
+ globalSkills,
879
+ typeSkills,
830
880
  registrations,
831
881
  },
832
882
  networking: {
@@ -863,7 +913,7 @@ export async function inspectSwarmStatus(context, url, refresh = false) {
863
913
  status: "unavailable",
864
914
  error: "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
865
915
  },
866
- networking: await swarmNetworking(context, url, config, directory),
916
+ networking: await swarmNetworking(context, url, config, directory, head.root),
867
917
  };
868
918
  }
869
919
  function accountProfileLocation(context, publicKey) {
@@ -961,7 +1011,7 @@ export async function accountProfile(context) {
961
1011
  async function ensureAccountProfile(context, changes = {}) {
962
1012
  const identity = await contextIdentity(context);
963
1013
  const dir = await accountProfileDirectory(context, identity.publicKey);
964
- return withPrivateLock(dir, async () => {
1014
+ return withSwarmLock(context, dir, async () => {
965
1015
  const existing = await storedAccountProfile(context);
966
1016
  if (existing &&
967
1017
  changes.name === undefined &&
@@ -1307,6 +1357,7 @@ async function privateSource(context, record, signal, candidates) {
1307
1357
  source: kuboSource(node, peers, context.diagnostic, context.env.IPAB_SWARM_DIAL_DEBUG === "1"),
1308
1358
  };
1309
1359
  }
1360
+ const pivotReadinessRefreshIntervalMs = 45_000;
1310
1361
  export async function swarmDaemon(context, signal, synchronize) {
1311
1362
  const lock = await privateDirectory(context.stateDir, "swarm-daemon");
1312
1363
  await withPrivateLock(lock, async () => {
@@ -1329,6 +1380,36 @@ export async function swarmDaemon(context, signal, synchronize) {
1329
1380
  }
1330
1381
  return secrets;
1331
1382
  };
1383
+ const telemetry = new DaemonTelemetry({
1384
+ env: context.env,
1385
+ logPath: join(context.stateDir, "swarm-daemon", telemetryLogFilename),
1386
+ secrets: () => collectSecrets(),
1387
+ });
1388
+ const [{ builtinContent }, { DaemonService, KeyedMutex, createDaemonApiHandler },] = await Promise.all([
1389
+ import("./builtins.js"),
1390
+ import("./daemon-api.js"),
1391
+ ]);
1392
+ const ownsDaemonState = !context.state;
1393
+ const builtins = ownsDaemonState ? await builtinContent() : undefined;
1394
+ const daemonState = context.state ??
1395
+ new State(context.stateDir, builtins?.pins ?? [], context.env, (db) => telemetry.wrapDatabase(db, "state"));
1396
+ const daemonStore = new IpfsStore({
1397
+ ...context.store.configuration,
1398
+ singleProcessCoordination: true,
1399
+ onCoordinationEvent: (event) => {
1400
+ telemetry.recordCoordination(event);
1401
+ },
1402
+ onSqlEvent: (event) => {
1403
+ telemetry.recordSql(event);
1404
+ },
1405
+ });
1406
+ const inProcessMutex = context.inProcessMutex ?? new KeyedMutex();
1407
+ const daemonContext = {
1408
+ ...context,
1409
+ state: daemonState,
1410
+ store: daemonStore,
1411
+ inProcessMutex,
1412
+ };
1332
1413
  const redact = (error, session) => error === null
1333
1414
  ? null
1334
1415
  : redactDaemonText(error, collectSecrets(session));
@@ -1336,6 +1417,40 @@ export async function swarmDaemon(context, signal, synchronize) {
1336
1417
  logBuffer.push(text, collectSecrets());
1337
1418
  context.diagnostic?.(text);
1338
1419
  };
1420
+ const dirtyDiscovery = new Set();
1421
+ const wakeState = { dirtyAllDiscovery: false, wakeRequested: false };
1422
+ let wakeSleep;
1423
+ const wakeDaemonLoop = (url) => {
1424
+ if (url)
1425
+ dirtyDiscovery.add(url);
1426
+ else
1427
+ wakeState.dirtyAllDiscovery = true;
1428
+ wakeState.wakeRequested = true;
1429
+ const resolveWake = wakeSleep;
1430
+ wakeSleep = undefined;
1431
+ resolveWake?.();
1432
+ };
1433
+ const daemonService = await DaemonService.create({
1434
+ stateDir: context.stateDir,
1435
+ env: context.env,
1436
+ state: daemonState,
1437
+ store: daemonStore,
1438
+ telemetry,
1439
+ inProcessMutex,
1440
+ diagnostic: emitDiagnostic,
1441
+ ensureDaemon: () => {
1442
+ wakeDaemonLoop();
1443
+ return Promise.resolve();
1444
+ },
1445
+ onSwarmChange: wakeDaemonLoop,
1446
+ ...(context.fetch ? { fetch: context.fetch } : {}),
1447
+ });
1448
+ const shutdownController = new AbortController();
1449
+ const shutdownRequested = () => shutdownController.signal.aborted;
1450
+ const effectiveSignal = AbortSignal.any([
1451
+ signal,
1452
+ shutdownController.signal,
1453
+ ]);
1339
1454
  const buildStatusSnapshot = () => {
1340
1455
  const now = Date.now();
1341
1456
  const urls = [...new Set([...knownAliases.keys(), ...sessions.keys()])];
@@ -1390,7 +1505,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1390
1505
  : "unknown",
1391
1506
  running: Boolean(session?.running),
1392
1507
  receiptRpc: {
1393
- active: Boolean(session?.pivotServer),
1508
+ active: Boolean(session?.pivotServer?.listening),
1394
1509
  protocol: pivotReceiptProtocol,
1395
1510
  epoch: session?.pivotServer?.epoch ?? null,
1396
1511
  headId: session?.pivotServer?.headId ?? null,
@@ -1433,10 +1548,17 @@ export async function swarmDaemon(context, signal, synchronize) {
1433
1548
  syncInterval: context.syncInterval ?? 60,
1434
1549
  swarms,
1435
1550
  logs: logBuffer.entries(),
1551
+ observability: telemetry.snapshot(collectSecrets()),
1436
1552
  };
1437
1553
  };
1438
1554
  const closeReadiness = await context.daemonReady?.(buildStatusSnapshot, ({ url }) => {
1439
1555
  uiUrl = url;
1556
+ }, {
1557
+ apiHandler: createDaemonApiHandler(daemonService),
1558
+ onShutdown: () => {
1559
+ shutdownController.abort(new HostError("Daemon shutdown requested.", 0, "SHUTDOWN", "daemon"));
1560
+ },
1561
+ hasActiveWork: () => daemonService.hasActiveRuns(),
1440
1562
  });
1441
1563
  emitDiagnostic(`IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.${uiUrl ? ` Status UI: ${uiUrl}` : ""}`);
1442
1564
  const stopPivotServer = async (session) => {
@@ -1455,7 +1577,9 @@ export async function swarmDaemon(context, signal, synchronize) {
1455
1577
  await session.context.finishRead?.();
1456
1578
  }
1457
1579
  finally {
1458
- await session.context.store.close();
1580
+ if (session.context.store !== daemonStore) {
1581
+ await session.context.store.close();
1582
+ }
1459
1583
  }
1460
1584
  }
1461
1585
  };
@@ -1492,12 +1616,43 @@ export async function swarmDaemon(context, signal, synchronize) {
1492
1616
  error: "No connection snapshot collected.",
1493
1617
  peers: [],
1494
1618
  },
1619
+ ...(session.context.pivotReadiness
1620
+ ? {
1621
+ readiness: Object.fromEntries(Object.entries(session.context.pivotReadiness).map(([peerId, value]) => [
1622
+ peerId,
1623
+ {
1624
+ ...value,
1625
+ error: redact(value.error, session),
1626
+ status: value.status
1627
+ ? {
1628
+ ...value.status,
1629
+ syncError: redact(value.status.syncError, session),
1630
+ }
1631
+ : null,
1632
+ },
1633
+ ])),
1634
+ }
1635
+ : {}),
1495
1636
  };
1496
1637
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1497
1638
  };
1498
1639
  try {
1499
- while (!signal.aborted) {
1500
- const registrations = withState(context, (state) => state.swarms());
1640
+ while (!effectiveSignal.aborted) {
1641
+ if (wakeState.dirtyAllDiscovery) {
1642
+ for (const session of sessions.values())
1643
+ session.nextDiscovery = 0;
1644
+ wakeState.dirtyAllDiscovery = false;
1645
+ dirtyDiscovery.clear();
1646
+ }
1647
+ else if (dirtyDiscovery.size > 0) {
1648
+ for (const dirtyUrl of dirtyDiscovery) {
1649
+ const session = sessions.get(dirtyUrl);
1650
+ if (session)
1651
+ session.nextDiscovery = 0;
1652
+ }
1653
+ dirtyDiscovery.clear();
1654
+ }
1655
+ const registrations = withState(daemonContext, (state) => state.swarms());
1501
1656
  knownAliases = new Map(registrations.map((entry) => [entry.cid, entry.alias]));
1502
1657
  const urls = new Set(registrations.map((entry) => entry.cid));
1503
1658
  for (const url of sessions.keys())
@@ -1507,14 +1662,14 @@ export async function swarmDaemon(context, signal, synchronize) {
1507
1662
  await closeSession(session);
1508
1663
  sessions.delete(url);
1509
1664
  }
1510
- await boundedMap(registrations, async ({ cid: url }) => {
1665
+ await boundedMap(registrations, async ({ cid: url }) => telemetry.runWithContext({ source: "daemon-bg", operation: "swarm-tick", swarm: url }, async () => {
1511
1666
  let session = sessions.get(url);
1512
1667
  if (!session) {
1513
1668
  session = {
1514
1669
  context: {
1515
- ...context,
1670
+ ...daemonContext,
1516
1671
  diagnostic: emitDiagnostic,
1517
- store: new IpfsStore(context.store.configuration),
1672
+ store: daemonStore.scope(),
1518
1673
  forceRefresh: true,
1519
1674
  },
1520
1675
  candidates: new PivotCandidates(),
@@ -1530,16 +1685,18 @@ export async function swarmDaemon(context, signal, synchronize) {
1530
1685
  };
1531
1686
  sessions.set(url, session);
1532
1687
  }
1688
+ let pivotListenerVerified = false;
1533
1689
  try {
1534
1690
  if (session.record?.config && context.pivot === undefined) {
1535
1691
  const self = session.record.config.members.find((member) => member.publicKey === session.record.account);
1536
1692
  const c = coordinates(url);
1537
- const profile = parseProfile((await client(session.context, c.service).read(c.scopeId, self.profileId, { signal })).value, self.peerId);
1693
+ const profile = parseProfile((await client(session.context, c.service).read(c.scopeId, self.profileId, { signal: effectiveSignal })).value, self.peerId);
1538
1694
  if ((profile.pivot ?? false) !== session.pivot)
1539
1695
  session.nextDiscovery = 0;
1540
1696
  }
1541
- if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
1542
- const record = await approvedMembership(session.context, url, signal);
1697
+ if (Date.now() >= session.nextDiscovery ||
1698
+ session.healthy < 1) {
1699
+ const record = await approvedMembership(session.context, url, effectiveSignal);
1543
1700
  const c = coordinates(url);
1544
1701
  const scope = nodeScope(c.service, record.config.scopeId);
1545
1702
  const existing = await readPrivate(join(context.stateDir, "swarm-nodes", scope), "node.json");
@@ -1556,7 +1713,9 @@ export async function swarmDaemon(context, signal, synchronize) {
1556
1713
  delete session.node;
1557
1714
  }
1558
1715
  session.record = record;
1559
- const result = await privateSource(session.context, record, signal, session.candidates);
1716
+ if (context.pivot === undefined)
1717
+ delete session.context.pivot;
1718
+ const result = await privateSource(session.context, record, effectiveSignal, session.candidates);
1560
1719
  session.node = result.node;
1561
1720
  session.pivot = result.pivot;
1562
1721
  session.context.pivot = result.pivot;
@@ -1570,15 +1729,31 @@ export async function swarmDaemon(context, signal, synchronize) {
1570
1729
  }
1571
1730
  if (!session.node)
1572
1731
  return;
1732
+ const currentRecord = session.record;
1733
+ const currentSelf = currentRecord.config.members.find((member) => member.publicKey === currentRecord.account);
1734
+ if (!(await nodeReady(session.node, effectiveSignal, session.context.fetch))) {
1735
+ if (session.pivotServer)
1736
+ session.pivotServer.listening = false;
1737
+ const currentDesired = memberPeers(currentSelf.peerId, session.candidates.active(), []);
1738
+ session.node = await startNode(context.stateDir, nodeScope(coordinates(url).service, currentRecord.config.scopeId), currentRecord.secret.swarmKey, currentRecord.config.epoch, context.listen, {
1739
+ self: currentSelf.peerId,
1740
+ pivot: session.pivot ?? false,
1741
+ peers: currentDesired,
1742
+ signal: effectiveSignal,
1743
+ });
1744
+ session.selected = new Set(currentDesired.map(({ ID }) => ID));
1745
+ session.context.node = session.node;
1746
+ emitDiagnostic(`[${url}] Managed Kubo was offline; restarted before probing peers.`);
1747
+ }
1573
1748
  let healthy = 0;
1574
1749
  await boundedMap([...session.candidates.active()], async ([id, addresses]) => {
1575
1750
  let success = false;
1576
1751
  let error = null;
1577
1752
  try {
1578
- success = await probePeer(session.node, id, addresses, signal);
1753
+ success = await probePeer(session.node, id, addresses, effectiveSignal);
1579
1754
  }
1580
1755
  catch (cause) {
1581
- signal.throwIfAborted();
1756
+ effectiveSignal.throwIfAborted();
1582
1757
  error = message(cause);
1583
1758
  emitDiagnostic(`[${url}] Pivot probe ${id}: ${message(cause)}`);
1584
1759
  }
@@ -1591,8 +1766,8 @@ export async function swarmDaemon(context, signal, synchronize) {
1591
1766
  }
1592
1767
  });
1593
1768
  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.
1769
+ // Reconcile active Pivot Bootstrap candidates via live Kubo RPC
1770
+ // without restarting the daemon unless startup-only config changed.
1596
1771
  const record = session.record;
1597
1772
  const self = record.config.members.find((member) => member.publicKey === record.account);
1598
1773
  const desired = memberPeers(self.peerId, session.candidates.active(), []);
@@ -1600,56 +1775,156 @@ export async function swarmDaemon(context, signal, synchronize) {
1600
1775
  self: self.peerId,
1601
1776
  pivot: session.pivot ?? false,
1602
1777
  peers: desired,
1603
- signal,
1778
+ signal: effectiveSignal,
1604
1779
  });
1605
1780
  session.selected = new Set(desired.map(({ ID }) => ID));
1606
1781
  session.context.node = session.node;
1782
+ try {
1783
+ const peers = await nodeConnections(session.node, effectiveSignal);
1784
+ session.connections = {
1785
+ observedAt: Date.now(),
1786
+ error: null,
1787
+ peers,
1788
+ };
1789
+ }
1790
+ catch (cause) {
1791
+ effectiveSignal.throwIfAborted();
1792
+ session.connections = {
1793
+ observedAt: session.connections?.observedAt ?? null,
1794
+ error: message(cause).slice(0, 2048),
1795
+ peers: session.connections?.peers ?? [],
1796
+ };
1797
+ }
1798
+ // Persist connectivity before potentially slow content acquisition.
1799
+ await persist(url, session, true);
1607
1800
  if (session.pivot) {
1608
1801
  if (!session.pivotServer ||
1802
+ !session.pivotServer.server.listening ||
1609
1803
  session.pivotServer.nodeApi !== session.node.api ||
1610
1804
  session.pivotServer.epoch !== record.config.epoch ||
1611
1805
  session.pivotServer.headId !== record.config.headId) {
1612
1806
  await stopPivotServer(session);
1613
1807
  const pivotNode = session.node;
1614
1808
  const mounted = await mountPivotServer(pivotNode, {
1615
- receipt: (receiptRequest, requestSignal) => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal),
1809
+ status: (requestSignal) => telemetry.runWithContext({
1810
+ source: "pivot-rpc",
1811
+ operation: "GET /v1/status",
1812
+ swarm: url,
1813
+ }, () => pivotStatus({ ...session.context, node: pivotNode }, url, requestSignal)),
1814
+ replicate: (request, requestSignal) => telemetry.runWithContext({
1815
+ source: "pivot-rpc",
1816
+ operation: "POST /v1/replicate",
1817
+ swarm: url,
1818
+ }, async () => {
1819
+ const requestContext = {
1820
+ ...session.context,
1821
+ node: pivotNode,
1822
+ };
1823
+ try {
1824
+ return await handlePivotReplicateRequest(requestContext, url, request, requestSignal);
1825
+ }
1826
+ finally {
1827
+ session.context.pivotSyncError =
1828
+ requestContext.pivotSyncError ?? null;
1829
+ }
1830
+ }),
1831
+ receipt: (receiptRequest, requestSignal) => telemetry.runWithContext({
1832
+ source: "pivot-rpc",
1833
+ operation: "POST /v1/receipt",
1834
+ swarm: url,
1835
+ }, () => handlePivotReceiptRequest({ ...session.context, node: pivotNode }, url, receiptRequest, requestSignal)),
1616
1836
  search: (params) => withState(session.context, (state) => queryLocalSearchIndex(state, url, params)),
1617
1837
  ...(context.diagnostic
1618
1838
  ? { diagnostic: context.diagnostic }
1619
1839
  : {}),
1620
- }, session.context.fetch);
1840
+ }, session.context.fetch, effectiveSignal);
1621
1841
  session.pivotServer = {
1622
1842
  server: mounted,
1623
1843
  nodeApi: session.node.api,
1624
1844
  epoch: record.config.epoch,
1625
1845
  headId: record.config.headId,
1846
+ listening: true,
1626
1847
  };
1627
1848
  }
1628
- await syncPivotPublications(session.context, url, signal);
1849
+ else {
1850
+ const remounted = await ensurePivotListener(session.node, session.pivotServer.server.address, effectiveSignal, session.context.fetch);
1851
+ session.pivotServer.listening = true;
1852
+ if (remounted) {
1853
+ emitDiagnostic(`[${url}] Re-mounted Pivot P2P listener ${pivotReceiptProtocol} -> ${session.pivotServer.server.address}.`);
1854
+ }
1855
+ }
1856
+ pivotListenerVerified = true;
1629
1857
  }
1630
1858
  else {
1631
1859
  await stopPivotServer(session);
1632
1860
  }
1633
- try {
1634
- const peers = await nodeConnections(session.node, signal);
1635
- session.connections = {
1636
- observedAt: Date.now(),
1637
- error: null,
1638
- peers,
1639
- };
1861
+ const now = Date.now();
1862
+ const replicationIntervalMs = (context.syncInterval ?? 60) * 1000;
1863
+ const knownRemotePivots = session.candidates.observations();
1864
+ const online = new Set([
1865
+ ...[...knownRemotePivots]
1866
+ .filter(([, value]) => value.probe === "success")
1867
+ .map(([peerId]) => peerId),
1868
+ ...session.connections.peers.map((peer) => peer.peerId),
1869
+ ]);
1870
+ const remoteOnline = [...online].filter((peerId) => peerId !== session.node.peerId);
1871
+ const onlineRemotePivots = remoteOnline.filter((peerId) => knownRemotePivots.has(peerId));
1872
+ const remoteReadinessDue = onlineRemotePivots.some((peerId) => {
1873
+ const entry = session.context.pivotReadiness?.[peerId];
1874
+ return (!entry ||
1875
+ now - entry.observedAt >=
1876
+ pivotReadinessRefreshIntervalMs);
1877
+ });
1878
+ const replicationDue = now >= (session.nextReplication ?? 0);
1879
+ if ((onlineRemotePivots.length > 0 &&
1880
+ (remoteReadinessDue || replicationDue)) ||
1881
+ (remoteOnline.length > 0 && replicationDue)) {
1882
+ session.nextReplication = now + replicationIntervalMs;
1883
+ await replicateSwarm(session.context, url, effectiveSignal, {
1884
+ automatic: true,
1885
+ onlinePeers: online,
1886
+ });
1640
1887
  }
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
- };
1888
+ if (session.pivot) {
1889
+ const pivotSyncDue = now >= (session.nextPivotSync ?? 0);
1890
+ const selfReadiness = session.context.pivotReadiness?.[session.node.peerId];
1891
+ const selfReadinessDue = !selfReadiness ||
1892
+ now - selfReadiness.observedAt >=
1893
+ pivotReadinessRefreshIntervalMs;
1894
+ if (pivotSyncDue) {
1895
+ session.nextPivotSync = now + replicationIntervalMs;
1896
+ try {
1897
+ await syncPivotPublications(session.context, url, effectiveSignal);
1898
+ }
1899
+ finally {
1900
+ if (!effectiveSignal.aborted) {
1901
+ const status = await pivotStatus(session.context, url, effectiveSignal);
1902
+ session.context.pivotReadiness ??= {};
1903
+ session.context.pivotReadiness[session.node.peerId] =
1904
+ {
1905
+ observedAt: Date.now(),
1906
+ status,
1907
+ error: null,
1908
+ };
1909
+ }
1910
+ }
1911
+ }
1912
+ else if (selfReadinessDue) {
1913
+ const status = await pivotStatus(session.context, url, effectiveSignal);
1914
+ session.context.pivotReadiness ??= {};
1915
+ session.context.pivotReadiness[session.node.peerId] = {
1916
+ observedAt: Date.now(),
1917
+ status,
1918
+ error: null,
1919
+ };
1920
+ }
1648
1921
  }
1649
1922
  }
1650
1923
  catch (cause) {
1651
- if (signal.aborted)
1924
+ if (effectiveSignal.aborted)
1652
1925
  return;
1926
+ if (!pivotListenerVerified && session.pivotServer)
1927
+ session.pivotServer.listening = false;
1653
1928
  session.error = message(cause);
1654
1929
  session.nextDiscovery = 0;
1655
1930
  emitDiagnostic(`[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`);
@@ -1667,7 +1942,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1667
1942
  }
1668
1943
  if (synchronize &&
1669
1944
  session.node &&
1670
- !signal.aborted &&
1945
+ !effectiveSignal.aborted &&
1671
1946
  Date.now() >= session.nextSync) {
1672
1947
  let deferIsolatedPivot = false;
1673
1948
  if (session.pivot &&
@@ -1676,10 +1951,12 @@ export async function swarmDaemon(context, signal, synchronize) {
1676
1951
  session.record?.config) {
1677
1952
  try {
1678
1953
  const c = coordinates(url);
1679
- const head = headValue(await client(session.context, c.service).read(c.scopeId, session.record.config.headId, { signal }));
1954
+ const head = headValue(await client(session.context, c.service).read(c.scopeId, session.record.config.headId, { signal: effectiveSignal }));
1680
1955
  deferIsolatedPivot = !(await hasLocalBlock(session.context.store, head.root));
1681
1956
  }
1682
1957
  catch (cause) {
1958
+ if (shutdownController.signal.aborted)
1959
+ return;
1683
1960
  signal.throwIfAborted();
1684
1961
  emitDiagnostic(`[${url}] Isolated Pivot HEAD check failed: ${message(cause)}`);
1685
1962
  }
@@ -1695,7 +1972,7 @@ export async function swarmDaemon(context, signal, synchronize) {
1695
1972
  try {
1696
1973
  const summary = await raceAbort(synchronize(session.context, url, (partial) => {
1697
1974
  reported = partial;
1698
- }), signal);
1975
+ }), effectiveSignal);
1699
1976
  const applied = summary ?? reported;
1700
1977
  if (applied) {
1701
1978
  session.sync = {
@@ -1718,6 +1995,8 @@ export async function swarmDaemon(context, signal, synchronize) {
1718
1995
  }
1719
1996
  }
1720
1997
  catch (cause) {
1998
+ if (shutdownController.signal.aborted)
1999
+ return;
1721
2000
  signal.throwIfAborted();
1722
2001
  const detail = message(cause);
1723
2002
  emitDiagnostic(`[${url}] Swarm sync failed; will retry next interval: ${detail}`);
@@ -1736,46 +2015,98 @@ export async function swarmDaemon(context, signal, synchronize) {
1736
2015
  }
1737
2016
  }
1738
2017
  }
1739
- await persist(url, session, true);
1740
- });
2018
+ if (!effectiveSignal.aborted) {
2019
+ await persist(url, session, true);
2020
+ }
2021
+ }));
2022
+ if (shutdownRequested())
2023
+ break;
2024
+ signal.throwIfAborted();
2025
+ if (wakeState.wakeRequested) {
2026
+ wakeState.wakeRequested = false;
2027
+ continue;
2028
+ }
2029
+ const sleepController = new AbortController();
2030
+ const onWake = () => {
2031
+ sleepController.abort();
2032
+ };
2033
+ wakeSleep = onWake;
1741
2034
  try {
1742
2035
  const nextSync = synchronize
1743
2036
  ? Math.min(...[...sessions.values()]
1744
2037
  .filter((session) => session.node)
1745
2038
  .map((session) => Math.max(0, session.nextSync - Date.now())))
1746
2039
  : Infinity;
1747
- await delay(Math.min(30_000 + Math.random() * 15_000, nextSync), undefined, { signal });
2040
+ await delay(Math.min(30_000 + Math.random() * 15_000, nextSync), undefined, {
2041
+ signal: AbortSignal.any([
2042
+ effectiveSignal,
2043
+ sleepController.signal,
2044
+ ]),
2045
+ });
1748
2046
  }
1749
2047
  catch {
2048
+ if (shutdownRequested())
2049
+ break;
1750
2050
  signal.throwIfAborted();
1751
2051
  }
2052
+ finally {
2053
+ if (wakeSleep === onWake)
2054
+ wakeSleep = undefined;
2055
+ wakeState.wakeRequested = false;
2056
+ }
1752
2057
  }
1753
2058
  }
1754
2059
  finally {
1755
2060
  try {
1756
- for (const [url, session] of sessions) {
2061
+ await closeReadiness?.();
2062
+ }
2063
+ finally {
2064
+ try {
2065
+ for (const [url, session] of sessions) {
2066
+ try {
2067
+ await persist(url, session, false);
2068
+ }
2069
+ finally {
2070
+ await closeSession(session);
2071
+ }
2072
+ }
2073
+ }
2074
+ finally {
1757
2075
  try {
1758
- await persist(url, session, false);
2076
+ await daemonService.close();
1759
2077
  }
1760
2078
  finally {
1761
- await closeSession(session);
2079
+ try {
2080
+ await telemetry.flush();
2081
+ }
2082
+ finally {
2083
+ try {
2084
+ await daemonStore.close();
2085
+ }
2086
+ finally {
2087
+ if (ownsDaemonState)
2088
+ daemonState.close();
2089
+ }
2090
+ }
1762
2091
  }
1763
2092
  }
1764
2093
  }
1765
- finally {
1766
- await closeReadiness?.();
1767
- }
1768
2094
  }
1769
2095
  }, signal, 1);
1770
2096
  }
2097
+ const derivedLocalStores = new WeakSet();
1771
2098
  async function activate(context, record) {
1772
2099
  const { node, peers, source } = await privateSource(context, record);
1773
2100
  if (context.node?.api !== node.api ||
1774
2101
  context.sourcePeers?.length !== peers.length ||
1775
2102
  peers.some((peer, i) => context.sourcePeers?.[i] !== peer)) {
1776
- const store = context.store.withLocalSource(source);
1777
- await context.store.close();
2103
+ const previous = context.store;
2104
+ const store = previous.withLocalSource(source);
2105
+ derivedLocalStores.add(store);
1778
2106
  context.store = store;
2107
+ if (derivedLocalStores.has(previous)) {
2108
+ await previous.close();
2109
+ }
1779
2110
  context.sourcePeers = peers;
1780
2111
  }
1781
2112
  context.node = node;
@@ -1925,13 +2256,12 @@ async function boundPointer(context, configUrl, record) {
1925
2256
  writeWithReceipt: (receipt) => client(context, c.service).writeWithReceipt(c.scopeId, record.config.headId, receipt),
1926
2257
  };
1927
2258
  }
1928
- async function writeNamesHead(context, url, head, root, cid) {
2259
+ export async function writeNamesHead(context, url, head, root, cid) {
1929
2260
  if (isLocalSwarm(url)) {
1930
- await head.write(root, cid, uniqueId());
1931
- return;
2261
+ return head.write(root, cid, uniqueId());
1932
2262
  }
1933
2263
  const lock = await privateDirectory(await directory(context), `state-pin-${createHash("sha256").update(url).digest("hex")}`);
1934
- await withPrivateLock(lock, async () => {
2264
+ return withSwarmLock(context, lock, async () => {
1935
2265
  if (context.confirmPublication) {
1936
2266
  try {
1937
2267
  await context.confirmPublication(url, root);
@@ -1939,8 +2269,7 @@ async function writeNamesHead(context, url, head, root, cid) {
1939
2269
  catch (cause) {
1940
2270
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1941
2271
  }
1942
- await head.write(root, cid, uniqueId());
1943
- return;
2272
+ return head.write(root, cid, uniqueId());
1944
2273
  }
1945
2274
  const idempotencyKey = uniqueId();
1946
2275
  let receipt;
@@ -1951,10 +2280,9 @@ async function writeNamesHead(context, url, head, root, cid) {
1951
2280
  throw new HostError(`Pivot replication failed; HEAD was not changed: ${message(cause)}`, 1, "PIVOT_PIN_FAILED", "publication");
1952
2281
  }
1953
2282
  if (receipt === null) {
1954
- await head.write(root, cid, idempotencyKey);
1955
- return;
2283
+ return head.write(root, cid, idempotencyKey);
1956
2284
  }
1957
- await head.writeWithReceipt(receipt);
2285
+ return head.writeWithReceipt(receipt);
1958
2286
  });
1959
2287
  }
1960
2288
  async function requestPivotWriteReceipt(context, url, root, ifCid, idempotencyKey) {
@@ -2176,16 +2504,275 @@ export async function syncPivotPublications(context, url, signal) {
2176
2504
  }
2177
2505
  const source = context.store.withLocalSource(kuboSource(node, peers, context.diagnostic));
2178
2506
  try {
2507
+ if (CID.parse(head.root).code === dagPb.code)
2508
+ await pinPublication(source, [head.root], node, signal, context.fetch);
2179
2509
  await readSnapshot(source, head.root, url);
2180
2510
  const roots = CID.parse(head.root).code === dagPb.code
2181
2511
  ? [head.root]
2182
2512
  : await frozenPublicationClosure(source, head.root);
2183
2513
  await pinPublication(source, roots, node, signal, context.fetch);
2514
+ await finishPivotReplication(context, url, record, head, source, signal);
2515
+ context.pivotSyncError = null;
2516
+ }
2517
+ catch (cause) {
2518
+ context.pivotSyncError = message(cause).slice(0, 2048);
2519
+ throw cause;
2184
2520
  }
2185
2521
  finally {
2186
2522
  await source.close();
2187
2523
  }
2188
2524
  }
2525
+ async function localHeadClosure(context, headCid, signal, url) {
2526
+ const local = context.store.supportsRetention
2527
+ ? new IpfsStore({
2528
+ dataDir: context.store.configuration.dataDir,
2529
+ limits: context.store.limits,
2530
+ })
2531
+ : context.store;
2532
+ try {
2533
+ await local.prepare(headCid, { signal });
2534
+ if (url)
2535
+ await readSnapshot(local, headCid, url);
2536
+ if (CID.parse(headCid).code !== dagPb.code) {
2537
+ for (const root of await frozenPublicationClosure(local, headCid))
2538
+ await local.prepare(root, { signal });
2539
+ }
2540
+ return true;
2541
+ }
2542
+ catch (cause) {
2543
+ signal.throwIfAborted();
2544
+ if (missingContent(cause))
2545
+ return false;
2546
+ throw cause;
2547
+ }
2548
+ finally {
2549
+ if (local !== context.store)
2550
+ await local.close();
2551
+ }
2552
+ }
2553
+ export async function pivotStatus(context, url, signal) {
2554
+ rejectLocalSwarm(url, "Pivot status");
2555
+ const record = await approvedMembership(context, url, signal);
2556
+ const c = coordinates(url);
2557
+ const head = headValue(await client(context, c.service).read(c.scopeId, record.config.headId, {
2558
+ signal,
2559
+ }));
2560
+ const indexedHeadCid = withState(context, (state) => state.searchIndexState(url)?.headCid ?? null);
2561
+ const local = await localHeadClosure(context, head.root, signal, url);
2562
+ const pinned = local &&
2563
+ Boolean(context.node) &&
2564
+ (await isRecursivelyPinned(context.node, head.root, signal, context.fetch));
2565
+ const indexed = CID.parse(head.root).code !== dagPb.code || indexedHeadCid === head.root;
2566
+ return {
2567
+ v: 1,
2568
+ ready: pinned && indexed && !context.pivotSyncError,
2569
+ headCid: pinned ? head.root : null,
2570
+ indexedHeadCid,
2571
+ syncError: context.pivotSyncError ??
2572
+ (!pinned
2573
+ ? "Current HEAD is not fully replicated and recursively pinned."
2574
+ : !indexed
2575
+ ? "Current HEAD is not indexed."
2576
+ : null),
2577
+ };
2578
+ }
2579
+ async function finishPivotReplication(context, url, record, head, source, signal) {
2580
+ const snapshot = await readSnapshot(source, head.root, url);
2581
+ const roots = CID.parse(head.root).code === dagPb.code
2582
+ ? [head.root]
2583
+ : await frozenPublicationClosure(source, head.root);
2584
+ const owner = `daemon-pivot-root:${createHash("sha256").update(url).digest("hex")}`;
2585
+ await retainDaemonRoots(source, owner, roots, signal);
2586
+ const fresh = await approvedMembership(context, url, signal);
2587
+ const c = coordinates(url);
2588
+ const current = headValue(await client(context, c.service).read(c.scopeId, fresh.config.headId, {
2589
+ signal,
2590
+ }));
2591
+ if (fresh.config.epoch !== record.config.epoch ||
2592
+ fresh.config.headId !== record.config.headId ||
2593
+ current.root !== head.root)
2594
+ throw new HostError("HEAD or membership changed during replication; retry the current HEAD.");
2595
+ if (CID.parse(head.root).code === dagPb.code) {
2596
+ await syncPivotReplicationAndIndex({ ...context, pivot: true, store: source }, url, {
2597
+ head,
2598
+ snapshot,
2599
+ config: fresh.config,
2600
+ source: "network",
2601
+ verifiedAt: new Date().toISOString(),
2602
+ stateCid: head.root,
2603
+ }, signal);
2604
+ }
2605
+ }
2606
+ export async function handlePivotReplicateRequest(context, url, input, signal) {
2607
+ rejectLocalSwarm(url, "Pivot replicate");
2608
+ const request = parsePivotReplicateRequest(input);
2609
+ const record = await approvedMembership(context, url, signal);
2610
+ const c = coordinates(url);
2611
+ const config = record.config;
2612
+ if (request.service !== c.service ||
2613
+ request.scopeId !== c.scopeId ||
2614
+ request.headId !== config.headId ||
2615
+ request.epoch !== config.epoch)
2616
+ throw new HostError("Replicate request does not match the current Swarm configuration.");
2617
+ if (!config.members.some((member) => member.publicKey === request.member))
2618
+ throw new HostError("Replicate requester is not an approved Swarm member.", 1, "PIVOT_UNAUTHORIZED");
2619
+ await verifyPivotReplicateRequest(request);
2620
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId, { signal }));
2621
+ if (head.root !== request.headCid)
2622
+ throw new HostError("Replicate headCid must equal the current verified HEAD.");
2623
+ if (!context.node)
2624
+ throw new HostError("Replication requires an active Pivot node.");
2625
+ const status = await pivotStatus(context, url, signal);
2626
+ if (status.ready && status.headCid === head.root)
2627
+ return { ready: true, headCid: head.root };
2628
+ const source = context.store.withLocalSource(kuboSource(context.node, [], context.diagnostic));
2629
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(120_000)]);
2630
+ try {
2631
+ await pinPublication(source, [head.root], context.node, bounded, context.fetch);
2632
+ await finishPivotReplication(context, url, record, head, source, bounded);
2633
+ const fresh = await approvedMembership(context, url, bounded);
2634
+ const current = headValue(await client(context, c.service).read(c.scopeId, fresh.config.headId, {
2635
+ signal: bounded,
2636
+ }));
2637
+ if (!fresh.config.members.some((member) => member.publicKey === request.member) ||
2638
+ fresh.config.epoch !== config.epoch ||
2639
+ fresh.config.headId !== config.headId ||
2640
+ current.root !== head.root)
2641
+ throw new HostError("HEAD or requester membership changed during replication; retry.");
2642
+ context.pivotSyncError = null;
2643
+ return { ready: true, headCid: head.root };
2644
+ }
2645
+ catch (cause) {
2646
+ context.pivotSyncError = message(cause).slice(0, 2048);
2647
+ throw cause;
2648
+ }
2649
+ finally {
2650
+ await source.close();
2651
+ }
2652
+ }
2653
+ export async function replicateSwarm(context, url, signal = AbortSignal.timeout(180_000), options = {}) {
2654
+ const { automatic = false, onlinePeers } = options;
2655
+ rejectLocalSwarm(url, "swarm replicate");
2656
+ const record = await approvedMembership(context, url, signal);
2657
+ const c = coordinates(url);
2658
+ const config = record.config;
2659
+ const head = headValue(await client(context, c.service).read(c.scopeId, config.headId, { signal }));
2660
+ const members = await memberDirectory(context, url, config);
2661
+ let targets = members.filter(({ member, profile }) => member.publicKey !== record.account &&
2662
+ memberIsPivot(config, member, profile) &&
2663
+ (!automatic || !onlinePeers || onlinePeers.has(member.peerId)));
2664
+ if (options.pivot !== undefined) {
2665
+ const selector = options.pivot;
2666
+ targets = targets.filter(({ member, profile }) => member.publicKey === selector ||
2667
+ member.peerId === selector ||
2668
+ profile.name === selector);
2669
+ if (targets.length !== 1)
2670
+ throw new HostError(`Pivot "${selector}" is ${targets.length ? "ambiguous; use its public key or PeerID" : "not a declared remote Pivot; run swarm members"}.`);
2671
+ }
2672
+ const results = [];
2673
+ if (!targets.length) {
2674
+ if (!automatic)
2675
+ throw new HostError("No remote Pivot is declared. Approve a Pivot and run its daemon first.");
2676
+ return { headCid: head.root, results };
2677
+ }
2678
+ const complete = await localHeadClosure(context, head.root, signal, url);
2679
+ if (!automatic && !complete)
2680
+ throw new HostError("This member does not hold the complete current HEAD locally; replication was not started.");
2681
+ if (!context.node) {
2682
+ if (automatic)
2683
+ throw new HostError("Automatic replication requires an active node.");
2684
+ await activate(context, record);
2685
+ }
2686
+ let provided = false;
2687
+ for (const { member, profile } of targets) {
2688
+ const options = {
2689
+ node: context.node,
2690
+ pivotPeerId: member.peerId,
2691
+ pivotAddresses: automatic ? [] : profile.addresses,
2692
+ signal,
2693
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
2694
+ };
2695
+ let reachable = false;
2696
+ try {
2697
+ if (!automatic)
2698
+ context.diagnostic?.(`Checking Pivot ${profile.name || member.peerId} readiness...`);
2699
+ const status = await pivotReadinessOverP2p(options);
2700
+ context.pivotReadiness ??= {};
2701
+ context.pivotReadiness[member.peerId] = {
2702
+ observedAt: Date.now(),
2703
+ status: "v" in status ? status : null,
2704
+ error: null,
2705
+ };
2706
+ reachable = true;
2707
+ if (status.ready && status.headCid === head.root) {
2708
+ results.push({ peerId: member.peerId, status: "ready" });
2709
+ if (automatic)
2710
+ continue;
2711
+ break;
2712
+ }
2713
+ if (!complete)
2714
+ continue;
2715
+ if (!provided) {
2716
+ await provideContent(context.store, [head.root], context.node.api, context.fetch, context.node.auth, [head.root], signal);
2717
+ provided = true;
2718
+ }
2719
+ const identity = await contextIdentity(context);
2720
+ const request = await signPivotReplicateRequest({
2721
+ service: c.service,
2722
+ scopeId: c.scopeId,
2723
+ headId: config.headId,
2724
+ epoch: config.epoch,
2725
+ headCid: head.root,
2726
+ member: identity.publicKey,
2727
+ }, identity.privateKey);
2728
+ context.diagnostic?.(`Replicating ${head.root} to Pivot ${profile.name || member.peerId}...`);
2729
+ await pivotReadinessOverP2p(options, request);
2730
+ context.pivotReadiness[member.peerId] = {
2731
+ observedAt: Date.now(),
2732
+ status: {
2733
+ v: 1,
2734
+ ready: true,
2735
+ headCid: head.root,
2736
+ indexedHeadCid: CID.parse(head.root).code === dagPb.code ? head.root : null,
2737
+ syncError: null,
2738
+ },
2739
+ error: null,
2740
+ };
2741
+ results.push({ peerId: member.peerId, status: "replicated" });
2742
+ break;
2743
+ }
2744
+ catch (cause) {
2745
+ signal.throwIfAborted();
2746
+ const error = message(cause);
2747
+ const reportError = !automatic || reachable;
2748
+ context.pivotReadiness ??= {};
2749
+ context.pivotReadiness[member.peerId] = {
2750
+ observedAt: Date.now(),
2751
+ status: reachable
2752
+ ? {
2753
+ v: 1,
2754
+ ready: false,
2755
+ headCid: null,
2756
+ indexedHeadCid: null,
2757
+ syncError: error.slice(0, 2048),
2758
+ }
2759
+ : null,
2760
+ error: reportError ? error.slice(0, 2048) : null,
2761
+ };
2762
+ if (reportError)
2763
+ context.diagnostic?.(`Pivot ${member.peerId} replication check failed: ${error}`);
2764
+ results.push({
2765
+ peerId: member.peerId,
2766
+ status: reachable ? "failed" : "unreachable",
2767
+ error,
2768
+ });
2769
+ }
2770
+ }
2771
+ if (!automatic &&
2772
+ !results.some((result) => result.status === "ready" || result.status === "replicated"))
2773
+ throw new HostError(`No Pivot confirmed current HEAD readiness: ${results.map((result) => result.error).join("; ")}`);
2774
+ return { headCid: head.root, results };
2775
+ }
2189
2776
  export async function typedJson(store, cid, type) {
2190
2777
  const { bundle, value } = await bundleJson(store, cid);
2191
2778
  if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
@@ -2263,46 +2850,6 @@ async function writeV7RootBundle(store, configuration, configUrl) {
2263
2850
  });
2264
2851
  return jsonBundle(store, swarmRootType, value);
2265
2852
  }
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
2853
  async function readV7Root(store, cid) {
2307
2854
  const canonical = cid.toV1();
2308
2855
  const rootKey = canonical.toString();
@@ -2528,7 +3075,7 @@ async function publication(store, state, previous, writer) {
2528
3075
  await store.put(cid, data);
2529
3076
  return cid.toString();
2530
3077
  }
2531
- function missingContent(cause) {
3078
+ export function missingContent(cause) {
2532
3079
  let failure = cause;
2533
3080
  for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2534
3081
  failure = failure.cause;
@@ -2807,7 +3354,7 @@ function headerProjection(header) {
2807
3354
  throw new HostError("A verified account projection is required.");
2808
3355
  return header.projection;
2809
3356
  }
2810
- async function localHeader(context, url) {
3357
+ export async function localHeader(context, url) {
2811
3358
  if (isLocalSwarm(url))
2812
3359
  return { header: await readLocalSwarmHeader(context), account: "local" };
2813
3360
  if (context.forceRefresh)
@@ -2845,7 +3392,7 @@ async function localHeader(context, url) {
2845
3392
  }
2846
3393
  // SharedContent invokes this source only after a genuine local ENOENT. Its
2847
3394
  // store is not replaced from inside its own pending read (which would deadlock).
2848
- async function lazyPrivateSource(context, url, account, basis) {
3395
+ export async function lazyPrivateSource(context, url, account, basis) {
2849
3396
  rejectLocalSwarm(url, "private Kubo networking");
2850
3397
  const finishPrevious = context.finishRead;
2851
3398
  delete context.finishRead;
@@ -2870,9 +3417,10 @@ async function lazyPrivateSource(context, url, account, basis) {
2870
3417
  return source;
2871
3418
  };
2872
3419
  // Same lock order as Owner rotation: credentials first, then the node.
2873
- return withPrivateLock(await directory(scoped), authorize, signal);
3420
+ return withSwarmLock(context, await directory(scoped), authorize, signal);
2874
3421
  };
2875
- const store = context.store.withLocalSource({
3422
+ const previous = context.store;
3423
+ const store = previous.withLocalSource({
2876
3424
  block: {
2877
3425
  async get(cid, options = {}) {
2878
3426
  const signal = options.signal
@@ -2885,8 +3433,11 @@ async function lazyPrivateSource(context, url, account, basis) {
2885
3433
  },
2886
3434
  },
2887
3435
  });
2888
- await context.store.close();
3436
+ derivedLocalStores.add(store);
2889
3437
  context.store = store;
3438
+ if (derivedLocalStores.has(previous)) {
3439
+ await previous.close();
3440
+ }
2890
3441
  delete context.node;
2891
3442
  delete context.sourcePeers;
2892
3443
  context.finishRead = async () => {
@@ -2971,7 +3522,7 @@ export async function createSwarm(context, options = {}) {
2971
3522
  const skill = await seedSkillSource();
2972
3523
  for (const [cid, data] of skill.blocks)
2973
3524
  await context.store.put(CID.parse(cid), data);
2974
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
3525
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
2975
3526
  let root;
2976
3527
  if (record.stateVersion === 7) {
2977
3528
  let currentRoot = CID.parse(await writeV7RootBundle(context.store, {
@@ -3803,60 +4354,6 @@ export async function resumeRemoval(context, url) {
3803
4354
  }
3804
4355
  });
3805
4356
  }
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
4357
  export async function resolveReference(context, reference, swarm, local, raw = false, mode = "active") {
3861
4358
  const shared = parseNameReference(reference);
3862
4359
  let source;
@@ -3919,7 +4416,7 @@ export async function resolveReference(context, reference, swarm, local, raw = f
3919
4416
  return headContentFailure(context, source.configUrl, source.header.config, source.header.head, cause);
3920
4417
  }
3921
4418
  }
3922
- async function artifactValue(store, targetCid, protect) {
4419
+ export async function artifactValue(store, targetCid, protect) {
3923
4420
  let cid = targetCid;
3924
4421
  const visited = new Set();
3925
4422
  for (let depth = 0;; depth++) {
@@ -4306,11 +4803,55 @@ function metaCid(snapshot) {
4306
4803
  function hasMeta(snapshot) {
4307
4804
  return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
4308
4805
  }
4806
+ export const swarmFsTransport = {
4807
+ pointer,
4808
+ writeNamesHead,
4809
+ readSnapshot,
4810
+ swarmHeader,
4811
+ localHeader,
4812
+ lazyPrivateSource,
4813
+ invalidateSwarmHeader,
4814
+ prepareNamesPublication,
4815
+ missingContent,
4816
+ };
4817
+ const swarmFs = createSwarmFs(swarmFsTransport);
4818
+ function missingSkillPathError(snapshot) {
4819
+ return new HostError(snapshot.stateBundle
4820
+ ? "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."
4821
+ : `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.`);
4822
+ }
4823
+ function canonicalTypeSkillLeaf(name, leaf) {
4824
+ try {
4825
+ if (exactCid(leaf, true) === leaf)
4826
+ return leaf;
4827
+ }
4828
+ catch {
4829
+ // Fall through to typed error below.
4830
+ }
4831
+ throw new HostError(`Type Skill Name "${name}" must use a canonical schema CID.`);
4832
+ }
4833
+ async function inspectDirectTypeSkill(store, name, targetCid) {
4834
+ let bundle;
4835
+ try {
4836
+ bundle = await openBundle(CID.parse(targetCid), {
4837
+ resolveCid: (key) => store.block.get(key.toString()),
4838
+ });
4839
+ }
4840
+ catch (cause) {
4841
+ if (cause instanceof HostError)
4842
+ throw cause;
4843
+ throw new HostError(`Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
4844
+ }
4845
+ if (bundle.schemaKey !== skillSchema.cid.toString())
4846
+ throw new HostError(`Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
4847
+ return inspectSkillBundle(bundle);
4848
+ }
4309
4849
  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));
4850
+ let ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4851
+ mode: "active",
4852
+ preferLocalCache: true,
4853
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
4854
+ });
4314
4855
  const roots = new Set();
4315
4856
  const protect = async (cid) => {
4316
4857
  roots.add(cid);
@@ -4319,29 +4860,24 @@ export async function swarmSkills(context, configUrl, requested, owner) {
4319
4860
  await context.store.confirmRetained(owner, values);
4320
4861
  };
4321
4862
  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)) {
4863
+ if (hasMeta(ctx.snapshot)) {
4864
+ if (ctx.isV7) {
4328
4865
  if (context.store.supportsRetention) {
4329
- const rootId = metaCid(header.snapshot);
4866
+ const rootId = metaCid(ctx.snapshot);
4330
4867
  await context.store.retainDirect(owner, [rootId]);
4331
4868
  await context.store.confirmDirectRetained(owner, [rootId]);
4332
4869
  }
4333
4870
  }
4334
4871
  else {
4335
- await protect(metaCid(header.snapshot));
4872
+ await protect(metaCid(ctx.snapshot));
4336
4873
  }
4337
4874
  }
4338
- const meta = await swarmMeta(context, header);
4875
+ const meta = await swarmMeta(context, ctx.header);
4339
4876
  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);
4877
+ throw missingSkillPathError(ctx.snapshot);
4878
+ const globalDir = `${meta.skillPath}/global`;
4879
+ const prefix = `${globalDir}/`;
4880
+ const entries = await listSubtreeNames(context.store, ctx.snapshot, globalDir, false);
4345
4881
  for (const { cid: target } of entries)
4346
4882
  roots.add(target.toString());
4347
4883
  await context.store.registerOwnerAsync(owner, [...roots]);
@@ -4349,52 +4885,357 @@ export async function swarmSkills(context, configUrl, requested, owner) {
4349
4885
  const identities = new Set();
4350
4886
  for (const { name, cid: target } of entries) {
4351
4887
  if (name.slice(prefix.length).includes("/"))
4352
- throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
4888
+ throw new HostError(`Skill Name "${name}" must be flat under ${globalDir}.`);
4353
4889
  const cid = await artifactValue(context.store, target.toString(), protect);
4354
4890
  const bundle = await openBundle(CID.parse(cid), {
4355
4891
  resolveCid: (key) => context.store.block.get(key.toString()),
4356
4892
  });
4357
4893
  if (bundle.schemaKey !== skillSchema.cid.toString())
4358
4894
  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 });
4895
+ const metadata = await inspectSkillBundle(bundle);
4896
+ if (identities.has(metadata.name))
4897
+ throw new HostError(`Duplicate Skill installation name "${metadata.name}" in this Swarm.`);
4898
+ identities.add(metadata.name);
4899
+ result.push({
4900
+ name,
4901
+ cid,
4902
+ identity: metadata.name,
4903
+ description: metadata.description,
4904
+ });
4364
4905
  }
4365
4906
  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);
4907
+ if (missing.length && !attempt && ctx.source === "cache" && !ctx.isLocal) {
4908
+ ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4909
+ mode: "active",
4910
+ forceRefresh: true,
4911
+ });
4368
4912
  continue;
4369
4913
  }
4370
4914
  if (missing.length)
4371
- throw new HostError(`Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`);
4915
+ throw new HostError(`Skill identities or shared Names not found under ${globalDir}: ${missing.join(", ")}.`);
4372
4916
  return result;
4373
4917
  }
4374
4918
  }
4919
+ export async function swarmTypeSkills(context, configUrl, options = {}) {
4920
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4921
+ mode: options.mode ?? "local-first",
4922
+ ...(options.forceRefresh !== undefined
4923
+ ? { forceRefresh: options.forceRefresh }
4924
+ : {}),
4925
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
4926
+ });
4927
+ const roots = new Set();
4928
+ if (options.owner && hasMeta(ctx.snapshot)) {
4929
+ const rootId = metaCid(ctx.snapshot);
4930
+ if (ctx.isV7) {
4931
+ if (context.store.supportsRetention) {
4932
+ await context.store.retainDirect(options.owner, [rootId]);
4933
+ await context.store.confirmDirectRetained(options.owner, [rootId]);
4934
+ }
4935
+ }
4936
+ else {
4937
+ roots.add(rootId);
4938
+ await context.store.retain(options.owner, [...roots]);
4939
+ await context.store.confirmRetained(options.owner, [...roots]);
4940
+ }
4941
+ }
4942
+ const meta = await swarmMeta(context, ctx.header);
4943
+ if (!meta.skillPath)
4944
+ throw missingSkillPathError(ctx.snapshot);
4945
+ const typesDir = `${meta.skillPath}/types`;
4946
+ const prefix = `${typesDir}/`;
4947
+ const entries = await listSubtreeNames(context.store, ctx.snapshot, typesDir, false);
4948
+ if (options.owner) {
4949
+ for (const { cid: target } of entries)
4950
+ roots.add(target.toString());
4951
+ await context.store.registerOwnerAsync(options.owner, [...roots]);
4952
+ }
4953
+ const result = [];
4954
+ for (const { name, cid: target } of entries) {
4955
+ if (name.slice(prefix.length).includes("/"))
4956
+ throw new HostError(`Type Skill Name "${name}" must be flat under ${typesDir}.`);
4957
+ const leaf = name.slice(prefix.length);
4958
+ const schemaCid = canonicalTypeSkillLeaf(name, leaf);
4959
+ const targetCid = target.toString();
4960
+ const metadata = await inspectDirectTypeSkill(context.store, name, targetCid);
4961
+ result.push({
4962
+ name,
4963
+ schemaCid,
4964
+ cid: targetCid,
4965
+ identity: metadata.name,
4966
+ description: metadata.description,
4967
+ });
4968
+ }
4969
+ return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
4970
+ }
4971
+ export async function swarmTypeSkill(context, configUrl, schemaCid, options = {}) {
4972
+ const canonicalSchema = exactCid(schemaCid, true);
4973
+ let cachedHeader;
4974
+ let cachedName;
4975
+ let cachedTarget;
4976
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
4977
+ mode: options.mode ?? "local-first",
4978
+ ...(options.forceRefresh !== undefined
4979
+ ? { forceRefresh: options.forceRefresh }
4980
+ : {}),
4981
+ shouldRefresh: async (current) => {
4982
+ if (!hasMeta(current.snapshot))
4983
+ return true;
4984
+ await current.ensureLocalSource();
4985
+ const meta = await swarmMeta(context, current.header);
4986
+ if (!meta.skillPath)
4987
+ return false;
4988
+ const name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
4989
+ const target = await resolveSnapshotName(context.store, current.snapshot, name);
4990
+ cachedHeader = current.header;
4991
+ cachedName = name;
4992
+ cachedTarget = target;
4993
+ return !target;
4994
+ },
4995
+ });
4996
+ let name;
4997
+ let target;
4998
+ if (ctx.header === cachedHeader && cachedName !== undefined) {
4999
+ name = cachedName;
5000
+ target = cachedTarget;
5001
+ }
5002
+ else {
5003
+ const meta = await swarmMeta(context, ctx.header);
5004
+ if (!meta.skillPath)
5005
+ throw missingSkillPathError(ctx.snapshot);
5006
+ name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
5007
+ try {
5008
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
5009
+ }
5010
+ catch (cause) {
5011
+ if (!missingContent(cause))
5012
+ throw cause;
5013
+ await ctx.ensureLocalSource();
5014
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
5015
+ }
5016
+ }
5017
+ if (!target)
5018
+ return undefined;
5019
+ const targetCid = target.toString();
5020
+ const metadata = await inspectDirectTypeSkill(context.store, name, targetCid);
5021
+ return {
5022
+ name,
5023
+ schemaCid: canonicalSchema,
5024
+ cid: targetCid,
5025
+ identity: metadata.name,
5026
+ description: metadata.description,
5027
+ };
5028
+ }
5029
+ export async function setSwarmSkill(context, configUrl, input) {
5030
+ if (!input.global && input.types.length === 0)
5031
+ syntax("skills set requires --global and/or at least one --type SCHEMA.");
5032
+ const skillCid = exactCid(input.skillCid);
5033
+ const canonicalTypes = [
5034
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
5035
+ ].sort((left, right) => left.localeCompare(right));
5036
+ let bundle;
5037
+ try {
5038
+ bundle = await openBundle(CID.parse(skillCid), {
5039
+ resolveCid: (key) => context.store.block.get(key.toString()),
5040
+ });
5041
+ }
5042
+ catch (cause) {
5043
+ if (cause instanceof HostError)
5044
+ throw cause;
5045
+ throw new HostError(`Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
5046
+ }
5047
+ if (bundle.schemaKey !== skillSchema.cid.toString())
5048
+ throw new HostError(`Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`);
5049
+ const metadata = await inspectSkillBundle(bundle);
5050
+ let expectedSkillPath;
5051
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
5052
+ allowLegacyNames: true,
5053
+ refreshAfterCommit: true,
5054
+ maxAttempts: 8,
5055
+ plan: async (planCtx) => {
5056
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
5057
+ if (!meta.skillPath)
5058
+ throw missingSkillPathError(planCtx.snapshot);
5059
+ if (expectedSkillPath !== undefined &&
5060
+ meta.skillPath !== expectedSkillPath)
5061
+ throw new HostError("Swarm skillPath changed concurrently; retry ipab skills set.", 3, "EDIT_CONFLICT", "publication");
5062
+ expectedSkillPath = meta.skillPath;
5063
+ const plannedTargets = [];
5064
+ if (input.global) {
5065
+ const path = formalName(`${meta.skillPath}/global/${metadata.name}`);
5066
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
5067
+ plannedTargets.push({ scope: "global", name: path });
5068
+ }
5069
+ for (const schemaCid of canonicalTypes) {
5070
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
5071
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
5072
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
5073
+ }
5074
+ const resolvedTargets = await Promise.all(plannedTargets.map(async (target) => ({
5075
+ ...target,
5076
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
5077
+ })));
5078
+ const conflicts = resolvedTargets.filter((target) => target.existing !== null && target.existing !== skillCid);
5079
+ if (conflicts.length > 0 && !input.replace)
5080
+ 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");
5081
+ const pending = resolvedTargets.filter((target) => target.existing !== skillCid);
5082
+ const targets = resolvedTargets.map((target) => ({
5083
+ scope: target.scope,
5084
+ name: target.name,
5085
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
5086
+ cid: skillCid,
5087
+ previousCid: target.existing,
5088
+ changed: target.existing !== skillCid,
5089
+ }));
5090
+ if (pending.length === 0)
5091
+ return {
5092
+ kind: "noop",
5093
+ result: { skillPath: meta.skillPath, targets },
5094
+ };
5095
+ const operations = pending.map((target) => ({
5096
+ op: "set",
5097
+ path: target.name,
5098
+ targetCid: CID.parse(skillCid),
5099
+ }));
5100
+ return {
5101
+ kind: "commit",
5102
+ operations,
5103
+ recursiveRoots: [skillCid],
5104
+ retainedRecursive: [skillCid],
5105
+ result: { skillPath: meta.skillPath, targets },
5106
+ };
5107
+ },
5108
+ messages: {
5109
+ unconfirmed: (cause) => `Skill association unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5110
+ pinStale: (cause) => `Skill association committed, but HEAD/subscription refresh failed: ${message(cause)}.`,
5111
+ headBusy: () => "HEAD is busy; retry ipab skills set.",
5112
+ },
5113
+ });
5114
+ return {
5115
+ swarm: committed.swarm,
5116
+ skillPath: committed.result.skillPath,
5117
+ cid: skillCid,
5118
+ identity: metadata.name,
5119
+ description: metadata.description,
5120
+ headCid: committed.headCid,
5121
+ previousHeadCid: committed.previousHeadCid,
5122
+ rootCid: committed.rootCid,
5123
+ previousRootCid: committed.previousRootCid,
5124
+ changed: committed.changed,
5125
+ targets: committed.result.targets,
5126
+ };
5127
+ }
5128
+ export async function removeSwarmSkill(context, configUrl, input) {
5129
+ if (input.globalName === undefined && input.types.length === 0)
5130
+ syntax("skills remove requires --global NAME and/or at least one --type SCHEMA.");
5131
+ if (input.globalName !== undefined &&
5132
+ (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(input.globalName) ||
5133
+ input.globalName.length > 64))
5134
+ syntax(`Invalid global Skill name "${input.globalName}". Expected lowercase kebab-case (1..64 characters).`);
5135
+ const canonicalTypes = [
5136
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
5137
+ ].sort((left, right) => left.localeCompare(right));
5138
+ let expectedSkillPath;
5139
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
5140
+ allowLegacyNames: true,
5141
+ refreshAfterCommit: true,
5142
+ maxAttempts: 8,
5143
+ plan: async (planCtx) => {
5144
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
5145
+ if (!meta.skillPath)
5146
+ throw missingSkillPathError(planCtx.snapshot);
5147
+ if (expectedSkillPath !== undefined &&
5148
+ meta.skillPath !== expectedSkillPath)
5149
+ throw new HostError("Swarm skillPath changed concurrently; retry ipab skills remove.", 3, "EDIT_CONFLICT", "publication");
5150
+ expectedSkillPath = meta.skillPath;
5151
+ const plannedTargets = [];
5152
+ if (input.globalName !== undefined) {
5153
+ const path = formalName(`${meta.skillPath}/global/${input.globalName}`);
5154
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
5155
+ plannedTargets.push({ scope: "global", name: path });
5156
+ }
5157
+ for (const schemaCid of canonicalTypes) {
5158
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
5159
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
5160
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
5161
+ }
5162
+ const resolvedTargets = await Promise.all(plannedTargets.map(async (target) => ({
5163
+ ...target,
5164
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
5165
+ })));
5166
+ const missing = resolvedTargets.filter((target) => target.existing === null);
5167
+ if (missing.length > 0)
5168
+ throw new HostError(`Skill target(s) not found: ${missing.map((target) => target.name).join(", ")}.`, 1, "SKILL_NOT_FOUND", "state");
5169
+ const operations = resolvedTargets.map((target) => ({
5170
+ op: "delete",
5171
+ path: target.name,
5172
+ }));
5173
+ const removed = resolvedTargets.map((target) => ({
5174
+ scope: target.scope,
5175
+ name: target.name,
5176
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
5177
+ removedCid: target.existing,
5178
+ }));
5179
+ return {
5180
+ kind: "commit",
5181
+ operations,
5182
+ recursiveRoots: [],
5183
+ retainedRecursive: [],
5184
+ result: { skillPath: meta.skillPath, removed },
5185
+ };
5186
+ },
5187
+ messages: {
5188
+ unconfirmed: (cause) => `Skill removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5189
+ pinStale: (cause) => `Skill removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
5190
+ headBusy: () => "HEAD is busy; retry ipab skills remove.",
5191
+ },
5192
+ });
5193
+ return {
5194
+ swarm: committed.swarm,
5195
+ skillPath: committed.result.skillPath,
5196
+ headCid: committed.headCid,
5197
+ previousHeadCid: committed.previousHeadCid,
5198
+ rootCid: committed.rootCid,
5199
+ previousRootCid: committed.previousRootCid,
5200
+ changed: committed.changed,
5201
+ removed: committed.result.removed,
5202
+ };
5203
+ }
4375
5204
  export async function resolveTemplateSelector(context, selector, configUrl) {
4376
5205
  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);
5206
+ let cachedHeader;
5207
+ let cachedName;
5208
+ let cachedTarget;
5209
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5210
+ mode: "active",
5211
+ preferLocalCache: true,
5212
+ shouldRefresh: async (current) => {
5213
+ if (!hasMeta(current.snapshot))
5214
+ return true;
5215
+ await current.ensureLocalSource();
5216
+ const meta = await swarmMeta(context, current.header);
5217
+ const name = formalName(`${meta.templatePath}/${selector}`);
5218
+ const target = await resolveSnapshotName(context.store, current.snapshot, name);
5219
+ cachedHeader = current.header;
5220
+ cachedName = name;
5221
+ cachedTarget = target;
5222
+ return !target;
5223
+ },
5224
+ });
5225
+ let name;
5226
+ let target;
5227
+ if (ctx.header === cachedHeader) {
5228
+ name = cachedName;
5229
+ target = cachedTarget;
4392
5230
  }
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);
5231
+ else {
5232
+ const meta = await swarmMeta(context, ctx.header);
5233
+ name = formalName(`${meta.templatePath}/${selector}`);
5234
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
5235
+ }
5236
+ if (target)
5237
+ return artifactValue(context.store, target.toString());
5238
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
4398
5239
  }
4399
5240
  async function templateEntry(context, configUrl, header, selector) {
4400
5241
  const meta = await swarmMeta(context, header);
@@ -4414,19 +5255,55 @@ async function templateEntry(context, configUrl, header, selector) {
4414
5255
  ...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
4415
5256
  };
4416
5257
  }
4417
- async function retainDaemonRoots(store, owner, roots) {
5258
+ async function retainDaemonRoots(store, owner, roots, signal) {
4418
5259
  const unique = [...new Set(roots)];
5260
+ const options = signal ? [{ signal }] : [];
4419
5261
  if (!store.supportsRetention) {
4420
5262
  for (const root of unique)
4421
- await store.prepare(root);
5263
+ await store.prepare(root, ...options);
4422
5264
  return;
4423
5265
  }
4424
- await store.recoverOwner(owner, []);
5266
+ await store.recoverOwner(owner, [], ...options);
4425
5267
  if (unique.length) {
4426
- await store.retain(owner, unique);
4427
- await store.confirmRetained(owner, unique);
5268
+ await store.retain(owner, unique, ...options);
5269
+ await store.confirmRetained(owner, unique, ...options);
5270
+ }
5271
+ await store.reconcile(owner, unique, ...options);
5272
+ }
5273
+ export async function syncSwarmTypeSkills(context, configUrl, header) {
5274
+ if (!hasMeta(header.snapshot))
5275
+ return 0;
5276
+ const meta = await swarmMeta(context, header);
5277
+ if (!meta.skillPath)
5278
+ return 0;
5279
+ const typesDir = `${meta.skillPath}/types`;
5280
+ const prefix = `${typesDir}/`;
5281
+ const entries = await listSubtreeNames(context.store, header.snapshot, typesDir, false);
5282
+ const roots = [];
5283
+ for (const { name, cid: target } of entries) {
5284
+ if (name.slice(prefix.length).includes("/"))
5285
+ throw new HostError(`Type Skill Name "${name}" must be flat under ${typesDir}.`);
5286
+ const leaf = name.slice(prefix.length);
5287
+ canonicalTypeSkillLeaf(name, leaf);
5288
+ const targetCid = target.toString();
5289
+ await inspectDirectTypeSkill(context.store, name, targetCid);
5290
+ roots.push(targetCid);
5291
+ }
5292
+ const owner = `daemon-type-skills:${createHash("sha256").update(configUrl).digest("hex")}`;
5293
+ if (roots.length) {
5294
+ if (isV7Snapshot(header.snapshot)) {
5295
+ if (context.store.supportsRetention) {
5296
+ const rootId = metaCid(header.snapshot);
5297
+ await context.store.retainDirect(owner, [rootId]);
5298
+ await context.store.confirmDirectRetained(owner, [rootId]);
5299
+ }
5300
+ }
5301
+ else {
5302
+ roots.unshift(metaCid(header.snapshot));
5303
+ }
4428
5304
  }
4429
- await store.reconcile(owner, unique);
5305
+ await retainDaemonRoots(context.store, owner, roots);
5306
+ return entries.length;
4430
5307
  }
4431
5308
  export async function syncSwarmTemplates(context, configUrl, header) {
4432
5309
  if (!hasMeta(header.snapshot))
@@ -4488,13 +5365,17 @@ export async function syncSwarmRegistry(context, configUrl, header) {
4488
5365
  export async function syncPivotReplicationAndIndex(context, configUrl, header, signal) {
4489
5366
  if (!context.pivot || !isV7Snapshot(header.snapshot))
4490
5367
  return;
5368
+ const lock = await privateDirectory(context.stateDir, `pivot-index-${createHash("sha256").update(configUrl).digest("hex")}`);
5369
+ return withSwarmLock(context, lock, () => updatePivotReplicationAndIndex(context, configUrl, header, signal), signal);
5370
+ }
5371
+ async function updatePivotReplicationAndIndex(context, configUrl, header, signal) {
4491
5372
  const headCid = CID.parse(header.stateCid).toV1().toString();
4492
5373
  const previousHead = withState(context, (state) => state.searchIndexState(configUrl)?.headCid ?? null);
4493
5374
  if (context.node) {
4494
5375
  await pinAdd(context.node, headCid, true, signal);
4495
5376
  }
4496
5377
  const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
4497
- await retainDaemonRoots(context.store, owner, [headCid]);
5378
+ await retainDaemonRoots(context.store, owner, [headCid], signal);
4498
5379
  await withStateAsync(context, (state) => indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
4499
5380
  skipRootFiles: v7RootSkipFiles(header.snapshot),
4500
5381
  ...(signal ? { signal } : {}),
@@ -4506,39 +5387,32 @@ export async function syncPivotReplicationAndIndex(context, configUrl, header, s
4506
5387
  export async function swarmTemplates(context, configUrl, selector) {
4507
5388
  if (selector !== undefined)
4508
5389
  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
- }
5390
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5391
+ mode: "local-first",
5392
+ preferLocalCache: true,
5393
+ shouldRefresh: async (current) => {
5394
+ if (!hasMeta(current.snapshot))
5395
+ return true;
5396
+ if (selector === undefined)
5397
+ return false;
5398
+ await current.ensureLocalSource();
5399
+ const meta = await swarmMeta(context, current.header);
5400
+ const name = formalName(`${meta.templatePath}/${selector}`);
5401
+ return !(await resolveSnapshotName(context.store, current.snapshot, name));
5402
+ },
5403
+ });
5404
+ const meta = await swarmMeta(context, ctx.header);
5405
+ const selectors = selector === undefined
5406
+ ? (await listSubtreeNames(context.store, ctx.snapshot, meta.templatePath, false)).map((entry) => entry.name.slice(meta.templatePath.length + 1))
5407
+ : [selector];
5408
+ const items = [];
5409
+ for (const item of selectors)
5410
+ items.push(await templateEntry(context, configUrl, ctx.header, item));
5411
+ return items;
4538
5412
  }
4539
5413
  export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
4540
5414
  templateName(selector);
4541
- await pointer(context, configUrl);
5415
+ await swarmFsTransport.pointer(context, configUrl);
4542
5416
  const content = await templatePublicationSource(source, context.store);
4543
5417
  const details = await inspectTemplate(context.store, content);
4544
5418
  let location;
@@ -4568,57 +5442,44 @@ export async function setSwarmTemplate(context, configUrl, selector, source, exp
4568
5442
  export async function removeSwarmTemplate(context, configUrl, selector, expect) {
4569
5443
  templateName(selector);
4570
5444
  const expected = exactCid(expect);
4571
- const head = await pointer(context, configUrl);
4572
5445
  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.");
5446
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
5447
+ allowLegacyNames: true,
5448
+ refreshAfterCommit: true,
5449
+ plan: async (planCtx) => {
5450
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
5451
+ const name = formalName(`${meta.templatePath}/${selector}`);
5452
+ if (basis !== undefined && basis !== name)
5453
+ throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
5454
+ basis = name;
5455
+ const old = (await planCtx.resolve(name))?.toString();
5456
+ if (!old)
5457
+ throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
5458
+ if (old !== expected)
5459
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
5460
+ return {
5461
+ kind: "commit",
5462
+ operations: [{ op: "delete", path: name }],
5463
+ recursiveRoots: [],
5464
+ retainedRecursive: [],
5465
+ result: {
5466
+ swarm: configUrl,
5467
+ templatePath: meta.templatePath,
5468
+ metaCid: metaCid(planCtx.snapshot),
5469
+ selector,
5470
+ name,
5471
+ reference: formatNameReference(configUrl, name),
5472
+ targetCid: old,
5473
+ },
5474
+ };
5475
+ },
5476
+ messages: {
5477
+ unconfirmed: (cause) => `Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5478
+ pinStale: (cause) => `Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
5479
+ headBusy: () => "HEAD is busy; retry the template removal.",
5480
+ },
5481
+ });
5482
+ return committed.result;
4622
5483
  }
4623
5484
  async function registryAssociations(context, header) {
4624
5485
  assertNamesRegistry(header.snapshot);
@@ -4637,18 +5498,13 @@ async function registryAssociations(context, header) {
4637
5498
  return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
4638
5499
  }
4639
5500
  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);
5501
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5502
+ mode: "active",
5503
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
5504
+ });
5505
+ return registryAssociations(context, ctx.header);
4644
5506
  }
4645
5507
  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
5508
  const findAssociation = async (current) => {
4653
5509
  if (isV7Snapshot(current.snapshot)) {
4654
5510
  const meta = await swarmMeta(context, current);
@@ -4659,54 +5515,25 @@ export async function swarmAssociation(context, configUrl, schemaCid, mode = "ac
4659
5515
  }
4660
5516
  return (await registryAssociations(context, current)).find((item) => item.schemaCid === schemaCid);
4661
5517
  };
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);
5518
+ let cachedHeader;
5519
+ let cachedResult;
5520
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
5521
+ mode: "active",
5522
+ preferLocalCache: mode === "local-first",
5523
+ shouldRefresh: async (current) => {
5524
+ if (!hasMeta(current.snapshot))
5525
+ return true;
5526
+ await current.ensureLocalSource();
5527
+ cachedHeader = current.header;
5528
+ cachedResult = await findAssociation(current.header);
5529
+ return !cachedResult;
5530
+ },
4706
5531
  });
4707
- return newRootCid.toString();
5532
+ return ctx.header === cachedHeader
5533
+ ? cachedResult
5534
+ : findAssociation(ctx.header);
4708
5535
  }
4709
- async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
5536
+ export async function prepareNamesPublication(context, configUrl, current, names, roots, retainedRoots) {
4710
5537
  const identity = await contextIdentity(context);
4711
5538
  const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }, configUrl), undefined, identity.publicKey);
4712
5539
  await provideContent(context.store, [...new Set([next, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...(retainedRoots ?? roots)])]);
@@ -4716,7 +5543,7 @@ async function prepareNamesPublication(context, configUrl, current, names, roots
4716
5543
  return next;
4717
5544
  }
4718
5545
  async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
4719
- const head = await pointer(context, configUrl);
5546
+ await swarmFsTransport.pointer(context, configUrl);
4720
5547
  if (association) {
4721
5548
  const app = await openBundle(CID.parse(association.appCid), {
4722
5549
  resolveCid: (cid) => context.store.block.get(cid.toString()),
@@ -4727,49 +5554,43 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
4727
5554
  const roots = association
4728
5555
  ? await dependencies(context.store, association.appCid)
4729
5556
  : 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.`);
5557
+ await swarmFs.commitSwarmPaths(context, configUrl, {
5558
+ allowLegacyNames: true,
5559
+ refreshAfterCommit: false,
5560
+ plan: async (planCtx) => {
5561
+ assertNamesRegistry(planCtx.snapshot);
5562
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
5563
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
5564
+ const oldCid = (await planCtx.resolve(name))?.toString();
5565
+ if (association) {
5566
+ if (oldCid === association.appCid)
5567
+ return { kind: "noop", result: undefined };
5568
+ if (oldCid && !replace)
5569
+ throw new HostError("Schema has another association; use --replace.");
5570
+ return {
5571
+ kind: "commit",
5572
+ operations: [
5573
+ { op: "set", path: name, targetCid: CID.parse(association.appCid) },
5574
+ ],
5575
+ recursiveRoots: roots,
5576
+ result: undefined,
5577
+ };
5578
+ }
5579
+ if (!oldCid)
5580
+ throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
5581
+ return {
5582
+ kind: "commit",
5583
+ operations: [{ op: "delete", path: name }],
5584
+ recursiveRoots: [],
5585
+ retainedRecursive: [],
5586
+ result: undefined,
5587
+ };
5588
+ },
5589
+ messages: {
5590
+ unconfirmed: (cause, url) => `Registry publication unconfirmed for ${url}: ${message(cause)}. Inspect the Swarm registry before retry.`,
5591
+ headBusy: (url) => `HEAD is busy for ${url}; retry the registry edit.`,
5592
+ },
5593
+ });
4773
5594
  }
4774
5595
  export async function setSwarmAssociation(context, configUrl, value, replace = false) {
4775
5596
  if (value.argv.length !== 1 || value.argv[0] !== "%")
@@ -4880,41 +5701,31 @@ export async function unpublish(context, options) {
4880
5701
  throw new HostError("Unpublish requires a selected Swarm configuration URL or alias.");
4881
5702
  const name = formalName(options.name);
4882
5703
  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.");
5704
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
5705
+ allowLegacyNames: true,
5706
+ refreshAfterCommit: true,
5707
+ plan: async (planCtx) => {
5708
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
5709
+ const old = (await planCtx.resolve(name))?.toString();
5710
+ if (!old)
5711
+ throw new HostError(`Name "${name}" is missing; nothing was removed.`);
5712
+ if (old !== expected)
5713
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
5714
+ return {
5715
+ kind: "commit",
5716
+ operations: [{ op: "delete", path: name }],
5717
+ recursiveRoots: [],
5718
+ retainedRecursive: [],
5719
+ result: { name, targetCid: old },
5720
+ };
5721
+ },
5722
+ messages: {
5723
+ unconfirmed: (cause) => `Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
5724
+ pinStale: (cause) => `Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
5725
+ headBusy: () => "HEAD is busy; retry unpublish.",
5726
+ },
5727
+ });
5728
+ return committed.result;
4918
5729
  }
4919
5730
  export async function publish(context, content, options) {
4920
5731
  return publishContent(context, content, options);
@@ -4922,7 +5733,7 @@ export async function publish(context, content, options) {
4922
5733
  async function publishContent(context, content, options, nameForSnapshot) {
4923
5734
  if (!options.swarm)
4924
5735
  throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
4925
- const head = await pointer(context, options.swarm);
5736
+ await swarmFsTransport.pointer(context, options.swarm);
4926
5737
  const roots = await dependencies(context.store, content);
4927
5738
  const currentRoots = [...(await currentDependencies(context.store, content))];
4928
5739
  await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
@@ -4947,45 +5758,43 @@ async function publishContent(context, content, options, nameForSnapshot) {
4947
5758
  timestamp: new Date().toISOString(),
4948
5759
  });
4949
5760
  roots.add(candidate);
4950
- if (expected)
4951
- for (const root of await dependencies(context.store, expected))
5761
+ const expectedDeps = expected
5762
+ ? await dependencies(context.store, expected)
5763
+ : undefined;
5764
+ if (expectedDeps)
5765
+ for (const root of expectedDeps)
4952
5766
  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.`);
5767
+ const retained = [candidate, ...(expectedDeps ?? [])];
5768
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
5769
+ allowLegacyNames: true,
5770
+ refreshAfterCommit: true,
5771
+ plan: async (planCtx) => {
5772
+ if (nameForSnapshot) {
5773
+ name = await nameForSnapshot(planCtx.snapshot);
5774
+ if (resolvedName !== undefined && resolvedName !== name)
5775
+ throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
5776
+ resolvedName = name;
5777
+ }
5778
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
5779
+ const existing = (await planCtx.resolve(name))?.toString();
5780
+ if (existing !== expected)
5781
+ 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");
5782
+ return {
5783
+ kind: "commit",
5784
+ operations: [
5785
+ { op: "set", path: name, targetCid: CID.parse(candidate) },
5786
+ ],
5787
+ recursiveRoots: roots,
5788
+ retainedRecursive: retained,
5789
+ result: candidate,
5790
+ };
5791
+ },
5792
+ messages: {
5793
+ unconfirmed: (cause) => `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
5794
+ 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.`,
5795
+ headBusy: () => `HEAD is busy; candidate ${candidate} remains retained.`,
5796
+ },
5797
+ });
5798
+ return committed.result;
4990
5799
  }
4991
5800
  //# sourceMappingURL=swarm.js.map