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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +15 -10
  2. package/dist/authoring.d.ts +6 -2
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +65 -18
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/builtins/skill.ipab.car +0 -0
  7. package/dist/cli.d.ts +2 -1
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +854 -179
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config-secret.js +1 -1
  12. package/dist/config-secret.js.map +1 -1
  13. package/dist/daemon-ui.d.ts +1 -0
  14. package/dist/daemon-ui.d.ts.map +1 -1
  15. package/dist/daemon-ui.js +2 -0
  16. package/dist/daemon-ui.js.map +1 -1
  17. package/dist/history.d.ts +3 -1
  18. package/dist/history.d.ts.map +1 -1
  19. package/dist/history.js +16 -1
  20. package/dist/history.js.map +1 -1
  21. package/dist/kubo-topology.d.ts +2 -0
  22. package/dist/kubo-topology.d.ts.map +1 -1
  23. package/dist/kubo-topology.js +17 -20
  24. package/dist/kubo-topology.js.map +1 -1
  25. package/dist/kubo.d.ts +5 -3
  26. package/dist/kubo.d.ts.map +1 -1
  27. package/dist/kubo.js +83 -13
  28. package/dist/kubo.js.map +1 -1
  29. package/dist/name-reference.d.ts +8 -0
  30. package/dist/name-reference.d.ts.map +1 -0
  31. package/dist/name-reference.js +63 -0
  32. package/dist/name-reference.js.map +1 -0
  33. package/dist/pivot-rpc.d.ts +37 -2
  34. package/dist/pivot-rpc.d.ts.map +1 -1
  35. package/dist/pivot-rpc.js +188 -8
  36. package/dist/pivot-rpc.js.map +1 -1
  37. package/dist/search-index.d.ts.map +1 -1
  38. package/dist/search-index.js +1 -0
  39. package/dist/search-index.js.map +1 -1
  40. package/dist/skill-definition.d.ts +9 -0
  41. package/dist/skill-definition.d.ts.map +1 -1
  42. package/dist/skill-definition.js +26 -2
  43. package/dist/skill-definition.js.map +1 -1
  44. package/dist/skill-source.d.ts +1 -0
  45. package/dist/skill-source.d.ts.map +1 -1
  46. package/dist/skill-source.js +10 -4
  47. package/dist/skill-source.js.map +1 -1
  48. package/dist/skills.d.ts +8 -2
  49. package/dist/skills.d.ts.map +1 -1
  50. package/dist/skills.js +31 -2
  51. package/dist/skills.js.map +1 -1
  52. package/dist/swarm-fs-core.d.ts +217 -0
  53. package/dist/swarm-fs-core.d.ts.map +1 -0
  54. package/dist/swarm-fs-core.js +885 -0
  55. package/dist/swarm-fs-core.js.map +1 -0
  56. package/dist/swarm-fs-path.d.ts +17 -0
  57. package/dist/swarm-fs-path.d.ts.map +1 -0
  58. package/dist/swarm-fs-path.js +46 -0
  59. package/dist/swarm-fs-path.js.map +1 -0
  60. package/dist/swarm-fs.d.ts +9 -0
  61. package/dist/swarm-fs.d.ts.map +1 -0
  62. package/dist/swarm-fs.js +21 -0
  63. package/dist/swarm-fs.js.map +1 -0
  64. package/dist/swarm-observations.d.ts +6 -0
  65. package/dist/swarm-observations.d.ts.map +1 -1
  66. package/dist/swarm-observations.js +28 -8
  67. package/dist/swarm-observations.js.map +1 -1
  68. package/dist/swarm.d.ts +124 -17
  69. package/dist/swarm.d.ts.map +1 -1
  70. package/dist/swarm.js +1085 -450
  71. package/dist/swarm.js.map +1 -1
  72. package/dist/unixfs-tree.d.ts +55 -0
  73. package/dist/unixfs-tree.d.ts.map +1 -1
  74. package/dist/unixfs-tree.js +361 -2
  75. package/dist/unixfs-tree.js.map +1 -1
  76. package/package.json +5 -5
  77. package/src/authoring.ts +88 -28
  78. package/src/cli.ts +1142 -267
  79. package/src/config-secret.ts +1 -1
  80. package/src/daemon-ui.ts +3 -0
  81. package/src/history.ts +26 -1
  82. package/src/kubo-topology.ts +25 -22
  83. package/src/kubo.ts +127 -9
  84. package/src/name-reference.ts +91 -0
  85. package/src/pivot-rpc.ts +272 -14
  86. package/src/search-index.ts +1 -0
  87. package/src/skill-definition.ts +45 -3
  88. package/src/skill-source.ts +10 -4
  89. package/src/skills.ts +43 -2
  90. package/src/swarm-fs-core.ts +1461 -0
  91. package/src/swarm-fs-path.ts +68 -0
  92. package/src/swarm-fs.ts +104 -0
  93. package/src/swarm-observations.ts +40 -14
  94. package/src/swarm.ts +1538 -656
  95. package/src/unixfs-tree.ts +447 -2
