@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/src/swarm.ts CHANGED
@@ -49,7 +49,7 @@ import {
49
49
  signEd25519,
50
50
  verifyEd25519,
51
51
  } from "@ipab/bundle/pointer/crypto";
52
- import { HostError, object, message } from "./errors.js";
52
+ import { HostError, object, message, syntax } from "./errors.js";
53
53
  import {
54
54
  accountIdentity,
55
55
  protectedPath,
@@ -64,32 +64,51 @@ import {
64
64
  isReservedLocalHost,
65
65
  swarmUrl as canonicalSwarmUrl,
66
66
  } from "./config.js";
67
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
67
68
  import {
68
- bundleJson,
69
- contentCar,
70
- provideContent,
71
- provideShallowContent,
72
- } from "./content-provider.js";
73
- import {
74
- deleteUnixfsPath,
75
- listUnixfsDirectory,
76
- resolveUnixfsPath,
77
69
  setUnixfsPath,
78
70
  walkUnixfsNames,
71
+ type UnixfsMutation,
79
72
  } from "./unixfs-tree.js";
73
+ import {
74
+ assertWritableSwarmFsPath,
75
+ createSwarmFs,
76
+ isV7Snapshot,
77
+ listSubtreeNames,
78
+ normalizeSwarmFsPath,
79
+ resolveSnapshotName,
80
+ v7RootSkipFiles,
81
+ type BoundHead,
82
+ type SwarmFsTransport,
83
+ type SwarmReadMode,
84
+ } from "./swarm-fs-core.js";
85
+
86
+ export {
87
+ isV7Snapshot,
88
+ listSubtreeNames,
89
+ resolveSnapshotName,
90
+ v7RootSkipFiles,
91
+ type BoundHead,
92
+ };
80
93
  import {
81
94
  parsePublicationPins,
82
95
  pinPublication,
83
96
  type PublicationPins,
84
97
  } from "./pivot-service.js";
85
98
  import {
99
+ ensurePivotListener,
86
100
  mountPivotServer,
101
+ parsePivotReplicateRequest,
102
+ pivotReadinessOverP2p,
87
103
  parsePivotReceiptRequest,
88
104
  requestPivotReceiptOverP2p,
89
105
  signPivotReceiptRequest,
106
+ signPivotReplicateRequest,
107
+ verifyPivotReplicateRequest,
90
108
  verifyPivotReceiptRequest,
91
109
  type PivotReceiptRequest,
92
110
  type PivotServer,
111
+ type PivotStatus,
93
112
  } from "./pivot-rpc.js";
94
113
  import {
95
114
  failedPin,
@@ -98,7 +117,19 @@ import {
98
117
  reservePin,
99
118
  retainPin,
100
119
  } from "./pins.js";
101
- import { bytes, relativePath } from "./space.js";
120
+ import { bytes } from "./space.js";
121
+ import {
122
+ formalName,
123
+ parseNameReference,
124
+ formatNameReference,
125
+ templateName,
126
+ } from "./name-reference.js";
127
+ export {
128
+ formalName,
129
+ parseNameReference,
130
+ formatNameReference,
131
+ templateName,
132
+ } from "./name-reference.js";
102
133
  import { appSchemaCid } from "./app-definition.js";
103
134
  import {
104
135
  State,
@@ -130,8 +161,10 @@ import {
130
161
  import {
131
162
  checkCachedNode,
132
163
  kuboSource,
164
+ nodeReady,
133
165
  peerId,
134
166
  pinAdd,
167
+ isRecursivelyPinned,
135
168
  pinRm,
136
169
  prepareNode,
137
170
  startNode,
@@ -157,6 +190,8 @@ import {
157
190
  queryRemotePivotSearch,
158
191
  rankPivotCandidates,
159
192
  } from "./search-service.js";
193
+ import { DaemonTelemetry, telemetryLogFilename } from "./daemon-telemetry.js";
194
+ import type { DaemonApiHandler } from "./daemon.js";
160
195
  import {
161
196
  DaemonLogBuffer,
162
197
  emptySyncState,
@@ -179,7 +214,7 @@ import {
179
214
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
180
215
  import { inspectTemplate, templatePublicationSource } from "./templates.js";
181
216
  import { seedSkillSource } from "./skill-source.js";
182
- import { skillIdentity, skillSchema } from "./skill-definition.js";
217
+ import { inspectSkillBundle, skillSchema } from "./skill-definition.js";
183
218
  import {
184
219
  parseSwarmMeta,
185
220
  swarmMetaType,
@@ -283,12 +318,22 @@ interface LegacyMembershipRequest {
283
318
  peerSignature: string;
284
319
  signature: string;
285
320
  }
321
+ export interface InProcessKeyedMutex {
322
+ run<T>(key: string, action: () => Promise<T>): Promise<T>;
323
+ }
324
+
286
325
  export interface SwarmContext {
287
326
  ensureDaemon?: () => Promise<void>;
288
327
  daemonReady?: (
289
328
  status?: () => DaemonStatusSnapshot,
290
329
  onListen?: (info: { port: number; url: string }) => void,
330
+ options?: {
331
+ apiHandler?: DaemonApiHandler;
332
+ onShutdown?: () => void;
333
+ hasActiveWork?: () => boolean;
334
+ },
291
335
  ) => Promise<() => Promise<void>>;
336
+ inProcessMutex?: InProcessKeyedMutex;
292
337
  confirmPublication?: (url: string, root: string) => Promise<void>;
293
338
  requestPivotReceipt?: (
294
339
  pivot: { member: Member; profile: Profile },
@@ -309,6 +354,8 @@ export interface SwarmContext {
309
354
  node?: KuboNode;
310
355
  sourcePeers?: readonly string[];
311
356
  finishRead?: () => Promise<void>;
357
+ pivotSyncError?: string | null;
358
+ pivotReadiness?: NetworkingSnapshot["readiness"];
312
359
  identity?: Identity;
313
360
  listen?: ListenMode;
314
361
  pivot?: boolean;
@@ -426,6 +473,20 @@ export interface Artifact {
426
473
  previous?: string;
427
474
  timestamp: string;
428
475
  }
476
+ function withSwarmLock<T>(
477
+ context: SwarmContext,
478
+ lockDir: string,
479
+ action: () => Promise<T>,
480
+ signal?: AbortSignal,
481
+ ): Promise<T> {
482
+ if (context.inProcessMutex) {
483
+ return context.inProcessMutex.run(lockDir, async () => {
484
+ signal?.throwIfAborted();
485
+ return action();
486
+ });
487
+ }
488
+ return withPrivateLock(lockDir, action, signal);
489
+ }
429
490
  function withState<T>(
430
491
  context: SwarmContext,
431
492
  operation: (state: State) => T,
@@ -438,6 +499,14 @@ function withState<T>(
438
499
  state.close();
439
500
  }
440
501
  }
502
+ export function invalidateSwarmHeader(
503
+ context: SwarmContext,
504
+ configUrl: string,
505
+ ): void {
506
+ withState(context, (state) => {
507
+ state.invalidateSwarmHeader(configUrl);
508
+ });
509
+ }
441
510
  export { canonicalSwarmUrl };
442
511
  function coordinates(configUrl: string): {
443
512
  service: string;
@@ -523,7 +592,7 @@ async function ensureLocalSwarm(
523
592
  const skill = await seedSkillSource();
524
593
  for (const [cid, data] of skill.blocks)
525
594
  await context.store.put(CID.parse(cid), data);
526
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
595
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
527
596
 
528
597
  let currentRoot = CID.parse(
529
598
  await writeV7RootBundle(
@@ -1037,7 +1106,8 @@ async function inspection(context: SwarmContext, url: string, refresh = false) {
1037
1106
  ]);
1038
1107
  let snapshot: InspectionSnapshot;
1039
1108
  if (saved === undefined) {
1040
- snapshot = await withPrivateLock(
1109
+ snapshot = await withSwarmLock(
1110
+ context,
1041
1111
  await privateDirectory(context.stateDir, "swarm-inspections"),
1042
1112
  async () => {
1043
1113
  const { config, variable } = await fetchConfig(context, url);
@@ -1174,6 +1244,7 @@ export async function swarmNetworking(
1174
1244
  url: string,
1175
1245
  config: Organization,
1176
1246
  directory?: Awaited<ReturnType<typeof memberDirectory>>,
1247
+ currentHeadCid?: string,
1177
1248
  ) {
1178
1249
  rejectLocalSwarm(url, "swarm networking");
1179
1250
  directory ??= (await inspection(context, url)).directory;
@@ -1243,6 +1314,11 @@ export async function swarmNetworking(
1243
1314
  : actual.length
1244
1315
  ? "relay"
1245
1316
  : "disconnected";
1317
+ const readiness = local.snapshot?.readiness?.[member.peerId];
1318
+ const readinessCurrent =
1319
+ local.status === "current" &&
1320
+ readiness &&
1321
+ Date.now() - readiness.observedAt <= 90_000;
1246
1322
  return {
1247
1323
  publicKey: member.publicKey,
1248
1324
  name: profile.name,
@@ -1273,6 +1349,22 @@ export async function swarmNetworking(
1273
1349
  freshness,
1274
1350
  addresses: actual.map((entry) => entry.address),
1275
1351
  },
1352
+ readiness: {
1353
+ status: !readinessCurrent
1354
+ ? "unknown"
1355
+ : !readiness.status
1356
+ ? "unreachable"
1357
+ : readiness.status.ready &&
1358
+ readiness.status.headCid === currentHeadCid
1359
+ ? "ready"
1360
+ : "not-ready",
1361
+ observedAt: readiness
1362
+ ? new Date(readiness.observedAt).toISOString()
1363
+ : null,
1364
+ headCid: readiness?.status?.headCid ?? null,
1365
+ indexedHeadCid: readiness?.status?.indexedHeadCid ?? null,
1366
+ error: readiness?.error ?? readiness?.status?.syncError ?? null,
1367
+ },
1276
1368
  };
1277
1369
  }),
1278
1370
  };
@@ -1294,16 +1386,26 @@ export async function inspectSwarmStatus(
1294
1386
  },
1295
1387
  );
1296
1388
  const templatePrefix = `${meta.templatePath}/`;
1297
- const skillPrefix = meta.skillPath ? `${meta.skillPath}/` : undefined;
1389
+ const globalSkillPrefix = meta.skillPath
1390
+ ? `${meta.skillPath}/global/`
1391
+ : undefined;
1392
+ const typeSkillPrefix = meta.skillPath
1393
+ ? `${meta.skillPath}/types/`
1394
+ : undefined;
1298
1395
  const registryPrefix = `${meta.registryPath}/`;
1299
1396
  let templates = 0;
1300
- let skills = 0;
1397
+ let globalSkills = 0;
1398
+ let typeSkills = 0;
1301
1399
  let registrations = 0;
1302
1400
  for (const entry of walked.entries) {
1303
1401
  if (entry.name.startsWith(templatePrefix)) templates++;
1304
- else if (skillPrefix && entry.name.startsWith(skillPrefix)) skills++;
1402
+ else if (globalSkillPrefix && entry.name.startsWith(globalSkillPrefix))
1403
+ globalSkills++;
1404
+ else if (typeSkillPrefix && entry.name.startsWith(typeSkillPrefix))
1405
+ typeSkills++;
1305
1406
  else if (entry.name.startsWith(registryPrefix)) registrations++;
1306
1407
  }
1408
+ const skills = globalSkills + typeSkills;
1307
1409
  return {
1308
1410
  mode: "local" as const,
1309
1411
  configUrl: LOCAL_SWARM_URL,
@@ -1323,6 +1425,8 @@ export async function inspectSwarmStatus(
1323
1425
  names: walked.entries.length,
1324
1426
  templates,
1325
1427
  skills,
1428
+ globalSkills,
1429
+ typeSkills,
1326
1430
  registrations,
1327
1431
  },
1328
1432
  networking: {
@@ -1366,7 +1470,13 @@ export async function inspectSwarmStatus(
1366
1470
  error:
1367
1471
  "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
1368
1472
  },
1369
- networking: await swarmNetworking(context, url, config, directory),
1473
+ networking: await swarmNetworking(
1474
+ context,
1475
+ url,
1476
+ config,
1477
+ directory,
1478
+ head.root,
1479
+ ),
1370
1480
  };
1371
1481
  }
1372
1482
 
@@ -1489,7 +1599,7 @@ async function ensureAccountProfile(
1489
1599
  ) {
1490
1600
  const identity = await contextIdentity(context);
1491
1601
  const dir = await accountProfileDirectory(context, identity.publicKey);
1492
- return withPrivateLock(dir, async () => {
1602
+ return withSwarmLock(context, dir, async () => {
1493
1603
  const existing = await storedAccountProfile(context);
1494
1604
  if (
1495
1605
  existing &&
@@ -2009,6 +2119,8 @@ async function privateSource(
2009
2119
  ),
2010
2120
  };
2011
2121
  }
2122
+ const pivotReadinessRefreshIntervalMs = 45_000;
2123
+
2012
2124
  export async function swarmDaemon(
2013
2125
  context: SwarmContext,
2014
2126
  signal: AbortSignal,
@@ -2033,6 +2145,8 @@ export async function swarmDaemon(
2033
2145
  candidates: PivotCandidates;
2034
2146
  nextDiscovery: number;
2035
2147
  nextSync: number;
2148
+ nextReplication?: number;
2149
+ nextPivotSync?: number;
2036
2150
  healthy: number;
2037
2151
  record?: LocalMembership;
2038
2152
  node?: KuboNode;
@@ -2049,6 +2163,7 @@ export async function swarmDaemon(
2049
2163
  nodeApi: string;
2050
2164
  epoch: number;
2051
2165
  headId: string;
2166
+ listening: boolean;
2052
2167
  };
2053
2168
  }
2054
2169
  >();
@@ -2077,6 +2192,42 @@ export async function swarmDaemon(
2077
2192
  }
2078
2193
  return secrets;
2079
2194
  };
2195
+ const telemetry = new DaemonTelemetry({
2196
+ env: context.env,
2197
+ logPath: join(context.stateDir, "swarm-daemon", telemetryLogFilename),
2198
+ secrets: () => collectSecrets(),
2199
+ });
2200
+ const [
2201
+ { builtinContent },
2202
+ { DaemonService, KeyedMutex, createDaemonApiHandler },
2203
+ ] = await Promise.all([
2204
+ import("./builtins.js"),
2205
+ import("./daemon-api.js"),
2206
+ ]);
2207
+ const ownsDaemonState = !context.state;
2208
+ const builtins = ownsDaemonState ? await builtinContent() : undefined;
2209
+ const daemonState =
2210
+ context.state ??
2211
+ new State(context.stateDir, builtins?.pins ?? [], context.env, (db) =>
2212
+ telemetry.wrapDatabase(db, "state"),
2213
+ );
2214
+ const daemonStore = new IpfsStore({
2215
+ ...context.store.configuration,
2216
+ singleProcessCoordination: true,
2217
+ onCoordinationEvent: (event) => {
2218
+ telemetry.recordCoordination(event);
2219
+ },
2220
+ onSqlEvent: (event) => {
2221
+ telemetry.recordSql(event);
2222
+ },
2223
+ });
2224
+ const inProcessMutex = context.inProcessMutex ?? new KeyedMutex();
2225
+ const daemonContext: SwarmContext = {
2226
+ ...context,
2227
+ state: daemonState,
2228
+ store: daemonStore,
2229
+ inProcessMutex,
2230
+ };
2080
2231
  const redact = (
2081
2232
  error: string | null,
2082
2233
  session?: NonNullable<ReturnType<typeof sessions.get>>,
@@ -2088,6 +2239,38 @@ export async function swarmDaemon(
2088
2239
  logBuffer.push(text, collectSecrets());
2089
2240
  context.diagnostic?.(text);
2090
2241
  };
2242
+ const dirtyDiscovery = new Set<string>();
2243
+ const wakeState = { dirtyAllDiscovery: false, wakeRequested: false };
2244
+ let wakeSleep: (() => void) | undefined;
2245
+ const wakeDaemonLoop = (url?: string) => {
2246
+ if (url) dirtyDiscovery.add(url);
2247
+ else wakeState.dirtyAllDiscovery = true;
2248
+ wakeState.wakeRequested = true;
2249
+ const resolveWake = wakeSleep;
2250
+ wakeSleep = undefined;
2251
+ resolveWake?.();
2252
+ };
2253
+ const daemonService = await DaemonService.create({
2254
+ stateDir: context.stateDir,
2255
+ env: context.env,
2256
+ state: daemonState,
2257
+ store: daemonStore,
2258
+ telemetry,
2259
+ inProcessMutex,
2260
+ diagnostic: emitDiagnostic,
2261
+ ensureDaemon: () => {
2262
+ wakeDaemonLoop();
2263
+ return Promise.resolve();
2264
+ },
2265
+ onSwarmChange: wakeDaemonLoop,
2266
+ ...(context.fetch ? { fetch: context.fetch } : {}),
2267
+ });
2268
+ const shutdownController = new AbortController();
2269
+ const shutdownRequested = () => shutdownController.signal.aborted;
2270
+ const effectiveSignal = AbortSignal.any([
2271
+ signal,
2272
+ shutdownController.signal,
2273
+ ]);
2091
2274
  const buildStatusSnapshot = (): DaemonStatusSnapshot => {
2092
2275
  const now = Date.now();
2093
2276
  const urls = [...new Set([...knownAliases.keys(), ...sessions.keys()])];
@@ -2148,7 +2331,7 @@ export async function swarmDaemon(
2148
2331
  : "unknown",
2149
2332
  running: Boolean(session?.running),
2150
2333
  receiptRpc: {
2151
- active: Boolean(session?.pivotServer),
2334
+ active: Boolean(session?.pivotServer?.listening),
2152
2335
  protocol: pivotReceiptProtocol,
2153
2336
  epoch: session?.pivotServer?.epoch ?? null,
2154
2337
  headId: session?.pivotServer?.headId ?? null,
@@ -2193,6 +2376,7 @@ export async function swarmDaemon(
2193
2376
  syncInterval: context.syncInterval ?? 60,
2194
2377
  swarms,
2195
2378
  logs: logBuffer.entries(),
2379
+ observability: telemetry.snapshot(collectSecrets()),
2196
2380
  };
2197
2381
  };
2198
2382
  const closeReadiness = await context.daemonReady?.(
@@ -2200,6 +2384,20 @@ export async function swarmDaemon(
2200
2384
  ({ url }) => {
2201
2385
  uiUrl = url;
2202
2386
  },
2387
+ {
2388
+ apiHandler: createDaemonApiHandler(daemonService),
2389
+ onShutdown: () => {
2390
+ shutdownController.abort(
2391
+ new HostError(
2392
+ "Daemon shutdown requested.",
2393
+ 0,
2394
+ "SHUTDOWN",
2395
+ "daemon",
2396
+ ),
2397
+ );
2398
+ },
2399
+ hasActiveWork: () => daemonService.hasActiveRuns(),
2400
+ },
2203
2401
  );
2204
2402
  emitDiagnostic(
2205
2403
  `IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.${uiUrl ? ` Status UI: ${uiUrl}` : ""}`,
@@ -2221,7 +2419,9 @@ export async function swarmDaemon(
2221
2419
  try {
2222
2420
  await session.context.finishRead?.();
2223
2421
  } finally {
2224
- await session.context.store.close();
2422
+ if (session.context.store !== daemonStore) {
2423
+ await session.context.store.close();
2424
+ }
2225
2425
  }
2226
2426
  }
2227
2427
  };
@@ -2263,12 +2463,49 @@ export async function swarmDaemon(
2263
2463
  error: "No connection snapshot collected.",
2264
2464
  peers: [],
2265
2465
  },
2466
+ ...(session.context.pivotReadiness
2467
+ ? {
2468
+ readiness: Object.fromEntries(
2469
+ Object.entries(session.context.pivotReadiness).map(
2470
+ ([peerId, value]) => [
2471
+ peerId,
2472
+ {
2473
+ ...value,
2474
+ error: redact(value.error, session),
2475
+ status: value.status
2476
+ ? {
2477
+ ...value.status,
2478
+ syncError: redact(
2479
+ value.status.syncError,
2480
+ session,
2481
+ ),
2482
+ }
2483
+ : null,
2484
+ },
2485
+ ],
2486
+ ),
2487
+ ),
2488
+ }
2489
+ : {}),
2266
2490
  };
2267
2491
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
2268
2492
  };
2269
2493
  try {
2270
- while (!signal.aborted) {
2271
- const registrations = withState(context, (state) => state.swarms());
2494
+ while (!effectiveSignal.aborted) {
2495
+ if (wakeState.dirtyAllDiscovery) {
2496
+ for (const session of sessions.values()) session.nextDiscovery = 0;
2497
+ wakeState.dirtyAllDiscovery = false;
2498
+ dirtyDiscovery.clear();
2499
+ } else if (dirtyDiscovery.size > 0) {
2500
+ for (const dirtyUrl of dirtyDiscovery) {
2501
+ const session = sessions.get(dirtyUrl);
2502
+ if (session) session.nextDiscovery = 0;
2503
+ }
2504
+ dirtyDiscovery.clear();
2505
+ }
2506
+ const registrations = withState(daemonContext, (state) =>
2507
+ state.swarms(),
2508
+ );
2272
2509
  knownAliases = new Map(
2273
2510
  registrations.map((entry) => [entry.cid, entry.alias]),
2274
2511
  );
@@ -2280,330 +2517,557 @@ export async function swarmDaemon(
2280
2517
  await closeSession(session);
2281
2518
  sessions.delete(url);
2282
2519
  }
2283
- await boundedMap(registrations, async ({ cid: url }) => {
2284
- let session = sessions.get(url);
2285
- if (!session) {
2286
- session = {
2287
- context: {
2288
- ...context,
2289
- diagnostic: emitDiagnostic,
2290
- store: new IpfsStore(context.store.configuration),
2291
- forceRefresh: true,
2292
- },
2293
- candidates: new PivotCandidates(),
2294
- nextDiscovery: 0,
2295
- nextSync: 0,
2296
- healthy: 0,
2297
- selected: new Set(),
2298
- verifiedAt: null,
2299
- updatedAt: null,
2300
- running: false,
2301
- error: null,
2302
- sync: emptySyncState(),
2303
- };
2304
- sessions.set(url, session);
2305
- }
2306
- try {
2307
- if (session.record?.config && context.pivot === undefined) {
2308
- const self = session.record.config.members.find(
2309
- (member) => member.publicKey === session.record!.account,
2310
- )!;
2311
- const c = coordinates(url);
2312
- const profile = parseProfile(
2313
- (
2314
- await client(session.context, c.service).read(
2315
- c.scopeId,
2316
- self.profileId,
2317
- { signal },
2318
- )
2319
- ).value,
2320
- self.peerId,
2321
- );
2322
- if ((profile.pivot ?? false) !== session.pivot)
2323
- session.nextDiscovery = 0;
2324
- }
2325
- if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
2326
- const record = await approvedMembership(
2327
- session.context,
2328
- url,
2329
- signal,
2330
- );
2331
- const c = coordinates(url);
2332
- const scope = nodeScope(c.service, record.config!.scopeId);
2333
- const existing = await readPrivate<unknown>(
2334
- join(context.stateDir, "swarm-nodes", scope),
2335
- "node.json",
2336
- );
2337
- if (!existing)
2338
- throw new HostError(
2339
- "No existing managed node; activate this membership before running daemon.",
2340
- );
2341
- await saveLocal(session.context, record);
2342
- if (
2343
- !session.record?.config ||
2344
- networkingBinding(url, record.account, record.config!) !==
2345
- networkingBinding(
2346
- url,
2347
- session.record.account,
2348
- session.record.config,
2349
- )
2350
- ) {
2351
- session.candidates.reconcile(new Map());
2352
- session.selected.clear();
2353
- session.verifiedAt = null;
2354
- delete session.connections;
2355
- delete session.node;
2520
+ await boundedMap(registrations, async ({ cid: url }) =>
2521
+ telemetry.runWithContext(
2522
+ { source: "daemon-bg", operation: "swarm-tick", swarm: url },
2523
+ async () => {
2524
+ let session = sessions.get(url);
2525
+ if (!session) {
2526
+ session = {
2527
+ context: {
2528
+ ...daemonContext,
2529
+ diagnostic: emitDiagnostic,
2530
+ store: daemonStore.scope(),
2531
+ forceRefresh: true,
2532
+ },
2533
+ candidates: new PivotCandidates(),
2534
+ nextDiscovery: 0,
2535
+ nextSync: 0,
2536
+ healthy: 0,
2537
+ selected: new Set(),
2538
+ verifiedAt: null,
2539
+ updatedAt: null,
2540
+ running: false,
2541
+ error: null,
2542
+ sync: emptySyncState(),
2543
+ };
2544
+ sessions.set(url, session);
2356
2545
  }
2357
- session.record = record;
2358
- const result = await privateSource(
2359
- session.context,
2360
- record,
2361
- signal,
2362
- session.candidates,
2363
- );
2364
- session.node = result.node;
2365
- session.pivot = result.pivot;
2366
- session.context.pivot = result.pivot;
2367
- session.selected = new Set(result.selectedPeers);
2368
- session.error = result.observationError;
2369
- if (!session.error) session.verifiedAt = Date.now();
2370
- session.context.node = result.node;
2371
- session.nextDiscovery = Date.now() + 120_000;
2372
- await persist(url, session, true);
2373
- }
2374
- if (!session.node) return;
2375
- let healthy = 0;
2376
- await boundedMap(
2377
- [...session.candidates.active()],
2378
- async ([id, addresses]) => {
2379
- let success = false;
2380
- let error: string | null = null;
2381
- try {
2382
- success = await probePeer(
2383
- session.node!,
2384
- id,
2385
- addresses,
2386
- signal,
2546
+ let pivotListenerVerified = false;
2547
+ try {
2548
+ if (session.record?.config && context.pivot === undefined) {
2549
+ const self = session.record.config.members.find(
2550
+ (member) => member.publicKey === session.record!.account,
2551
+ )!;
2552
+ const c = coordinates(url);
2553
+ const profile = parseProfile(
2554
+ (
2555
+ await client(session.context, c.service).read(
2556
+ c.scopeId,
2557
+ self.profileId,
2558
+ { signal: effectiveSignal },
2559
+ )
2560
+ ).value,
2561
+ self.peerId,
2387
2562
  );
2388
- } catch (cause) {
2389
- signal.throwIfAborted();
2390
- error = message(cause);
2391
- emitDiagnostic(
2392
- `[${url}] Pivot probe ${id}: ${message(cause)}`,
2563
+ if ((profile.pivot ?? false) !== session.pivot)
2564
+ session.nextDiscovery = 0;
2565
+ }
2566
+ if (
2567
+ Date.now() >= session.nextDiscovery ||
2568
+ session.healthy < 1
2569
+ ) {
2570
+ const record = await approvedMembership(
2571
+ session.context,
2572
+ url,
2573
+ effectiveSignal,
2574
+ );
2575
+ const c = coordinates(url);
2576
+ const scope = nodeScope(c.service, record.config!.scopeId);
2577
+ const existing = await readPrivate<unknown>(
2578
+ join(context.stateDir, "swarm-nodes", scope),
2579
+ "node.json",
2393
2580
  );
2581
+ if (!existing)
2582
+ throw new HostError(
2583
+ "No existing managed node; activate this membership before running daemon.",
2584
+ );
2585
+ await saveLocal(session.context, record);
2586
+ if (
2587
+ !session.record?.config ||
2588
+ networkingBinding(url, record.account, record.config!) !==
2589
+ networkingBinding(
2590
+ url,
2591
+ session.record.account,
2592
+ session.record.config,
2593
+ )
2594
+ ) {
2595
+ session.candidates.reconcile(new Map());
2596
+ session.selected.clear();
2597
+ session.verifiedAt = null;
2598
+ delete session.connections;
2599
+ delete session.node;
2600
+ }
2601
+ session.record = record;
2602
+ if (context.pivot === undefined)
2603
+ delete session.context.pivot;
2604
+ const result = await privateSource(
2605
+ session.context,
2606
+ record,
2607
+ effectiveSignal,
2608
+ session.candidates,
2609
+ );
2610
+ session.node = result.node;
2611
+ session.pivot = result.pivot;
2612
+ session.context.pivot = result.pivot;
2613
+ session.selected = new Set(result.selectedPeers);
2614
+ session.error = result.observationError;
2615
+ if (!session.error) session.verifiedAt = Date.now();
2616
+ session.context.node = result.node;
2617
+ session.nextDiscovery = Date.now() + 120_000;
2618
+ await persist(url, session, true);
2394
2619
  }
2395
- session.candidates.result(
2396
- id,
2397
- success,
2398
- Date.now(),
2399
- Math.random(),
2400
- success ? null : (error ?? "Pivot dial failed."),
2401
- );
2402
- if (success) healthy++;
2403
- else {
2404
- session.nextDiscovery = 0;
2620
+ if (!session.node) return;
2621
+ const currentRecord = session.record!;
2622
+ const currentSelf = currentRecord.config!.members.find(
2623
+ (member) => member.publicKey === currentRecord.account,
2624
+ )!;
2625
+ if (
2626
+ !(await nodeReady(
2627
+ session.node,
2628
+ effectiveSignal,
2629
+ session.context.fetch,
2630
+ ))
2631
+ ) {
2632
+ if (session.pivotServer)
2633
+ session.pivotServer.listening = false;
2634
+ const currentDesired = memberPeers(
2635
+ currentSelf.peerId,
2636
+ session.candidates.active(),
2637
+ [],
2638
+ );
2639
+ session.node = await startNode(
2640
+ context.stateDir,
2641
+ nodeScope(
2642
+ coordinates(url).service,
2643
+ currentRecord.config!.scopeId,
2644
+ ),
2645
+ currentRecord.secret!.swarmKey,
2646
+ currentRecord.config!.epoch,
2647
+ context.listen,
2648
+ {
2649
+ self: currentSelf.peerId,
2650
+ pivot: session.pivot ?? false,
2651
+ peers: currentDesired,
2652
+ signal: effectiveSignal,
2653
+ },
2654
+ );
2655
+ session.selected = new Set(
2656
+ currentDesired.map(({ ID }) => ID),
2657
+ );
2658
+ session.context.node = session.node;
2405
2659
  emitDiagnostic(
2406
- `[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`,
2660
+ `[${url}] Managed Kubo was offline; restarted before probing peers.`,
2407
2661
  );
2408
2662
  }
2409
- },
2410
- );
2411
- session.healthy = healthy;
2412
- // Startup-captured relay/bootstrap options must be removed immediately
2413
- // when a candidate enters cooldown, not merely changed through config RPC.
2414
- const record = session.record!;
2415
- const self = record.config!.members.find(
2416
- (member) => member.publicKey === record.account,
2417
- )!;
2418
- const desired = memberPeers(
2419
- self.peerId,
2420
- session.candidates.active(),
2421
- [],
2422
- );
2423
- session.node = await startNode(
2424
- context.stateDir,
2425
- nodeScope(coordinates(url).service, record.config!.scopeId),
2426
- record.secret!.swarmKey,
2427
- record.config!.epoch,
2428
- context.listen,
2429
- {
2430
- self: self.peerId,
2431
- pivot: session.pivot ?? false,
2432
- peers: desired,
2433
- signal,
2434
- },
2435
- );
2436
- session.selected = new Set(desired.map(({ ID }) => ID));
2437
- session.context.node = session.node;
2438
- if (session.pivot) {
2439
- if (
2440
- !session.pivotServer ||
2441
- session.pivotServer.nodeApi !== session.node.api ||
2442
- session.pivotServer.epoch !== record.config!.epoch ||
2443
- session.pivotServer.headId !== record.config!.headId
2444
- ) {
2445
- await stopPivotServer(session);
2446
- const pivotNode = session.node;
2447
- const mounted = await mountPivotServer(
2448
- pivotNode,
2449
- {
2450
- receipt: (receiptRequest, requestSignal) =>
2451
- handlePivotReceiptRequest(
2452
- { ...session.context, node: pivotNode },
2453
- url,
2454
- receiptRequest,
2455
- requestSignal,
2456
- ),
2457
- search: (params) =>
2458
- withState(session.context, (state) =>
2459
- queryLocalSearchIndex(state, url, params),
2460
- ),
2461
- ...(context.diagnostic
2462
- ? { diagnostic: context.diagnostic }
2463
- : {}),
2663
+ let healthy = 0;
2664
+ await boundedMap(
2665
+ [...session.candidates.active()],
2666
+ async ([id, addresses]) => {
2667
+ let success = false;
2668
+ let error: string | null = null;
2669
+ try {
2670
+ success = await probePeer(
2671
+ session.node!,
2672
+ id,
2673
+ addresses,
2674
+ effectiveSignal,
2675
+ );
2676
+ } catch (cause) {
2677
+ effectiveSignal.throwIfAborted();
2678
+ error = message(cause);
2679
+ emitDiagnostic(
2680
+ `[${url}] Pivot probe ${id}: ${message(cause)}`,
2681
+ );
2682
+ }
2683
+ session.candidates.result(
2684
+ id,
2685
+ success,
2686
+ Date.now(),
2687
+ Math.random(),
2688
+ success ? null : (error ?? "Pivot dial failed."),
2689
+ );
2690
+ if (success) healthy++;
2691
+ else {
2692
+ session.nextDiscovery = 0;
2693
+ emitDiagnostic(
2694
+ `[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`,
2695
+ );
2696
+ }
2464
2697
  },
2465
- session.context.fetch,
2466
- );
2467
- session.pivotServer = {
2468
- server: mounted,
2469
- nodeApi: session.node.api,
2470
- epoch: record.config!.epoch,
2471
- headId: record.config!.headId,
2472
- };
2473
- }
2474
- await syncPivotPublications(session.context, url, signal);
2475
- } else {
2476
- await stopPivotServer(session);
2477
- }
2478
- try {
2479
- const peers = await nodeConnections(session.node, signal);
2480
- session.connections = {
2481
- observedAt: Date.now(),
2482
- error: null,
2483
- peers,
2484
- };
2485
- } catch (cause) {
2486
- signal.throwIfAborted();
2487
- session.connections = {
2488
- observedAt: session.connections?.observedAt ?? null,
2489
- error: message(cause).slice(0, 2048),
2490
- peers: session.connections?.peers ?? [],
2491
- };
2492
- }
2493
- } catch (cause) {
2494
- if (signal.aborted) return;
2495
- session.error = message(cause);
2496
- session.nextDiscovery = 0;
2497
- emitDiagnostic(
2498
- `[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`,
2499
- );
2500
- if (
2501
- cause instanceof HostError &&
2502
- /membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(
2503
- cause.message,
2504
- )
2505
- ) {
2506
- await stopPivotServer(session);
2507
- if (session.node) await stopNode(session.node);
2508
- session.candidates.reconcile(new Map());
2509
- delete session.node;
2510
- session.selected.clear();
2511
- await persist(url, session, false);
2512
- delete session.record;
2513
- }
2514
- }
2515
- if (
2516
- synchronize &&
2517
- session.node &&
2518
- !signal.aborted &&
2519
- Date.now() >= session.nextSync
2520
- ) {
2521
- let deferIsolatedPivot = false;
2522
- if (
2523
- session.pivot &&
2524
- (session.connections?.peers.length ?? 0) === 0 &&
2525
- session.candidates.active().size === 0 &&
2526
- session.record?.config
2527
- ) {
2528
- try {
2529
- const c = coordinates(url);
2530
- const head = headValue(
2531
- await client(session.context, c.service).read(
2532
- c.scopeId,
2533
- session.record.config.headId,
2534
- { signal },
2535
- ),
2536
2698
  );
2537
- deferIsolatedPivot = !(await hasLocalBlock(
2538
- session.context.store,
2539
- head.root,
2540
- ));
2541
- } catch (cause) {
2542
- signal.throwIfAborted();
2543
- emitDiagnostic(
2544
- `[${url}] Isolated Pivot HEAD check failed: ${message(cause)}`,
2699
+ session.healthy = healthy;
2700
+ // Reconcile active Pivot Bootstrap candidates via live Kubo RPC
2701
+ // without restarting the daemon unless startup-only config changed.
2702
+ const record = session.record!;
2703
+ const self = record.config!.members.find(
2704
+ (member) => member.publicKey === record.account,
2705
+ )!;
2706
+ const desired = memberPeers(
2707
+ self.peerId,
2708
+ session.candidates.active(),
2709
+ [],
2545
2710
  );
2546
- }
2547
- }
2548
- if (deferIsolatedPivot) {
2549
- session.nextSync = Date.now() + 5_000;
2550
- session.sync.nextSyncAt = new Date(
2551
- session.nextSync,
2552
- ).toISOString();
2553
- } else {
2554
- const attemptAt = new Date().toISOString();
2555
- session.sync.lastAttemptAt = attemptAt;
2556
- let reported: DaemonSyncSummary | undefined;
2557
- try {
2558
- const summary = await raceAbort(
2559
- synchronize(session.context, url, (partial) => {
2560
- reported = partial;
2561
- }),
2562
- signal,
2711
+ session.node = await startNode(
2712
+ context.stateDir,
2713
+ nodeScope(coordinates(url).service, record.config!.scopeId),
2714
+ record.secret!.swarmKey,
2715
+ record.config!.epoch,
2716
+ context.listen,
2717
+ {
2718
+ self: self.peerId,
2719
+ pivot: session.pivot ?? false,
2720
+ peers: desired,
2721
+ signal: effectiveSignal,
2722
+ },
2563
2723
  );
2564
- const applied = summary ?? reported;
2565
- if (applied) {
2566
- session.sync = {
2567
- ...session.sync,
2568
- ...applied,
2569
- lastAttemptAt: attemptAt,
2570
- lastSuccessAt: new Date().toISOString(),
2571
- status: "ok",
2724
+ session.selected = new Set(desired.map(({ ID }) => ID));
2725
+ session.context.node = session.node;
2726
+ try {
2727
+ const peers = await nodeConnections(
2728
+ session.node,
2729
+ effectiveSignal,
2730
+ );
2731
+ session.connections = {
2732
+ observedAt: Date.now(),
2572
2733
  error: null,
2734
+ peers,
2573
2735
  };
2574
- } else {
2575
- session.sync = {
2576
- ...session.sync,
2577
- lastAttemptAt: attemptAt,
2578
- lastSuccessAt: new Date().toISOString(),
2579
- status: "ok",
2580
- error: null,
2736
+ } catch (cause) {
2737
+ effectiveSignal.throwIfAborted();
2738
+ session.connections = {
2739
+ observedAt: session.connections?.observedAt ?? null,
2740
+ error: message(cause).slice(0, 2048),
2741
+ peers: session.connections?.peers ?? [],
2581
2742
  };
2582
2743
  }
2744
+ // Persist connectivity before potentially slow content acquisition.
2745
+ await persist(url, session, true);
2746
+ if (session.pivot) {
2747
+ if (
2748
+ !session.pivotServer ||
2749
+ !session.pivotServer.server.listening ||
2750
+ session.pivotServer.nodeApi !== session.node.api ||
2751
+ session.pivotServer.epoch !== record.config!.epoch ||
2752
+ session.pivotServer.headId !== record.config!.headId
2753
+ ) {
2754
+ await stopPivotServer(session);
2755
+ const pivotNode = session.node;
2756
+ const mounted = await mountPivotServer(
2757
+ pivotNode,
2758
+ {
2759
+ status: (requestSignal) =>
2760
+ telemetry.runWithContext(
2761
+ {
2762
+ source: "pivot-rpc",
2763
+ operation: "GET /v1/status",
2764
+ swarm: url,
2765
+ },
2766
+ () =>
2767
+ pivotStatus(
2768
+ { ...session.context, node: pivotNode },
2769
+ url,
2770
+ requestSignal,
2771
+ ),
2772
+ ),
2773
+ replicate: (request, requestSignal) =>
2774
+ telemetry.runWithContext(
2775
+ {
2776
+ source: "pivot-rpc",
2777
+ operation: "POST /v1/replicate",
2778
+ swarm: url,
2779
+ },
2780
+ async () => {
2781
+ const requestContext = {
2782
+ ...session.context,
2783
+ node: pivotNode,
2784
+ };
2785
+ try {
2786
+ return await handlePivotReplicateRequest(
2787
+ requestContext,
2788
+ url,
2789
+ request,
2790
+ requestSignal,
2791
+ );
2792
+ } finally {
2793
+ session.context.pivotSyncError =
2794
+ requestContext.pivotSyncError ?? null;
2795
+ }
2796
+ },
2797
+ ),
2798
+ receipt: (receiptRequest, requestSignal) =>
2799
+ telemetry.runWithContext(
2800
+ {
2801
+ source: "pivot-rpc",
2802
+ operation: "POST /v1/receipt",
2803
+ swarm: url,
2804
+ },
2805
+ () =>
2806
+ handlePivotReceiptRequest(
2807
+ { ...session.context, node: pivotNode },
2808
+ url,
2809
+ receiptRequest,
2810
+ requestSignal,
2811
+ ),
2812
+ ),
2813
+ search: (params) =>
2814
+ withState(session.context, (state) =>
2815
+ queryLocalSearchIndex(state, url, params),
2816
+ ),
2817
+ ...(context.diagnostic
2818
+ ? { diagnostic: context.diagnostic }
2819
+ : {}),
2820
+ },
2821
+ session.context.fetch,
2822
+ effectiveSignal,
2823
+ );
2824
+ session.pivotServer = {
2825
+ server: mounted,
2826
+ nodeApi: session.node.api,
2827
+ epoch: record.config!.epoch,
2828
+ headId: record.config!.headId,
2829
+ listening: true,
2830
+ };
2831
+ } else {
2832
+ const remounted = await ensurePivotListener(
2833
+ session.node,
2834
+ session.pivotServer.server.address,
2835
+ effectiveSignal,
2836
+ session.context.fetch,
2837
+ );
2838
+ session.pivotServer.listening = true;
2839
+ if (remounted) {
2840
+ emitDiagnostic(
2841
+ `[${url}] Re-mounted Pivot P2P listener ${pivotReceiptProtocol} -> ${session.pivotServer.server.address}.`,
2842
+ );
2843
+ }
2844
+ }
2845
+ pivotListenerVerified = true;
2846
+ } else {
2847
+ await stopPivotServer(session);
2848
+ }
2849
+ const now = Date.now();
2850
+ const replicationIntervalMs =
2851
+ (context.syncInterval ?? 60) * 1000;
2852
+ const knownRemotePivots = session.candidates.observations();
2853
+ const online = new Set([
2854
+ ...[...knownRemotePivots]
2855
+ .filter(([, value]) => value.probe === "success")
2856
+ .map(([peerId]) => peerId),
2857
+ ...session.connections.peers.map((peer) => peer.peerId),
2858
+ ]);
2859
+ const remoteOnline = [...online].filter(
2860
+ (peerId) => peerId !== session.node!.peerId,
2861
+ );
2862
+ const onlineRemotePivots = remoteOnline.filter((peerId) =>
2863
+ knownRemotePivots.has(peerId),
2864
+ );
2865
+ const remoteReadinessDue = onlineRemotePivots.some(
2866
+ (peerId) => {
2867
+ const entry = session.context.pivotReadiness?.[peerId];
2868
+ return (
2869
+ !entry ||
2870
+ now - entry.observedAt >=
2871
+ pivotReadinessRefreshIntervalMs
2872
+ );
2873
+ },
2874
+ );
2875
+ const replicationDue = now >= (session.nextReplication ?? 0);
2876
+ if (
2877
+ (onlineRemotePivots.length > 0 &&
2878
+ (remoteReadinessDue || replicationDue)) ||
2879
+ (remoteOnline.length > 0 && replicationDue)
2880
+ ) {
2881
+ session.nextReplication = now + replicationIntervalMs;
2882
+ await replicateSwarm(
2883
+ session.context,
2884
+ url,
2885
+ effectiveSignal,
2886
+ {
2887
+ automatic: true,
2888
+ onlinePeers: online,
2889
+ },
2890
+ );
2891
+ }
2892
+ if (session.pivot) {
2893
+ const pivotSyncDue = now >= (session.nextPivotSync ?? 0);
2894
+ const selfReadiness =
2895
+ session.context.pivotReadiness?.[session.node.peerId];
2896
+ const selfReadinessDue =
2897
+ !selfReadiness ||
2898
+ now - selfReadiness.observedAt >=
2899
+ pivotReadinessRefreshIntervalMs;
2900
+ if (pivotSyncDue) {
2901
+ session.nextPivotSync = now + replicationIntervalMs;
2902
+ try {
2903
+ await syncPivotPublications(
2904
+ session.context,
2905
+ url,
2906
+ effectiveSignal,
2907
+ );
2908
+ } finally {
2909
+ if (!effectiveSignal.aborted) {
2910
+ const status = await pivotStatus(
2911
+ session.context,
2912
+ url,
2913
+ effectiveSignal,
2914
+ );
2915
+ session.context.pivotReadiness ??= {};
2916
+ session.context.pivotReadiness[session.node.peerId] =
2917
+ {
2918
+ observedAt: Date.now(),
2919
+ status,
2920
+ error: null,
2921
+ };
2922
+ }
2923
+ }
2924
+ } else if (selfReadinessDue) {
2925
+ const status = await pivotStatus(
2926
+ session.context,
2927
+ url,
2928
+ effectiveSignal,
2929
+ );
2930
+ session.context.pivotReadiness ??= {};
2931
+ session.context.pivotReadiness[session.node.peerId] = {
2932
+ observedAt: Date.now(),
2933
+ status,
2934
+ error: null,
2935
+ };
2936
+ }
2937
+ }
2583
2938
  } catch (cause) {
2584
- signal.throwIfAborted();
2585
- const detail = message(cause);
2939
+ if (effectiveSignal.aborted) return;
2940
+ if (!pivotListenerVerified && session.pivotServer)
2941
+ session.pivotServer.listening = false;
2942
+ session.error = message(cause);
2943
+ session.nextDiscovery = 0;
2586
2944
  emitDiagnostic(
2587
- `[${url}] Swarm sync failed; will retry next interval: ${detail}`,
2945
+ `[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`,
2588
2946
  );
2589
- session.sync = {
2590
- ...session.sync,
2591
- ...(reported ?? {}),
2592
- lastAttemptAt: attemptAt,
2593
- status: "error",
2594
- error: redact(detail, session),
2595
- };
2596
- } finally {
2597
- session.nextSync =
2598
- Date.now() + (context.syncInterval ?? 60) * 1000;
2599
- session.sync.nextSyncAt = new Date(
2600
- session.nextSync,
2601
- ).toISOString();
2947
+ if (
2948
+ cause instanceof HostError &&
2949
+ /membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(
2950
+ cause.message,
2951
+ )
2952
+ ) {
2953
+ await stopPivotServer(session);
2954
+ if (session.node) await stopNode(session.node);
2955
+ session.candidates.reconcile(new Map());
2956
+ delete session.node;
2957
+ session.selected.clear();
2958
+ await persist(url, session, false);
2959
+ delete session.record;
2960
+ }
2602
2961
  }
2603
- }
2604
- }
2605
- await persist(url, session, true);
2606
- });
2962
+ if (
2963
+ synchronize &&
2964
+ session.node &&
2965
+ !effectiveSignal.aborted &&
2966
+ Date.now() >= session.nextSync
2967
+ ) {
2968
+ let deferIsolatedPivot = false;
2969
+ if (
2970
+ session.pivot &&
2971
+ (session.connections?.peers.length ?? 0) === 0 &&
2972
+ session.candidates.active().size === 0 &&
2973
+ session.record?.config
2974
+ ) {
2975
+ try {
2976
+ const c = coordinates(url);
2977
+ const head = headValue(
2978
+ await client(session.context, c.service).read(
2979
+ c.scopeId,
2980
+ session.record.config.headId,
2981
+ { signal: effectiveSignal },
2982
+ ),
2983
+ );
2984
+ deferIsolatedPivot = !(await hasLocalBlock(
2985
+ session.context.store,
2986
+ head.root,
2987
+ ));
2988
+ } catch (cause) {
2989
+ if (shutdownController.signal.aborted) return;
2990
+ signal.throwIfAborted();
2991
+ emitDiagnostic(
2992
+ `[${url}] Isolated Pivot HEAD check failed: ${message(cause)}`,
2993
+ );
2994
+ }
2995
+ }
2996
+ if (deferIsolatedPivot) {
2997
+ session.nextSync = Date.now() + 5_000;
2998
+ session.sync.nextSyncAt = new Date(
2999
+ session.nextSync,
3000
+ ).toISOString();
3001
+ } else {
3002
+ const attemptAt = new Date().toISOString();
3003
+ session.sync.lastAttemptAt = attemptAt;
3004
+ let reported: DaemonSyncSummary | undefined;
3005
+ try {
3006
+ const summary = await raceAbort(
3007
+ synchronize(session.context, url, (partial) => {
3008
+ reported = partial;
3009
+ }),
3010
+ effectiveSignal,
3011
+ );
3012
+ const applied = summary ?? reported;
3013
+ if (applied) {
3014
+ session.sync = {
3015
+ ...session.sync,
3016
+ ...applied,
3017
+ lastAttemptAt: attemptAt,
3018
+ lastSuccessAt: new Date().toISOString(),
3019
+ status: "ok",
3020
+ error: null,
3021
+ };
3022
+ } else {
3023
+ session.sync = {
3024
+ ...session.sync,
3025
+ lastAttemptAt: attemptAt,
3026
+ lastSuccessAt: new Date().toISOString(),
3027
+ status: "ok",
3028
+ error: null,
3029
+ };
3030
+ }
3031
+ } catch (cause) {
3032
+ if (shutdownController.signal.aborted) return;
3033
+ signal.throwIfAborted();
3034
+ const detail = message(cause);
3035
+ emitDiagnostic(
3036
+ `[${url}] Swarm sync failed; will retry next interval: ${detail}`,
3037
+ );
3038
+ session.sync = {
3039
+ ...session.sync,
3040
+ ...(reported ?? {}),
3041
+ lastAttemptAt: attemptAt,
3042
+ status: "error",
3043
+ error: redact(detail, session),
3044
+ };
3045
+ } finally {
3046
+ session.nextSync =
3047
+ Date.now() + (context.syncInterval ?? 60) * 1000;
3048
+ session.sync.nextSyncAt = new Date(
3049
+ session.nextSync,
3050
+ ).toISOString();
3051
+ }
3052
+ }
3053
+ }
3054
+ if (!effectiveSignal.aborted) {
3055
+ await persist(url, session, true);
3056
+ }
3057
+ },
3058
+ ),
3059
+ );
3060
+ if (shutdownRequested()) break;
3061
+ signal.throwIfAborted();
3062
+ if (wakeState.wakeRequested) {
3063
+ wakeState.wakeRequested = false;
3064
+ continue;
3065
+ }
3066
+ const sleepController = new AbortController();
3067
+ const onWake = () => {
3068
+ sleepController.abort();
3069
+ };
3070
+ wakeSleep = onWake;
2607
3071
  try {
2608
3072
  const nextSync = synchronize
2609
3073
  ? Math.min(
@@ -2617,23 +3081,48 @@ export async function swarmDaemon(
2617
3081
  await delay(
2618
3082
  Math.min(30_000 + Math.random() * 15_000, nextSync),
2619
3083
  undefined,
2620
- { signal },
3084
+ {
3085
+ signal: AbortSignal.any([
3086
+ effectiveSignal,
3087
+ sleepController.signal,
3088
+ ]),
3089
+ },
2621
3090
  );
2622
3091
  } catch {
3092
+ if (shutdownRequested()) break;
2623
3093
  signal.throwIfAborted();
3094
+ } finally {
3095
+ if (wakeSleep === onWake) wakeSleep = undefined;
3096
+ wakeState.wakeRequested = false;
2624
3097
  }
2625
3098
  }
2626
3099
  } finally {
2627
3100
  try {
2628
- for (const [url, session] of sessions) {
3101
+ await closeReadiness?.();
3102
+ } finally {
3103
+ try {
3104
+ for (const [url, session] of sessions) {
3105
+ try {
3106
+ await persist(url, session, false);
3107
+ } finally {
3108
+ await closeSession(session);
3109
+ }
3110
+ }
3111
+ } finally {
2629
3112
  try {
2630
- await persist(url, session, false);
3113
+ await daemonService.close();
2631
3114
  } finally {
2632
- await closeSession(session);
3115
+ try {
3116
+ await telemetry.flush();
3117
+ } finally {
3118
+ try {
3119
+ await daemonStore.close();
3120
+ } finally {
3121
+ if (ownsDaemonState) daemonState.close();
3122
+ }
3123
+ }
2633
3124
  }
2634
3125
  }
2635
- } finally {
2636
- await closeReadiness?.();
2637
3126
  }
2638
3127
  }
2639
3128
  },
@@ -2641,6 +3130,8 @@ export async function swarmDaemon(
2641
3130
  1,
2642
3131
  );
2643
3132
  }
3133
+ const derivedLocalStores = new WeakSet<IpfsStore>();
3134
+
2644
3135
  async function activate(context: SwarmContext, record: LocalMembership) {
2645
3136
  const { node, peers, source } = await privateSource(context, record);
2646
3137
  if (
@@ -2648,9 +3139,13 @@ async function activate(context: SwarmContext, record: LocalMembership) {
2648
3139
  context.sourcePeers?.length !== peers.length ||
2649
3140
  peers.some((peer, i) => context.sourcePeers?.[i] !== peer)
2650
3141
  ) {
2651
- const store = context.store.withLocalSource(source);
2652
- await context.store.close();
3142
+ const previous = context.store;
3143
+ const store = previous.withLocalSource(source);
3144
+ derivedLocalStores.add(store);
2653
3145
  context.store = store;
3146
+ if (derivedLocalStores.has(previous)) {
3147
+ await previous.close();
3148
+ }
2654
3149
  context.sourcePeers = peers;
2655
3150
  }
2656
3151
  context.node = node;
@@ -2801,11 +3296,6 @@ async function readyMembership(
2801
3296
  }
2802
3297
  return record;
2803
3298
  }
2804
- interface BoundHead {
2805
- read(): Promise<Variable & { root: string; etag: string }>;
2806
- write(root: string, cid: string, key: string): Promise<Variable>;
2807
- writeWithReceipt(receipt: ScopeWriteReceipt): Promise<Variable>;
2808
- }
2809
3299
  function headValue(head: Variable): Variable & { root: string; etag: string } {
2810
3300
  const value = object(head.value, "HEAD");
2811
3301
  if (Object.keys(value).join() !== "root" || typeof value.root !== "string")
@@ -2891,22 +3381,21 @@ async function boundPointer(
2891
3381
  ),
2892
3382
  };
2893
3383
  }
2894
- async function writeNamesHead(
3384
+ export async function writeNamesHead(
2895
3385
  context: SwarmContext,
2896
3386
  url: string,
2897
3387
  head: BoundHead,
2898
3388
  root: string,
2899
3389
  cid: string,
2900
- ): Promise<void> {
3390
+ ): Promise<Variable> {
2901
3391
  if (isLocalSwarm(url)) {
2902
- await head.write(root, cid, uniqueId());
2903
- return;
3392
+ return head.write(root, cid, uniqueId());
2904
3393
  }
2905
3394
  const lock = await privateDirectory(
2906
3395
  await directory(context),
2907
3396
  `state-pin-${createHash("sha256").update(url).digest("hex")}`,
2908
3397
  );
2909
- await withPrivateLock(lock, async () => {
3398
+ return withSwarmLock(context, lock, async () => {
2910
3399
  if (context.confirmPublication) {
2911
3400
  try {
2912
3401
  await context.confirmPublication(url, root);
@@ -2918,8 +3407,7 @@ async function writeNamesHead(
2918
3407
  "publication",
2919
3408
  );
2920
3409
  }
2921
- await head.write(root, cid, uniqueId());
2922
- return;
3410
+ return head.write(root, cid, uniqueId());
2923
3411
  }
2924
3412
  const idempotencyKey = uniqueId();
2925
3413
  let receipt: ScopeWriteReceipt | null;
@@ -2940,10 +3428,9 @@ async function writeNamesHead(
2940
3428
  );
2941
3429
  }
2942
3430
  if (receipt === null) {
2943
- await head.write(root, cid, idempotencyKey);
2944
- return;
3431
+ return head.write(root, cid, idempotencyKey);
2945
3432
  }
2946
- await head.writeWithReceipt(receipt);
3433
+ return head.writeWithReceipt(receipt);
2947
3434
  });
2948
3435
  }
2949
3436
 
@@ -3273,73 +3760,451 @@ export async function syncPivotPublications(
3273
3760
  kuboSource(node, peers, context.diagnostic),
3274
3761
  );
3275
3762
  try {
3763
+ if (CID.parse(head.root).code === dagPb.code)
3764
+ await pinPublication(source, [head.root], node, signal, context.fetch);
3276
3765
  await readSnapshot(source, head.root, url);
3277
3766
  const roots =
3278
3767
  CID.parse(head.root).code === dagPb.code
3279
3768
  ? [head.root]
3280
3769
  : await frozenPublicationClosure(source, head.root);
3281
3770
  await pinPublication(source, roots, node, signal, context.fetch);
3771
+ await finishPivotReplication(context, url, record, head, source, signal);
3772
+ context.pivotSyncError = null;
3773
+ } catch (cause) {
3774
+ context.pivotSyncError = message(cause).slice(0, 2048);
3775
+ throw cause;
3282
3776
  } finally {
3283
3777
  await source.close();
3284
3778
  }
3285
3779
  }
3286
3780
 
3287
- export async function typedJson(
3288
- store: IpfsStore,
3289
- cid: string,
3290
- type: BundleType,
3291
- ): Promise<unknown> {
3292
- const { bundle, value } = await bundleJson(store, cid);
3293
- if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
3294
- throw new HostError("Expected exact Bundle type CID.");
3295
- return value;
3781
+ async function localHeadClosure(
3782
+ context: SwarmContext,
3783
+ headCid: string,
3784
+ signal: AbortSignal,
3785
+ url?: string,
3786
+ ): Promise<boolean> {
3787
+ const local = context.store.supportsRetention
3788
+ ? new IpfsStore({
3789
+ dataDir: context.store.configuration.dataDir,
3790
+ limits: context.store.limits,
3791
+ })
3792
+ : context.store;
3793
+ try {
3794
+ await local.prepare(headCid, { signal });
3795
+ if (url) await readSnapshot(local, headCid, url);
3796
+ if (CID.parse(headCid).code !== dagPb.code) {
3797
+ for (const root of await frozenPublicationClosure(local, headCid))
3798
+ await local.prepare(root, { signal });
3799
+ }
3800
+ return true;
3801
+ } catch (cause) {
3802
+ signal.throwIfAborted();
3803
+ if (missingContent(cause)) return false;
3804
+ throw cause;
3805
+ } finally {
3806
+ if (local !== context.store) await local.close();
3807
+ }
3296
3808
  }
3297
- function parseArtifact(value: unknown): Artifact {
3298
- const data = object(value, "Artifact");
3299
- if (
3300
- Object.keys(data).some(
3301
- (key) => !["value", "previous", "timestamp"].includes(key),
3302
- ) ||
3303
- typeof data.value !== "string" ||
3304
- typeof data.timestamp !== "string" ||
3305
- !Number.isFinite(Date.parse(data.timestamp)) ||
3306
- (data.previous !== undefined && typeof data.previous !== "string")
3307
- )
3308
- throw new HostError("Invalid Artifact.");
3309
- CID.parse(data.value);
3310
- if (data.previous !== undefined) CID.parse(data.previous);
3809
+
3810
+ export async function pivotStatus(
3811
+ context: SwarmContext,
3812
+ url: string,
3813
+ signal: AbortSignal,
3814
+ ): Promise<PivotStatus> {
3815
+ rejectLocalSwarm(url, "Pivot status");
3816
+ const record = await approvedMembership(context, url, signal);
3817
+ const c = coordinates(url);
3818
+ const head = headValue(
3819
+ await client(context, c.service).read(c.scopeId, record.config!.headId, {
3820
+ signal,
3821
+ }),
3822
+ );
3823
+ const indexedHeadCid = withState(
3824
+ context,
3825
+ (state) => state.searchIndexState(url)?.headCid ?? null,
3826
+ );
3827
+ const local = await localHeadClosure(context, head.root, signal, url);
3828
+ const pinned =
3829
+ local &&
3830
+ Boolean(context.node) &&
3831
+ (await isRecursivelyPinned(
3832
+ context.node!,
3833
+ head.root,
3834
+ signal,
3835
+ context.fetch,
3836
+ ));
3837
+ const indexed =
3838
+ CID.parse(head.root).code !== dagPb.code || indexedHeadCid === head.root;
3311
3839
  return {
3312
- value: data.value,
3313
- timestamp: data.timestamp,
3314
- ...(data.previous !== undefined ? { previous: data.previous } : {}),
3840
+ v: 1,
3841
+ ready: pinned && indexed && !context.pivotSyncError,
3842
+ headCid: pinned ? head.root : null,
3843
+ indexedHeadCid,
3844
+ syncError:
3845
+ context.pivotSyncError ??
3846
+ (!pinned
3847
+ ? "Current HEAD is not fully replicated and recursively pinned."
3848
+ : !indexed
3849
+ ? "Current HEAD is not indexed."
3850
+ : null),
3315
3851
  };
3316
3852
  }
3317
- export async function jsonBundle(
3318
- store: IpfsStore,
3319
- type: BundleType,
3320
- value: unknown,
3321
- ): Promise<string> {
3322
- const encoded = await encodeBundleCar(
3323
- memoryTree(
3324
- new Map([
3325
- [
3326
- ".bundle.yaml",
3327
- new TextEncoder().encode(
3328
- stringify({
3329
- title: "IPAB Data",
3330
- entry: "entry.json",
3331
- type: ".bundle-type.yaml",
3332
- }),
3333
- ),
3334
- ],
3335
- [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
3336
- ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
3337
- ]),
3338
- ),
3853
+
3854
+ async function finishPivotReplication(
3855
+ context: SwarmContext,
3856
+ url: string,
3857
+ record: LocalMembership,
3858
+ head: ReturnType<typeof headValue>,
3859
+ source: IpfsStore,
3860
+ signal: AbortSignal,
3861
+ ): Promise<void> {
3862
+ const snapshot = await readSnapshot(source, head.root, url);
3863
+ const roots =
3864
+ CID.parse(head.root).code === dagPb.code
3865
+ ? [head.root]
3866
+ : await frozenPublicationClosure(source, head.root);
3867
+ const owner = `daemon-pivot-root:${createHash("sha256").update(url).digest("hex")}`;
3868
+ await retainDaemonRoots(source, owner, roots, signal);
3869
+ const fresh = await approvedMembership(context, url, signal);
3870
+ const c = coordinates(url);
3871
+ const current = headValue(
3872
+ await client(context, c.service).read(c.scopeId, fresh.config!.headId, {
3873
+ signal,
3874
+ }),
3339
3875
  );
3340
- try {
3341
- const iterator = await CarBlockIterator.fromIterable(
3342
- streamChunks(encoded.stream),
3876
+ if (
3877
+ fresh.config!.epoch !== record.config!.epoch ||
3878
+ fresh.config!.headId !== record.config!.headId ||
3879
+ current.root !== head.root
3880
+ )
3881
+ throw new HostError(
3882
+ "HEAD or membership changed during replication; retry the current HEAD.",
3883
+ );
3884
+ if (CID.parse(head.root).code === dagPb.code) {
3885
+ await syncPivotReplicationAndIndex(
3886
+ { ...context, pivot: true, store: source },
3887
+ url,
3888
+ {
3889
+ head,
3890
+ snapshot,
3891
+ config: fresh.config!,
3892
+ source: "network",
3893
+ verifiedAt: new Date().toISOString(),
3894
+ stateCid: head.root,
3895
+ },
3896
+ signal,
3897
+ );
3898
+ }
3899
+ }
3900
+
3901
+ export async function handlePivotReplicateRequest(
3902
+ context: SwarmContext,
3903
+ url: string,
3904
+ input: unknown,
3905
+ signal: AbortSignal,
3906
+ ): Promise<{ ready: true; headCid: string }> {
3907
+ rejectLocalSwarm(url, "Pivot replicate");
3908
+ const request = parsePivotReplicateRequest(input);
3909
+ const record = await approvedMembership(context, url, signal);
3910
+ const c = coordinates(url);
3911
+ const config = record.config!;
3912
+ if (
3913
+ request.service !== c.service ||
3914
+ request.scopeId !== c.scopeId ||
3915
+ request.headId !== config.headId ||
3916
+ request.epoch !== config.epoch
3917
+ )
3918
+ throw new HostError(
3919
+ "Replicate request does not match the current Swarm configuration.",
3920
+ );
3921
+ if (!config.members.some((member) => member.publicKey === request.member))
3922
+ throw new HostError(
3923
+ "Replicate requester is not an approved Swarm member.",
3924
+ 1,
3925
+ "PIVOT_UNAUTHORIZED",
3926
+ );
3927
+ await verifyPivotReplicateRequest(request);
3928
+ const head = headValue(
3929
+ await client(context, c.service).read(c.scopeId, config.headId, { signal }),
3930
+ );
3931
+ if (head.root !== request.headCid)
3932
+ throw new HostError(
3933
+ "Replicate headCid must equal the current verified HEAD.",
3934
+ );
3935
+ if (!context.node)
3936
+ throw new HostError("Replication requires an active Pivot node.");
3937
+ const status = await pivotStatus(context, url, signal);
3938
+ if (status.ready && status.headCid === head.root)
3939
+ return { ready: true, headCid: head.root };
3940
+ const source = context.store.withLocalSource(
3941
+ kuboSource(context.node, [], context.diagnostic),
3942
+ );
3943
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(120_000)]);
3944
+ try {
3945
+ await pinPublication(
3946
+ source,
3947
+ [head.root],
3948
+ context.node,
3949
+ bounded,
3950
+ context.fetch,
3951
+ );
3952
+ await finishPivotReplication(context, url, record, head, source, bounded);
3953
+ const fresh = await approvedMembership(context, url, bounded);
3954
+ const current = headValue(
3955
+ await client(context, c.service).read(c.scopeId, fresh.config!.headId, {
3956
+ signal: bounded,
3957
+ }),
3958
+ );
3959
+ if (
3960
+ !fresh.config!.members.some(
3961
+ (member) => member.publicKey === request.member,
3962
+ ) ||
3963
+ fresh.config!.epoch !== config.epoch ||
3964
+ fresh.config!.headId !== config.headId ||
3965
+ current.root !== head.root
3966
+ )
3967
+ throw new HostError(
3968
+ "HEAD or requester membership changed during replication; retry.",
3969
+ );
3970
+ context.pivotSyncError = null;
3971
+ return { ready: true, headCid: head.root };
3972
+ } catch (cause) {
3973
+ context.pivotSyncError = message(cause).slice(0, 2048);
3974
+ throw cause;
3975
+ } finally {
3976
+ await source.close();
3977
+ }
3978
+ }
3979
+
3980
+ export async function replicateSwarm(
3981
+ context: SwarmContext,
3982
+ url: string,
3983
+ signal: AbortSignal = AbortSignal.timeout(180_000),
3984
+ options: {
3985
+ automatic?: boolean;
3986
+ onlinePeers?: ReadonlySet<string>;
3987
+ pivot?: string;
3988
+ } = {},
3989
+ ) {
3990
+ const { automatic = false, onlinePeers } = options;
3991
+ rejectLocalSwarm(url, "swarm replicate");
3992
+ const record = await approvedMembership(context, url, signal);
3993
+ const c = coordinates(url);
3994
+ const config = record.config!;
3995
+ const head = headValue(
3996
+ await client(context, c.service).read(c.scopeId, config.headId, { signal }),
3997
+ );
3998
+ const members = await memberDirectory(context, url, config);
3999
+ let targets = members.filter(
4000
+ ({ member, profile }) =>
4001
+ member.publicKey !== record.account &&
4002
+ memberIsPivot(config, member, profile) &&
4003
+ (!automatic || !onlinePeers || onlinePeers.has(member.peerId)),
4004
+ );
4005
+ if (options.pivot !== undefined) {
4006
+ const selector = options.pivot;
4007
+ targets = targets.filter(
4008
+ ({ member, profile }) =>
4009
+ member.publicKey === selector ||
4010
+ member.peerId === selector ||
4011
+ profile.name === selector,
4012
+ );
4013
+ if (targets.length !== 1)
4014
+ throw new HostError(
4015
+ `Pivot "${selector}" is ${targets.length ? "ambiguous; use its public key or PeerID" : "not a declared remote Pivot; run swarm members"}.`,
4016
+ );
4017
+ }
4018
+ const results: Array<{
4019
+ peerId: string;
4020
+ status: "ready" | "replicated" | "unreachable" | "failed";
4021
+ error?: string;
4022
+ }> = [];
4023
+ if (!targets.length) {
4024
+ if (!automatic)
4025
+ throw new HostError(
4026
+ "No remote Pivot is declared. Approve a Pivot and run its daemon first.",
4027
+ );
4028
+ return { headCid: head.root, results };
4029
+ }
4030
+ const complete = await localHeadClosure(context, head.root, signal, url);
4031
+ if (!automatic && !complete)
4032
+ throw new HostError(
4033
+ "This member does not hold the complete current HEAD locally; replication was not started.",
4034
+ );
4035
+ if (!context.node) {
4036
+ if (automatic)
4037
+ throw new HostError("Automatic replication requires an active node.");
4038
+ await activate(context, record);
4039
+ }
4040
+ let provided = false;
4041
+ for (const { member, profile } of targets) {
4042
+ const options = {
4043
+ node: context.node!,
4044
+ pivotPeerId: member.peerId,
4045
+ pivotAddresses: automatic ? [] : profile.addresses,
4046
+ signal,
4047
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
4048
+ };
4049
+ let reachable = false;
4050
+ try {
4051
+ if (!automatic)
4052
+ context.diagnostic?.(
4053
+ `Checking Pivot ${profile.name || member.peerId} readiness...`,
4054
+ );
4055
+ const status = await pivotReadinessOverP2p(options);
4056
+ context.pivotReadiness ??= {};
4057
+ context.pivotReadiness[member.peerId] = {
4058
+ observedAt: Date.now(),
4059
+ status: "v" in status ? status : null,
4060
+ error: null,
4061
+ };
4062
+ reachable = true;
4063
+ if (status.ready && status.headCid === head.root) {
4064
+ results.push({ peerId: member.peerId, status: "ready" });
4065
+ if (automatic) continue;
4066
+ break;
4067
+ }
4068
+ if (!complete) continue;
4069
+ if (!provided) {
4070
+ await provideContent(
4071
+ context.store,
4072
+ [head.root],
4073
+ context.node!.api,
4074
+ context.fetch,
4075
+ context.node!.auth,
4076
+ [head.root],
4077
+ signal,
4078
+ );
4079
+ provided = true;
4080
+ }
4081
+ const identity = await contextIdentity(context);
4082
+ const request = await signPivotReplicateRequest(
4083
+ {
4084
+ service: c.service,
4085
+ scopeId: c.scopeId,
4086
+ headId: config.headId,
4087
+ epoch: config.epoch,
4088
+ headCid: head.root,
4089
+ member: identity.publicKey,
4090
+ },
4091
+ identity.privateKey,
4092
+ );
4093
+ context.diagnostic?.(
4094
+ `Replicating ${head.root} to Pivot ${profile.name || member.peerId}...`,
4095
+ );
4096
+ await pivotReadinessOverP2p(options, request);
4097
+ context.pivotReadiness[member.peerId] = {
4098
+ observedAt: Date.now(),
4099
+ status: {
4100
+ v: 1,
4101
+ ready: true,
4102
+ headCid: head.root,
4103
+ indexedHeadCid:
4104
+ CID.parse(head.root).code === dagPb.code ? head.root : null,
4105
+ syncError: null,
4106
+ },
4107
+ error: null,
4108
+ };
4109
+ results.push({ peerId: member.peerId, status: "replicated" });
4110
+ break;
4111
+ } catch (cause) {
4112
+ signal.throwIfAborted();
4113
+ const error = message(cause);
4114
+ const reportError = !automatic || reachable;
4115
+ context.pivotReadiness ??= {};
4116
+ context.pivotReadiness[member.peerId] = {
4117
+ observedAt: Date.now(),
4118
+ status: reachable
4119
+ ? {
4120
+ v: 1,
4121
+ ready: false,
4122
+ headCid: null,
4123
+ indexedHeadCid: null,
4124
+ syncError: error.slice(0, 2048),
4125
+ }
4126
+ : null,
4127
+ error: reportError ? error.slice(0, 2048) : null,
4128
+ };
4129
+ if (reportError)
4130
+ context.diagnostic?.(
4131
+ `Pivot ${member.peerId} replication check failed: ${error}`,
4132
+ );
4133
+ results.push({
4134
+ peerId: member.peerId,
4135
+ status: reachable ? "failed" : "unreachable",
4136
+ error,
4137
+ });
4138
+ }
4139
+ }
4140
+ if (
4141
+ !automatic &&
4142
+ !results.some(
4143
+ (result) => result.status === "ready" || result.status === "replicated",
4144
+ )
4145
+ )
4146
+ throw new HostError(
4147
+ `No Pivot confirmed current HEAD readiness: ${results.map((result) => result.error).join("; ")}`,
4148
+ );
4149
+ return { headCid: head.root, results };
4150
+ }
4151
+
4152
+ export async function typedJson(
4153
+ store: IpfsStore,
4154
+ cid: string,
4155
+ type: BundleType,
4156
+ ): Promise<unknown> {
4157
+ const { bundle, value } = await bundleJson(store, cid);
4158
+ if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
4159
+ throw new HostError("Expected exact Bundle type CID.");
4160
+ return value;
4161
+ }
4162
+ function parseArtifact(value: unknown): Artifact {
4163
+ const data = object(value, "Artifact");
4164
+ if (
4165
+ Object.keys(data).some(
4166
+ (key) => !["value", "previous", "timestamp"].includes(key),
4167
+ ) ||
4168
+ typeof data.value !== "string" ||
4169
+ typeof data.timestamp !== "string" ||
4170
+ !Number.isFinite(Date.parse(data.timestamp)) ||
4171
+ (data.previous !== undefined && typeof data.previous !== "string")
4172
+ )
4173
+ throw new HostError("Invalid Artifact.");
4174
+ CID.parse(data.value);
4175
+ if (data.previous !== undefined) CID.parse(data.previous);
4176
+ return {
4177
+ value: data.value,
4178
+ timestamp: data.timestamp,
4179
+ ...(data.previous !== undefined ? { previous: data.previous } : {}),
4180
+ };
4181
+ }
4182
+ export async function jsonBundle(
4183
+ store: IpfsStore,
4184
+ type: BundleType,
4185
+ value: unknown,
4186
+ ): Promise<string> {
4187
+ const encoded = await encodeBundleCar(
4188
+ memoryTree(
4189
+ new Map([
4190
+ [
4191
+ ".bundle.yaml",
4192
+ new TextEncoder().encode(
4193
+ stringify({
4194
+ title: "IPAB Data",
4195
+ entry: "entry.json",
4196
+ type: ".bundle-type.yaml",
4197
+ }),
4198
+ ),
4199
+ ],
4200
+ [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
4201
+ ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
4202
+ ]),
4203
+ ),
4204
+ );
4205
+ try {
4206
+ const iterator = await CarBlockIterator.fromIterable(
4207
+ streamChunks(encoded.stream),
3343
4208
  );
3344
4209
  for await (const block of iterator) await store.put(block.cid, block.bytes);
3345
4210
  return encoded.cid.toString();
@@ -3392,57 +4257,6 @@ async function writeV7RootBundle(
3392
4257
  });
3393
4258
  return jsonBundle(store, swarmRootType, value);
3394
4259
  }
3395
- function isV7Snapshot(snapshot: Snapshot): boolean {
3396
- return snapshot.stateBundle?.unixfsRoot?.version === 7;
3397
- }
3398
- function v7RootSkipFiles(snapshot: Snapshot): Set<string> {
3399
- const root = snapshot.stateBundle?.unixfsRoot;
3400
- if (!root) return new Set();
3401
- return new Set([".bundle.yaml", root.typeFile, root.entryFile]);
3402
- }
3403
- async function resolveSnapshotName(
3404
- store: IpfsStore,
3405
- snapshot: Snapshot,
3406
- name: string,
3407
- ): Promise<CID | undefined> {
3408
- if (isV7Snapshot(snapshot))
3409
- return resolveUnixfsPath(store, CID.parse(snapshot.stateBundle!.cid), name);
3410
- return Object.hasOwn(snapshot.names, name) ? snapshot.names[name] : undefined;
3411
- }
3412
- async function listSubtreeNames(
3413
- store: IpfsStore,
3414
- snapshot: Snapshot,
3415
- prefix: string,
3416
- flatOnly = false,
3417
- ): Promise<Array<{ name: string; cid: CID }>> {
3418
- if (isV7Snapshot(snapshot)) {
3419
- const dirCid = await resolveUnixfsPath(
3420
- store,
3421
- CID.parse(snapshot.stateBundle!.cid),
3422
- prefix,
3423
- );
3424
- if (!dirCid) return [];
3425
- if (flatOnly) {
3426
- const entries = await listUnixfsDirectory(store, dirCid);
3427
- return [...entries.entries()]
3428
- .map(([child, cid]) => ({ name: `${prefix}/${child}`, cid }))
3429
- .sort((a, b) => a.name.localeCompare(b.name));
3430
- }
3431
- const walked = await walkUnixfsNames(store, dirCid, {
3432
- prefix,
3433
- stopAtBundle: true,
3434
- });
3435
- return walked.entries.map((entry) => ({
3436
- name: entry.name,
3437
- cid: CID.parse(entry.targetCid),
3438
- }));
3439
- }
3440
- const needle = `${prefix}/`;
3441
- return Object.entries(snapshot.names)
3442
- .filter(([name]) => name.startsWith(needle))
3443
- .map(([name, cid]) => ({ name, cid }))
3444
- .sort((a, b) => a.name.localeCompare(b.name));
3445
- }
3446
4260
  async function readV7Root(store: IpfsStore, cid: CID): Promise<Snapshot> {
3447
4261
  const canonical = cid.toV1();
3448
4262
  const rootKey = canonical.toString();
@@ -3747,7 +4561,7 @@ export interface SwarmHeader {
3747
4561
  projection?: SwarmProjection;
3748
4562
  localSourceReady?: boolean;
3749
4563
  }
3750
- function missingContent(cause: unknown): boolean {
4564
+ export function missingContent(cause: unknown): boolean {
3751
4565
  let failure: unknown = cause;
3752
4566
  for (
3753
4567
  let depth = 0;
@@ -4118,7 +4932,7 @@ function headerProjection(header: SwarmHeader): SwarmProjection {
4118
4932
  throw new HostError("A verified account projection is required.");
4119
4933
  return header.projection;
4120
4934
  }
4121
- async function localHeader(context: SwarmContext, url: string) {
4935
+ export async function localHeader(context: SwarmContext, url: string) {
4122
4936
  if (isLocalSwarm(url))
4123
4937
  return { header: await readLocalSwarmHeader(context), account: "local" };
4124
4938
  if (context.forceRefresh) return;
@@ -4170,7 +4984,7 @@ async function localHeader(context: SwarmContext, url: string) {
4170
4984
 
4171
4985
  // SharedContent invokes this source only after a genuine local ENOENT. Its
4172
4986
  // store is not replaced from inside its own pending read (which would deadlock).
4173
- async function lazyPrivateSource(
4987
+ export async function lazyPrivateSource(
4174
4988
  context: SwarmContext,
4175
4989
  url: string,
4176
4990
  account: string,
@@ -4204,9 +5018,10 @@ async function lazyPrivateSource(
4204
5018
  return source;
4205
5019
  };
4206
5020
  // Same lock order as Owner rotation: credentials first, then the node.
4207
- return withPrivateLock(await directory(scoped), authorize, signal);
5021
+ return withSwarmLock(context, await directory(scoped), authorize, signal);
4208
5022
  };
4209
- const store = context.store.withLocalSource({
5023
+ const previous = context.store;
5024
+ const store = previous.withLocalSource({
4210
5025
  block: {
4211
5026
  async get(cid, options = {}) {
4212
5027
  const signal = options.signal
@@ -4219,8 +5034,11 @@ async function lazyPrivateSource(
4219
5034
  },
4220
5035
  },
4221
5036
  });
4222
- await context.store.close();
5037
+ derivedLocalStores.add(store);
4223
5038
  context.store = store;
5039
+ if (derivedLocalStores.has(previous)) {
5040
+ await previous.close();
5041
+ }
4224
5042
  delete context.node;
4225
5043
  delete context.sourcePeers;
4226
5044
  context.finishRead = async () => {
@@ -4353,7 +5171,7 @@ export async function createSwarm(
4353
5171
  const skill = await seedSkillSource();
4354
5172
  for (const [cid, data] of skill.blocks)
4355
5173
  await context.store.put(CID.parse(cid), data);
4356
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
5174
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
4357
5175
  let root: string;
4358
5176
  if (record.stateVersion === 7) {
4359
5177
  let currentRoot = CID.parse(
@@ -5611,82 +6429,6 @@ export async function resumeRemoval(
5611
6429
  }
5612
6430
  });
5613
6431
  }
5614
- export function formalName(name: string): string {
5615
- relativePath(name);
5616
- if (name.length > 256 || name.startsWith("builtin:"))
5617
- throw new HostError("Invalid formal Name.");
5618
- return name;
5619
- }
5620
- function decodeNameComponent(
5621
- value: string,
5622
- part: "authority" | "path",
5623
- ): string {
5624
- try {
5625
- return decodeURIComponent(value);
5626
- } catch {
5627
- throw new HostError(
5628
- `Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`,
5629
- );
5630
- }
5631
- }
5632
- export function parseNameReference(
5633
- reference: string,
5634
- ): { swarm?: string; name: string } | undefined {
5635
- if (/^name:/i.test(reference))
5636
- throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
5637
- if (!/^ipab:/i.test(reference)) return undefined;
5638
- if (/^ipab:\/\/https?:\/\//i.test(reference))
5639
- throw new HostError(
5640
- "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.",
5641
- );
5642
- const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
5643
- if (!match)
5644
- throw new HostError(
5645
- "Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.",
5646
- );
5647
- const authority = decodeNameComponent(match[1]!, "authority");
5648
- if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
5649
- if (!/^https?:\/\//i.test(authority))
5650
- throw new HostError(
5651
- "Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.",
5652
- );
5653
- canonicalSwarmUrl(authority);
5654
- }
5655
- if (/[?#\s]/.test(match[2]!))
5656
- throw new HostError(
5657
- "Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.",
5658
- );
5659
- const segments = match[2]!.split("/").map((segment) => {
5660
- const decoded = decodeNameComponent(segment, "path");
5661
- if (/[/\\]/.test(decoded))
5662
- throw new HostError(
5663
- "Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.",
5664
- );
5665
- return decoded;
5666
- });
5667
- try {
5668
- return {
5669
- ...(authority ? { swarm: authority } : {}),
5670
- name: match[2] === "" ? "" : formalName(segments.join("/")),
5671
- };
5672
- } catch (error) {
5673
- if (!(error instanceof HostError)) throw error;
5674
- throw new HostError(
5675
- "Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.",
5676
- error.exitCode,
5677
- error.code,
5678
- error.phase,
5679
- );
5680
- }
5681
- }
5682
- export function formatNameReference(swarm: string, name: string): string {
5683
- const segment = (value: string) =>
5684
- encodeURIComponent(value).replace(
5685
- /[!'()*]/g,
5686
- (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
5687
- );
5688
- return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
5689
- }
5690
6432
  export async function resolveReference(
5691
6433
  context: SwarmContext,
5692
6434
  reference: string,
@@ -5771,7 +6513,7 @@ export async function resolveReference(
5771
6513
  );
5772
6514
  }
5773
6515
  }
5774
- async function artifactValue(
6516
+ export async function artifactValue(
5775
6517
  store: IpfsStore,
5776
6518
  targetCid: string,
5777
6519
  protect?: (cid: string) => Promise<void>,
@@ -6317,62 +7059,174 @@ function hasMeta(snapshot: Snapshot): boolean {
6317
7059
  snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab")
6318
7060
  );
6319
7061
  }
7062
+ export const swarmFsTransport: SwarmFsTransport = {
7063
+ pointer,
7064
+ writeNamesHead,
7065
+ readSnapshot,
7066
+ swarmHeader,
7067
+ localHeader,
7068
+ lazyPrivateSource,
7069
+ invalidateSwarmHeader,
7070
+ prepareNamesPublication,
7071
+ missingContent,
7072
+ };
7073
+ const swarmFs = createSwarmFs(swarmFsTransport);
7074
+
6320
7075
  export interface SharedSkill {
6321
7076
  name: string;
6322
7077
  cid: string;
6323
7078
  identity: string;
7079
+ description: string;
6324
7080
  }
6325
- export async function swarmSkills(
6326
- context: SwarmContext,
6327
- configUrl: string,
6328
- requested: readonly string[],
6329
- owner: string,
6330
- ): Promise<SharedSkill[]> {
6331
- const warm = await localHeader(context, configUrl);
6332
- if (warm && !warm.header.localSourceReady)
6333
- await lazyPrivateSource(
6334
- context,
6335
- configUrl,
6336
- warm.account,
6337
- warm.header.config,
6338
- );
6339
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
6340
- const roots = new Set<string>();
6341
- const protect = async (cid: string) => {
6342
- roots.add(cid);
6343
- const values = [...roots];
6344
- await context.store.retain(owner, values);
6345
- await context.store.confirmRetained(owner, values);
6346
- };
6347
- for (let attempt = 0; ; attempt++) {
6348
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
6349
- header = await swarmHeader(context, configUrl, true);
6350
- continue;
6351
- }
6352
- if (hasMeta(header.snapshot)) {
6353
- if (isV7Snapshot(header.snapshot)) {
6354
- if (context.store.supportsRetention) {
6355
- const rootId = metaCid(header.snapshot);
6356
- await context.store.retainDirect(owner, [rootId]);
6357
- await context.store.confirmDirectRetained(owner, [rootId]);
6358
- }
6359
- } else {
6360
- await protect(metaCid(header.snapshot));
6361
- }
6362
- }
6363
- const meta = await swarmMeta(context, header);
6364
- if (!meta.skillPath)
6365
- throw new HostError(
6366
- header.snapshot.stateBundle
6367
- ? "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."
6368
- : `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.`,
6369
- );
6370
- const prefix = `${meta.skillPath}/`;
6371
- const entries = await listSubtreeNames(
7081
+
7082
+ export interface TypeSkillAssociation {
7083
+ name: string;
7084
+ schemaCid: string;
7085
+ cid: string;
7086
+ identity: string;
7087
+ description: string;
7088
+ }
7089
+
7090
+ export interface SwarmSkillsCatalog {
7091
+ skillPath: string;
7092
+ global: SharedSkill[];
7093
+ types: TypeSkillAssociation[];
7094
+ }
7095
+
7096
+ export interface SetSwarmSkillInput {
7097
+ skillCid: string;
7098
+ global: boolean;
7099
+ types: readonly string[];
7100
+ replace: boolean;
7101
+ }
7102
+
7103
+ export interface SetSwarmSkillTargetResult {
7104
+ scope: "global" | "type";
7105
+ name: string;
7106
+ schemaCid?: string;
7107
+ cid: string;
7108
+ previousCid: string | null;
7109
+ changed: boolean;
7110
+ }
7111
+
7112
+ export interface SetSwarmSkillResult {
7113
+ swarm: string;
7114
+ skillPath: string;
7115
+ cid: string;
7116
+ identity: string;
7117
+ description: string;
7118
+ headCid: string;
7119
+ previousHeadCid: string;
7120
+ rootCid: string;
7121
+ previousRootCid: string;
7122
+ changed: boolean;
7123
+ targets: SetSwarmSkillTargetResult[];
7124
+ }
7125
+
7126
+ export interface RemoveSwarmSkillInput {
7127
+ globalName?: string;
7128
+ types: readonly string[];
7129
+ }
7130
+
7131
+ export interface RemoveSwarmSkillTargetResult {
7132
+ scope: "global" | "type";
7133
+ name: string;
7134
+ schemaCid?: string;
7135
+ removedCid: string;
7136
+ }
7137
+
7138
+ export interface RemoveSwarmSkillResult {
7139
+ swarm: string;
7140
+ skillPath: string;
7141
+ headCid: string;
7142
+ previousHeadCid: string;
7143
+ rootCid: string;
7144
+ previousRootCid: string;
7145
+ changed: boolean;
7146
+ removed: RemoveSwarmSkillTargetResult[];
7147
+ }
7148
+
7149
+ function missingSkillPathError(snapshot: Snapshot): HostError {
7150
+ return new HostError(
7151
+ snapshot.stateBundle
7152
+ ? "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."
7153
+ : `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.`,
7154
+ );
7155
+ }
7156
+
7157
+ function canonicalTypeSkillLeaf(name: string, leaf: string): string {
7158
+ try {
7159
+ if (exactCid(leaf, true) === leaf) return leaf;
7160
+ } catch {
7161
+ // Fall through to typed error below.
7162
+ }
7163
+ throw new HostError(
7164
+ `Type Skill Name "${name}" must use a canonical schema CID.`,
7165
+ );
7166
+ }
7167
+
7168
+ async function inspectDirectTypeSkill(
7169
+ store: IpfsStore,
7170
+ name: string,
7171
+ targetCid: string,
7172
+ ) {
7173
+ let bundle: Awaited<ReturnType<typeof openBundle>>;
7174
+ try {
7175
+ bundle = await openBundle(CID.parse(targetCid), {
7176
+ resolveCid: (key) => store.block.get(key.toString()),
7177
+ });
7178
+ } catch (cause) {
7179
+ if (cause instanceof HostError) throw cause;
7180
+ throw new HostError(
7181
+ `Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
7182
+ );
7183
+ }
7184
+ if (bundle.schemaKey !== skillSchema.cid.toString())
7185
+ throw new HostError(
7186
+ `Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
7187
+ );
7188
+ return inspectSkillBundle(bundle);
7189
+ }
7190
+
7191
+ export async function swarmSkills(
7192
+ context: SwarmContext,
7193
+ configUrl: string,
7194
+ requested: readonly string[],
7195
+ owner: string,
7196
+ ): Promise<SharedSkill[]> {
7197
+ let ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7198
+ mode: "active",
7199
+ preferLocalCache: true,
7200
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
7201
+ });
7202
+ const roots = new Set<string>();
7203
+ const protect = async (cid: string) => {
7204
+ roots.add(cid);
7205
+ const values = [...roots];
7206
+ await context.store.retain(owner, values);
7207
+ await context.store.confirmRetained(owner, values);
7208
+ };
7209
+ for (let attempt = 0; ; attempt++) {
7210
+ if (hasMeta(ctx.snapshot)) {
7211
+ if (ctx.isV7) {
7212
+ if (context.store.supportsRetention) {
7213
+ const rootId = metaCid(ctx.snapshot);
7214
+ await context.store.retainDirect(owner, [rootId]);
7215
+ await context.store.confirmDirectRetained(owner, [rootId]);
7216
+ }
7217
+ } else {
7218
+ await protect(metaCid(ctx.snapshot));
7219
+ }
7220
+ }
7221
+ const meta = await swarmMeta(context, ctx.header);
7222
+ if (!meta.skillPath) throw missingSkillPathError(ctx.snapshot);
7223
+ const globalDir = `${meta.skillPath}/global`;
7224
+ const prefix = `${globalDir}/`;
7225
+ const entries = await listSubtreeNames(
6372
7226
  context.store,
6373
- header.snapshot,
6374
- meta.skillPath,
6375
- true,
7227
+ ctx.snapshot,
7228
+ globalDir,
7229
+ false,
6376
7230
  );
6377
7231
  for (const { cid: target } of entries) roots.add(target.toString());
6378
7232
  await context.store.registerOwnerAsync(owner, [...roots]);
@@ -6381,7 +7235,7 @@ export async function swarmSkills(
6381
7235
  for (const { name, cid: target } of entries) {
6382
7236
  if (name.slice(prefix.length).includes("/"))
6383
7237
  throw new HostError(
6384
- `Skill Name "${name}" must be flat under ${meta.skillPath}.`,
7238
+ `Skill Name "${name}" must be flat under ${globalDir}.`,
6385
7239
  );
6386
7240
  const cid = await artifactValue(
6387
7241
  context.store,
@@ -6395,13 +7249,18 @@ export async function swarmSkills(
6395
7249
  throw new HostError(
6396
7250
  `Name "${name}" is not an exact Skill type Bundle.`,
6397
7251
  );
6398
- const identity = await skillIdentity(bundle);
6399
- if (identities.has(identity))
7252
+ const metadata = await inspectSkillBundle(bundle);
7253
+ if (identities.has(metadata.name))
6400
7254
  throw new HostError(
6401
- `Duplicate Skill installation name "${identity}" in this Swarm.`,
7255
+ `Duplicate Skill installation name "${metadata.name}" in this Swarm.`,
6402
7256
  );
6403
- identities.add(identity);
6404
- result.push({ name, cid, identity });
7257
+ identities.add(metadata.name);
7258
+ result.push({
7259
+ name,
7260
+ cid,
7261
+ identity: metadata.name,
7262
+ description: metadata.description,
7263
+ });
6405
7264
  }
6406
7265
  const missing = requested.filter(
6407
7266
  (reference) =>
@@ -6409,56 +7268,438 @@ export async function swarmSkills(
6409
7268
  (skill) => skill.name === reference || skill.identity === reference,
6410
7269
  ),
6411
7270
  );
6412
- if (missing.length && !attempt && header.source === "cache") {
6413
- header = await swarmHeader(context, configUrl, true);
7271
+ if (missing.length && !attempt && ctx.source === "cache" && !ctx.isLocal) {
7272
+ ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7273
+ mode: "active",
7274
+ forceRefresh: true,
7275
+ });
6414
7276
  continue;
6415
7277
  }
6416
7278
  if (missing.length)
6417
7279
  throw new HostError(
6418
- `Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`,
7280
+ `Skill identities or shared Names not found under ${globalDir}: ${missing.join(", ")}.`,
6419
7281
  );
6420
7282
  return result;
6421
7283
  }
6422
7284
  }
6423
- export async function resolveTemplateSelector(
7285
+
7286
+ export async function swarmTypeSkills(
6424
7287
  context: SwarmContext,
6425
- selector: string,
6426
7288
  configUrl: string,
6427
- ): Promise<string> {
6428
- formalName(selector);
6429
- const warm = await localHeader(context, configUrl);
6430
- if (warm && !warm.header.localSourceReady)
6431
- await lazyPrivateSource(
6432
- context,
6433
- configUrl,
6434
- warm.account,
6435
- warm.header.config,
6436
- );
6437
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
6438
- if (!hasMeta(header.snapshot) && header.source === "cache")
6439
- header = await swarmHeader(context, configUrl, true);
6440
- for (let attempt = 0; ; attempt++) {
6441
- const meta = await swarmMeta(context, header);
6442
- const name = formalName(`${meta.templatePath}/${selector}`);
6443
- const target = await resolveSnapshotName(
7289
+ options: {
7290
+ owner?: string;
7291
+ mode?: SwarmReadMode;
7292
+ forceRefresh?: boolean;
7293
+ } = {},
7294
+ ): Promise<TypeSkillAssociation[]> {
7295
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7296
+ mode: options.mode ?? "local-first",
7297
+ ...(options.forceRefresh !== undefined
7298
+ ? { forceRefresh: options.forceRefresh }
7299
+ : {}),
7300
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
7301
+ });
7302
+ const roots = new Set<string>();
7303
+ if (options.owner && hasMeta(ctx.snapshot)) {
7304
+ const rootId = metaCid(ctx.snapshot);
7305
+ if (ctx.isV7) {
7306
+ if (context.store.supportsRetention) {
7307
+ await context.store.retainDirect(options.owner, [rootId]);
7308
+ await context.store.confirmDirectRetained(options.owner, [rootId]);
7309
+ }
7310
+ } else {
7311
+ roots.add(rootId);
7312
+ await context.store.retain(options.owner, [...roots]);
7313
+ await context.store.confirmRetained(options.owner, [...roots]);
7314
+ }
7315
+ }
7316
+ const meta = await swarmMeta(context, ctx.header);
7317
+ if (!meta.skillPath) throw missingSkillPathError(ctx.snapshot);
7318
+ const typesDir = `${meta.skillPath}/types`;
7319
+ const prefix = `${typesDir}/`;
7320
+ const entries = await listSubtreeNames(
7321
+ context.store,
7322
+ ctx.snapshot,
7323
+ typesDir,
7324
+ false,
7325
+ );
7326
+ if (options.owner) {
7327
+ for (const { cid: target } of entries) roots.add(target.toString());
7328
+ await context.store.registerOwnerAsync(options.owner, [...roots]);
7329
+ }
7330
+ const result: TypeSkillAssociation[] = [];
7331
+ for (const { name, cid: target } of entries) {
7332
+ if (name.slice(prefix.length).includes("/"))
7333
+ throw new HostError(
7334
+ `Type Skill Name "${name}" must be flat under ${typesDir}.`,
7335
+ );
7336
+ const leaf = name.slice(prefix.length);
7337
+ const schemaCid = canonicalTypeSkillLeaf(name, leaf);
7338
+ const targetCid = target.toString();
7339
+ const metadata = await inspectDirectTypeSkill(
6444
7340
  context.store,
6445
- header.snapshot,
6446
7341
  name,
7342
+ targetCid,
6447
7343
  );
6448
- if (target) return artifactValue(context.store, target.toString());
6449
- if (attempt || header.source !== "cache")
6450
- throw new HostError(
6451
- `Template Name "${name}" was not found after refreshing HEAD.`,
7344
+ result.push({
7345
+ name,
7346
+ schemaCid,
7347
+ cid: targetCid,
7348
+ identity: metadata.name,
7349
+ description: metadata.description,
7350
+ });
7351
+ }
7352
+ return result.sort((left, right) =>
7353
+ left.schemaCid.localeCompare(right.schemaCid),
7354
+ );
7355
+ }
7356
+
7357
+ export async function swarmTypeSkill(
7358
+ context: SwarmContext,
7359
+ configUrl: string,
7360
+ schemaCid: string,
7361
+ options: {
7362
+ mode?: SwarmReadMode;
7363
+ forceRefresh?: boolean;
7364
+ } = {},
7365
+ ): Promise<TypeSkillAssociation | undefined> {
7366
+ const canonicalSchema = exactCid(schemaCid, true);
7367
+ let cachedHeader: SwarmHeader | undefined;
7368
+ let cachedName: string | undefined;
7369
+ let cachedTarget: CID | undefined;
7370
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7371
+ mode: options.mode ?? "local-first",
7372
+ ...(options.forceRefresh !== undefined
7373
+ ? { forceRefresh: options.forceRefresh }
7374
+ : {}),
7375
+ shouldRefresh: async (current) => {
7376
+ if (!hasMeta(current.snapshot)) return true;
7377
+ await current.ensureLocalSource();
7378
+ const meta = await swarmMeta(context, current.header);
7379
+ if (!meta.skillPath) return false;
7380
+ const name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
7381
+ const target = await resolveSnapshotName(
7382
+ context.store,
7383
+ current.snapshot,
7384
+ name,
6452
7385
  );
6453
- header = await swarmHeader(context, configUrl, true);
7386
+ cachedHeader = current.header;
7387
+ cachedName = name;
7388
+ cachedTarget = target;
7389
+ return !target;
7390
+ },
7391
+ });
7392
+ let name: string;
7393
+ let target: CID | undefined;
7394
+ if (ctx.header === cachedHeader && cachedName !== undefined) {
7395
+ name = cachedName;
7396
+ target = cachedTarget;
7397
+ } else {
7398
+ const meta = await swarmMeta(context, ctx.header);
7399
+ if (!meta.skillPath) throw missingSkillPathError(ctx.snapshot);
7400
+ name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
7401
+ try {
7402
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
7403
+ } catch (cause) {
7404
+ if (!missingContent(cause)) throw cause;
7405
+ await ctx.ensureLocalSource();
7406
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
7407
+ }
6454
7408
  }
7409
+ if (!target) return undefined;
7410
+ const targetCid = target.toString();
7411
+ const metadata = await inspectDirectTypeSkill(context.store, name, targetCid);
7412
+ return {
7413
+ name,
7414
+ schemaCid: canonicalSchema,
7415
+ cid: targetCid,
7416
+ identity: metadata.name,
7417
+ description: metadata.description,
7418
+ };
6455
7419
  }
6456
- export function templateName(name: string): string {
6457
- if (name.includes(":"))
7420
+
7421
+ export async function setSwarmSkill(
7422
+ context: SwarmContext,
7423
+ configUrl: string,
7424
+ input: SetSwarmSkillInput,
7425
+ ): Promise<SetSwarmSkillResult> {
7426
+ if (!input.global && input.types.length === 0)
7427
+ syntax("skills set requires --global and/or at least one --type SCHEMA.");
7428
+ const skillCid = exactCid(input.skillCid);
7429
+ const canonicalTypes = [
7430
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
7431
+ ].sort((left, right) => left.localeCompare(right));
7432
+ let bundle: Awaited<ReturnType<typeof openBundle>>;
7433
+ try {
7434
+ bundle = await openBundle(CID.parse(skillCid), {
7435
+ resolveCid: (key) => context.store.block.get(key.toString()),
7436
+ });
7437
+ } catch (cause) {
7438
+ if (cause instanceof HostError) throw cause;
6458
7439
  throw new HostError(
6459
- "Template NAME must be a safe relative Name, not a URI.",
7440
+ `Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
7441
+ );
7442
+ }
7443
+ if (bundle.schemaKey !== skillSchema.cid.toString())
7444
+ throw new HostError(
7445
+ `Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
7446
+ );
7447
+ const metadata = await inspectSkillBundle(bundle);
7448
+ let expectedSkillPath: string | undefined;
7449
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
7450
+ allowLegacyNames: true,
7451
+ refreshAfterCommit: true,
7452
+ maxAttempts: 8,
7453
+ plan: async (planCtx) => {
7454
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
7455
+ if (!meta.skillPath) throw missingSkillPathError(planCtx.snapshot);
7456
+ if (
7457
+ expectedSkillPath !== undefined &&
7458
+ meta.skillPath !== expectedSkillPath
7459
+ )
7460
+ throw new HostError(
7461
+ "Swarm skillPath changed concurrently; retry ipab skills set.",
7462
+ 3,
7463
+ "EDIT_CONFLICT",
7464
+ "publication",
7465
+ );
7466
+ expectedSkillPath = meta.skillPath;
7467
+ const plannedTargets: Array<{
7468
+ scope: "global" | "type";
7469
+ name: string;
7470
+ schemaCid?: string;
7471
+ }> = [];
7472
+ if (input.global) {
7473
+ const path = formalName(`${meta.skillPath}/global/${metadata.name}`);
7474
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7475
+ plannedTargets.push({ scope: "global", name: path });
7476
+ }
7477
+ for (const schemaCid of canonicalTypes) {
7478
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
7479
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7480
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
7481
+ }
7482
+ const resolvedTargets = await Promise.all(
7483
+ plannedTargets.map(async (target) => ({
7484
+ ...target,
7485
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
7486
+ })),
7487
+ );
7488
+ const conflicts = resolvedTargets.filter(
7489
+ (target) => target.existing !== null && target.existing !== skillCid,
7490
+ );
7491
+ if (conflicts.length > 0 && !input.replace)
7492
+ throw new HostError(
7493
+ `Skill target(s) already point to a different CID (${conflicts.map((target) => target.name).join(", ")}); use --replace to overwrite.`,
7494
+ 3,
7495
+ "EDIT_CONFLICT",
7496
+ "publication",
7497
+ );
7498
+ const pending = resolvedTargets.filter(
7499
+ (target) => target.existing !== skillCid,
7500
+ );
7501
+ const targets: SetSwarmSkillTargetResult[] = resolvedTargets.map(
7502
+ (target) => ({
7503
+ scope: target.scope,
7504
+ name: target.name,
7505
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
7506
+ cid: skillCid,
7507
+ previousCid: target.existing,
7508
+ changed: target.existing !== skillCid,
7509
+ }),
7510
+ );
7511
+ if (pending.length === 0)
7512
+ return {
7513
+ kind: "noop" as const,
7514
+ result: { skillPath: meta.skillPath, targets },
7515
+ };
7516
+ const operations: UnixfsMutation[] = pending.map((target) => ({
7517
+ op: "set" as const,
7518
+ path: target.name,
7519
+ targetCid: CID.parse(skillCid),
7520
+ }));
7521
+ return {
7522
+ kind: "commit" as const,
7523
+ operations,
7524
+ recursiveRoots: [skillCid],
7525
+ retainedRecursive: [skillCid],
7526
+ result: { skillPath: meta.skillPath, targets },
7527
+ };
7528
+ },
7529
+ messages: {
7530
+ unconfirmed: (cause) =>
7531
+ `Skill association unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
7532
+ pinStale: (cause) =>
7533
+ `Skill association committed, but HEAD/subscription refresh failed: ${message(cause)}.`,
7534
+ headBusy: () => "HEAD is busy; retry ipab skills set.",
7535
+ },
7536
+ });
7537
+ return {
7538
+ swarm: committed.swarm,
7539
+ skillPath: committed.result.skillPath,
7540
+ cid: skillCid,
7541
+ identity: metadata.name,
7542
+ description: metadata.description,
7543
+ headCid: committed.headCid,
7544
+ previousHeadCid: committed.previousHeadCid,
7545
+ rootCid: committed.rootCid,
7546
+ previousRootCid: committed.previousRootCid,
7547
+ changed: committed.changed,
7548
+ targets: committed.result.targets,
7549
+ };
7550
+ }
7551
+
7552
+ export async function removeSwarmSkill(
7553
+ context: SwarmContext,
7554
+ configUrl: string,
7555
+ input: RemoveSwarmSkillInput,
7556
+ ): Promise<RemoveSwarmSkillResult> {
7557
+ if (input.globalName === undefined && input.types.length === 0)
7558
+ syntax(
7559
+ "skills remove requires --global NAME and/or at least one --type SCHEMA.",
7560
+ );
7561
+ if (
7562
+ input.globalName !== undefined &&
7563
+ (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(input.globalName) ||
7564
+ input.globalName.length > 64)
7565
+ )
7566
+ syntax(
7567
+ `Invalid global Skill name "${input.globalName}". Expected lowercase kebab-case (1..64 characters).`,
6460
7568
  );
6461
- return formalName(name);
7569
+ const canonicalTypes = [
7570
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
7571
+ ].sort((left, right) => left.localeCompare(right));
7572
+ let expectedSkillPath: string | undefined;
7573
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
7574
+ allowLegacyNames: true,
7575
+ refreshAfterCommit: true,
7576
+ maxAttempts: 8,
7577
+ plan: async (planCtx) => {
7578
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
7579
+ if (!meta.skillPath) throw missingSkillPathError(planCtx.snapshot);
7580
+ if (
7581
+ expectedSkillPath !== undefined &&
7582
+ meta.skillPath !== expectedSkillPath
7583
+ )
7584
+ throw new HostError(
7585
+ "Swarm skillPath changed concurrently; retry ipab skills remove.",
7586
+ 3,
7587
+ "EDIT_CONFLICT",
7588
+ "publication",
7589
+ );
7590
+ expectedSkillPath = meta.skillPath;
7591
+ const plannedTargets: Array<{
7592
+ scope: "global" | "type";
7593
+ name: string;
7594
+ schemaCid?: string;
7595
+ }> = [];
7596
+ if (input.globalName !== undefined) {
7597
+ const path = formalName(`${meta.skillPath}/global/${input.globalName}`);
7598
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7599
+ plannedTargets.push({ scope: "global", name: path });
7600
+ }
7601
+ for (const schemaCid of canonicalTypes) {
7602
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
7603
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7604
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
7605
+ }
7606
+ const resolvedTargets = await Promise.all(
7607
+ plannedTargets.map(async (target) => ({
7608
+ ...target,
7609
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
7610
+ })),
7611
+ );
7612
+ const missing = resolvedTargets.filter(
7613
+ (target) => target.existing === null,
7614
+ );
7615
+ if (missing.length > 0)
7616
+ throw new HostError(
7617
+ `Skill target(s) not found: ${missing.map((target) => target.name).join(", ")}.`,
7618
+ 1,
7619
+ "SKILL_NOT_FOUND",
7620
+ "state",
7621
+ );
7622
+ const operations: UnixfsMutation[] = resolvedTargets.map((target) => ({
7623
+ op: "delete" as const,
7624
+ path: target.name,
7625
+ }));
7626
+ const removed: RemoveSwarmSkillTargetResult[] = resolvedTargets.map(
7627
+ (target) => ({
7628
+ scope: target.scope,
7629
+ name: target.name,
7630
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
7631
+ removedCid: target.existing!,
7632
+ }),
7633
+ );
7634
+ return {
7635
+ kind: "commit" as const,
7636
+ operations,
7637
+ recursiveRoots: [],
7638
+ retainedRecursive: [],
7639
+ result: { skillPath: meta.skillPath, removed },
7640
+ };
7641
+ },
7642
+ messages: {
7643
+ unconfirmed: (cause) =>
7644
+ `Skill removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
7645
+ pinStale: (cause) =>
7646
+ `Skill removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
7647
+ headBusy: () => "HEAD is busy; retry ipab skills remove.",
7648
+ },
7649
+ });
7650
+ return {
7651
+ swarm: committed.swarm,
7652
+ skillPath: committed.result.skillPath,
7653
+ headCid: committed.headCid,
7654
+ previousHeadCid: committed.previousHeadCid,
7655
+ rootCid: committed.rootCid,
7656
+ previousRootCid: committed.previousRootCid,
7657
+ changed: committed.changed,
7658
+ removed: committed.result.removed,
7659
+ };
7660
+ }
7661
+ export async function resolveTemplateSelector(
7662
+ context: SwarmContext,
7663
+ selector: string,
7664
+ configUrl: string,
7665
+ ): Promise<string> {
7666
+ formalName(selector);
7667
+ let cachedHeader: SwarmHeader | undefined;
7668
+ let cachedName: string | undefined;
7669
+ let cachedTarget: CID | undefined;
7670
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7671
+ mode: "active",
7672
+ preferLocalCache: true,
7673
+ shouldRefresh: async (current) => {
7674
+ if (!hasMeta(current.snapshot)) return true;
7675
+ await current.ensureLocalSource();
7676
+ const meta = await swarmMeta(context, current.header);
7677
+ const name = formalName(`${meta.templatePath}/${selector}`);
7678
+ const target = await resolveSnapshotName(
7679
+ context.store,
7680
+ current.snapshot,
7681
+ name,
7682
+ );
7683
+ cachedHeader = current.header;
7684
+ cachedName = name;
7685
+ cachedTarget = target;
7686
+ return !target;
7687
+ },
7688
+ });
7689
+ let name: string;
7690
+ let target: CID | undefined;
7691
+ if (ctx.header === cachedHeader) {
7692
+ name = cachedName!;
7693
+ target = cachedTarget;
7694
+ } else {
7695
+ const meta = await swarmMeta(context, ctx.header);
7696
+ name = formalName(`${meta.templatePath}/${selector}`);
7697
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
7698
+ }
7699
+ if (target) return artifactValue(context.store, target.toString());
7700
+ throw new HostError(
7701
+ `Template Name "${name}" was not found after refreshing HEAD.`,
7702
+ );
6462
7703
  }
6463
7704
  async function templateEntry(
6464
7705
  context: SwarmContext,
@@ -6496,18 +7737,63 @@ async function retainDaemonRoots(
6496
7737
  store: IpfsStore,
6497
7738
  owner: string,
6498
7739
  roots: readonly string[],
7740
+ signal?: AbortSignal,
6499
7741
  ): Promise<void> {
6500
7742
  const unique = [...new Set(roots)];
7743
+ const options: [] | [{ signal: AbortSignal }] = signal ? [{ signal }] : [];
6501
7744
  if (!store.supportsRetention) {
6502
- for (const root of unique) await store.prepare(root);
7745
+ for (const root of unique) await store.prepare(root, ...options);
6503
7746
  return;
6504
7747
  }
6505
- await store.recoverOwner(owner, []);
7748
+ await store.recoverOwner(owner, [], ...options);
6506
7749
  if (unique.length) {
6507
- await store.retain(owner, unique);
6508
- await store.confirmRetained(owner, unique);
7750
+ await store.retain(owner, unique, ...options);
7751
+ await store.confirmRetained(owner, unique, ...options);
7752
+ }
7753
+ await store.reconcile(owner, unique, ...options);
7754
+ }
7755
+ export async function syncSwarmTypeSkills(
7756
+ context: SwarmContext,
7757
+ configUrl: string,
7758
+ header: SwarmHeader,
7759
+ ): Promise<number> {
7760
+ if (!hasMeta(header.snapshot)) return 0;
7761
+ const meta = await swarmMeta(context, header);
7762
+ if (!meta.skillPath) return 0;
7763
+ const typesDir = `${meta.skillPath}/types`;
7764
+ const prefix = `${typesDir}/`;
7765
+ const entries = await listSubtreeNames(
7766
+ context.store,
7767
+ header.snapshot,
7768
+ typesDir,
7769
+ false,
7770
+ );
7771
+ const roots: string[] = [];
7772
+ for (const { name, cid: target } of entries) {
7773
+ if (name.slice(prefix.length).includes("/"))
7774
+ throw new HostError(
7775
+ `Type Skill Name "${name}" must be flat under ${typesDir}.`,
7776
+ );
7777
+ const leaf = name.slice(prefix.length);
7778
+ canonicalTypeSkillLeaf(name, leaf);
7779
+ const targetCid = target.toString();
7780
+ await inspectDirectTypeSkill(context.store, name, targetCid);
7781
+ roots.push(targetCid);
7782
+ }
7783
+ const owner = `daemon-type-skills:${createHash("sha256").update(configUrl).digest("hex")}`;
7784
+ if (roots.length) {
7785
+ if (isV7Snapshot(header.snapshot)) {
7786
+ if (context.store.supportsRetention) {
7787
+ const rootId = metaCid(header.snapshot);
7788
+ await context.store.retainDirect(owner, [rootId]);
7789
+ await context.store.confirmDirectRetained(owner, [rootId]);
7790
+ }
7791
+ } else {
7792
+ roots.unshift(metaCid(header.snapshot));
7793
+ }
6509
7794
  }
6510
- await store.reconcile(owner, unique);
7795
+ await retainDaemonRoots(context.store, owner, roots);
7796
+ return entries.length;
6511
7797
  }
6512
7798
  export async function syncSwarmTemplates(
6513
7799
  context: SwarmContext,
@@ -6584,6 +7870,23 @@ export async function syncPivotReplicationAndIndex(
6584
7870
  signal?: AbortSignal,
6585
7871
  ): Promise<void> {
6586
7872
  if (!context.pivot || !isV7Snapshot(header.snapshot)) return;
7873
+ const lock = await privateDirectory(
7874
+ context.stateDir,
7875
+ `pivot-index-${createHash("sha256").update(configUrl).digest("hex")}`,
7876
+ );
7877
+ return withSwarmLock(
7878
+ context,
7879
+ lock,
7880
+ () => updatePivotReplicationAndIndex(context, configUrl, header, signal),
7881
+ signal,
7882
+ );
7883
+ }
7884
+ async function updatePivotReplicationAndIndex(
7885
+ context: SwarmContext,
7886
+ configUrl: string,
7887
+ header: SwarmHeader,
7888
+ signal?: AbortSignal,
7889
+ ): Promise<void> {
6587
7890
  const headCid = CID.parse(header.stateCid).toV1().toString();
6588
7891
  const previousHead = withState(
6589
7892
  context,
@@ -6593,7 +7896,7 @@ export async function syncPivotReplicationAndIndex(
6593
7896
  await pinAdd(context.node, headCid, true, signal);
6594
7897
  }
6595
7898
  const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
6596
- await retainDaemonRoots(context.store, owner, [headCid]);
7899
+ await retainDaemonRoots(context.store, owner, [headCid], signal);
6597
7900
  await withStateAsync(context, (state) =>
6598
7901
  indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
6599
7902
  skipRootFiles: v7RootSkipFiles(header.snapshot),
@@ -6610,52 +7913,38 @@ export async function swarmTemplates(
6610
7913
  selector?: string,
6611
7914
  ) {
6612
7915
  if (selector !== undefined) templateName(selector);
6613
- const warm = await localHeader(context, configUrl);
6614
- if (warm && !warm.header.localSourceReady)
6615
- await lazyPrivateSource(
6616
- context,
6617
- configUrl,
6618
- warm.account,
6619
- warm.header.config,
6620
- );
6621
- let header =
6622
- warm?.header ??
6623
- (await swarmHeader(context, configUrl, undefined, "local-first"));
6624
- for (let attempt = 0; ; attempt++) {
6625
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
6626
- header = await swarmHeader(context, configUrl, true, "local-first");
6627
- continue;
6628
- }
6629
- const meta = await swarmMeta(context, header);
6630
- const name =
6631
- selector === undefined
6632
- ? undefined
6633
- : formalName(`${meta.templatePath}/${selector}`);
6634
- if (
6635
- name &&
6636
- !(await resolveSnapshotName(context.store, header.snapshot, name)) &&
6637
- header.source === "cache" &&
6638
- !attempt
6639
- ) {
6640
- header = await swarmHeader(context, configUrl, true, "local-first");
6641
- continue;
6642
- }
6643
- const selectors =
6644
- selector === undefined
6645
- ? (
6646
- await listSubtreeNames(
6647
- context.store,
6648
- header.snapshot,
6649
- meta.templatePath,
6650
- false,
6651
- )
6652
- ).map((entry) => entry.name.slice(meta.templatePath.length + 1))
6653
- : [selector];
6654
- const items = [];
6655
- for (const item of selectors)
6656
- items.push(await templateEntry(context, configUrl, header, item));
6657
- return items;
6658
- }
7916
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7917
+ mode: "local-first",
7918
+ preferLocalCache: true,
7919
+ shouldRefresh: async (current) => {
7920
+ if (!hasMeta(current.snapshot)) return true;
7921
+ if (selector === undefined) return false;
7922
+ await current.ensureLocalSource();
7923
+ const meta = await swarmMeta(context, current.header);
7924
+ const name = formalName(`${meta.templatePath}/${selector}`);
7925
+ return !(await resolveSnapshotName(
7926
+ context.store,
7927
+ current.snapshot,
7928
+ name,
7929
+ ));
7930
+ },
7931
+ });
7932
+ const meta = await swarmMeta(context, ctx.header);
7933
+ const selectors =
7934
+ selector === undefined
7935
+ ? (
7936
+ await listSubtreeNames(
7937
+ context.store,
7938
+ ctx.snapshot,
7939
+ meta.templatePath,
7940
+ false,
7941
+ )
7942
+ ).map((entry) => entry.name.slice(meta.templatePath.length + 1))
7943
+ : [selector];
7944
+ const items = [];
7945
+ for (const item of selectors)
7946
+ items.push(await templateEntry(context, configUrl, ctx.header, item));
7947
+ return items;
6659
7948
  }
6660
7949
  export async function setSwarmTemplate(
6661
7950
  context: SwarmContext,
@@ -6665,7 +7954,7 @@ export async function setSwarmTemplate(
6665
7954
  expect?: string,
6666
7955
  ) {
6667
7956
  templateName(selector);
6668
- await pointer(context, configUrl);
7957
+ await swarmFsTransport.pointer(context, configUrl);
6669
7958
  const content = await templatePublicationSource(source, context.store);
6670
7959
  const details = await inspectTemplate(context.store, content);
6671
7960
  let location:
@@ -6706,87 +7995,58 @@ export async function removeSwarmTemplate(
6706
7995
  ) {
6707
7996
  templateName(selector);
6708
7997
  const expected = exactCid(expect);
6709
- const head = await pointer(context, configUrl);
6710
7998
  let basis: string | undefined;
6711
- for (let attempt = 0; attempt < 8; attempt++) {
6712
- const currentHead = await head.read();
6713
- const current = await readSnapshot(
6714
- context.store,
6715
- currentHead.root,
6716
- configUrl,
6717
- );
6718
- const meta = await swarmMeta(context, { snapshot: current });
6719
- const name = formalName(`${meta.templatePath}/${selector}`);
6720
- if (basis !== undefined && basis !== name)
6721
- throw new HostError(
6722
- "Template Meta path changed during removal; inspect and retry.",
6723
- 3,
6724
- "EDIT_CONFLICT",
6725
- "publication",
6726
- );
6727
- basis = name;
6728
- const old = (
6729
- await resolveSnapshotName(context.store, current, name)
6730
- )?.toString();
6731
- if (!old)
6732
- throw new HostError(
6733
- `Template Name "${name}" is missing; nothing was removed.`,
6734
- );
6735
- if (old !== expected)
6736
- throw new HostError(
6737
- `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
6738
- 3,
6739
- "EDIT_CONFLICT",
6740
- "publication",
6741
- );
6742
- let next: string;
6743
- if (isV7Snapshot(current)) {
6744
- next = await prepareV7PathDelete(context, configUrl, current, name);
6745
- } else {
6746
- const names = { ...current.names };
6747
- delete names[name];
6748
- next = await prepareNamesPublication(
6749
- context,
6750
- configUrl,
6751
- current,
6752
- names,
6753
- [],
6754
- );
6755
- }
6756
- try {
6757
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
6758
- } catch (cause) {
6759
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
6760
- throw cause;
6761
- if (cause instanceof ScopeApiError && cause.status === 412) continue;
6762
- throw new HostError(
7999
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
8000
+ allowLegacyNames: true,
8001
+ refreshAfterCommit: true,
8002
+ plan: async (planCtx) => {
8003
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
8004
+ const name = formalName(`${meta.templatePath}/${selector}`);
8005
+ if (basis !== undefined && basis !== name)
8006
+ throw new HostError(
8007
+ "Template Meta path changed during removal; inspect and retry.",
8008
+ 3,
8009
+ "EDIT_CONFLICT",
8010
+ "publication",
8011
+ );
8012
+ basis = name;
8013
+ const old = (await planCtx.resolve(name))?.toString();
8014
+ if (!old)
8015
+ throw new HostError(
8016
+ `Template Name "${name}" is missing; nothing was removed.`,
8017
+ );
8018
+ if (old !== expected)
8019
+ throw new HostError(
8020
+ `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
8021
+ 3,
8022
+ "EDIT_CONFLICT",
8023
+ "publication",
8024
+ );
8025
+ return {
8026
+ kind: "commit",
8027
+ operations: [{ op: "delete", path: name }],
8028
+ recursiveRoots: [],
8029
+ retainedRecursive: [],
8030
+ result: {
8031
+ swarm: configUrl,
8032
+ templatePath: meta.templatePath,
8033
+ metaCid: metaCid(planCtx.snapshot),
8034
+ selector,
8035
+ name,
8036
+ reference: formatNameReference(configUrl, name),
8037
+ targetCid: old,
8038
+ },
8039
+ };
8040
+ },
8041
+ messages: {
8042
+ unconfirmed: (cause) =>
6763
8043
  `Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
6764
- 1,
6765
- "HEAD_UNCONFIRMED",
6766
- "publication",
6767
- );
6768
- }
6769
- try {
6770
- await swarmHeader(context, configUrl, true);
6771
- } catch (cause) {
6772
- throw new HostError(
8044
+ pinStale: (cause) =>
6773
8045
  `Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
6774
- 1,
6775
- "PIN_STALE",
6776
- "publication",
6777
- );
6778
- }
6779
- return {
6780
- swarm: configUrl,
6781
- templatePath: meta.templatePath,
6782
- metaCid: metaCid(current),
6783
- selector,
6784
- name,
6785
- reference: formatNameReference(configUrl, name),
6786
- targetCid: old,
6787
- };
6788
- }
6789
- throw new HostError("HEAD is busy; retry the template removal.");
8046
+ headBusy: () => "HEAD is busy; retry the template removal.",
8047
+ },
8048
+ });
8049
+ return committed.result;
6790
8050
  }
6791
8051
  async function registryAssociations(
6792
8052
  context: SwarmContext,
@@ -6819,10 +8079,11 @@ export async function swarmRegistrations(
6819
8079
  context: SwarmContext,
6820
8080
  configUrl: string,
6821
8081
  ): Promise<Association[]> {
6822
- let header = await swarmHeader(context, configUrl);
6823
- if (!hasMeta(header.snapshot) && header.source === "cache")
6824
- header = await swarmHeader(context, configUrl, true);
6825
- return registryAssociations(context, header);
8082
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
8083
+ mode: "active",
8084
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
8085
+ });
8086
+ return registryAssociations(context, ctx.header);
6826
8087
  }
6827
8088
  export async function swarmAssociation(
6828
8089
  context: SwarmContext,
@@ -6830,18 +8091,6 @@ export async function swarmAssociation(
6830
8091
  schemaCid: string,
6831
8092
  mode: "active" | "local-first" = "active",
6832
8093
  ): Promise<Association | undefined> {
6833
- const warm =
6834
- mode === "local-first" ? await localHeader(context, configUrl) : undefined;
6835
- if (warm && !warm.header.localSourceReady)
6836
- await lazyPrivateSource(
6837
- context,
6838
- configUrl,
6839
- warm.account,
6840
- warm.header.config,
6841
- );
6842
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
6843
- if (!hasMeta(header.snapshot) && header.source === "cache")
6844
- header = await swarmHeader(context, configUrl, true);
6845
8094
  const findAssociation = async (
6846
8095
  current: SwarmHeader,
6847
8096
  ): Promise<Association | undefined> => {
@@ -6860,74 +8109,24 @@ export async function swarmAssociation(
6860
8109
  (item) => item.schemaCid === schemaCid,
6861
8110
  );
6862
8111
  };
6863
- let association = await findAssociation(header);
6864
- if (!association && header.source === "cache") {
6865
- header = await swarmHeader(context, configUrl, true);
6866
- association = await findAssociation(header);
6867
- }
6868
- return association;
6869
- }
6870
- async function prepareV7PathSet(
6871
- context: SwarmContext,
6872
- configUrl: string,
6873
- current: Snapshot,
6874
- name: string,
6875
- targetCid: CID,
6876
- roots: Iterable<string>,
6877
- retainedRoots?: Iterable<string>,
6878
- ): Promise<string> {
6879
- const { newRootCid, createdDirCids } = await setUnixfsPath(
6880
- context.store,
6881
- CID.parse(current.stateBundle!.cid),
6882
- name,
6883
- targetCid,
6884
- );
6885
- if (isLocalSwarm(configUrl)) return newRootCid.toString();
6886
- const recursiveRoots = [...new Set(roots)];
6887
- const retainedRecursive = [...new Set(retainedRoots ?? roots)];
6888
- await provideShallowContent(context.store, {
6889
- directBlocks: createdDirCids,
6890
- recursiveRoots,
6891
- retainedDirect: createdDirCids,
6892
- retainedRecursive,
6893
- endpoint: context.node!.api,
6894
- ...(context.fetch ? { fetcher: context.fetch } : {}),
6895
- authorizationToken: context.node!.auth,
6896
- owner: `publication:${newRootCid.toString()}`,
6897
- });
6898
- withState(context, (state) => {
6899
- state.invalidateSwarmHeader(configUrl);
6900
- });
6901
- return newRootCid.toString();
6902
- }
6903
- async function prepareV7PathDelete(
6904
- context: SwarmContext,
6905
- configUrl: string,
6906
- current: Snapshot,
6907
- name: string,
6908
- ): Promise<string> {
6909
- const { newRootCid, createdDirCids } = await deleteUnixfsPath(
6910
- context.store,
6911
- CID.parse(current.stateBundle!.cid),
6912
- name,
6913
- );
6914
- if (isLocalSwarm(configUrl)) return newRootCid.toString();
6915
- await provideShallowContent(context.store, {
6916
- directBlocks: createdDirCids,
6917
- recursiveRoots: [],
6918
- retainedDirect: createdDirCids,
6919
- retainedRecursive: [],
6920
- endpoint: context.node!.api,
6921
- ...(context.fetch ? { fetcher: context.fetch } : {}),
6922
- authorizationToken: context.node!.auth,
6923
- owner: `publication:${newRootCid.toString()}`,
6924
- });
6925
- withState(context, (state) => {
6926
- state.invalidateSwarmHeader(configUrl);
8112
+ let cachedHeader: SwarmHeader | undefined;
8113
+ let cachedResult: Association | undefined;
8114
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
8115
+ mode: "active",
8116
+ preferLocalCache: mode === "local-first",
8117
+ shouldRefresh: async (current) => {
8118
+ if (!hasMeta(current.snapshot)) return true;
8119
+ await current.ensureLocalSource();
8120
+ cachedHeader = current.header;
8121
+ cachedResult = await findAssociation(current.header);
8122
+ return !cachedResult;
8123
+ },
6927
8124
  });
6928
- return newRootCid.toString();
8125
+ return ctx.header === cachedHeader
8126
+ ? cachedResult
8127
+ : findAssociation(ctx.header);
6929
8128
  }
6930
- async function prepareNamesPublication(
8129
+ export async function prepareNamesPublication(
6931
8130
  context: SwarmContext,
6932
8131
  configUrl: string,
6933
8132
  current: Snapshot,
@@ -6962,7 +8161,7 @@ async function editSwarmAssociation(
6962
8161
  association: Association | undefined,
6963
8162
  replace: boolean,
6964
8163
  ): Promise<void> {
6965
- const head = await pointer(context, configUrl);
8164
+ await swarmFsTransport.pointer(context, configUrl);
6966
8165
  if (association) {
6967
8166
  const app = await openBundle(CID.parse(association.appCid), {
6968
8167
  resolveCid: (cid) => context.store.block.get(cid.toString()),
@@ -6975,71 +8174,46 @@ async function editSwarmAssociation(
6975
8174
  const roots = association
6976
8175
  ? await dependencies(context.store, association.appCid)
6977
8176
  : new Set<string>();
6978
- for (let attempt = 0; attempt < 8; attempt++) {
6979
- const currentHead = await head.read();
6980
- const current = await readSnapshot(
6981
- context.store,
6982
- currentHead.root,
6983
- configUrl,
6984
- );
6985
- assertNamesRegistry(current);
6986
- const meta = await swarmMeta(context, { snapshot: current });
6987
- const name = formalName(`${meta.registryPath}/${schemaCid}`);
6988
- const oldCid = (
6989
- await resolveSnapshotName(context.store, current, name)
6990
- )?.toString();
6991
- if (association) {
6992
- if (oldCid === association.appCid) return;
6993
- if (oldCid && !replace)
6994
- throw new HostError("Schema has another association; use --replace.");
6995
- } else if (!oldCid) {
6996
- throw new HostError(
6997
- "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
6998
- );
6999
- }
7000
- let next: string;
7001
- if (isV7Snapshot(current)) {
7002
- next = association
7003
- ? await prepareV7PathSet(
7004
- context,
7005
- configUrl,
7006
- current,
7007
- name,
7008
- CID.parse(association.appCid),
7009
- roots,
7010
- )
7011
- : await prepareV7PathDelete(context, configUrl, current, name);
7012
- } else {
7013
- const names = { ...current.names };
7014
- if (association) names[name] = CID.parse(association.appCid);
7015
- else delete names[name];
7016
- next = await prepareNamesPublication(
7017
- context,
7018
- configUrl,
7019
- current,
7020
- names,
7021
- roots,
7022
- );
7023
- }
7024
- try {
7025
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
7026
- return;
7027
- } catch (cause) {
7028
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
7029
- throw cause;
7030
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
8177
+ await swarmFs.commitSwarmPaths(context, configUrl, {
8178
+ allowLegacyNames: true,
8179
+ refreshAfterCommit: false,
8180
+ plan: async (planCtx) => {
8181
+ assertNamesRegistry(planCtx.snapshot);
8182
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
8183
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
8184
+ const oldCid = (await planCtx.resolve(name))?.toString();
8185
+ if (association) {
8186
+ if (oldCid === association.appCid)
8187
+ return { kind: "noop", result: undefined };
8188
+ if (oldCid && !replace)
8189
+ throw new HostError("Schema has another association; use --replace.");
8190
+ return {
8191
+ kind: "commit",
8192
+ operations: [
8193
+ { op: "set", path: name, targetCid: CID.parse(association.appCid) },
8194
+ ],
8195
+ recursiveRoots: roots,
8196
+ result: undefined,
8197
+ };
8198
+ }
8199
+ if (!oldCid)
7031
8200
  throw new HostError(
7032
- `Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`,
7033
- 1,
7034
- "HEAD_UNCONFIRMED",
7035
- "publication",
8201
+ "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
7036
8202
  );
7037
- continue;
7038
- }
7039
- }
7040
- throw new HostError(
7041
- `HEAD is busy for ${configUrl}; retry the registry edit.`,
7042
- );
8203
+ return {
8204
+ kind: "commit",
8205
+ operations: [{ op: "delete", path: name }],
8206
+ recursiveRoots: [],
8207
+ retainedRecursive: [],
8208
+ result: undefined,
8209
+ };
8210
+ },
8211
+ messages: {
8212
+ unconfirmed: (cause, url) =>
8213
+ `Registry publication unconfirmed for ${url}: ${message(cause)}. Inspect the Swarm registry before retry.`,
8214
+ headBusy: (url) => `HEAD is busy for ${url}; retry the registry edit.`,
8215
+ },
8216
+ });
7043
8217
  }
7044
8218
  export async function setSwarmAssociation(
7045
8219
  context: SwarmContext,
@@ -7194,64 +8368,38 @@ export async function unpublish(
7194
8368
  );
7195
8369
  const name = formalName(options.name);
7196
8370
  const expected = exactCid(options.expect);
7197
- const head = await pointer(context, options.swarm);
7198
- for (let attempt = 0; attempt < 8; attempt++) {
7199
- const currentHead = await head.read();
7200
- const current = await readSnapshot(
7201
- context.store,
7202
- currentHead.root,
7203
- options.swarm,
7204
- );
7205
- const old = (
7206
- await resolveSnapshotName(context.store, current, name)
7207
- )?.toString();
7208
- if (!old)
7209
- throw new HostError(`Name "${name}" is missing; nothing was removed.`);
7210
- if (old !== expected)
7211
- throw new HostError(
7212
- `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
7213
- 3,
7214
- "EDIT_CONFLICT",
7215
- "publication",
7216
- );
7217
- let next: string;
7218
- if (isV7Snapshot(current)) {
7219
- next = await prepareV7PathDelete(context, options.swarm, current, name);
7220
- } else {
7221
- const names = { ...current.names };
7222
- delete names[name];
7223
- next = await prepareNamesPublication(
7224
- context,
7225
- options.swarm,
7226
- current,
7227
- names,
7228
- [],
7229
- );
7230
- }
7231
- try {
7232
- await head.write(next, currentHead.cid, uniqueId());
7233
- } catch (cause) {
7234
- if (cause instanceof ScopeApiError && cause.status === 412) continue;
7235
- throw new HostError(
8371
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
8372
+ allowLegacyNames: true,
8373
+ refreshAfterCommit: true,
8374
+ plan: async (planCtx) => {
8375
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
8376
+ const old = (await planCtx.resolve(name))?.toString();
8377
+ if (!old)
8378
+ throw new HostError(`Name "${name}" is missing; nothing was removed.`);
8379
+ if (old !== expected)
8380
+ throw new HostError(
8381
+ `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
8382
+ 3,
8383
+ "EDIT_CONFLICT",
8384
+ "publication",
8385
+ );
8386
+ return {
8387
+ kind: "commit",
8388
+ operations: [{ op: "delete", path: name }],
8389
+ recursiveRoots: [],
8390
+ retainedRecursive: [],
8391
+ result: { name, targetCid: old },
8392
+ };
8393
+ },
8394
+ messages: {
8395
+ unconfirmed: (cause) =>
7236
8396
  `Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
7237
- 1,
7238
- "HEAD_UNCONFIRMED",
7239
- "publication",
7240
- );
7241
- }
7242
- try {
7243
- await swarmHeader(context, options.swarm, true);
7244
- } catch (cause) {
7245
- throw new HostError(
8397
+ pinStale: (cause) =>
7246
8398
  `Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
7247
- 1,
7248
- "PIN_STALE",
7249
- "publication",
7250
- );
7251
- }
7252
- return { name, targetCid: old };
7253
- }
7254
- throw new HostError("HEAD is busy; retry unpublish.");
8399
+ headBusy: () => "HEAD is busy; retry unpublish.",
8400
+ },
8401
+ });
8402
+ return committed.result;
7255
8403
  }
7256
8404
  export async function publish(
7257
8405
  context: SwarmContext,
@@ -7280,7 +8428,7 @@ async function publishContent(
7280
8428
  throw new HostError(
7281
8429
  "Publication requires a selected Swarm configuration URL or alias.",
7282
8430
  );
7283
- const head = await pointer(context, options.swarm);
8431
+ await swarmFsTransport.pointer(context, options.swarm);
7284
8432
  const roots = await dependencies(context.store, content);
7285
8433
  const currentRoots = [...(await currentDependencies(context.store, content))];
7286
8434
  await withStateAsync(context, (state) =>
@@ -7309,84 +8457,52 @@ async function publishContent(
7309
8457
  timestamp: new Date().toISOString(),
7310
8458
  });
7311
8459
  roots.add(candidate);
7312
- if (expected)
7313
- for (const root of await dependencies(context.store, expected))
7314
- roots.add(root);
7315
- for (let attempt = 0; attempt < 8; attempt++) {
7316
- const currentHead = await head.read(),
7317
- current = await readSnapshot(
7318
- context.store,
7319
- currentHead.root,
7320
- options.swarm,
7321
- );
7322
- if (nameForSnapshot) {
7323
- name = await nameForSnapshot(current);
7324
- if (resolvedName !== undefined && resolvedName !== name)
8460
+ const expectedDeps = expected
8461
+ ? await dependencies(context.store, expected)
8462
+ : undefined;
8463
+ if (expectedDeps) for (const root of expectedDeps) roots.add(root);
8464
+ const retained = [candidate, ...(expectedDeps ?? [])];
8465
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
8466
+ allowLegacyNames: true,
8467
+ refreshAfterCommit: true,
8468
+ plan: async (planCtx) => {
8469
+ if (nameForSnapshot) {
8470
+ name = await nameForSnapshot(planCtx.snapshot);
8471
+ if (resolvedName !== undefined && resolvedName !== name)
8472
+ throw new HostError(
8473
+ "Template Meta path changed during publication; inspect and retry. Content remains pinned.",
8474
+ 3,
8475
+ "EDIT_CONFLICT",
8476
+ "publication",
8477
+ );
8478
+ resolvedName = name;
8479
+ }
8480
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
8481
+ const existing = (await planCtx.resolve(name))?.toString();
8482
+ if (existing !== expected)
7325
8483
  throw new HostError(
7326
- "Template Meta path changed during publication; inspect and retry. Content remains pinned.",
8484
+ `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.`,
7327
8485
  3,
7328
8486
  "EDIT_CONFLICT",
7329
8487
  "publication",
7330
8488
  );
7331
- resolvedName = name;
7332
- }
7333
- const existing = (
7334
- await resolveSnapshotName(context.store, current, name)
7335
- )?.toString();
7336
- if (existing !== expected)
7337
- throw new HostError(
7338
- `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.`,
7339
- 3,
7340
- "EDIT_CONFLICT",
7341
- "publication",
7342
- );
7343
- const retained = [
7344
- candidate,
7345
- ...(expected ? await dependencies(context.store, expected) : []),
7346
- ];
7347
- const next = isV7Snapshot(current)
7348
- ? await prepareV7PathSet(
7349
- context,
7350
- options.swarm,
7351
- current,
7352
- name,
7353
- CID.parse(candidate),
7354
- roots,
7355
- retained,
7356
- )
7357
- : await prepareNamesPublication(
7358
- context,
7359
- options.swarm,
7360
- current,
7361
- { ...current.names, [name]: CID.parse(candidate) },
7362
- roots,
7363
- retained,
7364
- );
7365
- try {
7366
- await writeNamesHead(context, options.swarm, head, next, currentHead.cid);
7367
- } catch (cause) {
7368
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
7369
- throw cause;
7370
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
7371
- throw new HostError(
7372
- `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
7373
- 1,
7374
- "HEAD_UNCONFIRMED",
7375
- "publication",
7376
- );
7377
- continue;
7378
- }
7379
- try {
7380
- await swarmHeader(context, options.swarm, true);
7381
- } catch (cause) {
7382
- throw new HostError(
8489
+ return {
8490
+ kind: "commit",
8491
+ operations: [
8492
+ { op: "set", path: name, targetCid: CID.parse(candidate) },
8493
+ ],
8494
+ recursiveRoots: roots,
8495
+ retainedRecursive: retained,
8496
+ result: candidate,
8497
+ };
8498
+ },
8499
+ messages: {
8500
+ unconfirmed: (cause) =>
8501
+ `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
8502
+ pinStale: (cause) =>
7383
8503
  `Publication committed as ${candidate}, but its HEAD/subscription refresh failed: ${message(cause)}. Published content remains pinned; inspect HEAD and retry the affected Name pin.`,
7384
- 1,
7385
- "PIN_STALE",
7386
- "publication",
7387
- );
7388
- }
7389
- return candidate;
7390
- }
7391
- throw new HostError(`HEAD is busy; candidate ${candidate} remains retained.`);
8504
+ headBusy: () => `HEAD is busy; candidate ${candidate} remains retained.`,
8505
+ },
8506
+ });
8507
+ return committed.result;
7392
8508
  }