package/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,
@@ -179,7 +212,7 @@ import {
179
212
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
180
213
  import { inspectTemplate, templatePublicationSource } from "./templates.js";
181
214
  import { seedSkillSource } from "./skill-source.js";
182
- import { skillIdentity, skillSchema } from "./skill-definition.js";
215
+ import { inspectSkillBundle, skillSchema } from "./skill-definition.js";
183
216
  import {
184
217
  parseSwarmMeta,
185
218
  swarmMetaType,
@@ -309,6 +342,8 @@ export interface SwarmContext {
309
342
  node?: KuboNode;
310
343
  sourcePeers?: readonly string[];
311
344
  finishRead?: () => Promise<void>;
345
+ pivotSyncError?: string | null;
346
+ pivotReadiness?: NetworkingSnapshot["readiness"];
312
347
  identity?: Identity;
313
348
  listen?: ListenMode;
314
349
  pivot?: boolean;
@@ -438,6 +473,14 @@ function withState<T>(
438
473
  state.close();
439
474
  }
440
475
  }
476
+ export function invalidateSwarmHeader(
477
+ context: SwarmContext,
478
+ configUrl: string,
479
+ ): void {
480
+ withState(context, (state) => {
481
+ state.invalidateSwarmHeader(configUrl);
482
+ });
483
+ }
441
484
  export { canonicalSwarmUrl };
442
485
  function coordinates(configUrl: string): {
443
486
  service: string;
@@ -523,7 +566,7 @@ async function ensureLocalSwarm(
523
566
  const skill = await seedSkillSource();
524
567
  for (const [cid, data] of skill.blocks)
525
568
  await context.store.put(CID.parse(cid), data);
526
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
569
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
527
570
 
528
571
  let currentRoot = CID.parse(
529
572
  await writeV7RootBundle(
@@ -1174,6 +1217,7 @@ export async function swarmNetworking(
1174
1217
  url: string,
1175
1218
  config: Organization,
1176
1219
  directory?: Awaited<ReturnType<typeof memberDirectory>>,
1220
+ currentHeadCid?: string,
1177
1221
  ) {
1178
1222
  rejectLocalSwarm(url, "swarm networking");
1179
1223
  directory ??= (await inspection(context, url)).directory;
@@ -1243,6 +1287,11 @@ export async function swarmNetworking(
1243
1287
  : actual.length
1244
1288
  ? "relay"
1245
1289
  : "disconnected";
1290
+ const readiness = local.snapshot?.readiness?.[member.peerId];
1291
+ const readinessCurrent =
1292
+ local.status === "current" &&
1293
+ readiness &&
1294
+ Date.now() - readiness.observedAt <= 90_000;
1246
1295
  return {
1247
1296
  publicKey: member.publicKey,
1248
1297
  name: profile.name,
@@ -1273,6 +1322,22 @@ export async function swarmNetworking(
1273
1322
  freshness,
1274
1323
  addresses: actual.map((entry) => entry.address),
1275
1324
  },
1325
+ readiness: {
1326
+ status: !readinessCurrent
1327
+ ? "unknown"
1328
+ : !readiness.status
1329
+ ? "unreachable"
1330
+ : readiness.status.ready &&
1331
+ readiness.status.headCid === currentHeadCid
1332
+ ? "ready"
1333
+ : "not-ready",
1334
+ observedAt: readiness
1335
+ ? new Date(readiness.observedAt).toISOString()
1336
+ : null,
1337
+ headCid: readiness?.status?.headCid ?? null,
1338
+ indexedHeadCid: readiness?.status?.indexedHeadCid ?? null,
1339
+ error: readiness?.error ?? readiness?.status?.syncError ?? null,
1340
+ },
1276
1341
  };
1277
1342
  }),
1278
1343
  };
@@ -1294,16 +1359,26 @@ export async function inspectSwarmStatus(
1294
1359
  },
1295
1360
  );
1296
1361
  const templatePrefix = `${meta.templatePath}/`;
1297
- const skillPrefix = meta.skillPath ? `${meta.skillPath}/` : undefined;
1362
+ const globalSkillPrefix = meta.skillPath
1363
+ ? `${meta.skillPath}/global/`
1364
+ : undefined;
1365
+ const typeSkillPrefix = meta.skillPath
1366
+ ? `${meta.skillPath}/types/`
1367
+ : undefined;
1298
1368
  const registryPrefix = `${meta.registryPath}/`;
1299
1369
  let templates = 0;
1300
- let skills = 0;
1370
+ let globalSkills = 0;
1371
+ let typeSkills = 0;
1301
1372
  let registrations = 0;
1302
1373
  for (const entry of walked.entries) {
1303
1374
  if (entry.name.startsWith(templatePrefix)) templates++;
1304
- else if (skillPrefix && entry.name.startsWith(skillPrefix)) skills++;
1375
+ else if (globalSkillPrefix && entry.name.startsWith(globalSkillPrefix))
1376
+ globalSkills++;
1377
+ else if (typeSkillPrefix && entry.name.startsWith(typeSkillPrefix))
1378
+ typeSkills++;
1305
1379
  else if (entry.name.startsWith(registryPrefix)) registrations++;
1306
1380
  }
1381
+ const skills = globalSkills + typeSkills;
1307
1382
  return {
1308
1383
  mode: "local" as const,
1309
1384
  configUrl: LOCAL_SWARM_URL,
@@ -1323,6 +1398,8 @@ export async function inspectSwarmStatus(
1323
1398
  names: walked.entries.length,
1324
1399
  templates,
1325
1400
  skills,
1401
+ globalSkills,
1402
+ typeSkills,
1326
1403
  registrations,
1327
1404
  },
1328
1405
  networking: {
@@ -1366,7 +1443,13 @@ export async function inspectSwarmStatus(
1366
1443
  error:
1367
1444
  "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
1368
1445
  },
1369
- networking: await swarmNetworking(context, url, config, directory),
1446
+ networking: await swarmNetworking(
1447
+ context,
1448
+ url,
1449
+ config,
1450
+ directory,
1451
+ head.root,
1452
+ ),
1370
1453
  };
1371
1454
  }
1372
1455
 
@@ -2009,6 +2092,8 @@ async function privateSource(
2009
2092
  ),
2010
2093
  };
2011
2094
  }
2095
+ const pivotReadinessRefreshIntervalMs = 45_000;
2096
+
2012
2097
  export async function swarmDaemon(
2013
2098
  context: SwarmContext,
2014
2099
  signal: AbortSignal,
@@ -2033,6 +2118,8 @@ export async function swarmDaemon(
2033
2118
  candidates: PivotCandidates;
2034
2119
  nextDiscovery: number;
2035
2120
  nextSync: number;
2121
+ nextReplication?: number;
2122
+ nextPivotSync?: number;
2036
2123
  healthy: number;
2037
2124
  record?: LocalMembership;
2038
2125
  node?: KuboNode;
@@ -2049,6 +2136,7 @@ export async function swarmDaemon(
2049
2136
  nodeApi: string;
2050
2137
  epoch: number;
2051
2138
  headId: string;
2139
+ listening: boolean;
2052
2140
  };
2053
2141
  }
2054
2142
  >();
@@ -2148,7 +2236,7 @@ export async function swarmDaemon(
2148
2236
  : "unknown",
2149
2237
  running: Boolean(session?.running),
2150
2238
  receiptRpc: {
2151
- active: Boolean(session?.pivotServer),
2239
+ active: Boolean(session?.pivotServer?.listening),
2152
2240
  protocol: pivotReceiptProtocol,
2153
2241
  epoch: session?.pivotServer?.epoch ?? null,
2154
2242
  headId: session?.pivotServer?.headId ?? null,
@@ -2263,6 +2351,30 @@ export async function swarmDaemon(
2263
2351
  error: "No connection snapshot collected.",
2264
2352
  peers: [],
2265
2353
  },
2354
+ ...(session.context.pivotReadiness
2355
+ ? {
2356
+ readiness: Object.fromEntries(
2357
+ Object.entries(session.context.pivotReadiness).map(
2358
+ ([peerId, value]) => [
2359
+ peerId,
2360
+ {
2361
+ ...value,
2362
+ error: redact(value.error, session),
2363
+ status: value.status
2364
+ ? {
2365
+ ...value.status,
2366
+ syncError: redact(
2367
+ value.status.syncError,
2368
+ session,
2369
+ ),
2370
+ }
2371
+ : null,
2372
+ },
2373
+ ],
2374
+ ),
2375
+ ),
2376
+ }
2377
+ : {}),
2266
2378
  };
2267
2379
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
2268
2380
  };
@@ -2303,6 +2415,7 @@ export async function swarmDaemon(
2303
2415
  };
2304
2416
  sessions.set(url, session);
2305
2417
  }
2418
+ let pivotListenerVerified = false;
2306
2419
  try {
2307
2420
  if (session.record?.config && context.pivot === undefined) {
2308
2421
  const self = session.record.config.members.find(
@@ -2372,6 +2485,41 @@ export async function swarmDaemon(
2372
2485
  await persist(url, session, true);
2373
2486
  }
2374
2487
  if (!session.node) return;
2488
+ const currentRecord = session.record!;
2489
+ const currentSelf = currentRecord.config!.members.find(
2490
+ (member) => member.publicKey === currentRecord.account,
2491
+ )!;
2492
+ if (
2493
+ !(await nodeReady(session.node, signal, session.context.fetch))
2494
+ ) {
2495
+ if (session.pivotServer) session.pivotServer.listening = false;
2496
+ const currentDesired = memberPeers(
2497
+ currentSelf.peerId,
2498
+ session.candidates.active(),
2499
+ [],
2500
+ );
2501
+ session.node = await startNode(
2502
+ context.stateDir,
2503
+ nodeScope(
2504
+ coordinates(url).service,
2505
+ currentRecord.config!.scopeId,
2506
+ ),
2507
+ currentRecord.secret!.swarmKey,
2508
+ currentRecord.config!.epoch,
2509
+ context.listen,
2510
+ {
2511
+ self: currentSelf.peerId,
2512
+ pivot: session.pivot ?? false,
2513
+ peers: currentDesired,
2514
+ signal,
2515
+ },
2516
+ );
2517
+ session.selected = new Set(currentDesired.map(({ ID }) => ID));
2518
+ session.context.node = session.node;
2519
+ emitDiagnostic(
2520
+ `[${url}] Managed Kubo was offline; restarted before probing peers.`,
2521
+ );
2522
+ }
2375
2523
  let healthy = 0;
2376
2524
  await boundedMap(
2377
2525
  [...session.candidates.active()],
@@ -2409,8 +2557,8 @@ export async function swarmDaemon(
2409
2557
  },
2410
2558
  );
2411
2559
  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.
2560
+ // Reconcile active Pivot Bootstrap candidates via live Kubo RPC
2561
+ // without restarting the daemon unless startup-only config changed.
2414
2562
  const record = session.record!;
2415
2563
  const self = record.config!.members.find(
2416
2564
  (member) => member.publicKey === record.account,
@@ -2435,9 +2583,27 @@ export async function swarmDaemon(
2435
2583
  );
2436
2584
  session.selected = new Set(desired.map(({ ID }) => ID));
2437
2585
  session.context.node = session.node;
2586
+ try {
2587
+ const peers = await nodeConnections(session.node, signal);
2588
+ session.connections = {
2589
+ observedAt: Date.now(),
2590
+ error: null,
2591
+ peers,
2592
+ };
2593
+ } catch (cause) {
2594
+ signal.throwIfAborted();
2595
+ session.connections = {
2596
+ observedAt: session.connections?.observedAt ?? null,
2597
+ error: message(cause).slice(0, 2048),
2598
+ peers: session.connections?.peers ?? [],
2599
+ };
2600
+ }
2601
+ // Persist connectivity before potentially slow content acquisition.
2602
+ await persist(url, session, true);
2438
2603
  if (session.pivot) {
2439
2604
  if (
2440
2605
  !session.pivotServer ||
2606
+ !session.pivotServer.server.listening ||
2441
2607
  session.pivotServer.nodeApi !== session.node.api ||
2442
2608
  session.pivotServer.epoch !== record.config!.epoch ||
2443
2609
  session.pivotServer.headId !== record.config!.headId
@@ -2447,6 +2613,29 @@ export async function swarmDaemon(
2447
2613
  const mounted = await mountPivotServer(
2448
2614
  pivotNode,
2449
2615
  {
2616
+ status: (requestSignal) =>
2617
+ pivotStatus(
2618
+ { ...session.context, node: pivotNode },
2619
+ url,
2620
+ requestSignal,
2621
+ ),
2622
+ replicate: async (request, requestSignal) => {
2623
+ const requestContext = {
2624
+ ...session.context,
2625
+ node: pivotNode,
2626
+ };
2627
+ try {
2628
+ return await handlePivotReplicateRequest(
2629
+ requestContext,
2630
+ url,
2631
+ request,
2632
+ requestSignal,
2633
+ );
2634
+ } finally {
2635
+ session.context.pivotSyncError =
2636
+ requestContext.pivotSyncError ?? null;
2637
+ }
2638
+ },
2450
2639
  receipt: (receiptRequest, requestSignal) =>
2451
2640
  handlePivotReceiptRequest(
2452
2641
  { ...session.context, node: pivotNode },
@@ -2463,35 +2652,112 @@ export async function swarmDaemon(
2463
2652
  : {}),
2464
2653
  },
2465
2654
  session.context.fetch,
2655
+ signal,
2466
2656
  );
2467
2657
  session.pivotServer = {
2468
2658
  server: mounted,
2469
2659
  nodeApi: session.node.api,
2470
2660
  epoch: record.config!.epoch,
2471
2661
  headId: record.config!.headId,
2662
+ listening: true,
2472
2663
  };
2664
+ } else {
2665
+ const remounted = await ensurePivotListener(
2666
+ session.node,
2667
+ session.pivotServer.server.address,
2668
+ signal,
2669
+ session.context.fetch,
2670
+ );
2671
+ session.pivotServer.listening = true;
2672
+ if (remounted) {
2673
+ emitDiagnostic(
2674
+ `[${url}] Re-mounted Pivot P2P listener ${pivotReceiptProtocol} -> ${session.pivotServer.server.address}.`,
2675
+ );
2676
+ }
2473
2677
  }
2474
- await syncPivotPublications(session.context, url, signal);
2678
+ pivotListenerVerified = true;
2475
2679
  } else {
2476
2680
  await stopPivotServer(session);
2477
2681
  }
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
- };
2682
+ const now = Date.now();
2683
+ const replicationIntervalMs = (context.syncInterval ?? 60) * 1000;
2684
+ const knownRemotePivots = session.candidates.observations();
2685
+ const online = new Set([
2686
+ ...[...knownRemotePivots]
2687
+ .filter(([, value]) => value.probe === "success")
2688
+ .map(([peerId]) => peerId),
2689
+ ...session.connections.peers.map((peer) => peer.peerId),
2690
+ ]);
2691
+ const remoteOnline = [...online].filter(
2692
+ (peerId) => peerId !== session.node!.peerId,
2693
+ );
2694
+ const onlineRemotePivots = remoteOnline.filter((peerId) =>
2695
+ knownRemotePivots.has(peerId),
2696
+ );
2697
+ const remoteReadinessDue = onlineRemotePivots.some((peerId) => {
2698
+ const entry = session.context.pivotReadiness?.[peerId];
2699
+ return (
2700
+ !entry ||
2701
+ now - entry.observedAt >= pivotReadinessRefreshIntervalMs
2702
+ );
2703
+ });
2704
+ const replicationDue = now >= (session.nextReplication ?? 0);
2705
+ if (
2706
+ (onlineRemotePivots.length > 0 &&
2707
+ (remoteReadinessDue || replicationDue)) ||
2708
+ (remoteOnline.length > 0 && replicationDue)
2709
+ ) {
2710
+ session.nextReplication = now + replicationIntervalMs;
2711
+ await replicateSwarm(session.context, url, signal, {
2712
+ automatic: true,
2713
+ onlinePeers: online,
2714
+ });
2715
+ }
2716
+ if (session.pivot) {
2717
+ const pivotSyncDue = now >= (session.nextPivotSync ?? 0);
2718
+ const selfReadiness =
2719
+ session.context.pivotReadiness?.[session.node.peerId];
2720
+ const selfReadinessDue =
2721
+ !selfReadiness ||
2722
+ now - selfReadiness.observedAt >=
2723
+ pivotReadinessRefreshIntervalMs;
2724
+ if (pivotSyncDue) {
2725
+ session.nextPivotSync = now + replicationIntervalMs;
2726
+ try {
2727
+ await syncPivotPublications(session.context, url, signal);
2728
+ } finally {
2729
+ if (!signal.aborted) {
2730
+ const status = await pivotStatus(
2731
+ session.context,
2732
+ url,
2733
+ signal,
2734
+ );
2735
+ session.context.pivotReadiness ??= {};
2736
+ session.context.pivotReadiness[session.node.peerId] = {
2737
+ observedAt: Date.now(),
2738
+ status,
2739
+ error: null,
2740
+ };
2741
+ }
2742
+ }
2743
+ } else if (selfReadinessDue) {
2744
+ const status = await pivotStatus(
2745
+ session.context,
2746
+ url,
2747
+ signal,
2748
+ );
2749
+ session.context.pivotReadiness ??= {};
2750
+ session.context.pivotReadiness[session.node.peerId] = {
2751
+ observedAt: Date.now(),
2752
+ status,
2753
+ error: null,
2754
+ };
2755
+ }
2492
2756
  }
2493
2757
  } catch (cause) {
2494
2758
  if (signal.aborted) return;
2759
+ if (!pivotListenerVerified && session.pivotServer)
2760
+ session.pivotServer.listening = false;
2495
2761
  session.error = message(cause);
2496
2762
  session.nextDiscovery = 0;
2497
2763
  emitDiagnostic(
@@ -2801,11 +3067,6 @@ async function readyMembership(
2801
3067
  }
2802
3068
  return record;
2803
3069
  }
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
3070
  function headValue(head: Variable): Variable & { root: string; etag: string } {
2810
3071
  const value = object(head.value, "HEAD");
2811
3072
  if (Object.keys(value).join() !== "root" || typeof value.root !== "string")
@@ -2891,22 +3152,21 @@ async function boundPointer(
2891
3152
  ),
2892
3153
  };
2893
3154
  }
2894
- async function writeNamesHead(
3155
+ export async function writeNamesHead(
2895
3156
  context: SwarmContext,
2896
3157
  url: string,
2897
3158
  head: BoundHead,
2898
3159
  root: string,
2899
3160
  cid: string,
2900
- ): Promise<void> {
3161
+ ): Promise<Variable> {
2901
3162
  if (isLocalSwarm(url)) {
2902
- await head.write(root, cid, uniqueId());
2903
- return;
3163
+ return head.write(root, cid, uniqueId());
2904
3164
  }
2905
3165
  const lock = await privateDirectory(
2906
3166
  await directory(context),
2907
3167
  `state-pin-${createHash("sha256").update(url).digest("hex")}`,
2908
3168
  );
2909
- await withPrivateLock(lock, async () => {
3169
+ return withPrivateLock(lock, async () => {
2910
3170
  if (context.confirmPublication) {
2911
3171
  try {
2912
3172
  await context.confirmPublication(url, root);
@@ -2918,8 +3178,7 @@ async function writeNamesHead(
2918
3178
  "publication",
2919
3179
  );
2920
3180
  }
2921
- await head.write(root, cid, uniqueId());
2922
- return;
3181
+ return head.write(root, cid, uniqueId());
2923
3182
  }
2924
3183
  const idempotencyKey = uniqueId();
2925
3184
  let receipt: ScopeWriteReceipt | null;
@@ -2940,10 +3199,9 @@ async function writeNamesHead(
2940
3199
  );
2941
3200
  }
2942
3201
  if (receipt === null) {
2943
- await head.write(root, cid, idempotencyKey);
2944
- return;
3202
+ return head.write(root, cid, idempotencyKey);
2945
3203
  }
2946
- await head.writeWithReceipt(receipt);
3204
+ return head.writeWithReceipt(receipt);
2947
3205
  });
2948
3206
  }
2949
3207
 
@@ -3273,17 +3531,395 @@ export async function syncPivotPublications(
3273
3531
  kuboSource(node, peers, context.diagnostic),
3274
3532
  );
3275
3533
  try {
3534
+ if (CID.parse(head.root).code === dagPb.code)
3535
+ await pinPublication(source, [head.root], node, signal, context.fetch);
3276
3536
  await readSnapshot(source, head.root, url);
3277
3537
  const roots =
3278
3538
  CID.parse(head.root).code === dagPb.code
3279
3539
  ? [head.root]
3280
3540
  : await frozenPublicationClosure(source, head.root);
3281
3541
  await pinPublication(source, roots, node, signal, context.fetch);
3542
+ await finishPivotReplication(context, url, record, head, source, signal);
3543
+ context.pivotSyncError = null;
3544
+ } catch (cause) {
3545
+ context.pivotSyncError = message(cause).slice(0, 2048);
3546
+ throw cause;
3547
+ } finally {
3548
+ await source.close();
3549
+ }
3550
+ }
3551
+
3552
+ async function localHeadClosure(
3553
+ context: SwarmContext,
3554
+ headCid: string,
3555
+ signal: AbortSignal,
3556
+ url?: string,
3557
+ ): Promise<boolean> {
3558
+ const local = context.store.supportsRetention
3559
+ ? new IpfsStore({
3560
+ dataDir: context.store.configuration.dataDir,
3561
+ limits: context.store.limits,
3562
+ })
3563
+ : context.store;
3564
+ try {
3565
+ await local.prepare(headCid, { signal });
3566
+ if (url) await readSnapshot(local, headCid, url);
3567
+ if (CID.parse(headCid).code !== dagPb.code) {
3568
+ for (const root of await frozenPublicationClosure(local, headCid))
3569
+ await local.prepare(root, { signal });
3570
+ }
3571
+ return true;
3572
+ } catch (cause) {
3573
+ signal.throwIfAborted();
3574
+ if (missingContent(cause)) return false;
3575
+ throw cause;
3576
+ } finally {
3577
+ if (local !== context.store) await local.close();
3578
+ }
3579
+ }
3580
+
3581
+ export async function pivotStatus(
3582
+ context: SwarmContext,
3583
+ url: string,
3584
+ signal: AbortSignal,
3585
+ ): Promise<PivotStatus> {
3586
+ rejectLocalSwarm(url, "Pivot status");
3587
+ const record = await approvedMembership(context, url, signal);
3588
+ const c = coordinates(url);
3589
+ const head = headValue(
3590
+ await client(context, c.service).read(c.scopeId, record.config!.headId, {
3591
+ signal,
3592
+ }),
3593
+ );
3594
+ const indexedHeadCid = withState(
3595
+ context,
3596
+ (state) => state.searchIndexState(url)?.headCid ?? null,
3597
+ );
3598
+ const local = await localHeadClosure(context, head.root, signal, url);
3599
+ const pinned =
3600
+ local &&
3601
+ Boolean(context.node) &&
3602
+ (await isRecursivelyPinned(
3603
+ context.node!,
3604
+ head.root,
3605
+ signal,
3606
+ context.fetch,
3607
+ ));
3608
+ const indexed =
3609
+ CID.parse(head.root).code !== dagPb.code || indexedHeadCid === head.root;
3610
+ return {
3611
+ v: 1,
3612
+ ready: pinned && indexed && !context.pivotSyncError,
3613
+ headCid: pinned ? head.root : null,
3614
+ indexedHeadCid,
3615
+ syncError:
3616
+ context.pivotSyncError ??
3617
+ (!pinned
3618
+ ? "Current HEAD is not fully replicated and recursively pinned."
3619
+ : !indexed
3620
+ ? "Current HEAD is not indexed."
3621
+ : null),
3622
+ };
3623
+ }
3624
+
3625
+ async function finishPivotReplication(
3626
+ context: SwarmContext,
3627
+ url: string,
3628
+ record: LocalMembership,
3629
+ head: ReturnType<typeof headValue>,
3630
+ source: IpfsStore,
3631
+ signal: AbortSignal,
3632
+ ): Promise<void> {
3633
+ const snapshot = await readSnapshot(source, head.root, url);
3634
+ const roots =
3635
+ CID.parse(head.root).code === dagPb.code
3636
+ ? [head.root]
3637
+ : await frozenPublicationClosure(source, head.root);
3638
+ const owner = `daemon-pivot-root:${createHash("sha256").update(url).digest("hex")}`;
3639
+ await retainDaemonRoots(source, owner, roots, signal);
3640
+ const fresh = await approvedMembership(context, url, signal);
3641
+ const c = coordinates(url);
3642
+ const current = headValue(
3643
+ await client(context, c.service).read(c.scopeId, fresh.config!.headId, {
3644
+ signal,
3645
+ }),
3646
+ );
3647
+ if (
3648
+ fresh.config!.epoch !== record.config!.epoch ||
3649
+ fresh.config!.headId !== record.config!.headId ||
3650
+ current.root !== head.root
3651
+ )
3652
+ throw new HostError(
3653
+ "HEAD or membership changed during replication; retry the current HEAD.",
3654
+ );
3655
+ if (CID.parse(head.root).code === dagPb.code) {
3656
+ await syncPivotReplicationAndIndex(
3657
+ { ...context, pivot: true, store: source },
3658
+ url,
3659
+ {
3660
+ head,
3661
+ snapshot,
3662
+ config: fresh.config!,
3663
+ source: "network",
3664
+ verifiedAt: new Date().toISOString(),
3665
+ stateCid: head.root,
3666
+ },
3667
+ signal,
3668
+ );
3669
+ }
3670
+ }
3671
+
3672
+ export async function handlePivotReplicateRequest(
3673
+ context: SwarmContext,
3674
+ url: string,
3675
+ input: unknown,
3676
+ signal: AbortSignal,
3677
+ ): Promise<{ ready: true; headCid: string }> {
3678
+ rejectLocalSwarm(url, "Pivot replicate");
3679
+ const request = parsePivotReplicateRequest(input);
3680
+ const record = await approvedMembership(context, url, signal);
3681
+ const c = coordinates(url);
3682
+ const config = record.config!;
3683
+ if (
3684
+ request.service !== c.service ||
3685
+ request.scopeId !== c.scopeId ||
3686
+ request.headId !== config.headId ||
3687
+ request.epoch !== config.epoch
3688
+ )
3689
+ throw new HostError(
3690
+ "Replicate request does not match the current Swarm configuration.",
3691
+ );
3692
+ if (!config.members.some((member) => member.publicKey === request.member))
3693
+ throw new HostError(
3694
+ "Replicate requester is not an approved Swarm member.",
3695
+ 1,
3696
+ "PIVOT_UNAUTHORIZED",
3697
+ );
3698
+ await verifyPivotReplicateRequest(request);
3699
+ const head = headValue(
3700
+ await client(context, c.service).read(c.scopeId, config.headId, { signal }),
3701
+ );
3702
+ if (head.root !== request.headCid)
3703
+ throw new HostError(
3704
+ "Replicate headCid must equal the current verified HEAD.",
3705
+ );
3706
+ if (!context.node)
3707
+ throw new HostError("Replication requires an active Pivot node.");
3708
+ const status = await pivotStatus(context, url, signal);
3709
+ if (status.ready && status.headCid === head.root)
3710
+ return { ready: true, headCid: head.root };
3711
+ const source = context.store.withLocalSource(
3712
+ kuboSource(context.node, [], context.diagnostic),
3713
+ );
3714
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(120_000)]);
3715
+ try {
3716
+ await pinPublication(
3717
+ source,
3718
+ [head.root],
3719
+ context.node,
3720
+ bounded,
3721
+ context.fetch,
3722
+ );
3723
+ await finishPivotReplication(context, url, record, head, source, bounded);
3724
+ const fresh = await approvedMembership(context, url, bounded);
3725
+ const current = headValue(
3726
+ await client(context, c.service).read(c.scopeId, fresh.config!.headId, {
3727
+ signal: bounded,
3728
+ }),
3729
+ );
3730
+ if (
3731
+ !fresh.config!.members.some(
3732
+ (member) => member.publicKey === request.member,
3733
+ ) ||
3734
+ fresh.config!.epoch !== config.epoch ||
3735
+ fresh.config!.headId !== config.headId ||
3736
+ current.root !== head.root
3737
+ )
3738
+ throw new HostError(
3739
+ "HEAD or requester membership changed during replication; retry.",
3740
+ );
3741
+ context.pivotSyncError = null;
3742
+ return { ready: true, headCid: head.root };
3743
+ } catch (cause) {
3744
+ context.pivotSyncError = message(cause).slice(0, 2048);
3745
+ throw cause;
3282
3746
  } finally {
3283
3747
  await source.close();
3284
3748
  }
3285
3749
  }
3286
3750
 
3751
+ export async function replicateSwarm(
3752
+ context: SwarmContext,
3753
+ url: string,
3754
+ signal: AbortSignal = AbortSignal.timeout(180_000),
3755
+ options: {
3756
+ automatic?: boolean;
3757
+ onlinePeers?: ReadonlySet<string>;
3758
+ pivot?: string;
3759
+ } = {},
3760
+ ) {
3761
+ const { automatic = false, onlinePeers } = options;
3762
+ rejectLocalSwarm(url, "swarm replicate");
3763
+ const record = await approvedMembership(context, url, signal);
3764
+ const c = coordinates(url);
3765
+ const config = record.config!;
3766
+ const head = headValue(
3767
+ await client(context, c.service).read(c.scopeId, config.headId, { signal }),
3768
+ );
3769
+ const members = await memberDirectory(context, url, config);
3770
+ let targets = members.filter(
3771
+ ({ member, profile }) =>
3772
+ member.publicKey !== record.account &&
3773
+ memberIsPivot(config, member, profile) &&
3774
+ (!automatic || !onlinePeers || onlinePeers.has(member.peerId)),
3775
+ );
3776
+ if (options.pivot !== undefined) {
3777
+ const selector = options.pivot;
3778
+ targets = targets.filter(
3779
+ ({ member, profile }) =>
3780
+ member.publicKey === selector ||
3781
+ member.peerId === selector ||
3782
+ profile.name === selector,
3783
+ );
3784
+ if (targets.length !== 1)
3785
+ throw new HostError(
3786
+ `Pivot "${selector}" is ${targets.length ? "ambiguous; use its public key or PeerID" : "not a declared remote Pivot; run swarm members"}.`,
3787
+ );
3788
+ }
3789
+ const results: Array<{
3790
+ peerId: string;
3791
+ status: "ready" | "replicated" | "unreachable" | "failed";
3792
+ error?: string;
3793
+ }> = [];
3794
+ if (!targets.length) {
3795
+ if (!automatic)
3796
+ throw new HostError(
3797
+ "No remote Pivot is declared. Approve a Pivot and run its daemon first.",
3798
+ );
3799
+ return { headCid: head.root, results };
3800
+ }
3801
+ const complete = await localHeadClosure(context, head.root, signal, url);
3802
+ if (!automatic && !complete)
3803
+ throw new HostError(
3804
+ "This member does not hold the complete current HEAD locally; replication was not started.",
3805
+ );
3806
+ if (!context.node) {
3807
+ if (automatic)
3808
+ throw new HostError("Automatic replication requires an active node.");
3809
+ await activate(context, record);
3810
+ }
3811
+ let provided = false;
3812
+ for (const { member, profile } of targets) {
3813
+ const options = {
3814
+ node: context.node!,
3815
+ pivotPeerId: member.peerId,
3816
+ pivotAddresses: automatic ? [] : profile.addresses,
3817
+ signal,
3818
+ ...(context.fetch ? { fetcher: context.fetch } : {}),
3819
+ };
3820
+ let reachable = false;
3821
+ try {
3822
+ if (!automatic)
3823
+ context.diagnostic?.(
3824
+ `Checking Pivot ${profile.name || member.peerId} readiness...`,
3825
+ );
3826
+ const status = await pivotReadinessOverP2p(options);
3827
+ context.pivotReadiness ??= {};
3828
+ context.pivotReadiness[member.peerId] = {
3829
+ observedAt: Date.now(),
3830
+ status: "v" in status ? status : null,
3831
+ error: null,
3832
+ };
3833
+ reachable = true;
3834
+ if (status.ready && status.headCid === head.root) {
3835
+ results.push({ peerId: member.peerId, status: "ready" });
3836
+ if (automatic) continue;
3837
+ break;
3838
+ }
3839
+ if (!complete) continue;
3840
+ if (!provided) {
3841
+ await provideContent(
3842
+ context.store,
3843
+ [head.root],
3844
+ context.node!.api,
3845
+ context.fetch,
3846
+ context.node!.auth,
3847
+ [head.root],
3848
+ signal,
3849
+ );
3850
+ provided = true;
3851
+ }
3852
+ const identity = await contextIdentity(context);
3853
+ const request = await signPivotReplicateRequest(
3854
+ {
3855
+ service: c.service,
3856
+ scopeId: c.scopeId,
3857
+ headId: config.headId,
3858
+ epoch: config.epoch,
3859
+ headCid: head.root,
3860
+ member: identity.publicKey,
3861
+ },
3862
+ identity.privateKey,
3863
+ );
3864
+ context.diagnostic?.(
3865
+ `Replicating ${head.root} to Pivot ${profile.name || member.peerId}...`,
3866
+ );
3867
+ await pivotReadinessOverP2p(options, request);
3868
+ context.pivotReadiness[member.peerId] = {
3869
+ observedAt: Date.now(),
3870
+ status: {
3871
+ v: 1,
3872
+ ready: true,
3873
+ headCid: head.root,
3874
+ indexedHeadCid:
3875
+ CID.parse(head.root).code === dagPb.code ? head.root : null,
3876
+ syncError: null,
3877
+ },
3878
+ error: null,
3879
+ };
3880
+ results.push({ peerId: member.peerId, status: "replicated" });
3881
+ break;
3882
+ } catch (cause) {
3883
+ signal.throwIfAborted();
3884
+ const error = message(cause);
3885
+ const reportError = !automatic || reachable;
3886
+ context.pivotReadiness ??= {};
3887
+ context.pivotReadiness[member.peerId] = {
3888
+ observedAt: Date.now(),
3889
+ status: reachable
3890
+ ? {
3891
+ v: 1,
3892
+ ready: false,
3893
+ headCid: null,
3894
+ indexedHeadCid: null,
3895
+ syncError: error.slice(0, 2048),
3896
+ }
3897
+ : null,
3898
+ error: reportError ? error.slice(0, 2048) : null,
3899
+ };
3900
+ if (reportError)
3901
+ context.diagnostic?.(
3902
+ `Pivot ${member.peerId} replication check failed: ${error}`,
3903
+ );
3904
+ results.push({
3905
+ peerId: member.peerId,
3906
+ status: reachable ? "failed" : "unreachable",
3907
+ error,
3908
+ });
3909
+ }
3910
+ }
3911
+ if (
3912
+ !automatic &&
3913
+ !results.some(
3914
+ (result) => result.status === "ready" || result.status === "replicated",
3915
+ )
3916
+ )
3917
+ throw new HostError(
3918
+ `No Pivot confirmed current HEAD readiness: ${results.map((result) => result.error).join("; ")}`,
3919
+ );
3920
+ return { headCid: head.root, results };
3921
+ }
3922
+
3287
3923
  export async function typedJson(
3288
3924
  store: IpfsStore,
3289
3925
  cid: string,
@@ -3392,57 +4028,6 @@ async function writeV7RootBundle(
3392
4028
  });
3393
4029
  return jsonBundle(store, swarmRootType, value);
3394
4030
  }
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
4031
  async function readV7Root(store: IpfsStore, cid: CID): Promise<Snapshot> {
3447
4032
  const canonical = cid.toV1();
3448
4033
  const rootKey = canonical.toString();
@@ -3747,7 +4332,7 @@ export interface SwarmHeader {
3747
4332
  projection?: SwarmProjection;
3748
4333
  localSourceReady?: boolean;
3749
4334
  }
3750
- function missingContent(cause: unknown): boolean {
4335
+ export function missingContent(cause: unknown): boolean {
3751
4336
  let failure: unknown = cause;
3752
4337
  for (
3753
4338
  let depth = 0;
@@ -4118,7 +4703,7 @@ function headerProjection(header: SwarmHeader): SwarmProjection {
4118
4703
  throw new HostError("A verified account projection is required.");
4119
4704
  return header.projection;
4120
4705
  }
4121
- async function localHeader(context: SwarmContext, url: string) {
4706
+ export async function localHeader(context: SwarmContext, url: string) {
4122
4707
  if (isLocalSwarm(url))
4123
4708
  return { header: await readLocalSwarmHeader(context), account: "local" };
4124
4709
  if (context.forceRefresh) return;
@@ -4170,7 +4755,7 @@ async function localHeader(context: SwarmContext, url: string) {
4170
4755
 
4171
4756
  // SharedContent invokes this source only after a genuine local ENOENT. Its
4172
4757
  // store is not replaced from inside its own pending read (which would deadlock).
4173
- async function lazyPrivateSource(
4758
+ export async function lazyPrivateSource(
4174
4759
  context: SwarmContext,
4175
4760
  url: string,
4176
4761
  account: string,
@@ -4353,7 +4938,7 @@ export async function createSwarm(
4353
4938
  const skill = await seedSkillSource();
4354
4939
  for (const [cid, data] of skill.blocks)
4355
4940
  await context.store.put(CID.parse(cid), data);
4356
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
4941
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
4357
4942
  let root: string;
4358
4943
  if (record.stateVersion === 7) {
4359
4944
  let currentRoot = CID.parse(
@@ -5611,82 +6196,6 @@ export async function resumeRemoval(
5611
6196
  }
5612
6197
  });
5613
6198
  }
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
6199
  export async function resolveReference(
5691
6200
  context: SwarmContext,
5692
6201
  reference: string,
@@ -5771,7 +6280,7 @@ export async function resolveReference(
5771
6280
  );
5772
6281
  }
5773
6282
  }
5774
- async function artifactValue(
6283
+ export async function artifactValue(
5775
6284
  store: IpfsStore,
5776
6285
  targetCid: string,
5777
6286
  protect?: (cid: string) => Promise<void>,
@@ -6317,26 +6826,146 @@ function hasMeta(snapshot: Snapshot): boolean {
6317
6826
  snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab")
6318
6827
  );
6319
6828
  }
6829
+ export const swarmFsTransport: SwarmFsTransport = {
6830
+ pointer,
6831
+ writeNamesHead,
6832
+ readSnapshot,
6833
+ swarmHeader,
6834
+ localHeader,
6835
+ lazyPrivateSource,
6836
+ invalidateSwarmHeader,
6837
+ prepareNamesPublication,
6838
+ missingContent,
6839
+ };
6840
+ const swarmFs = createSwarmFs(swarmFsTransport);
6841
+
6320
6842
  export interface SharedSkill {
6321
6843
  name: string;
6322
6844
  cid: string;
6323
6845
  identity: string;
6846
+ description: string;
6847
+ }
6848
+
6849
+ export interface TypeSkillAssociation {
6850
+ name: string;
6851
+ schemaCid: string;
6852
+ cid: string;
6853
+ identity: string;
6854
+ description: string;
6855
+ }
6856
+
6857
+ export interface SwarmSkillsCatalog {
6858
+ skillPath: string;
6859
+ global: SharedSkill[];
6860
+ types: TypeSkillAssociation[];
6861
+ }
6862
+
6863
+ export interface SetSwarmSkillInput {
6864
+ skillCid: string;
6865
+ global: boolean;
6866
+ types: readonly string[];
6867
+ replace: boolean;
6868
+ }
6869
+
6870
+ export interface SetSwarmSkillTargetResult {
6871
+ scope: "global" | "type";
6872
+ name: string;
6873
+ schemaCid?: string;
6874
+ cid: string;
6875
+ previousCid: string | null;
6876
+ changed: boolean;
6877
+ }
6878
+
6879
+ export interface SetSwarmSkillResult {
6880
+ swarm: string;
6881
+ skillPath: string;
6882
+ cid: string;
6883
+ identity: string;
6884
+ description: string;
6885
+ headCid: string;
6886
+ previousHeadCid: string;
6887
+ rootCid: string;
6888
+ previousRootCid: string;
6889
+ changed: boolean;
6890
+ targets: SetSwarmSkillTargetResult[];
6891
+ }
6892
+
6893
+ export interface RemoveSwarmSkillInput {
6894
+ globalName?: string;
6895
+ types: readonly string[];
6896
+ }
6897
+
6898
+ export interface RemoveSwarmSkillTargetResult {
6899
+ scope: "global" | "type";
6900
+ name: string;
6901
+ schemaCid?: string;
6902
+ removedCid: string;
6903
+ }
6904
+
6905
+ export interface RemoveSwarmSkillResult {
6906
+ swarm: string;
6907
+ skillPath: string;
6908
+ headCid: string;
6909
+ previousHeadCid: string;
6910
+ rootCid: string;
6911
+ previousRootCid: string;
6912
+ changed: boolean;
6913
+ removed: RemoveSwarmSkillTargetResult[];
6914
+ }
6915
+
6916
+ function missingSkillPathError(snapshot: Snapshot): HostError {
6917
+ return new HostError(
6918
+ snapshot.stateBundle
6919
+ ? "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."
6920
+ : `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.`,
6921
+ );
6922
+ }
6923
+
6924
+ function canonicalTypeSkillLeaf(name: string, leaf: string): string {
6925
+ try {
6926
+ if (exactCid(leaf, true) === leaf) return leaf;
6927
+ } catch {
6928
+ // Fall through to typed error below.
6929
+ }
6930
+ throw new HostError(
6931
+ `Type Skill Name "${name}" must use a canonical schema CID.`,
6932
+ );
6933
+ }
6934
+
6935
+ async function inspectDirectTypeSkill(
6936
+ store: IpfsStore,
6937
+ name: string,
6938
+ targetCid: string,
6939
+ ) {
6940
+ let bundle: Awaited<ReturnType<typeof openBundle>>;
6941
+ try {
6942
+ bundle = await openBundle(CID.parse(targetCid), {
6943
+ resolveCid: (key) => store.block.get(key.toString()),
6944
+ });
6945
+ } catch (cause) {
6946
+ if (cause instanceof HostError) throw cause;
6947
+ throw new HostError(
6948
+ `Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
6949
+ );
6950
+ }
6951
+ if (bundle.schemaKey !== skillSchema.cid.toString())
6952
+ throw new HostError(
6953
+ `Type Skill Name "${name}" must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
6954
+ );
6955
+ return inspectSkillBundle(bundle);
6324
6956
  }
6957
+
6325
6958
  export async function swarmSkills(
6326
6959
  context: SwarmContext,
6327
6960
  configUrl: string,
6328
6961
  requested: readonly string[],
6329
6962
  owner: string,
6330
6963
  ): 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));
6964
+ let ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
6965
+ mode: "active",
6966
+ preferLocalCache: true,
6967
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
6968
+ });
6340
6969
  const roots = new Set<string>();
6341
6970
  const protect = async (cid: string) => {
6342
6971
  roots.add(cid);
@@ -6345,34 +6974,26 @@ export async function swarmSkills(
6345
6974
  await context.store.confirmRetained(owner, values);
6346
6975
  };
6347
6976
  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)) {
6977
+ if (hasMeta(ctx.snapshot)) {
6978
+ if (ctx.isV7) {
6354
6979
  if (context.store.supportsRetention) {
6355
- const rootId = metaCid(header.snapshot);
6980
+ const rootId = metaCid(ctx.snapshot);
6356
6981
  await context.store.retainDirect(owner, [rootId]);
6357
6982
  await context.store.confirmDirectRetained(owner, [rootId]);
6358
6983
  }
6359
6984
  } else {
6360
- await protect(metaCid(header.snapshot));
6985
+ await protect(metaCid(ctx.snapshot));
6361
6986
  }
6362
6987
  }
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}/`;
6988
+ const meta = await swarmMeta(context, ctx.header);
6989
+ if (!meta.skillPath) throw missingSkillPathError(ctx.snapshot);
6990
+ const globalDir = `${meta.skillPath}/global`;
6991
+ const prefix = `${globalDir}/`;
6371
6992
  const entries = await listSubtreeNames(
6372
6993
  context.store,
6373
- header.snapshot,
6374
- meta.skillPath,
6375
- true,
6994
+ ctx.snapshot,
6995
+ globalDir,
6996
+ false,
6376
6997
  );
6377
6998
  for (const { cid: target } of entries) roots.add(target.toString());
6378
6999
  await context.store.registerOwnerAsync(owner, [...roots]);
@@ -6381,7 +7002,7 @@ export async function swarmSkills(
6381
7002
  for (const { name, cid: target } of entries) {
6382
7003
  if (name.slice(prefix.length).includes("/"))
6383
7004
  throw new HostError(
6384
- `Skill Name "${name}" must be flat under ${meta.skillPath}.`,
7005
+ `Skill Name "${name}" must be flat under ${globalDir}.`,
6385
7006
  );
6386
7007
  const cid = await artifactValue(
6387
7008
  context.store,
@@ -6395,13 +7016,18 @@ export async function swarmSkills(
6395
7016
  throw new HostError(
6396
7017
  `Name "${name}" is not an exact Skill type Bundle.`,
6397
7018
  );
6398
- const identity = await skillIdentity(bundle);
6399
- if (identities.has(identity))
7019
+ const metadata = await inspectSkillBundle(bundle);
7020
+ if (identities.has(metadata.name))
6400
7021
  throw new HostError(
6401
- `Duplicate Skill installation name "${identity}" in this Swarm.`,
7022
+ `Duplicate Skill installation name "${metadata.name}" in this Swarm.`,
6402
7023
  );
6403
- identities.add(identity);
6404
- result.push({ name, cid, identity });
7024
+ identities.add(metadata.name);
7025
+ result.push({
7026
+ name,
7027
+ cid,
7028
+ identity: metadata.name,
7029
+ description: metadata.description,
7030
+ });
6405
7031
  }
6406
7032
  const missing = requested.filter(
6407
7033
  (reference) =>
@@ -6409,56 +7035,438 @@ export async function swarmSkills(
6409
7035
  (skill) => skill.name === reference || skill.identity === reference,
6410
7036
  ),
6411
7037
  );
6412
- if (missing.length && !attempt && header.source === "cache") {
6413
- header = await swarmHeader(context, configUrl, true);
7038
+ if (missing.length && !attempt && ctx.source === "cache" && !ctx.isLocal) {
7039
+ ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7040
+ mode: "active",
7041
+ forceRefresh: true,
7042
+ });
6414
7043
  continue;
6415
7044
  }
6416
7045
  if (missing.length)
6417
7046
  throw new HostError(
6418
- `Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`,
7047
+ `Skill identities or shared Names not found under ${globalDir}: ${missing.join(", ")}.`,
6419
7048
  );
6420
7049
  return result;
6421
7050
  }
6422
7051
  }
6423
- export async function resolveTemplateSelector(
7052
+
7053
+ export async function swarmTypeSkills(
6424
7054
  context: SwarmContext,
6425
- selector: string,
6426
7055
  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(
7056
+ options: {
7057
+ owner?: string;
7058
+ mode?: SwarmReadMode;
7059
+ forceRefresh?: boolean;
7060
+ } = {},
7061
+ ): Promise<TypeSkillAssociation[]> {
7062
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7063
+ mode: options.mode ?? "local-first",
7064
+ ...(options.forceRefresh !== undefined
7065
+ ? { forceRefresh: options.forceRefresh }
7066
+ : {}),
7067
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
7068
+ });
7069
+ const roots = new Set<string>();
7070
+ if (options.owner && hasMeta(ctx.snapshot)) {
7071
+ const rootId = metaCid(ctx.snapshot);
7072
+ if (ctx.isV7) {
7073
+ if (context.store.supportsRetention) {
7074
+ await context.store.retainDirect(options.owner, [rootId]);
7075
+ await context.store.confirmDirectRetained(options.owner, [rootId]);
7076
+ }
7077
+ } else {
7078
+ roots.add(rootId);
7079
+ await context.store.retain(options.owner, [...roots]);
7080
+ await context.store.confirmRetained(options.owner, [...roots]);
7081
+ }
7082
+ }
7083
+ const meta = await swarmMeta(context, ctx.header);
7084
+ if (!meta.skillPath) throw missingSkillPathError(ctx.snapshot);
7085
+ const typesDir = `${meta.skillPath}/types`;
7086
+ const prefix = `${typesDir}/`;
7087
+ const entries = await listSubtreeNames(
7088
+ context.store,
7089
+ ctx.snapshot,
7090
+ typesDir,
7091
+ false,
7092
+ );
7093
+ if (options.owner) {
7094
+ for (const { cid: target } of entries) roots.add(target.toString());
7095
+ await context.store.registerOwnerAsync(options.owner, [...roots]);
7096
+ }
7097
+ const result: TypeSkillAssociation[] = [];
7098
+ for (const { name, cid: target } of entries) {
7099
+ if (name.slice(prefix.length).includes("/"))
7100
+ throw new HostError(
7101
+ `Type Skill Name "${name}" must be flat under ${typesDir}.`,
7102
+ );
7103
+ const leaf = name.slice(prefix.length);
7104
+ const schemaCid = canonicalTypeSkillLeaf(name, leaf);
7105
+ const targetCid = target.toString();
7106
+ const metadata = await inspectDirectTypeSkill(
6444
7107
  context.store,
6445
- header.snapshot,
6446
7108
  name,
7109
+ targetCid,
6447
7110
  );
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.`,
7111
+ result.push({
7112
+ name,
7113
+ schemaCid,
7114
+ cid: targetCid,
7115
+ identity: metadata.name,
7116
+ description: metadata.description,
7117
+ });
7118
+ }
7119
+ return result.sort((left, right) =>
7120
+ left.schemaCid.localeCompare(right.schemaCid),
7121
+ );
7122
+ }
7123
+
7124
+ export async function swarmTypeSkill(
7125
+ context: SwarmContext,
7126
+ configUrl: string,
7127
+ schemaCid: string,
7128
+ options: {
7129
+ mode?: SwarmReadMode;
7130
+ forceRefresh?: boolean;
7131
+ } = {},
7132
+ ): Promise<TypeSkillAssociation | undefined> {
7133
+ const canonicalSchema = exactCid(schemaCid, true);
7134
+ let cachedHeader: SwarmHeader | undefined;
7135
+ let cachedName: string | undefined;
7136
+ let cachedTarget: CID | undefined;
7137
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7138
+ mode: options.mode ?? "local-first",
7139
+ ...(options.forceRefresh !== undefined
7140
+ ? { forceRefresh: options.forceRefresh }
7141
+ : {}),
7142
+ shouldRefresh: async (current) => {
7143
+ if (!hasMeta(current.snapshot)) return true;
7144
+ await current.ensureLocalSource();
7145
+ const meta = await swarmMeta(context, current.header);
7146
+ if (!meta.skillPath) return false;
7147
+ const name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
7148
+ const target = await resolveSnapshotName(
7149
+ context.store,
7150
+ current.snapshot,
7151
+ name,
6452
7152
  );
6453
- header = await swarmHeader(context, configUrl, true);
7153
+ cachedHeader = current.header;
7154
+ cachedName = name;
7155
+ cachedTarget = target;
7156
+ return !target;
7157
+ },
7158
+ });
7159
+ let name: string;
7160
+ let target: CID | undefined;
7161
+ if (ctx.header === cachedHeader && cachedName !== undefined) {
7162
+ name = cachedName;
7163
+ target = cachedTarget;
7164
+ } else {
7165
+ const meta = await swarmMeta(context, ctx.header);
7166
+ if (!meta.skillPath) throw missingSkillPathError(ctx.snapshot);
7167
+ name = formalName(`${meta.skillPath}/types/${canonicalSchema}`);
7168
+ try {
7169
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
7170
+ } catch (cause) {
7171
+ if (!missingContent(cause)) throw cause;
7172
+ await ctx.ensureLocalSource();
7173
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
7174
+ }
6454
7175
  }
7176
+ if (!target) return undefined;
7177
+ const targetCid = target.toString();
7178
+ const metadata = await inspectDirectTypeSkill(context.store, name, targetCid);
7179
+ return {
7180
+ name,
7181
+ schemaCid: canonicalSchema,
7182
+ cid: targetCid,
7183
+ identity: metadata.name,
7184
+ description: metadata.description,
7185
+ };
6455
7186
  }
6456
- export function templateName(name: string): string {
6457
- if (name.includes(":"))
7187
+
7188
+ export async function setSwarmSkill(
7189
+ context: SwarmContext,
7190
+ configUrl: string,
7191
+ input: SetSwarmSkillInput,
7192
+ ): Promise<SetSwarmSkillResult> {
7193
+ if (!input.global && input.types.length === 0)
7194
+ syntax("skills set requires --global and/or at least one --type SCHEMA.");
7195
+ const skillCid = exactCid(input.skillCid);
7196
+ const canonicalTypes = [
7197
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
7198
+ ].sort((left, right) => left.localeCompare(right));
7199
+ let bundle: Awaited<ReturnType<typeof openBundle>>;
7200
+ try {
7201
+ bundle = await openBundle(CID.parse(skillCid), {
7202
+ resolveCid: (key) => context.store.block.get(key.toString()),
7203
+ });
7204
+ } catch (cause) {
7205
+ if (cause instanceof HostError) throw cause;
7206
+ throw new HostError(
7207
+ `Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
7208
+ );
7209
+ }
7210
+ if (bundle.schemaKey !== skillSchema.cid.toString())
6458
7211
  throw new HostError(
6459
- "Template NAME must be a safe relative Name, not a URI.",
7212
+ `Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
6460
7213
  );
6461
- return formalName(name);
7214
+ const metadata = await inspectSkillBundle(bundle);
7215
+ let expectedSkillPath: string | undefined;
7216
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
7217
+ allowLegacyNames: true,
7218
+ refreshAfterCommit: true,
7219
+ maxAttempts: 8,
7220
+ plan: async (planCtx) => {
7221
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
7222
+ if (!meta.skillPath) throw missingSkillPathError(planCtx.snapshot);
7223
+ if (
7224
+ expectedSkillPath !== undefined &&
7225
+ meta.skillPath !== expectedSkillPath
7226
+ )
7227
+ throw new HostError(
7228
+ "Swarm skillPath changed concurrently; retry ipab skills set.",
7229
+ 3,
7230
+ "EDIT_CONFLICT",
7231
+ "publication",
7232
+ );
7233
+ expectedSkillPath = meta.skillPath;
7234
+ const plannedTargets: Array<{
7235
+ scope: "global" | "type";
7236
+ name: string;
7237
+ schemaCid?: string;
7238
+ }> = [];
7239
+ if (input.global) {
7240
+ const path = formalName(`${meta.skillPath}/global/${metadata.name}`);
7241
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7242
+ plannedTargets.push({ scope: "global", name: path });
7243
+ }
7244
+ for (const schemaCid of canonicalTypes) {
7245
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
7246
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7247
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
7248
+ }
7249
+ const resolvedTargets = await Promise.all(
7250
+ plannedTargets.map(async (target) => ({
7251
+ ...target,
7252
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
7253
+ })),
7254
+ );
7255
+ const conflicts = resolvedTargets.filter(
7256
+ (target) => target.existing !== null && target.existing !== skillCid,
7257
+ );
7258
+ if (conflicts.length > 0 && !input.replace)
7259
+ throw new HostError(
7260
+ `Skill target(s) already point to a different CID (${conflicts.map((target) => target.name).join(", ")}); use --replace to overwrite.`,
7261
+ 3,
7262
+ "EDIT_CONFLICT",
7263
+ "publication",
7264
+ );
7265
+ const pending = resolvedTargets.filter(
7266
+ (target) => target.existing !== skillCid,
7267
+ );
7268
+ const targets: SetSwarmSkillTargetResult[] = resolvedTargets.map(
7269
+ (target) => ({
7270
+ scope: target.scope,
7271
+ name: target.name,
7272
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
7273
+ cid: skillCid,
7274
+ previousCid: target.existing,
7275
+ changed: target.existing !== skillCid,
7276
+ }),
7277
+ );
7278
+ if (pending.length === 0)
7279
+ return {
7280
+ kind: "noop" as const,
7281
+ result: { skillPath: meta.skillPath, targets },
7282
+ };
7283
+ const operations: UnixfsMutation[] = pending.map((target) => ({
7284
+ op: "set" as const,
7285
+ path: target.name,
7286
+ targetCid: CID.parse(skillCid),
7287
+ }));
7288
+ return {
7289
+ kind: "commit" as const,
7290
+ operations,
7291
+ recursiveRoots: [skillCid],
7292
+ retainedRecursive: [skillCid],
7293
+ result: { skillPath: meta.skillPath, targets },
7294
+ };
7295
+ },
7296
+ messages: {
7297
+ unconfirmed: (cause) =>
7298
+ `Skill association unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
7299
+ pinStale: (cause) =>
7300
+ `Skill association committed, but HEAD/subscription refresh failed: ${message(cause)}.`,
7301
+ headBusy: () => "HEAD is busy; retry ipab skills set.",
7302
+ },
7303
+ });
7304
+ return {
7305
+ swarm: committed.swarm,
7306
+ skillPath: committed.result.skillPath,
7307
+ cid: skillCid,
7308
+ identity: metadata.name,
7309
+ description: metadata.description,
7310
+ headCid: committed.headCid,
7311
+ previousHeadCid: committed.previousHeadCid,
7312
+ rootCid: committed.rootCid,
7313
+ previousRootCid: committed.previousRootCid,
7314
+ changed: committed.changed,
7315
+ targets: committed.result.targets,
7316
+ };
7317
+ }
7318
+
7319
+ export async function removeSwarmSkill(
7320
+ context: SwarmContext,
7321
+ configUrl: string,
7322
+ input: RemoveSwarmSkillInput,
7323
+ ): Promise<RemoveSwarmSkillResult> {
7324
+ if (input.globalName === undefined && input.types.length === 0)
7325
+ syntax(
7326
+ "skills remove requires --global NAME and/or at least one --type SCHEMA.",
7327
+ );
7328
+ if (
7329
+ input.globalName !== undefined &&
7330
+ (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(input.globalName) ||
7331
+ input.globalName.length > 64)
7332
+ )
7333
+ syntax(
7334
+ `Invalid global Skill name "${input.globalName}". Expected lowercase kebab-case (1..64 characters).`,
7335
+ );
7336
+ const canonicalTypes = [
7337
+ ...new Set(input.types.map((schema) => exactCid(schema, true))),
7338
+ ].sort((left, right) => left.localeCompare(right));
7339
+ let expectedSkillPath: string | undefined;
7340
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
7341
+ allowLegacyNames: true,
7342
+ refreshAfterCommit: true,
7343
+ maxAttempts: 8,
7344
+ plan: async (planCtx) => {
7345
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
7346
+ if (!meta.skillPath) throw missingSkillPathError(planCtx.snapshot);
7347
+ if (
7348
+ expectedSkillPath !== undefined &&
7349
+ meta.skillPath !== expectedSkillPath
7350
+ )
7351
+ throw new HostError(
7352
+ "Swarm skillPath changed concurrently; retry ipab skills remove.",
7353
+ 3,
7354
+ "EDIT_CONFLICT",
7355
+ "publication",
7356
+ );
7357
+ expectedSkillPath = meta.skillPath;
7358
+ const plannedTargets: Array<{
7359
+ scope: "global" | "type";
7360
+ name: string;
7361
+ schemaCid?: string;
7362
+ }> = [];
7363
+ if (input.globalName !== undefined) {
7364
+ const path = formalName(`${meta.skillPath}/global/${input.globalName}`);
7365
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7366
+ plannedTargets.push({ scope: "global", name: path });
7367
+ }
7368
+ for (const schemaCid of canonicalTypes) {
7369
+ const path = formalName(`${meta.skillPath}/types/${schemaCid}`);
7370
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(path));
7371
+ plannedTargets.push({ scope: "type", schemaCid, name: path });
7372
+ }
7373
+ const resolvedTargets = await Promise.all(
7374
+ plannedTargets.map(async (target) => ({
7375
+ ...target,
7376
+ existing: (await planCtx.resolve(target.name))?.toString() ?? null,
7377
+ })),
7378
+ );
7379
+ const missing = resolvedTargets.filter(
7380
+ (target) => target.existing === null,
7381
+ );
7382
+ if (missing.length > 0)
7383
+ throw new HostError(
7384
+ `Skill target(s) not found: ${missing.map((target) => target.name).join(", ")}.`,
7385
+ 1,
7386
+ "SKILL_NOT_FOUND",
7387
+ "state",
7388
+ );
7389
+ const operations: UnixfsMutation[] = resolvedTargets.map((target) => ({
7390
+ op: "delete" as const,
7391
+ path: target.name,
7392
+ }));
7393
+ const removed: RemoveSwarmSkillTargetResult[] = resolvedTargets.map(
7394
+ (target) => ({
7395
+ scope: target.scope,
7396
+ name: target.name,
7397
+ ...(target.schemaCid ? { schemaCid: target.schemaCid } : {}),
7398
+ removedCid: target.existing!,
7399
+ }),
7400
+ );
7401
+ return {
7402
+ kind: "commit" as const,
7403
+ operations,
7404
+ recursiveRoots: [],
7405
+ retainedRecursive: [],
7406
+ result: { skillPath: meta.skillPath, removed },
7407
+ };
7408
+ },
7409
+ messages: {
7410
+ unconfirmed: (cause) =>
7411
+ `Skill removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
7412
+ pinStale: (cause) =>
7413
+ `Skill removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
7414
+ headBusy: () => "HEAD is busy; retry ipab skills remove.",
7415
+ },
7416
+ });
7417
+ return {
7418
+ swarm: committed.swarm,
7419
+ skillPath: committed.result.skillPath,
7420
+ headCid: committed.headCid,
7421
+ previousHeadCid: committed.previousHeadCid,
7422
+ rootCid: committed.rootCid,
7423
+ previousRootCid: committed.previousRootCid,
7424
+ changed: committed.changed,
7425
+ removed: committed.result.removed,
7426
+ };
7427
+ }
7428
+ export async function resolveTemplateSelector(
7429
+ context: SwarmContext,
7430
+ selector: string,
7431
+ configUrl: string,
7432
+ ): Promise<string> {
7433
+ formalName(selector);
7434
+ let cachedHeader: SwarmHeader | undefined;
7435
+ let cachedName: string | undefined;
7436
+ let cachedTarget: CID | undefined;
7437
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7438
+ mode: "active",
7439
+ preferLocalCache: true,
7440
+ shouldRefresh: async (current) => {
7441
+ if (!hasMeta(current.snapshot)) return true;
7442
+ await current.ensureLocalSource();
7443
+ const meta = await swarmMeta(context, current.header);
7444
+ const name = formalName(`${meta.templatePath}/${selector}`);
7445
+ const target = await resolveSnapshotName(
7446
+ context.store,
7447
+ current.snapshot,
7448
+ name,
7449
+ );
7450
+ cachedHeader = current.header;
7451
+ cachedName = name;
7452
+ cachedTarget = target;
7453
+ return !target;
7454
+ },
7455
+ });
7456
+ let name: string;
7457
+ let target: CID | undefined;
7458
+ if (ctx.header === cachedHeader) {
7459
+ name = cachedName!;
7460
+ target = cachedTarget;
7461
+ } else {
7462
+ const meta = await swarmMeta(context, ctx.header);
7463
+ name = formalName(`${meta.templatePath}/${selector}`);
7464
+ target = await resolveSnapshotName(context.store, ctx.snapshot, name);
7465
+ }
7466
+ if (target) return artifactValue(context.store, target.toString());
7467
+ throw new HostError(
7468
+ `Template Name "${name}" was not found after refreshing HEAD.`,
7469
+ );
6462
7470
  }
6463
7471
  async function templateEntry(
6464
7472
  context: SwarmContext,
@@ -6496,18 +7504,63 @@ async function retainDaemonRoots(
6496
7504
  store: IpfsStore,
6497
7505
  owner: string,
6498
7506
  roots: readonly string[],
7507
+ signal?: AbortSignal,
6499
7508
  ): Promise<void> {
6500
7509
  const unique = [...new Set(roots)];
7510
+ const options: [] | [{ signal: AbortSignal }] = signal ? [{ signal }] : [];
6501
7511
  if (!store.supportsRetention) {
6502
- for (const root of unique) await store.prepare(root);
7512
+ for (const root of unique) await store.prepare(root, ...options);
6503
7513
  return;
6504
7514
  }
6505
- await store.recoverOwner(owner, []);
7515
+ await store.recoverOwner(owner, [], ...options);
6506
7516
  if (unique.length) {
6507
- await store.retain(owner, unique);
6508
- await store.confirmRetained(owner, unique);
7517
+ await store.retain(owner, unique, ...options);
7518
+ await store.confirmRetained(owner, unique, ...options);
7519
+ }
7520
+ await store.reconcile(owner, unique, ...options);
7521
+ }
7522
+ export async function syncSwarmTypeSkills(
7523
+ context: SwarmContext,
7524
+ configUrl: string,
7525
+ header: SwarmHeader,
7526
+ ): Promise<number> {
7527
+ if (!hasMeta(header.snapshot)) return 0;
7528
+ const meta = await swarmMeta(context, header);
7529
+ if (!meta.skillPath) return 0;
7530
+ const typesDir = `${meta.skillPath}/types`;
7531
+ const prefix = `${typesDir}/`;
7532
+ const entries = await listSubtreeNames(
7533
+ context.store,
7534
+ header.snapshot,
7535
+ typesDir,
7536
+ false,
7537
+ );
7538
+ const roots: string[] = [];
7539
+ for (const { name, cid: target } of entries) {
7540
+ if (name.slice(prefix.length).includes("/"))
7541
+ throw new HostError(
7542
+ `Type Skill Name "${name}" must be flat under ${typesDir}.`,
7543
+ );
7544
+ const leaf = name.slice(prefix.length);
7545
+ canonicalTypeSkillLeaf(name, leaf);
7546
+ const targetCid = target.toString();
7547
+ await inspectDirectTypeSkill(context.store, name, targetCid);
7548
+ roots.push(targetCid);
7549
+ }
7550
+ const owner = `daemon-type-skills:${createHash("sha256").update(configUrl).digest("hex")}`;
7551
+ if (roots.length) {
7552
+ if (isV7Snapshot(header.snapshot)) {
7553
+ if (context.store.supportsRetention) {
7554
+ const rootId = metaCid(header.snapshot);
7555
+ await context.store.retainDirect(owner, [rootId]);
7556
+ await context.store.confirmDirectRetained(owner, [rootId]);
7557
+ }
7558
+ } else {
7559
+ roots.unshift(metaCid(header.snapshot));
7560
+ }
6509
7561
  }
6510
- await store.reconcile(owner, unique);
7562
+ await retainDaemonRoots(context.store, owner, roots);
7563
+ return entries.length;
6511
7564
  }
6512
7565
  export async function syncSwarmTemplates(
6513
7566
  context: SwarmContext,
@@ -6584,6 +7637,22 @@ export async function syncPivotReplicationAndIndex(
6584
7637
  signal?: AbortSignal,
6585
7638
  ): Promise<void> {
6586
7639
  if (!context.pivot || !isV7Snapshot(header.snapshot)) return;
7640
+ const lock = await privateDirectory(
7641
+ context.stateDir,
7642
+ `pivot-index-${createHash("sha256").update(configUrl).digest("hex")}`,
7643
+ );
7644
+ return withPrivateLock(
7645
+ lock,
7646
+ () => updatePivotReplicationAndIndex(context, configUrl, header, signal),
7647
+ signal,
7648
+ );
7649
+ }
7650
+ async function updatePivotReplicationAndIndex(
7651
+ context: SwarmContext,
7652
+ configUrl: string,
7653
+ header: SwarmHeader,
7654
+ signal?: AbortSignal,
7655
+ ): Promise<void> {
6587
7656
  const headCid = CID.parse(header.stateCid).toV1().toString();
6588
7657
  const previousHead = withState(
6589
7658
  context,
@@ -6593,7 +7662,7 @@ export async function syncPivotReplicationAndIndex(
6593
7662
  await pinAdd(context.node, headCid, true, signal);
6594
7663
  }
6595
7664
  const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
6596
- await retainDaemonRoots(context.store, owner, [headCid]);
7665
+ await retainDaemonRoots(context.store, owner, [headCid], signal);
6597
7666
  await withStateAsync(context, (state) =>
6598
7667
  indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
6599
7668
  skipRootFiles: v7RootSkipFiles(header.snapshot),
@@ -6610,52 +7679,38 @@ export async function swarmTemplates(
6610
7679
  selector?: string,
6611
7680
  ) {
6612
7681
  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
- }
7682
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7683
+ mode: "local-first",
7684
+ preferLocalCache: true,
7685
+ shouldRefresh: async (current) => {
7686
+ if (!hasMeta(current.snapshot)) return true;
7687
+ if (selector === undefined) return false;
7688
+ await current.ensureLocalSource();
7689
+ const meta = await swarmMeta(context, current.header);
7690
+ const name = formalName(`${meta.templatePath}/${selector}`);
7691
+ return !(await resolveSnapshotName(
7692
+ context.store,
7693
+ current.snapshot,
7694
+ name,
7695
+ ));
7696
+ },
7697
+ });
7698
+ const meta = await swarmMeta(context, ctx.header);
7699
+ const selectors =
7700
+ selector === undefined
7701
+ ? (
7702
+ await listSubtreeNames(
7703
+ context.store,
7704
+ ctx.snapshot,
7705
+ meta.templatePath,
7706
+ false,
7707
+ )
7708
+ ).map((entry) => entry.name.slice(meta.templatePath.length + 1))
7709
+ : [selector];
7710
+ const items = [];
7711
+ for (const item of selectors)
7712
+ items.push(await templateEntry(context, configUrl, ctx.header, item));
7713
+ return items;
6659
7714
  }
6660
7715
  export async function setSwarmTemplate(
6661
7716
  context: SwarmContext,
@@ -6665,7 +7720,7 @@ export async function setSwarmTemplate(
6665
7720
  expect?: string,
6666
7721
  ) {
6667
7722
  templateName(selector);
6668
- await pointer(context, configUrl);
7723
+ await swarmFsTransport.pointer(context, configUrl);
6669
7724
  const content = await templatePublicationSource(source, context.store);
6670
7725
  const details = await inspectTemplate(context.store, content);
6671
7726
  let location:
@@ -6706,87 +7761,58 @@ export async function removeSwarmTemplate(
6706
7761
  ) {
6707
7762
  templateName(selector);
6708
7763
  const expected = exactCid(expect);
6709
- const head = await pointer(context, configUrl);
6710
7764
  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(
7765
+ const committed = await swarmFs.commitSwarmPaths(context, configUrl, {
7766
+ allowLegacyNames: true,
7767
+ refreshAfterCommit: true,
7768
+ plan: async (planCtx) => {
7769
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
7770
+ const name = formalName(`${meta.templatePath}/${selector}`);
7771
+ if (basis !== undefined && basis !== name)
7772
+ throw new HostError(
7773
+ "Template Meta path changed during removal; inspect and retry.",
7774
+ 3,
7775
+ "EDIT_CONFLICT",
7776
+ "publication",
7777
+ );
7778
+ basis = name;
7779
+ const old = (await planCtx.resolve(name))?.toString();
7780
+ if (!old)
7781
+ throw new HostError(
7782
+ `Template Name "${name}" is missing; nothing was removed.`,
7783
+ );
7784
+ if (old !== expected)
7785
+ throw new HostError(
7786
+ `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
7787
+ 3,
7788
+ "EDIT_CONFLICT",
7789
+ "publication",
7790
+ );
7791
+ return {
7792
+ kind: "commit",
7793
+ operations: [{ op: "delete", path: name }],
7794
+ recursiveRoots: [],
7795
+ retainedRecursive: [],
7796
+ result: {
7797
+ swarm: configUrl,
7798
+ templatePath: meta.templatePath,
7799
+ metaCid: metaCid(planCtx.snapshot),
7800
+ selector,
7801
+ name,
7802
+ reference: formatNameReference(configUrl, name),
7803
+ targetCid: old,
7804
+ },
7805
+ };
7806
+ },
7807
+ messages: {
7808
+ unconfirmed: (cause) =>
6763
7809
  `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(
7810
+ pinStale: (cause) =>
6773
7811
  `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.");
7812
+ headBusy: () => "HEAD is busy; retry the template removal.",
7813
+ },
7814
+ });
7815
+ return committed.result;
6790
7816
  }
6791
7817
  async function registryAssociations(
6792
7818
  context: SwarmContext,
@@ -6819,10 +7845,11 @@ export async function swarmRegistrations(
6819
7845
  context: SwarmContext,
6820
7846
  configUrl: string,
6821
7847
  ): 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);
7848
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7849
+ mode: "active",
7850
+ shouldRefresh: (current) => !hasMeta(current.snapshot),
7851
+ });
7852
+ return registryAssociations(context, ctx.header);
6826
7853
  }
6827
7854
  export async function swarmAssociation(
6828
7855
  context: SwarmContext,
@@ -6830,18 +7857,6 @@ export async function swarmAssociation(
6830
7857
  schemaCid: string,
6831
7858
  mode: "active" | "local-first" = "active",
6832
7859
  ): 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
7860
  const findAssociation = async (
6846
7861
  current: SwarmHeader,
6847
7862
  ): Promise<Association | undefined> => {
@@ -6860,74 +7875,24 @@ export async function swarmAssociation(
6860
7875
  (item) => item.schemaCid === schemaCid,
6861
7876
  );
6862
7877
  };
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);
7878
+ let cachedHeader: SwarmHeader | undefined;
7879
+ let cachedResult: Association | undefined;
7880
+ const ctx = await swarmFs.readSwarmFsSnapshot(context, configUrl, {
7881
+ mode: "active",
7882
+ preferLocalCache: mode === "local-first",
7883
+ shouldRefresh: async (current) => {
7884
+ if (!hasMeta(current.snapshot)) return true;
7885
+ await current.ensureLocalSource();
7886
+ cachedHeader = current.header;
7887
+ cachedResult = await findAssociation(current.header);
7888
+ return !cachedResult;
7889
+ },
6927
7890
  });
6928
- return newRootCid.toString();
7891
+ return ctx.header === cachedHeader
7892
+ ? cachedResult
7893
+ : findAssociation(ctx.header);
6929
7894
  }
6930
- async function prepareNamesPublication(
7895
+ export async function prepareNamesPublication(
6931
7896
  context: SwarmContext,
6932
7897
  configUrl: string,
6933
7898
  current: Snapshot,
@@ -6962,7 +7927,7 @@ async function editSwarmAssociation(
6962
7927
  association: Association | undefined,
6963
7928
  replace: boolean,
6964
7929
  ): Promise<void> {
6965
- const head = await pointer(context, configUrl);
7930
+ await swarmFsTransport.pointer(context, configUrl);
6966
7931
  if (association) {
6967
7932
  const app = await openBundle(CID.parse(association.appCid), {
6968
7933
  resolveCid: (cid) => context.store.block.get(cid.toString()),
@@ -6975,71 +7940,46 @@ async function editSwarmAssociation(
6975
7940
  const roots = association
6976
7941
  ? await dependencies(context.store, association.appCid)
6977
7942
  : 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)
7943
+ await swarmFs.commitSwarmPaths(context, configUrl, {
7944
+ allowLegacyNames: true,
7945
+ refreshAfterCommit: false,
7946
+ plan: async (planCtx) => {
7947
+ assertNamesRegistry(planCtx.snapshot);
7948
+ const meta = await swarmMeta(context, { snapshot: planCtx.snapshot });
7949
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
7950
+ const oldCid = (await planCtx.resolve(name))?.toString();
7951
+ if (association) {
7952
+ if (oldCid === association.appCid)
7953
+ return { kind: "noop", result: undefined };
7954
+ if (oldCid && !replace)
7955
+ throw new HostError("Schema has another association; use --replace.");
7956
+ return {
7957
+ kind: "commit",
7958
+ operations: [
7959
+ { op: "set", path: name, targetCid: CID.parse(association.appCid) },
7960
+ ],
7961
+ recursiveRoots: roots,
7962
+ result: undefined,
7963
+ };
7964
+ }
7965
+ if (!oldCid)
7031
7966
  throw new HostError(
7032
- `Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`,
7033
- 1,
7034
- "HEAD_UNCONFIRMED",
7035
- "publication",
7967
+ "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
7036
7968
  );
7037
- continue;
7038
- }
7039
- }
7040
- throw new HostError(
7041
- `HEAD is busy for ${configUrl}; retry the registry edit.`,
7042
- );
7969
+ return {
7970
+ kind: "commit",
7971
+ operations: [{ op: "delete", path: name }],
7972
+ recursiveRoots: [],
7973
+ retainedRecursive: [],
7974
+ result: undefined,
7975
+ };
7976
+ },
7977
+ messages: {
7978
+ unconfirmed: (cause, url) =>
7979
+ `Registry publication unconfirmed for ${url}: ${message(cause)}. Inspect the Swarm registry before retry.`,
7980
+ headBusy: (url) => `HEAD is busy for ${url}; retry the registry edit.`,
7981
+ },
7982
+ });
7043
7983
  }
7044
7984
  export async function setSwarmAssociation(
7045
7985
  context: SwarmContext,
@@ -7194,64 +8134,38 @@ export async function unpublish(
7194
8134
  );
7195
8135
  const name = formalName(options.name);
7196
8136
  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(
8137
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
8138
+ allowLegacyNames: true,
8139
+ refreshAfterCommit: true,
8140
+ plan: async (planCtx) => {
8141
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
8142
+ const old = (await planCtx.resolve(name))?.toString();
8143
+ if (!old)
8144
+ throw new HostError(`Name "${name}" is missing; nothing was removed.`);
8145
+ if (old !== expected)
8146
+ throw new HostError(
8147
+ `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
8148
+ 3,
8149
+ "EDIT_CONFLICT",
8150
+ "publication",
8151
+ );
8152
+ return {
8153
+ kind: "commit",
8154
+ operations: [{ op: "delete", path: name }],
8155
+ recursiveRoots: [],
8156
+ retainedRecursive: [],
8157
+ result: { name, targetCid: old },
8158
+ };
8159
+ },
8160
+ messages: {
8161
+ unconfirmed: (cause) =>
7236
8162
  `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(
8163
+ pinStale: (cause) =>
7246
8164
  `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.");
8165
+ headBusy: () => "HEAD is busy; retry unpublish.",
8166
+ },
8167
+ });
8168
+ return committed.result;
7255
8169
  }
7256
8170
  export async function publish(
7257
8171
  context: SwarmContext,
@@ -7280,7 +8194,7 @@ async function publishContent(
7280
8194
  throw new HostError(
7281
8195
  "Publication requires a selected Swarm configuration URL or alias.",
7282
8196
  );
7283
- const head = await pointer(context, options.swarm);
8197
+ await swarmFsTransport.pointer(context, options.swarm);
7284
8198
  const roots = await dependencies(context.store, content);
7285
8199
  const currentRoots = [...(await currentDependencies(context.store, content))];
7286
8200
  await withStateAsync(context, (state) =>
@@ -7309,84 +8223,52 @@ async function publishContent(
7309
8223
  timestamp: new Date().toISOString(),
7310
8224
  });
7311
8225
  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)
8226
+ const expectedDeps = expected
8227
+ ? await dependencies(context.store, expected)
8228
+ : undefined;
8229
+ if (expectedDeps) for (const root of expectedDeps) roots.add(root);
8230
+ const retained = [candidate, ...(expectedDeps ?? [])];
8231
+ const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
8232
+ allowLegacyNames: true,
8233
+ refreshAfterCommit: true,
8234
+ plan: async (planCtx) => {
8235
+ if (nameForSnapshot) {
8236
+ name = await nameForSnapshot(planCtx.snapshot);
8237
+ if (resolvedName !== undefined && resolvedName !== name)
8238
+ throw new HostError(
8239
+ "Template Meta path changed during publication; inspect and retry. Content remains pinned.",
8240
+ 3,
8241
+ "EDIT_CONFLICT",
8242
+ "publication",
8243
+ );
8244
+ resolvedName = name;
8245
+ }
8246
+ assertWritableSwarmFsPath(planCtx.snapshot, normalizeSwarmFsPath(name));
8247
+ const existing = (await planCtx.resolve(name))?.toString();
8248
+ if (existing !== expected)
7325
8249
  throw new HostError(
7326
- "Template Meta path changed during publication; inspect and retry. Content remains pinned.",
8250
+ `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
8251
  3,
7328
8252
  "EDIT_CONFLICT",
7329
8253
  "publication",
7330
8254
  );
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(
8255
+ return {
8256
+ kind: "commit",
8257
+ operations: [
8258
+ { op: "set", path: name, targetCid: CID.parse(candidate) },
8259
+ ],
8260
+ recursiveRoots: roots,
8261
+ retainedRecursive: retained,
8262
+ result: candidate,
8263
+ };
8264
+ },
8265
+ messages: {
8266
+ unconfirmed: (cause) =>
8267
+ `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
8268
+ pinStale: (cause) =>
7383
8269
  `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.`);
8270
+ headBusy: () => `HEAD is busy; candidate ${candidate} remains retained.`,
8271
+ },
8272
+ });
8273
+ return committed.result;
7392
8274
  }