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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +24 -11
  2. package/dist/authoring.d.ts +7 -0
  3. package/dist/authoring.d.ts.map +1 -1
  4. package/dist/authoring.js +85 -5
  5. package/dist/authoring.js.map +1 -1
  6. package/dist/builtins/skill.ipab.car +0 -0
  7. package/dist/builtins/template.bundle-viewer.car +0 -0
  8. package/dist/builtins/template.check.car +0 -0
  9. package/dist/builtins/template.node.car +0 -0
  10. package/dist/builtins/template.web-app.car +0 -0
  11. package/dist/bundled-skills.d.ts +1 -1
  12. package/dist/cli.d.ts +2 -1
  13. package/dist/cli.d.ts.map +1 -1
  14. package/dist/cli.js +904 -183
  15. package/dist/cli.js.map +1 -1
  16. package/dist/config-secret.js +1 -1
  17. package/dist/config-secret.js.map +1 -1
  18. package/dist/config.d.ts +4 -0
  19. package/dist/config.d.ts.map +1 -1
  20. package/dist/config.js +17 -2
  21. package/dist/config.js.map +1 -1
  22. package/dist/daemon-ui.d.ts +1 -0
  23. package/dist/daemon-ui.d.ts.map +1 -1
  24. package/dist/daemon-ui.js +2 -0
  25. package/dist/daemon-ui.js.map +1 -1
  26. package/dist/doctor.d.ts.map +1 -1
  27. package/dist/doctor.js +7 -3
  28. package/dist/doctor.js.map +1 -1
  29. package/dist/get.d.ts.map +1 -1
  30. package/dist/get.js +1 -1
  31. package/dist/get.js.map +1 -1
  32. package/dist/history.d.ts +3 -1
  33. package/dist/history.d.ts.map +1 -1
  34. package/dist/history.js +16 -1
  35. package/dist/history.js.map +1 -1
  36. package/dist/kubo-topology.d.ts +2 -0
  37. package/dist/kubo-topology.d.ts.map +1 -1
  38. package/dist/kubo-topology.js +17 -20
  39. package/dist/kubo-topology.js.map +1 -1
  40. package/dist/kubo.d.ts +5 -3
  41. package/dist/kubo.d.ts.map +1 -1
  42. package/dist/kubo.js +83 -13
  43. package/dist/kubo.js.map +1 -1
  44. package/dist/name-reference.d.ts +8 -0
  45. package/dist/name-reference.d.ts.map +1 -0
  46. package/dist/name-reference.js +63 -0
  47. package/dist/name-reference.js.map +1 -0
  48. package/dist/pivot-rpc.d.ts +37 -2
  49. package/dist/pivot-rpc.d.ts.map +1 -1
  50. package/dist/pivot-rpc.js +188 -8
  51. package/dist/pivot-rpc.js.map +1 -1
  52. package/dist/search-index.d.ts.map +1 -1
  53. package/dist/search-index.js +1 -0
  54. package/dist/search-index.js.map +1 -1
  55. package/dist/skill-definition.d.ts +9 -0
  56. package/dist/skill-definition.d.ts.map +1 -1
  57. package/dist/skill-definition.js +26 -2
  58. package/dist/skill-definition.js.map +1 -1
  59. package/dist/skill-source.d.ts +1 -0
  60. package/dist/skill-source.d.ts.map +1 -1
  61. package/dist/skill-source.js +10 -4
  62. package/dist/skill-source.js.map +1 -1
  63. package/dist/skills.d.ts +9 -3
  64. package/dist/skills.d.ts.map +1 -1
  65. package/dist/skills.js +31 -2
  66. package/dist/skills.js.map +1 -1
  67. package/dist/state.d.ts +20 -0
  68. package/dist/state.d.ts.map +1 -1
  69. package/dist/state.js +87 -3
  70. package/dist/state.js.map +1 -1
  71. package/dist/swarm-fs-core.d.ts +217 -0
  72. package/dist/swarm-fs-core.d.ts.map +1 -0
  73. package/dist/swarm-fs-core.js +885 -0
  74. package/dist/swarm-fs-core.js.map +1 -0
  75. package/dist/swarm-fs-path.d.ts +17 -0
  76. package/dist/swarm-fs-path.d.ts.map +1 -0
  77. package/dist/swarm-fs-path.js +46 -0
  78. package/dist/swarm-fs-path.js.map +1 -0
  79. package/dist/swarm-fs.d.ts +9 -0
  80. package/dist/swarm-fs.d.ts.map +1 -0
  81. package/dist/swarm-fs.js +21 -0
  82. package/dist/swarm-fs.js.map +1 -0
  83. package/dist/swarm-observations.d.ts +6 -0
  84. package/dist/swarm-observations.d.ts.map +1 -1
  85. package/dist/swarm-observations.js +28 -8
  86. package/dist/swarm-observations.js.map +1 -1
  87. package/dist/swarm.d.ts +192 -17
  88. package/dist/swarm.d.ts.map +1 -1
  89. package/dist/swarm.js +1360 -442
  90. package/dist/swarm.js.map +1 -1
  91. package/dist/unixfs-tree.d.ts +55 -0
  92. package/dist/unixfs-tree.d.ts.map +1 -1
  93. package/dist/unixfs-tree.js +361 -2
  94. package/dist/unixfs-tree.js.map +1 -1
  95. package/package.json +5 -5
  96. package/src/authoring.ts +125 -8
  97. package/src/cli.ts +1215 -281
  98. package/src/config-secret.ts +1 -1
  99. package/src/config.ts +20 -2
  100. package/src/daemon-ui.ts +3 -0
  101. package/src/doctor.ts +12 -2
  102. package/src/get.ts +2 -1
  103. package/src/history.ts +26 -1
  104. package/src/kubo-topology.ts +25 -22
  105. package/src/kubo.ts +127 -9
  106. package/src/name-reference.ts +91 -0
  107. package/src/pivot-rpc.ts +272 -14
  108. package/src/search-index.ts +1 -0
  109. package/src/skill-definition.ts +45 -3
  110. package/src/skill-source.ts +10 -4
  111. package/src/skills.ts +43 -2
  112. package/src/state.ts +117 -2
  113. package/src/swarm-fs-core.ts +1461 -0
  114. package/src/swarm-fs-path.ts +68 -0
  115. package/src/swarm-fs.ts +104 -0
  116. package/src/swarm-observations.ts +40 -14
  117. package/src/swarm.ts +1950 -727
  118. package/src/unixfs-tree.ts +447 -2
package/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,
@@ -57,33 +57,58 @@ import {
57
57
  type Identity,
58
58
  } from "./identity.js";
59
59
  import { nodeError } from "./authoring.js";
60
- import { swarmUrl as canonicalSwarmUrl } from "./config.js";
61
60
  import {
62
- bundleJson,
63
- contentCar,
64
- provideContent,
65
- provideShallowContent,
66
- } from "./content-provider.js";
61
+ LOCAL_SWARM_ALIAS,
62
+ LOCAL_SWARM_URL,
63
+ isLocalSwarm,
64
+ isReservedLocalHost,
65
+ swarmUrl as canonicalSwarmUrl,
66
+ } from "./config.js";
67
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
67
68
  import {
68
- deleteUnixfsPath,
69
- listUnixfsDirectory,
70
- resolveUnixfsPath,
71
69
  setUnixfsPath,
72
70
  walkUnixfsNames,
71
+ type UnixfsMutation,
73
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
+ };
74
93
  import {
75
94
  parsePublicationPins,
76
95
  pinPublication,
77
96
  type PublicationPins,
78
97
  } from "./pivot-service.js";
79
98
  import {
99
+ ensurePivotListener,
80
100
  mountPivotServer,
101
+ parsePivotReplicateRequest,
102
+ pivotReadinessOverP2p,
81
103
  parsePivotReceiptRequest,
82
104
  requestPivotReceiptOverP2p,
83
105
  signPivotReceiptRequest,
106
+ signPivotReplicateRequest,
107
+ verifyPivotReplicateRequest,
84
108
  verifyPivotReceiptRequest,
85
109
  type PivotReceiptRequest,
86
110
  type PivotServer,
111
+ type PivotStatus,
87
112
  } from "./pivot-rpc.js";
88
113
  import {
89
114
  failedPin,
@@ -92,13 +117,26 @@ import {
92
117
  reservePin,
93
118
  retainPin,
94
119
  } from "./pins.js";
95
- 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";
96
133
  import { appSchemaCid } from "./app-definition.js";
97
134
  import {
98
135
  State,
99
136
  createAssociation,
100
137
  exactCid,
101
138
  type Association,
139
+ type LocalSwarmRecord,
102
140
  type SwarmProjection,
103
141
  } from "./state.js";
104
142
  import {
@@ -123,8 +161,10 @@ import {
123
161
  import {
124
162
  checkCachedNode,
125
163
  kuboSource,
164
+ nodeReady,
126
165
  peerId,
127
166
  pinAdd,
167
+ isRecursivelyPinned,
128
168
  pinRm,
129
169
  prepareNode,
130
170
  startNode,
@@ -172,7 +212,7 @@ import {
172
212
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
173
213
  import { inspectTemplate, templatePublicationSource } from "./templates.js";
174
214
  import { seedSkillSource } from "./skill-source.js";
175
- import { skillIdentity, skillSchema } from "./skill-definition.js";
215
+ import { inspectSkillBundle, skillSchema } from "./skill-definition.js";
176
216
  import {
177
217
  parseSwarmMeta,
178
218
  swarmMetaType,
@@ -302,6 +342,8 @@ export interface SwarmContext {
302
342
  node?: KuboNode;
303
343
  sourcePeers?: readonly string[];
304
344
  finishRead?: () => Promise<void>;
345
+ pivotSyncError?: string | null;
346
+ pivotReadiness?: NetworkingSnapshot["readiness"];
305
347
  identity?: Identity;
306
348
  listen?: ListenMode;
307
349
  pivot?: boolean;
@@ -431,6 +473,14 @@ function withState<T>(
431
473
  state.close();
432
474
  }
433
475
  }
476
+ export function invalidateSwarmHeader(
477
+ context: SwarmContext,
478
+ configUrl: string,
479
+ ): void {
480
+ withState(context, (state) => {
481
+ state.invalidateSwarmHeader(configUrl);
482
+ });
483
+ }
434
484
  export { canonicalSwarmUrl };
435
485
  function coordinates(configUrl: string): {
436
486
  service: string;
@@ -477,12 +527,185 @@ async function saveLocal(
477
527
  membership,
478
528
  );
479
529
  }
530
+ export const LOCAL_SWARM_HOLD_OWNER = "local-swarm-head";
531
+ const LOCAL_SWARM_NAME = "Local";
532
+ const LOCAL_SWARM_DESCRIPTION = "Built-in single-machine Swarm";
533
+ const LOCAL_SWARM_ORG: Organization = {
534
+ v: 3,
535
+ scopeId: "0000000000000000",
536
+ owner: "local",
537
+ name: LOCAL_SWARM_NAME,
538
+ description: LOCAL_SWARM_DESCRIPTION,
539
+ headId: "0000000000000000",
540
+ epoch: 1,
541
+ bootstrap: [],
542
+ members: [],
543
+ };
544
+
545
+ function rejectLocalSwarm(url: string, action: string): void {
546
+ if (isLocalSwarm(url) || isReservedLocalHost(url)) {
547
+ throw new HostError(
548
+ `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support ${action}.`,
549
+ );
550
+ }
551
+ }
552
+
553
+ async function ensureLocalSwarm(
554
+ context: SwarmContext,
555
+ ): Promise<LocalSwarmRecord> {
556
+ const existing = withState(context, (state) => state.localSwarmHead());
557
+ if (existing) return existing;
558
+
559
+ const names: Record<string, CID> = {};
560
+ for (const selector of seedTemplateNames) {
561
+ const template = await seedTemplateSource(selector);
562
+ for (const [cid, data] of template.blocks)
563
+ await context.store.put(CID.parse(cid), data);
564
+ names[`ipab/templates/${selector}`] = CID.parse(template.cid);
565
+ }
566
+ const skill = await seedSkillSource();
567
+ for (const [cid, data] of skill.blocks)
568
+ await context.store.put(CID.parse(cid), data);
569
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
570
+
571
+ let currentRoot = CID.parse(
572
+ await writeV7RootBundle(
573
+ context.store,
574
+ {
575
+ templatePath: "ipab/templates",
576
+ registryPath: "ipab/registry",
577
+ skillPath: "ipab/skills",
578
+ },
579
+ LOCAL_SWARM_URL,
580
+ ),
581
+ );
582
+ for (const [path, targetCid] of Object.entries(names)) {
583
+ currentRoot = (
584
+ await setUnixfsPath(context.store, currentRoot, path, targetCid)
585
+ ).newRootCid;
586
+ }
587
+ const root = currentRoot.toString();
588
+ const valCid = await valueCid({ root });
589
+ const now = new Date().toISOString();
590
+
591
+ if (context.store.supportsRetention) {
592
+ await context.store.retain(LOCAL_SWARM_HOLD_OWNER, [root]);
593
+ await context.store.confirmRetained(LOCAL_SWARM_HOLD_OWNER, [root]);
594
+ }
595
+ const { record, inserted } = withState(context, (state) =>
596
+ state.initLocalSwarmHead({
597
+ headCid: root,
598
+ valueCid: valCid,
599
+ createdAt: now,
600
+ updatedAt: now,
601
+ }),
602
+ );
603
+ if (context.store.supportsRetention) {
604
+ if (!inserted && record.headCid !== root) {
605
+ await context.store.retain(LOCAL_SWARM_HOLD_OWNER, [record.headCid]);
606
+ await context.store.confirmRetained(LOCAL_SWARM_HOLD_OWNER, [
607
+ record.headCid,
608
+ ]);
609
+ }
610
+ await context.store.reconcile(LOCAL_SWARM_HOLD_OWNER, [record.headCid]);
611
+ }
612
+ return record;
613
+ }
614
+
615
+ async function readLocalSwarmHeader(
616
+ context: SwarmContext,
617
+ ): Promise<SwarmHeader> {
618
+ const record = await ensureLocalSwarm(context);
619
+ const content = await readHeaderSnapshot(
620
+ context.store,
621
+ record.headCid,
622
+ LOCAL_SWARM_URL,
623
+ );
624
+ const head: Variable & { root: string; etag: string } = {
625
+ value: { root: record.headCid },
626
+ cid: record.valueCid,
627
+ root: record.headCid,
628
+ etag: `"${record.valueCid}"`,
629
+ };
630
+ const header: SwarmHeader = {
631
+ head,
632
+ ...content,
633
+ config: LOCAL_SWARM_ORG,
634
+ source: "cache",
635
+ verifiedAt: record.updatedAt,
636
+ localSourceReady: true,
637
+ };
638
+ await refreshNamePins(context, LOCAL_SWARM_URL, header);
639
+ return header;
640
+ }
641
+
642
+ function localSwarmPointer(context: SwarmContext): BoundHead {
643
+ return {
644
+ read: async () => {
645
+ const record = await ensureLocalSwarm(context);
646
+ return {
647
+ value: { root: record.headCid },
648
+ cid: record.valueCid,
649
+ root: record.headCid,
650
+ etag: `"${record.valueCid}"`,
651
+ };
652
+ },
653
+ write: async (root, expectedCid) => {
654
+ const valCid = await valueCid({ root });
655
+ const now = new Date().toISOString();
656
+ if (context.store.supportsRetention) {
657
+ await context.store.retain(LOCAL_SWARM_HOLD_OWNER, [root]);
658
+ await context.store.confirmRetained(LOCAL_SWARM_HOLD_OWNER, [root]);
659
+ }
660
+ const swapped = withState(context, (state) =>
661
+ state.compareAndSwapLocalSwarmHead(expectedCid, {
662
+ headCid: root,
663
+ valueCid: valCid,
664
+ updatedAt: now,
665
+ }),
666
+ );
667
+ if (!swapped) {
668
+ const current = withState(context, (state) => state.localSwarmHead());
669
+ if (context.store.supportsRetention && current) {
670
+ await context.store
671
+ .reconcile(LOCAL_SWARM_HOLD_OWNER, [current.headCid])
672
+ .catch(() => {});
673
+ }
674
+ throw new ScopeApiError(
675
+ 412,
676
+ "cas_conflict",
677
+ "Local Swarm HEAD changed concurrently; retry against the latest snapshot.",
678
+ undefined,
679
+ );
680
+ }
681
+ if (context.store.supportsRetention) {
682
+ await context.store.reconcile(LOCAL_SWARM_HOLD_OWNER, [root]);
683
+ }
684
+ return {
685
+ value: { root },
686
+ cid: valCid,
687
+ };
688
+ },
689
+ writeWithReceipt: () =>
690
+ Promise.reject(
691
+ new HostError(
692
+ `The built-in "${LOCAL_SWARM_ALIAS}" Swarm is a single-machine Swarm and does not support Pivot receipt writes.`,
693
+ ),
694
+ ),
695
+ };
696
+ }
697
+
480
698
  function client(
481
699
  context: SwarmContext,
482
700
  service: string,
483
701
  identity?: Identity,
484
702
  secret?: MembershipSecret,
485
703
  ): ScopeClient {
704
+ if (isReservedLocalHost(service)) {
705
+ throw new HostError(
706
+ `Refusing network request to reserved .invalid host (${service}) for the built-in "${LOCAL_SWARM_ALIAS}" Swarm.`,
707
+ );
708
+ }
486
709
  return new ScopeClient({
487
710
  service,
488
711
  ...(identity
@@ -930,6 +1153,36 @@ export async function swarmMembers(
930
1153
  url: string,
931
1154
  refresh = false,
932
1155
  ) {
1156
+ if (isLocalSwarm(url)) {
1157
+ const headRecord = withState(context, (state) => state.localSwarmHead());
1158
+ return {
1159
+ mode: "local" as const,
1160
+ configUrl: LOCAL_SWARM_URL,
1161
+ members: [
1162
+ {
1163
+ publicKey: "local",
1164
+ role: "owner",
1165
+ name: "Local user",
1166
+ description: "Single-machine built-in Swarm user",
1167
+ pivot: false,
1168
+ localStatus: null,
1169
+ peerId: "",
1170
+ updatedAt: headRecord?.updatedAt ?? "",
1171
+ },
1172
+ ],
1173
+ cache: {
1174
+ source: "cache" as const,
1175
+ freshness: "current" as const,
1176
+ updatedAt: headRecord?.updatedAt ?? new Date().toISOString(),
1177
+ },
1178
+ local: {
1179
+ status: "unavailable" as const,
1180
+ updatedAt: null,
1181
+ verifiedAt: null,
1182
+ error: null,
1183
+ },
1184
+ };
1185
+ }
933
1186
  const { config, directory, cache } = await inspection(context, url, refresh);
934
1187
  const observations = await localObservations(context, url, config);
935
1188
  const members = directory.map(({ member, profile }) => {
@@ -964,7 +1217,9 @@ export async function swarmNetworking(
964
1217
  url: string,
965
1218
  config: Organization,
966
1219
  directory?: Awaited<ReturnType<typeof memberDirectory>>,
1220
+ currentHeadCid?: string,
967
1221
  ) {
1222
+ rejectLocalSwarm(url, "swarm networking");
968
1223
  directory ??= (await inspection(context, url)).directory;
969
1224
  const { account, local } = await localObservations(context, url, config);
970
1225
  const saved = local.snapshot?.connections;
@@ -1032,6 +1287,11 @@ export async function swarmNetworking(
1032
1287
  : actual.length
1033
1288
  ? "relay"
1034
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;
1035
1295
  return {
1036
1296
  publicKey: member.publicKey,
1037
1297
  name: profile.name,
@@ -1062,6 +1322,22 @@ export async function swarmNetworking(
1062
1322
  freshness,
1063
1323
  addresses: actual.map((entry) => entry.address),
1064
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
+ },
1065
1341
  };
1066
1342
  }),
1067
1343
  };
@@ -1071,6 +1347,78 @@ export async function inspectSwarmStatus(
1071
1347
  url: string,
1072
1348
  refresh = false,
1073
1349
  ) {
1350
+ if (isLocalSwarm(url)) {
1351
+ const header = await readLocalSwarmHeader(context);
1352
+ const meta = await swarmMeta(context, header);
1353
+ const walked = await walkUnixfsNames(
1354
+ context.store,
1355
+ CID.parse(header.stateCid),
1356
+ {
1357
+ skipRootFiles: v7RootSkipFiles(header.snapshot),
1358
+ stopAtBundle: true,
1359
+ },
1360
+ );
1361
+ const templatePrefix = `${meta.templatePath}/`;
1362
+ const globalSkillPrefix = meta.skillPath
1363
+ ? `${meta.skillPath}/global/`
1364
+ : undefined;
1365
+ const typeSkillPrefix = meta.skillPath
1366
+ ? `${meta.skillPath}/types/`
1367
+ : undefined;
1368
+ const registryPrefix = `${meta.registryPath}/`;
1369
+ let templates = 0;
1370
+ let globalSkills = 0;
1371
+ let typeSkills = 0;
1372
+ let registrations = 0;
1373
+ for (const entry of walked.entries) {
1374
+ if (entry.name.startsWith(templatePrefix)) templates++;
1375
+ else if (globalSkillPrefix && entry.name.startsWith(globalSkillPrefix))
1376
+ globalSkills++;
1377
+ else if (typeSkillPrefix && entry.name.startsWith(typeSkillPrefix))
1378
+ typeSkills++;
1379
+ else if (entry.name.startsWith(registryPrefix)) registrations++;
1380
+ }
1381
+ const skills = globalSkills + typeSkills;
1382
+ return {
1383
+ mode: "local" as const,
1384
+ configUrl: LOCAL_SWARM_URL,
1385
+ config: LOCAL_SWARM_ORG,
1386
+ head: header.head,
1387
+ lastWriter: null,
1388
+ cache: {
1389
+ source: "cache" as const,
1390
+ freshness: "current" as const,
1391
+ updatedAt: header.verifiedAt,
1392
+ },
1393
+ state: {
1394
+ status: "available" as const,
1395
+ error: null,
1396
+ },
1397
+ local: {
1398
+ names: walked.entries.length,
1399
+ templates,
1400
+ skills,
1401
+ globalSkills,
1402
+ typeSkills,
1403
+ registrations,
1404
+ },
1405
+ networking: {
1406
+ daemon: {
1407
+ status: "unavailable" as const,
1408
+ updatedAt: null,
1409
+ verifiedAt: null,
1410
+ error: null,
1411
+ },
1412
+ connections: {
1413
+ observedAt: null,
1414
+ error: null,
1415
+ peers: [],
1416
+ freshness: "unavailable" as const,
1417
+ },
1418
+ pivots: [],
1419
+ },
1420
+ };
1421
+ }
1074
1422
  const { config, directory, head, cache } = await inspection(
1075
1423
  context,
1076
1424
  url,
@@ -1095,7 +1443,13 @@ export async function inspectSwarmStatus(
1095
1443
  error:
1096
1444
  "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
1097
1445
  },
1098
- networking: await swarmNetworking(context, url, config, directory),
1446
+ networking: await swarmNetworking(
1447
+ context,
1448
+ url,
1449
+ config,
1450
+ directory,
1451
+ head.root,
1452
+ ),
1099
1453
  };
1100
1454
  }
1101
1455
 
@@ -1316,6 +1670,7 @@ async function fetchConfig(
1316
1670
  configUrl: string,
1317
1671
  signal?: AbortSignal,
1318
1672
  ): Promise<{ config: Organization; variable: Variable }> {
1673
+ rejectLocalSwarm(configUrl, "remote configuration fetch");
1319
1674
  const c = coordinates(configUrl),
1320
1675
  api = client(context, c.service);
1321
1676
  const options = signal ? { signal } : {};
@@ -1535,6 +1890,7 @@ async function privateSource(
1535
1890
  signal?: AbortSignal,
1536
1891
  candidates?: PivotCandidates,
1537
1892
  ) {
1893
+ rejectLocalSwarm(record.configUrl, "private Kubo networking");
1538
1894
  const config = record.config!,
1539
1895
  secret = record.secret!;
1540
1896
  const identity = await contextIdentity(context);
@@ -1736,6 +2092,8 @@ async function privateSource(
1736
2092
  ),
1737
2093
  };
1738
2094
  }
2095
+ const pivotReadinessRefreshIntervalMs = 45_000;
2096
+
1739
2097
  export async function swarmDaemon(
1740
2098
  context: SwarmContext,
1741
2099
  signal: AbortSignal,
@@ -1760,6 +2118,8 @@ export async function swarmDaemon(
1760
2118
  candidates: PivotCandidates;
1761
2119
  nextDiscovery: number;
1762
2120
  nextSync: number;
2121
+ nextReplication?: number;
2122
+ nextPivotSync?: number;
1763
2123
  healthy: number;
1764
2124
  record?: LocalMembership;
1765
2125
  node?: KuboNode;
@@ -1776,6 +2136,7 @@ export async function swarmDaemon(
1776
2136
  nodeApi: string;
1777
2137
  epoch: number;
1778
2138
  headId: string;
2139
+ listening: boolean;
1779
2140
  };
1780
2141
  }
1781
2142
  >();
@@ -1875,7 +2236,7 @@ export async function swarmDaemon(
1875
2236
  : "unknown",
1876
2237
  running: Boolean(session?.running),
1877
2238
  receiptRpc: {
1878
- active: Boolean(session?.pivotServer),
2239
+ active: Boolean(session?.pivotServer?.listening),
1879
2240
  protocol: pivotReceiptProtocol,
1880
2241
  epoch: session?.pivotServer?.epoch ?? null,
1881
2242
  headId: session?.pivotServer?.headId ?? null,
@@ -1990,6 +2351,30 @@ export async function swarmDaemon(
1990
2351
  error: "No connection snapshot collected.",
1991
2352
  peers: [],
1992
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
+ : {}),
1993
2378
  };
1994
2379
  await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1995
2380
  };
@@ -2030,6 +2415,7 @@ export async function swarmDaemon(
2030
2415
  };
2031
2416
  sessions.set(url, session);
2032
2417
  }
2418
+ let pivotListenerVerified = false;
2033
2419
  try {
2034
2420
  if (session.record?.config && context.pivot === undefined) {
2035
2421
  const self = session.record.config.members.find(
@@ -2099,6 +2485,41 @@ export async function swarmDaemon(
2099
2485
  await persist(url, session, true);
2100
2486
  }
2101
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
+ }
2102
2523
  let healthy = 0;
2103
2524
  await boundedMap(
2104
2525
  [...session.candidates.active()],
@@ -2136,8 +2557,8 @@ export async function swarmDaemon(
2136
2557
  },
2137
2558
  );
2138
2559
  session.healthy = healthy;
2139
- // Startup-captured relay/bootstrap options must be removed immediately
2140
- // 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.
2141
2562
  const record = session.record!;
2142
2563
  const self = record.config!.members.find(
2143
2564
  (member) => member.publicKey === record.account,
@@ -2162,9 +2583,27 @@ export async function swarmDaemon(
2162
2583
  );
2163
2584
  session.selected = new Set(desired.map(({ ID }) => ID));
2164
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);
2165
2603
  if (session.pivot) {
2166
2604
  if (
2167
2605
  !session.pivotServer ||
2606
+ !session.pivotServer.server.listening ||
2168
2607
  session.pivotServer.nodeApi !== session.node.api ||
2169
2608
  session.pivotServer.epoch !== record.config!.epoch ||
2170
2609
  session.pivotServer.headId !== record.config!.headId
@@ -2174,6 +2613,29 @@ export async function swarmDaemon(
2174
2613
  const mounted = await mountPivotServer(
2175
2614
  pivotNode,
2176
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
+ },
2177
2639
  receipt: (receiptRequest, requestSignal) =>
2178
2640
  handlePivotReceiptRequest(
2179
2641
  { ...session.context, node: pivotNode },
@@ -2190,35 +2652,112 @@ export async function swarmDaemon(
2190
2652
  : {}),
2191
2653
  },
2192
2654
  session.context.fetch,
2655
+ signal,
2193
2656
  );
2194
2657
  session.pivotServer = {
2195
2658
  server: mounted,
2196
2659
  nodeApi: session.node.api,
2197
2660
  epoch: record.config!.epoch,
2198
2661
  headId: record.config!.headId,
2662
+ listening: true,
2199
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
+ }
2200
2677
  }
2201
- await syncPivotPublications(session.context, url, signal);
2678
+ pivotListenerVerified = true;
2202
2679
  } else {
2203
2680
  await stopPivotServer(session);
2204
2681
  }
2205
- try {
2206
- const peers = await nodeConnections(session.node, signal);
2207
- session.connections = {
2208
- observedAt: Date.now(),
2209
- error: null,
2210
- peers,
2211
- };
2212
- } catch (cause) {
2213
- signal.throwIfAborted();
2214
- session.connections = {
2215
- observedAt: session.connections?.observedAt ?? null,
2216
- error: message(cause).slice(0, 2048),
2217
- peers: session.connections?.peers ?? [],
2218
- };
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
+ }
2219
2756
  }
2220
2757
  } catch (cause) {
2221
2758
  if (signal.aborted) return;
2759
+ if (!pivotListenerVerified && session.pivotServer)
2760
+ session.pivotServer.listening = false;
2222
2761
  session.error = message(cause);
2223
2762
  session.nextDiscovery = 0;
2224
2763
  emitDiagnostic(
@@ -2405,6 +2944,7 @@ async function approvedMembership(
2405
2944
  configUrl: string,
2406
2945
  signal?: AbortSignal,
2407
2946
  ) {
2947
+ rejectLocalSwarm(configUrl, "remote membership");
2408
2948
  const record = await localForRead(context, configUrl);
2409
2949
  const { config } = await fetchConfig(context, configUrl, signal);
2410
2950
  if (config.owner !== record.owner)
@@ -2503,6 +3043,7 @@ async function readyMembership(
2503
3043
  context: SwarmContext,
2504
3044
  configUrl: string,
2505
3045
  ): Promise<LocalMembership> {
3046
+ rejectLocalSwarm(configUrl, "remote membership");
2506
3047
  const record = await localForRead(context, configUrl);
2507
3048
  if (!record.config || !record.secret) return refresh(context, configUrl);
2508
3049
  if (
@@ -2526,11 +3067,6 @@ async function readyMembership(
2526
3067
  }
2527
3068
  return record;
2528
3069
  }
2529
- interface BoundHead {
2530
- read(): Promise<Variable & { root: string; etag: string }>;
2531
- write(root: string, cid: string, key: string): Promise<Variable>;
2532
- writeWithReceipt(receipt: ScopeWriteReceipt): Promise<Variable>;
2533
- }
2534
3070
  function headValue(head: Variable): Variable & { root: string; etag: string } {
2535
3071
  const value = object(head.value, "HEAD");
2536
3072
  if (Object.keys(value).join() !== "root" || typeof value.root !== "string")
@@ -2545,6 +3081,7 @@ export async function pointer(
2545
3081
  context: SwarmContext,
2546
3082
  configUrl: string,
2547
3083
  ): Promise<BoundHead> {
3084
+ if (isLocalSwarm(configUrl)) return localSwarmPointer(context);
2548
3085
  return boundPointer(
2549
3086
  context,
2550
3087
  configUrl,
@@ -2615,18 +3152,21 @@ async function boundPointer(
2615
3152
  ),
2616
3153
  };
2617
3154
  }
2618
- async function writeNamesHead(
3155
+ export async function writeNamesHead(
2619
3156
  context: SwarmContext,
2620
3157
  url: string,
2621
3158
  head: BoundHead,
2622
3159
  root: string,
2623
3160
  cid: string,
2624
- ): Promise<void> {
3161
+ ): Promise<Variable> {
3162
+ if (isLocalSwarm(url)) {
3163
+ return head.write(root, cid, uniqueId());
3164
+ }
2625
3165
  const lock = await privateDirectory(
2626
3166
  await directory(context),
2627
3167
  `state-pin-${createHash("sha256").update(url).digest("hex")}`,
2628
3168
  );
2629
- await withPrivateLock(lock, async () => {
3169
+ return withPrivateLock(lock, async () => {
2630
3170
  if (context.confirmPublication) {
2631
3171
  try {
2632
3172
  await context.confirmPublication(url, root);
@@ -2638,11 +3178,10 @@ async function writeNamesHead(
2638
3178
  "publication",
2639
3179
  );
2640
3180
  }
2641
- await head.write(root, cid, uniqueId());
2642
- return;
3181
+ return head.write(root, cid, uniqueId());
2643
3182
  }
2644
3183
  const idempotencyKey = uniqueId();
2645
- let receipt: ScopeWriteReceipt;
3184
+ let receipt: ScopeWriteReceipt | null;
2646
3185
  try {
2647
3186
  receipt = await requestPivotWriteReceipt(
2648
3187
  context,
@@ -2659,7 +3198,10 @@ async function writeNamesHead(
2659
3198
  "publication",
2660
3199
  );
2661
3200
  }
2662
- await head.writeWithReceipt(receipt);
3201
+ if (receipt === null) {
3202
+ return head.write(root, cid, idempotencyKey);
3203
+ }
3204
+ return head.writeWithReceipt(receipt);
2663
3205
  });
2664
3206
  }
2665
3207
 
@@ -2669,7 +3211,7 @@ async function requestPivotWriteReceipt(
2669
3211
  root: string,
2670
3212
  ifCid: string,
2671
3213
  idempotencyKey: string,
2672
- ): Promise<ScopeWriteReceipt> {
3214
+ ): Promise<ScopeWriteReceipt | null> {
2673
3215
  const record = await approvedMembership(context, url);
2674
3216
  const config = record.config!;
2675
3217
  const identity = await contextIdentity(context);
@@ -2684,10 +3226,21 @@ async function requestPivotWriteReceipt(
2684
3226
  const remote = pivots.filter(
2685
3227
  ({ member }) => member.publicKey !== record.account,
2686
3228
  );
2687
- if (!remote.length)
3229
+ if (!remote.length) {
3230
+ if (
3231
+ members.length === 1 &&
3232
+ members[0]!.member.publicKey === record.account &&
3233
+ record.account === config.owner
3234
+ ) {
3235
+ context.diagnostic?.(
3236
+ `[${url}] Solo self-Pivot Swarm detected; publishing ${root} directly without remote Pivot receipt.`,
3237
+ );
3238
+ return null;
3239
+ }
2688
3240
  throw new HostError(
2689
3241
  "Publication requires an independent Pivot node. Declare another member with swarm profile --pivot true; HEAD was not changed.",
2690
3242
  );
3243
+ }
2691
3244
  const authorized = remote.filter(
2692
3245
  ({ member }) =>
2693
3246
  member.publicKey === config.owner ||
@@ -2773,6 +3326,7 @@ export async function handlePivotReceiptRequest(
2773
3326
  input: unknown,
2774
3327
  signal: AbortSignal,
2775
3328
  ): Promise<ScopeWriteReceipt> {
3329
+ rejectLocalSwarm(url, "Pivot receipt RPC");
2776
3330
  const request = parsePivotReceiptRequest(input);
2777
3331
  const record = await approvedMembership(context, url, signal);
2778
3332
  const config = record.config!;
@@ -2932,6 +3486,7 @@ export async function syncPivotPublications(
2932
3486
  url: string,
2933
3487
  signal: AbortSignal,
2934
3488
  ): Promise<void> {
3489
+ rejectLocalSwarm(url, "Pivot publication sync");
2935
3490
  if (context.pivot === false) return;
2936
3491
  const record = await approvedMembership(context, url, signal);
2937
3492
  const config = record.config!;
@@ -2976,89 +3531,467 @@ export async function syncPivotPublications(
2976
3531
  kuboSource(node, peers, context.diagnostic),
2977
3532
  );
2978
3533
  try {
3534
+ if (CID.parse(head.root).code === dagPb.code)
3535
+ await pinPublication(source, [head.root], node, signal, context.fetch);
2979
3536
  await readSnapshot(source, head.root, url);
2980
3537
  const roots =
2981
3538
  CID.parse(head.root).code === dagPb.code
2982
3539
  ? [head.root]
2983
3540
  : await frozenPublicationClosure(source, head.root);
2984
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;
2985
3547
  } finally {
2986
3548
  await source.close();
2987
3549
  }
2988
3550
  }
2989
3551
 
2990
- export async function typedJson(
2991
- store: IpfsStore,
2992
- cid: string,
2993
- type: BundleType,
2994
- ): Promise<unknown> {
2995
- const { bundle, value } = await bundleJson(store, cid);
2996
- if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
2997
- throw new HostError("Expected exact Bundle type CID.");
2998
- return value;
2999
- }
3000
- function parseArtifact(value: unknown): Artifact {
3001
- const data = object(value, "Artifact");
3002
- if (
3003
- Object.keys(data).some(
3004
- (key) => !["value", "previous", "timestamp"].includes(key),
3005
- ) ||
3006
- typeof data.value !== "string" ||
3007
- typeof data.timestamp !== "string" ||
3008
- !Number.isFinite(Date.parse(data.timestamp)) ||
3009
- (data.previous !== undefined && typeof data.previous !== "string")
3010
- )
3011
- throw new HostError("Invalid Artifact.");
3012
- CID.parse(data.value);
3013
- if (data.previous !== undefined) CID.parse(data.previous);
3014
- return {
3015
- value: data.value,
3016
- timestamp: data.timestamp,
3017
- ...(data.previous !== undefined ? { previous: data.previous } : {}),
3018
- };
3019
- }
3020
- export async function jsonBundle(
3021
- store: IpfsStore,
3022
- type: BundleType,
3023
- value: unknown,
3024
- ): Promise<string> {
3025
- const encoded = await encodeBundleCar(
3026
- memoryTree(
3027
- new Map([
3028
- [
3029
- ".bundle.yaml",
3030
- new TextEncoder().encode(
3031
- stringify({
3032
- title: "IPAB Data",
3033
- entry: "entry.json",
3034
- type: ".bundle-type.yaml",
3035
- }),
3036
- ),
3037
- ],
3038
- [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
3039
- ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
3040
- ]),
3041
- ),
3042
- );
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;
3043
3564
  try {
3044
- const iterator = await CarBlockIterator.fromIterable(
3045
- streamChunks(encoded.stream),
3046
- );
3047
- for await (const block of iterator) await store.put(block.cid, block.bytes);
3048
- return encoded.cid.toString();
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;
3049
3576
  } finally {
3050
- await encoded.close();
3577
+ if (local !== context.store) await local.close();
3051
3578
  }
3052
3579
  }
3053
- async function writeStateBundle(
3054
- store: IpfsStore,
3055
- configuration: SwarmMeta,
3056
- targets: Record<string, CID>,
3057
- configUrl?: string,
3058
- ): Promise<string> {
3059
- const meta = parseSwarmMeta(configuration);
3060
- const names = Object.fromEntries(
3061
- Object.entries(targets).map(([name, cid]) => [
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;
3746
+ } finally {
3747
+ await source.close();
3748
+ }
3749
+ }
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
+
3923
+ export async function typedJson(
3924
+ store: IpfsStore,
3925
+ cid: string,
3926
+ type: BundleType,
3927
+ ): Promise<unknown> {
3928
+ const { bundle, value } = await bundleJson(store, cid);
3929
+ if (bundle.schemaKey !== (await encodeSchema(type)).cid.toString())
3930
+ throw new HostError("Expected exact Bundle type CID.");
3931
+ return value;
3932
+ }
3933
+ function parseArtifact(value: unknown): Artifact {
3934
+ const data = object(value, "Artifact");
3935
+ if (
3936
+ Object.keys(data).some(
3937
+ (key) => !["value", "previous", "timestamp"].includes(key),
3938
+ ) ||
3939
+ typeof data.value !== "string" ||
3940
+ typeof data.timestamp !== "string" ||
3941
+ !Number.isFinite(Date.parse(data.timestamp)) ||
3942
+ (data.previous !== undefined && typeof data.previous !== "string")
3943
+ )
3944
+ throw new HostError("Invalid Artifact.");
3945
+ CID.parse(data.value);
3946
+ if (data.previous !== undefined) CID.parse(data.previous);
3947
+ return {
3948
+ value: data.value,
3949
+ timestamp: data.timestamp,
3950
+ ...(data.previous !== undefined ? { previous: data.previous } : {}),
3951
+ };
3952
+ }
3953
+ export async function jsonBundle(
3954
+ store: IpfsStore,
3955
+ type: BundleType,
3956
+ value: unknown,
3957
+ ): Promise<string> {
3958
+ const encoded = await encodeBundleCar(
3959
+ memoryTree(
3960
+ new Map([
3961
+ [
3962
+ ".bundle.yaml",
3963
+ new TextEncoder().encode(
3964
+ stringify({
3965
+ title: "IPAB Data",
3966
+ entry: "entry.json",
3967
+ type: ".bundle-type.yaml",
3968
+ }),
3969
+ ),
3970
+ ],
3971
+ [".bundle-type.yaml", new TextEncoder().encode(stringify(type))],
3972
+ ["entry.json", new TextEncoder().encode(`${JSON.stringify(value)}\n`)],
3973
+ ]),
3974
+ ),
3975
+ );
3976
+ try {
3977
+ const iterator = await CarBlockIterator.fromIterable(
3978
+ streamChunks(encoded.stream),
3979
+ );
3980
+ for await (const block of iterator) await store.put(block.cid, block.bytes);
3981
+ return encoded.cid.toString();
3982
+ } finally {
3983
+ await encoded.close();
3984
+ }
3985
+ }
3986
+ async function writeStateBundle(
3987
+ store: IpfsStore,
3988
+ configuration: SwarmMeta,
3989
+ targets: Record<string, CID>,
3990
+ configUrl?: string,
3991
+ ): Promise<string> {
3992
+ const meta = parseSwarmMeta(configuration);
3993
+ const names = Object.fromEntries(
3994
+ Object.entries(targets).map(([name, cid]) => [
3062
3995
  formalName(name),
3063
3996
  cid.toString(),
3064
3997
  ]),
@@ -3095,57 +4028,6 @@ async function writeV7RootBundle(
3095
4028
  });
3096
4029
  return jsonBundle(store, swarmRootType, value);
3097
4030
  }
3098
- function isV7Snapshot(snapshot: Snapshot): boolean {
3099
- return snapshot.stateBundle?.unixfsRoot?.version === 7;
3100
- }
3101
- function v7RootSkipFiles(snapshot: Snapshot): Set<string> {
3102
- const root = snapshot.stateBundle?.unixfsRoot;
3103
- if (!root) return new Set();
3104
- return new Set([".bundle.yaml", root.typeFile, root.entryFile]);
3105
- }
3106
- async function resolveSnapshotName(
3107
- store: IpfsStore,
3108
- snapshot: Snapshot,
3109
- name: string,
3110
- ): Promise<CID | undefined> {
3111
- if (isV7Snapshot(snapshot))
3112
- return resolveUnixfsPath(store, CID.parse(snapshot.stateBundle!.cid), name);
3113
- return Object.hasOwn(snapshot.names, name) ? snapshot.names[name] : undefined;
3114
- }
3115
- async function listSubtreeNames(
3116
- store: IpfsStore,
3117
- snapshot: Snapshot,
3118
- prefix: string,
3119
- flatOnly = false,
3120
- ): Promise<Array<{ name: string; cid: CID }>> {
3121
- if (isV7Snapshot(snapshot)) {
3122
- const dirCid = await resolveUnixfsPath(
3123
- store,
3124
- CID.parse(snapshot.stateBundle!.cid),
3125
- prefix,
3126
- );
3127
- if (!dirCid) return [];
3128
- if (flatOnly) {
3129
- const entries = await listUnixfsDirectory(store, dirCid);
3130
- return [...entries.entries()]
3131
- .map(([child, cid]) => ({ name: `${prefix}/${child}`, cid }))
3132
- .sort((a, b) => a.name.localeCompare(b.name));
3133
- }
3134
- const walked = await walkUnixfsNames(store, dirCid, {
3135
- prefix,
3136
- stopAtBundle: true,
3137
- });
3138
- return walked.entries.map((entry) => ({
3139
- name: entry.name,
3140
- cid: CID.parse(entry.targetCid),
3141
- }));
3142
- }
3143
- const needle = `${prefix}/`;
3144
- return Object.entries(snapshot.names)
3145
- .filter(([name]) => name.startsWith(needle))
3146
- .map(([name, cid]) => ({ name, cid }))
3147
- .sort((a, b) => a.name.localeCompare(b.name));
3148
- }
3149
4031
  async function readV7Root(store: IpfsStore, cid: CID): Promise<Snapshot> {
3150
4032
  const canonical = cid.toV1();
3151
4033
  const rootKey = canonical.toString();
@@ -3450,7 +4332,7 @@ export interface SwarmHeader {
3450
4332
  projection?: SwarmProjection;
3451
4333
  localSourceReady?: boolean;
3452
4334
  }
3453
- function missingContent(cause: unknown): boolean {
4335
+ export function missingContent(cause: unknown): boolean {
3454
4336
  let failure: unknown = cause;
3455
4337
  for (
3456
4338
  let depth = 0;
@@ -3528,6 +4410,7 @@ export async function sharedSwarmStatus(
3528
4410
  context: SwarmContext,
3529
4411
  configUrl: string,
3530
4412
  ): Promise<SwarmHeader> {
4413
+ if (isLocalSwarm(configUrl)) return readLocalSwarmHeader(context);
3531
4414
  const { config } = await fetchConfig(context, configUrl);
3532
4415
  const c = coordinates(configUrl);
3533
4416
  const head = headValue(
@@ -3596,6 +4479,7 @@ async function readSwarmHeader(
3596
4479
  mode: "active" | "local-first" = "active",
3597
4480
  ): Promise<SwarmHeader> {
3598
4481
  canonicalSwarmUrl(configUrl);
4482
+ if (isLocalSwarm(configUrl)) return readLocalSwarmHeader(context);
3599
4483
  let record =
3600
4484
  mode === "local-first"
3601
4485
  ? await approvedMembership(context, configUrl)
@@ -3819,7 +4703,9 @@ function headerProjection(header: SwarmHeader): SwarmProjection {
3819
4703
  throw new HostError("A verified account projection is required.");
3820
4704
  return header.projection;
3821
4705
  }
3822
- async function localHeader(context: SwarmContext, url: string) {
4706
+ export async function localHeader(context: SwarmContext, url: string) {
4707
+ if (isLocalSwarm(url))
4708
+ return { header: await readLocalSwarmHeader(context), account: "local" };
3823
4709
  if (context.forceRefresh) return;
3824
4710
  canonicalSwarmUrl(url);
3825
4711
  const record = await localForRead(context, url);
@@ -3869,12 +4755,13 @@ async function localHeader(context: SwarmContext, url: string) {
3869
4755
 
3870
4756
  // SharedContent invokes this source only after a genuine local ENOENT. Its
3871
4757
  // store is not replaced from inside its own pending read (which would deadlock).
3872
- async function lazyPrivateSource(
4758
+ export async function lazyPrivateSource(
3873
4759
  context: SwarmContext,
3874
4760
  url: string,
3875
4761
  account: string,
3876
4762
  basis: Organization,
3877
4763
  ) {
4764
+ rejectLocalSwarm(url, "private Kubo networking");
3878
4765
  const finishPrevious = context.finishRead;
3879
4766
  delete context.finishRead;
3880
4767
  await finishPrevious?.();
@@ -3956,6 +4843,10 @@ export async function createSwarm(
3956
4843
  addresses?: string[];
3957
4844
  } = {},
3958
4845
  ): Promise<string> {
4846
+ if (options.alias === LOCAL_SWARM_ALIAS)
4847
+ throw new HostError(
4848
+ `Swarm alias "${LOCAL_SWARM_ALIAS}" is reserved for the built-in local Swarm.`,
4849
+ );
3959
4850
  if (
3960
4851
  (options.properties?.name.length ?? 0) > 256 ||
3961
4852
  (options.properties?.description.length ?? 0) > 2048 ||
@@ -4047,7 +4938,7 @@ export async function createSwarm(
4047
4938
  const skill = await seedSkillSource();
4048
4939
  for (const [cid, data] of skill.blocks)
4049
4940
  await context.store.put(CID.parse(cid), data);
4050
- names["ipab/skills/ipab"] = CID.parse(skill.cid);
4941
+ names["ipab/skills/global/ipab"] = CID.parse(skill.cid);
4051
4942
  let root: string;
4052
4943
  if (record.stateVersion === 7) {
4053
4944
  let currentRoot = CID.parse(
@@ -4244,6 +5135,7 @@ export async function exportRequest(
4244
5135
  url: string,
4245
5136
  output: string,
4246
5137
  ): Promise<string> {
5138
+ rejectLocalSwarm(url, "swarm export");
4247
5139
  const record = await local(context, canonicalSwarmUrl(url));
4248
5140
  if (!record.request) throw new HostError("Owner membership has no Request.");
4249
5141
  const handle = await open(output, "wx", 0o600);
@@ -4267,6 +5159,7 @@ export async function requestMembership(
4267
5159
  request: MembershipRequest;
4268
5160
  file?: string;
4269
5161
  }> {
5162
+ rejectLocalSwarm(url, "swarm request");
4270
5163
  if ("name" in options)
4271
5164
  throw new HostError(
4272
5165
  "Set your account-wide name with ipab profile --name NAME; membership requests no longer embed display names.",
@@ -4531,6 +5424,7 @@ export async function approveMembership(
4531
5424
  ? await verifiedRequest(input)
4532
5425
  : await verifyRequest(input),
4533
5426
  url = request.configUrl;
5427
+ rejectLocalSwarm(url, "swarm approve");
4534
5428
  const dir = await directory(context);
4535
5429
  return withPrivateLock(dir, async () => {
4536
5430
  const { identity, record } = await ownerCheck(context, url);
@@ -4789,6 +5683,7 @@ export async function grantPivotAuthority(
4789
5683
  url: string,
4790
5684
  memberPublicKey: string,
4791
5685
  ): Promise<{ configUrl: string; member: string; headId: string }> {
5686
+ rejectLocalSwarm(url, "swarm pivot grant");
4792
5687
  if (!isCanonicalPublicKey(memberPublicKey))
4793
5688
  throw new HostError("Invalid member public key.");
4794
5689
  const dir = await directory(context);
@@ -4891,6 +5786,7 @@ export async function updateSwarm(
4891
5786
  url: string,
4892
5787
  changes: { name?: string; description?: string },
4893
5788
  ) {
5789
+ rejectLocalSwarm(url, "swarm update");
4894
5790
  if (
4895
5791
  (changes.name?.length ?? 0) > 256 ||
4896
5792
  (changes.description?.length ?? 0) > 2048
@@ -4923,6 +5819,7 @@ export async function updateProfile(
4923
5819
  url: string,
4924
5820
  changes: { addresses?: string[]; pivot?: boolean },
4925
5821
  ): Promise<Profile> {
5822
+ rejectLocalSwarm(url, "swarm profile");
4926
5823
  if ("name" in changes || "description" in changes)
4927
5824
  throw new HostError(
4928
5825
  "Use ipab profile --name NAME --description TEXT for personal data; swarm profile configures network addresses only.",
@@ -5027,6 +5924,7 @@ export async function removeMember(
5027
5924
  url: string,
5028
5925
  member: string,
5029
5926
  ): Promise<void> {
5927
+ rejectLocalSwarm(url, "swarm exclude");
5030
5928
  const dir = await directory(context);
5031
5929
  await withPrivateLock(dir, async () => {
5032
5930
  const { identity, record: membership } = await ownerCheck(context, url);
@@ -5053,6 +5951,7 @@ export async function resumeRemoval(
5053
5951
  context: SwarmContext,
5054
5952
  url: string,
5055
5953
  ): Promise<void> {
5954
+ rejectLocalSwarm(url, "swarm resume");
5056
5955
  const dir = await directory(context);
5057
5956
  return withPrivateLock(dir, async () => {
5058
5957
  const identity = await contextIdentity(context);
@@ -5297,84 +6196,8 @@ export async function resumeRemoval(
5297
6196
  }
5298
6197
  });
5299
6198
  }
5300
- export function formalName(name: string): string {
5301
- relativePath(name);
5302
- if (name.length > 256 || name.startsWith("builtin:"))
5303
- throw new HostError("Invalid formal Name.");
5304
- return name;
5305
- }
5306
- function decodeNameComponent(
5307
- value: string,
5308
- part: "authority" | "path",
5309
- ): string {
5310
- try {
5311
- return decodeURIComponent(value);
5312
- } catch {
5313
- throw new HostError(
5314
- `Malformed percent-encoding in IPAB URI ${part}; use valid UTF-8 escapes or copy the reference from ipab search.`,
5315
- );
5316
- }
5317
- }
5318
- export function parseNameReference(
5319
- reference: string,
5320
- ): { swarm?: string; name: string } | undefined {
5321
- if (/^name:/i.test(reference))
5322
- throw new HostError("name: is unsupported; use ipab://ALIAS/PATH.");
5323
- if (!/^ipab:/i.test(reference)) return undefined;
5324
- if (/^ipab:\/\/https?:\/\//i.test(reference))
5325
- throw new HostError(
5326
- "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.",
5327
- );
5328
- const match = /^ipab:\/\/([^/]*)\/(.*)$/is.exec(reference);
5329
- if (!match)
5330
- throw new HostError(
5331
- "Invalid IPAB URI; percent-encode the configuration URL authority and each path segment.",
5332
- );
5333
- const authority = decodeNameComponent(match[1]!, "authority");
5334
- if (authority && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(authority)) {
5335
- if (!/^https?:\/\//i.test(authority))
5336
- throw new HostError(
5337
- "Invalid IPAB URI authority; use a registered alias or the percent-encoded configuration URL.",
5338
- );
5339
- canonicalSwarmUrl(authority);
5340
- }
5341
- if (/[?#\s]/.test(match[2]!))
5342
- throw new HostError(
5343
- "Invalid IPAB URI path; percent-encode each Name path segment. Queries and fragments are not supported.",
5344
- );
5345
- const segments = match[2]!.split("/").map((segment) => {
5346
- const decoded = decodeNameComponent(segment, "path");
5347
- if (/[/\\]/.test(decoded))
5348
- throw new HostError(
5349
- "Invalid IPAB URI path separator; use literal / between Name segments, never an encoded slash or backslash.",
5350
- );
5351
- return decoded;
5352
- });
5353
- try {
5354
- return {
5355
- ...(authority ? { swarm: authority } : {}),
5356
- name: match[2] === "" ? "" : formalName(segments.join("/")),
5357
- };
5358
- } catch (error) {
5359
- if (!(error instanceof HostError)) throw error;
5360
- throw new HostError(
5361
- "Invalid IPAB URI path; use a safe relative Name of at most 256 characters without empty, . or .. segments.",
5362
- error.exitCode,
5363
- error.code,
5364
- error.phase,
5365
- );
5366
- }
5367
- }
5368
- export function formatNameReference(swarm: string, name: string): string {
5369
- const segment = (value: string) =>
5370
- encodeURIComponent(value).replace(
5371
- /[!'()*]/g,
5372
- (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,
5373
- );
5374
- return `ipab://${segment(swarm)}/${name.split("/").map(segment).join("/")}`;
5375
- }
5376
- export async function resolveReference(
5377
- context: SwarmContext,
6199
+ export async function resolveReference(
6200
+ context: SwarmContext,
5378
6201
  reference: string,
5379
6202
  swarm: string | undefined,
5380
6203
  local: (reference: string) => string,
@@ -5428,7 +6251,7 @@ export async function resolveReference(
5428
6251
  }
5429
6252
  };
5430
6253
  let link = await target();
5431
- if (!link && header.source === "cache") {
6254
+ if (!link && header.source === "cache" && !isLocalSwarm(selected)) {
5432
6255
  header = await swarmHeader(context, selected, true);
5433
6256
  link = await target();
5434
6257
  }
@@ -5440,7 +6263,7 @@ export async function resolveReference(
5440
6263
  targetCid = link;
5441
6264
  source = { configUrl: selected, header };
5442
6265
  } else {
5443
- if (swarm) await readyMembership(context, swarm);
6266
+ if (swarm && !isLocalSwarm(swarm)) await readyMembership(context, swarm);
5444
6267
  targetCid = local(reference);
5445
6268
  }
5446
6269
  try {
@@ -5457,7 +6280,7 @@ export async function resolveReference(
5457
6280
  );
5458
6281
  }
5459
6282
  }
5460
- async function artifactValue(
6283
+ export async function artifactValue(
5461
6284
  store: IpfsStore,
5462
6285
  targetCid: string,
5463
6286
  protect?: (cid: string) => Promise<void>,
@@ -5525,6 +6348,7 @@ export async function pinNameSubscription(
5525
6348
  } catch (cause) {
5526
6349
  if (!selected || !missingContent(cause)) throw cause;
5527
6350
  const swarm = withState(context, (state) => state.resolveSwarm(selected));
6351
+ if (isLocalSwarm(swarm)) throw cause;
5528
6352
  await readyMembership(context, swarm);
5529
6353
  roots = [
5530
6354
  ...(await currentDependencies(context.store, canonical.reference)),
@@ -5885,12 +6709,36 @@ export async function searchNames(
5885
6709
  "local-first",
5886
6710
  ));
5887
6711
  if (isV7Snapshot(header.snapshot)) {
5888
- const response = await searchV7ViaPivot(
5889
- context,
5890
- swarm.cid,
5891
- header,
5892
- validated,
5893
- );
6712
+ let response: SearchApiResponse;
6713
+ if (isLocalSwarm(swarm.cid)) {
6714
+ await withStateAsync(context, async (state) => {
6715
+ if (
6716
+ state.searchIndexState(LOCAL_SWARM_URL)?.headCid !==
6717
+ header.head.root
6718
+ ) {
6719
+ await indexV7UnixfsSwarm(
6720
+ state,
6721
+ context.store,
6722
+ LOCAL_SWARM_URL,
6723
+ header.head.root,
6724
+ { skipRootFiles: v7RootSkipFiles(header.snapshot) },
6725
+ );
6726
+ }
6727
+ });
6728
+ const localResponse = withState(context, (state) =>
6729
+ queryLocalSearchIndex(state, LOCAL_SWARM_URL, validated),
6730
+ );
6731
+ if (!localResponse)
6732
+ throw new HostError("Local Swarm search index is unavailable.");
6733
+ response = localResponse;
6734
+ } else {
6735
+ response = await searchV7ViaPivot(
6736
+ context,
6737
+ swarm.cid,
6738
+ header,
6739
+ validated,
6740
+ );
6741
+ }
5894
6742
  searched.push({
5895
6743
  configUrl: swarm.cid,
5896
6744
  source: header.source,
@@ -5978,26 +6826,146 @@ function hasMeta(snapshot: Snapshot): boolean {
5978
6826
  snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab")
5979
6827
  );
5980
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
+
5981
6842
  export interface SharedSkill {
5982
6843
  name: string;
5983
6844
  cid: string;
5984
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;
5985
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);
6956
+ }
6957
+
5986
6958
  export async function swarmSkills(
5987
6959
  context: SwarmContext,
5988
6960
  configUrl: string,
5989
6961
  requested: readonly string[],
5990
6962
  owner: string,
5991
6963
  ): Promise<SharedSkill[]> {
5992
- const warm = await localHeader(context, configUrl);
5993
- if (warm && !warm.header.localSourceReady)
5994
- await lazyPrivateSource(
5995
- context,
5996
- configUrl,
5997
- warm.account,
5998
- warm.header.config,
5999
- );
6000
- 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
+ });
6001
6969
  const roots = new Set<string>();
6002
6970
  const protect = async (cid: string) => {
6003
6971
  roots.add(cid);
@@ -6006,34 +6974,26 @@ export async function swarmSkills(
6006
6974
  await context.store.confirmRetained(owner, values);
6007
6975
  };
6008
6976
  for (let attempt = 0; ; attempt++) {
6009
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
6010
- header = await swarmHeader(context, configUrl, true);
6011
- continue;
6012
- }
6013
- if (hasMeta(header.snapshot)) {
6014
- if (isV7Snapshot(header.snapshot)) {
6977
+ if (hasMeta(ctx.snapshot)) {
6978
+ if (ctx.isV7) {
6015
6979
  if (context.store.supportsRetention) {
6016
- const rootId = metaCid(header.snapshot);
6980
+ const rootId = metaCid(ctx.snapshot);
6017
6981
  await context.store.retainDirect(owner, [rootId]);
6018
6982
  await context.store.confirmDirectRetained(owner, [rootId]);
6019
6983
  }
6020
6984
  } else {
6021
- await protect(metaCid(header.snapshot));
6985
+ await protect(metaCid(ctx.snapshot));
6022
6986
  }
6023
6987
  }
6024
- const meta = await swarmMeta(context, header);
6025
- if (!meta.skillPath)
6026
- throw new HostError(
6027
- header.snapshot.stateBundle
6028
- ? "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."
6029
- : `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.`,
6030
- );
6031
- 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}/`;
6032
6992
  const entries = await listSubtreeNames(
6033
6993
  context.store,
6034
- header.snapshot,
6035
- meta.skillPath,
6036
- true,
6994
+ ctx.snapshot,
6995
+ globalDir,
6996
+ false,
6037
6997
  );
6038
6998
  for (const { cid: target } of entries) roots.add(target.toString());
6039
6999
  await context.store.registerOwnerAsync(owner, [...roots]);
@@ -6042,7 +7002,7 @@ export async function swarmSkills(
6042
7002
  for (const { name, cid: target } of entries) {
6043
7003
  if (name.slice(prefix.length).includes("/"))
6044
7004
  throw new HostError(
6045
- `Skill Name "${name}" must be flat under ${meta.skillPath}.`,
7005
+ `Skill Name "${name}" must be flat under ${globalDir}.`,
6046
7006
  );
6047
7007
  const cid = await artifactValue(
6048
7008
  context.store,
@@ -6056,13 +7016,18 @@ export async function swarmSkills(
6056
7016
  throw new HostError(
6057
7017
  `Name "${name}" is not an exact Skill type Bundle.`,
6058
7018
  );
6059
- const identity = await skillIdentity(bundle);
6060
- if (identities.has(identity))
7019
+ const metadata = await inspectSkillBundle(bundle);
7020
+ if (identities.has(metadata.name))
6061
7021
  throw new HostError(
6062
- `Duplicate Skill installation name "${identity}" in this Swarm.`,
7022
+ `Duplicate Skill installation name "${metadata.name}" in this Swarm.`,
6063
7023
  );
6064
- identities.add(identity);
6065
- 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
+ });
6066
7031
  }
6067
7032
  const missing = requested.filter(
6068
7033
  (reference) =>
@@ -6070,56 +7035,438 @@ export async function swarmSkills(
6070
7035
  (skill) => skill.name === reference || skill.identity === reference,
6071
7036
  ),
6072
7037
  );
6073
- if (missing.length && !attempt && header.source === "cache") {
6074
- 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
+ });
6075
7043
  continue;
6076
7044
  }
6077
7045
  if (missing.length)
6078
7046
  throw new HostError(
6079
- `Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`,
7047
+ `Skill identities or shared Names not found under ${globalDir}: ${missing.join(", ")}.`,
6080
7048
  );
6081
7049
  return result;
6082
7050
  }
6083
7051
  }
6084
- export async function resolveTemplateSelector(
7052
+
7053
+ export async function swarmTypeSkills(
6085
7054
  context: SwarmContext,
6086
- selector: string,
6087
7055
  configUrl: string,
6088
- ): Promise<string> {
6089
- formalName(selector);
6090
- const warm = await localHeader(context, configUrl);
6091
- if (warm && !warm.header.localSourceReady)
6092
- await lazyPrivateSource(
6093
- context,
6094
- configUrl,
6095
- warm.account,
6096
- warm.header.config,
6097
- );
6098
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
6099
- if (!hasMeta(header.snapshot) && header.source === "cache")
6100
- header = await swarmHeader(context, configUrl, true);
6101
- for (let attempt = 0; ; attempt++) {
6102
- const meta = await swarmMeta(context, header);
6103
- const name = formalName(`${meta.templatePath}/${selector}`);
6104
- 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(
6105
7107
  context.store,
6106
- header.snapshot,
6107
7108
  name,
7109
+ targetCid,
6108
7110
  );
6109
- if (target) return artifactValue(context.store, target.toString());
6110
- if (attempt || header.source !== "cache")
6111
- throw new HostError(
6112
- `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,
6113
7152
  );
6114
- 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
+ }
6115
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
+ };
6116
7186
  }
6117
- export function templateName(name: string): string {
6118
- 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;
6119
7206
  throw new HostError(
6120
- "Template NAME must be a safe relative Name, not a URI.",
7207
+ `Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
6121
7208
  );
6122
- return formalName(name);
7209
+ }
7210
+ if (bundle.schemaKey !== skillSchema.cid.toString())
7211
+ throw new HostError(
7212
+ `Skill target ${skillCid} must directly reference an exact Skill type Bundle, not an Artifact or another content type.`,
7213
+ );
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
+ );
6123
7470
  }
6124
7471
  async function templateEntry(
6125
7472
  context: SwarmContext,
@@ -6157,18 +7504,63 @@ async function retainDaemonRoots(
6157
7504
  store: IpfsStore,
6158
7505
  owner: string,
6159
7506
  roots: readonly string[],
7507
+ signal?: AbortSignal,
6160
7508
  ): Promise<void> {
6161
7509
  const unique = [...new Set(roots)];
7510
+ const options: [] | [{ signal: AbortSignal }] = signal ? [{ signal }] : [];
6162
7511
  if (!store.supportsRetention) {
6163
- for (const root of unique) await store.prepare(root);
7512
+ for (const root of unique) await store.prepare(root, ...options);
6164
7513
  return;
6165
7514
  }
6166
- await store.recoverOwner(owner, []);
7515
+ await store.recoverOwner(owner, [], ...options);
6167
7516
  if (unique.length) {
6168
- await store.retain(owner, unique);
6169
- await store.confirmRetained(owner, unique);
7517
+ await store.retain(owner, unique, ...options);
7518
+ await store.confirmRetained(owner, unique, ...options);
6170
7519
  }
6171
- await store.reconcile(owner, unique);
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
+ }
7561
+ }
7562
+ await retainDaemonRoots(context.store, owner, roots);
7563
+ return entries.length;
6172
7564
  }
6173
7565
  export async function syncSwarmTemplates(
6174
7566
  context: SwarmContext,
@@ -6245,6 +7637,22 @@ export async function syncPivotReplicationAndIndex(
6245
7637
  signal?: AbortSignal,
6246
7638
  ): Promise<void> {
6247
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> {
6248
7656
  const headCid = CID.parse(header.stateCid).toV1().toString();
6249
7657
  const previousHead = withState(
6250
7658
  context,
@@ -6254,7 +7662,7 @@ export async function syncPivotReplicationAndIndex(
6254
7662
  await pinAdd(context.node, headCid, true, signal);
6255
7663
  }
6256
7664
  const owner = `daemon-pivot-root:${createHash("sha256").update(configUrl).digest("hex")}`;
6257
- await retainDaemonRoots(context.store, owner, [headCid]);
7665
+ await retainDaemonRoots(context.store, owner, [headCid], signal);
6258
7666
  await withStateAsync(context, (state) =>
6259
7667
  indexV7UnixfsSwarm(state, context.store, configUrl, headCid, {
6260
7668
  skipRootFiles: v7RootSkipFiles(header.snapshot),
@@ -6271,52 +7679,38 @@ export async function swarmTemplates(
6271
7679
  selector?: string,
6272
7680
  ) {
6273
7681
  if (selector !== undefined) templateName(selector);
6274
- const warm = await localHeader(context, configUrl);
6275
- if (warm && !warm.header.localSourceReady)
6276
- await lazyPrivateSource(
6277
- context,
6278
- configUrl,
6279
- warm.account,
6280
- warm.header.config,
6281
- );
6282
- let header =
6283
- warm?.header ??
6284
- (await swarmHeader(context, configUrl, undefined, "local-first"));
6285
- for (let attempt = 0; ; attempt++) {
6286
- if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
6287
- header = await swarmHeader(context, configUrl, true, "local-first");
6288
- continue;
6289
- }
6290
- const meta = await swarmMeta(context, header);
6291
- const name =
6292
- selector === undefined
6293
- ? undefined
6294
- : formalName(`${meta.templatePath}/${selector}`);
6295
- if (
6296
- name &&
6297
- !(await resolveSnapshotName(context.store, header.snapshot, name)) &&
6298
- header.source === "cache" &&
6299
- !attempt
6300
- ) {
6301
- header = await swarmHeader(context, configUrl, true, "local-first");
6302
- continue;
6303
- }
6304
- const selectors =
6305
- selector === undefined
6306
- ? (
6307
- await listSubtreeNames(
6308
- context.store,
6309
- header.snapshot,
6310
- meta.templatePath,
6311
- false,
6312
- )
6313
- ).map((entry) => entry.name.slice(meta.templatePath.length + 1))
6314
- : [selector];
6315
- const items = [];
6316
- for (const item of selectors)
6317
- items.push(await templateEntry(context, configUrl, header, item));
6318
- return items;
6319
- }
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;
6320
7714
  }
6321
7715
  export async function setSwarmTemplate(
6322
7716
  context: SwarmContext,
@@ -6326,7 +7720,7 @@ export async function setSwarmTemplate(
6326
7720
  expect?: string,
6327
7721
  ) {
6328
7722
  templateName(selector);
6329
- await pointer(context, configUrl);
7723
+ await swarmFsTransport.pointer(context, configUrl);
6330
7724
  const content = await templatePublicationSource(source, context.store);
6331
7725
  const details = await inspectTemplate(context.store, content);
6332
7726
  let location:
@@ -6367,87 +7761,58 @@ export async function removeSwarmTemplate(
6367
7761
  ) {
6368
7762
  templateName(selector);
6369
7763
  const expected = exactCid(expect);
6370
- const head = await pointer(context, configUrl);
6371
7764
  let basis: string | undefined;
6372
- for (let attempt = 0; attempt < 8; attempt++) {
6373
- const currentHead = await head.read();
6374
- const current = await readSnapshot(
6375
- context.store,
6376
- currentHead.root,
6377
- configUrl,
6378
- );
6379
- const meta = await swarmMeta(context, { snapshot: current });
6380
- const name = formalName(`${meta.templatePath}/${selector}`);
6381
- if (basis !== undefined && basis !== name)
6382
- throw new HostError(
6383
- "Template Meta path changed during removal; inspect and retry.",
6384
- 3,
6385
- "EDIT_CONFLICT",
6386
- "publication",
6387
- );
6388
- basis = name;
6389
- const old = (
6390
- await resolveSnapshotName(context.store, current, name)
6391
- )?.toString();
6392
- if (!old)
6393
- throw new HostError(
6394
- `Template Name "${name}" is missing; nothing was removed.`,
6395
- );
6396
- if (old !== expected)
6397
- throw new HostError(
6398
- `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
6399
- 3,
6400
- "EDIT_CONFLICT",
6401
- "publication",
6402
- );
6403
- let next: string;
6404
- if (isV7Snapshot(current)) {
6405
- next = await prepareV7PathDelete(context, configUrl, current, name);
6406
- } else {
6407
- const names = { ...current.names };
6408
- delete names[name];
6409
- next = await prepareNamesPublication(
6410
- context,
6411
- configUrl,
6412
- current,
6413
- names,
6414
- [],
6415
- );
6416
- }
6417
- try {
6418
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
6419
- } catch (cause) {
6420
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
6421
- throw cause;
6422
- if (cause instanceof ScopeApiError && cause.status === 412) continue;
6423
- 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) =>
6424
7809
  `Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
6425
- 1,
6426
- "HEAD_UNCONFIRMED",
6427
- "publication",
6428
- );
6429
- }
6430
- try {
6431
- await swarmHeader(context, configUrl, true);
6432
- } catch (cause) {
6433
- throw new HostError(
7810
+ pinStale: (cause) =>
6434
7811
  `Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
6435
- 1,
6436
- "PIN_STALE",
6437
- "publication",
6438
- );
6439
- }
6440
- return {
6441
- swarm: configUrl,
6442
- templatePath: meta.templatePath,
6443
- metaCid: metaCid(current),
6444
- selector,
6445
- name,
6446
- reference: formatNameReference(configUrl, name),
6447
- targetCid: old,
6448
- };
6449
- }
6450
- 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;
6451
7816
  }
6452
7817
  async function registryAssociations(
6453
7818
  context: SwarmContext,
@@ -6480,10 +7845,11 @@ export async function swarmRegistrations(
6480
7845
  context: SwarmContext,
6481
7846
  configUrl: string,
6482
7847
  ): Promise<Association[]> {
6483
- let header = await swarmHeader(context, configUrl);
6484
- if (!hasMeta(header.snapshot) && header.source === "cache")
6485
- header = await swarmHeader(context, configUrl, true);
6486
- 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);
6487
7853
  }
6488
7854
  export async function swarmAssociation(
6489
7855
  context: SwarmContext,
@@ -6491,18 +7857,6 @@ export async function swarmAssociation(
6491
7857
  schemaCid: string,
6492
7858
  mode: "active" | "local-first" = "active",
6493
7859
  ): Promise<Association | undefined> {
6494
- const warm =
6495
- mode === "local-first" ? await localHeader(context, configUrl) : undefined;
6496
- if (warm && !warm.header.localSourceReady)
6497
- await lazyPrivateSource(
6498
- context,
6499
- configUrl,
6500
- warm.account,
6501
- warm.header.config,
6502
- );
6503
- let header = warm?.header ?? (await swarmHeader(context, configUrl));
6504
- if (!hasMeta(header.snapshot) && header.source === "cache")
6505
- header = await swarmHeader(context, configUrl, true);
6506
7860
  const findAssociation = async (
6507
7861
  current: SwarmHeader,
6508
7862
  ): Promise<Association | undefined> => {
@@ -6521,72 +7875,24 @@ export async function swarmAssociation(
6521
7875
  (item) => item.schemaCid === schemaCid,
6522
7876
  );
6523
7877
  };
6524
- let association = await findAssociation(header);
6525
- if (!association && header.source === "cache") {
6526
- header = await swarmHeader(context, configUrl, true);
6527
- association = await findAssociation(header);
6528
- }
6529
- return association;
6530
- }
6531
- async function prepareV7PathSet(
6532
- context: SwarmContext,
6533
- configUrl: string,
6534
- current: Snapshot,
6535
- name: string,
6536
- targetCid: CID,
6537
- roots: Iterable<string>,
6538
- retainedRoots?: Iterable<string>,
6539
- ): Promise<string> {
6540
- const { newRootCid, createdDirCids } = await setUnixfsPath(
6541
- context.store,
6542
- CID.parse(current.stateBundle!.cid),
6543
- name,
6544
- targetCid,
6545
- );
6546
- const recursiveRoots = [...new Set(roots)];
6547
- const retainedRecursive = [...new Set(retainedRoots ?? roots)];
6548
- await provideShallowContent(context.store, {
6549
- directBlocks: createdDirCids,
6550
- recursiveRoots,
6551
- retainedDirect: createdDirCids,
6552
- retainedRecursive,
6553
- endpoint: context.node!.api,
6554
- ...(context.fetch ? { fetcher: context.fetch } : {}),
6555
- authorizationToken: context.node!.auth,
6556
- owner: `publication:${newRootCid.toString()}`,
6557
- });
6558
- withState(context, (state) => {
6559
- state.invalidateSwarmHeader(configUrl);
6560
- });
6561
- return newRootCid.toString();
6562
- }
6563
- async function prepareV7PathDelete(
6564
- context: SwarmContext,
6565
- configUrl: string,
6566
- current: Snapshot,
6567
- name: string,
6568
- ): Promise<string> {
6569
- const { newRootCid, createdDirCids } = await deleteUnixfsPath(
6570
- context.store,
6571
- CID.parse(current.stateBundle!.cid),
6572
- name,
6573
- );
6574
- await provideShallowContent(context.store, {
6575
- directBlocks: createdDirCids,
6576
- recursiveRoots: [],
6577
- retainedDirect: createdDirCids,
6578
- retainedRecursive: [],
6579
- endpoint: context.node!.api,
6580
- ...(context.fetch ? { fetcher: context.fetch } : {}),
6581
- authorizationToken: context.node!.auth,
6582
- owner: `publication:${newRootCid.toString()}`,
6583
- });
6584
- withState(context, (state) => {
6585
- 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
+ },
6586
7890
  });
6587
- return newRootCid.toString();
7891
+ return ctx.header === cachedHeader
7892
+ ? cachedResult
7893
+ : findAssociation(ctx.header);
6588
7894
  }
6589
- async function prepareNamesPublication(
7895
+ export async function prepareNamesPublication(
6590
7896
  context: SwarmContext,
6591
7897
  configUrl: string,
6592
7898
  current: Snapshot,
@@ -6621,7 +7927,7 @@ async function editSwarmAssociation(
6621
7927
  association: Association | undefined,
6622
7928
  replace: boolean,
6623
7929
  ): Promise<void> {
6624
- const head = await pointer(context, configUrl);
7930
+ await swarmFsTransport.pointer(context, configUrl);
6625
7931
  if (association) {
6626
7932
  const app = await openBundle(CID.parse(association.appCid), {
6627
7933
  resolveCid: (cid) => context.store.block.get(cid.toString()),
@@ -6634,71 +7940,46 @@ async function editSwarmAssociation(
6634
7940
  const roots = association
6635
7941
  ? await dependencies(context.store, association.appCid)
6636
7942
  : new Set<string>();
6637
- for (let attempt = 0; attempt < 8; attempt++) {
6638
- const currentHead = await head.read();
6639
- const current = await readSnapshot(
6640
- context.store,
6641
- currentHead.root,
6642
- configUrl,
6643
- );
6644
- assertNamesRegistry(current);
6645
- const meta = await swarmMeta(context, { snapshot: current });
6646
- const name = formalName(`${meta.registryPath}/${schemaCid}`);
6647
- const oldCid = (
6648
- await resolveSnapshotName(context.store, current, name)
6649
- )?.toString();
6650
- if (association) {
6651
- if (oldCid === association.appCid) return;
6652
- if (oldCid && !replace)
6653
- throw new HostError("Schema has another association; use --replace.");
6654
- } else if (!oldCid) {
6655
- throw new HostError(
6656
- "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
6657
- );
6658
- }
6659
- let next: string;
6660
- if (isV7Snapshot(current)) {
6661
- next = association
6662
- ? await prepareV7PathSet(
6663
- context,
6664
- configUrl,
6665
- current,
6666
- name,
6667
- CID.parse(association.appCid),
6668
- roots,
6669
- )
6670
- : await prepareV7PathDelete(context, configUrl, current, name);
6671
- } else {
6672
- const names = { ...current.names };
6673
- if (association) names[name] = CID.parse(association.appCid);
6674
- else delete names[name];
6675
- next = await prepareNamesPublication(
6676
- context,
6677
- configUrl,
6678
- current,
6679
- names,
6680
- roots,
6681
- );
6682
- }
6683
- try {
6684
- await writeNamesHead(context, configUrl, head, next, currentHead.cid);
6685
- return;
6686
- } catch (cause) {
6687
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
6688
- throw cause;
6689
- 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)
6690
7966
  throw new HostError(
6691
- `Registry publication unconfirmed for ${configUrl}: ${message(cause)}. Inspect the Swarm registry before retry.`,
6692
- 1,
6693
- "HEAD_UNCONFIRMED",
6694
- "publication",
7967
+ "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
6695
7968
  );
6696
- continue;
6697
- }
6698
- }
6699
- throw new HostError(
6700
- `HEAD is busy for ${configUrl}; retry the registry edit.`,
6701
- );
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
+ });
6702
7983
  }
6703
7984
  export async function setSwarmAssociation(
6704
7985
  context: SwarmContext,
@@ -6853,64 +8134,38 @@ export async function unpublish(
6853
8134
  );
6854
8135
  const name = formalName(options.name);
6855
8136
  const expected = exactCid(options.expect);
6856
- const head = await pointer(context, options.swarm);
6857
- for (let attempt = 0; attempt < 8; attempt++) {
6858
- const currentHead = await head.read();
6859
- const current = await readSnapshot(
6860
- context.store,
6861
- currentHead.root,
6862
- options.swarm,
6863
- );
6864
- const old = (
6865
- await resolveSnapshotName(context.store, current, name)
6866
- )?.toString();
6867
- if (!old)
6868
- throw new HostError(`Name "${name}" is missing; nothing was removed.`);
6869
- if (old !== expected)
6870
- throw new HostError(
6871
- `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
6872
- 3,
6873
- "EDIT_CONFLICT",
6874
- "publication",
6875
- );
6876
- let next: string;
6877
- if (isV7Snapshot(current)) {
6878
- next = await prepareV7PathDelete(context, options.swarm, current, name);
6879
- } else {
6880
- const names = { ...current.names };
6881
- delete names[name];
6882
- next = await prepareNamesPublication(
6883
- context,
6884
- options.swarm,
6885
- current,
6886
- names,
6887
- [],
6888
- );
6889
- }
6890
- try {
6891
- await head.write(next, currentHead.cid, uniqueId());
6892
- } catch (cause) {
6893
- if (cause instanceof ScopeApiError && cause.status === 412) continue;
6894
- 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) =>
6895
8162
  `Unpublish unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
6896
- 1,
6897
- "HEAD_UNCONFIRMED",
6898
- "publication",
6899
- );
6900
- }
6901
- try {
6902
- await swarmHeader(context, options.swarm, true);
6903
- } catch (cause) {
6904
- throw new HostError(
8163
+ pinStale: (cause) =>
6905
8164
  `Unpublish committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
6906
- 1,
6907
- "PIN_STALE",
6908
- "publication",
6909
- );
6910
- }
6911
- return { name, targetCid: old };
6912
- }
6913
- throw new HostError("HEAD is busy; retry unpublish.");
8165
+ headBusy: () => "HEAD is busy; retry unpublish.",
8166
+ },
8167
+ });
8168
+ return committed.result;
6914
8169
  }
6915
8170
  export async function publish(
6916
8171
  context: SwarmContext,
@@ -6939,7 +8194,7 @@ async function publishContent(
6939
8194
  throw new HostError(
6940
8195
  "Publication requires a selected Swarm configuration URL or alias.",
6941
8196
  );
6942
- const head = await pointer(context, options.swarm);
8197
+ await swarmFsTransport.pointer(context, options.swarm);
6943
8198
  const roots = await dependencies(context.store, content);
6944
8199
  const currentRoots = [...(await currentDependencies(context.store, content))];
6945
8200
  await withStateAsync(context, (state) =>
@@ -6968,84 +8223,52 @@ async function publishContent(
6968
8223
  timestamp: new Date().toISOString(),
6969
8224
  });
6970
8225
  roots.add(candidate);
6971
- if (expected)
6972
- for (const root of await dependencies(context.store, expected))
6973
- roots.add(root);
6974
- for (let attempt = 0; attempt < 8; attempt++) {
6975
- const currentHead = await head.read(),
6976
- current = await readSnapshot(
6977
- context.store,
6978
- currentHead.root,
6979
- options.swarm,
6980
- );
6981
- if (nameForSnapshot) {
6982
- name = await nameForSnapshot(current);
6983
- 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)
6984
8249
  throw new HostError(
6985
- "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.`,
6986
8251
  3,
6987
8252
  "EDIT_CONFLICT",
6988
8253
  "publication",
6989
8254
  );
6990
- resolvedName = name;
6991
- }
6992
- const existing = (
6993
- await resolveSnapshotName(context.store, current, name)
6994
- )?.toString();
6995
- if (existing !== expected)
6996
- throw new HostError(
6997
- `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.`,
6998
- 3,
6999
- "EDIT_CONFLICT",
7000
- "publication",
7001
- );
7002
- const retained = [
7003
- candidate,
7004
- ...(expected ? await dependencies(context.store, expected) : []),
7005
- ];
7006
- const next = isV7Snapshot(current)
7007
- ? await prepareV7PathSet(
7008
- context,
7009
- options.swarm,
7010
- current,
7011
- name,
7012
- CID.parse(candidate),
7013
- roots,
7014
- retained,
7015
- )
7016
- : await prepareNamesPublication(
7017
- context,
7018
- options.swarm,
7019
- current,
7020
- { ...current.names, [name]: CID.parse(candidate) },
7021
- roots,
7022
- retained,
7023
- );
7024
- try {
7025
- await writeNamesHead(context, options.swarm, head, next, currentHead.cid);
7026
- } catch (cause) {
7027
- if (cause instanceof HostError && cause.code === "PIVOT_PIN_FAILED")
7028
- throw cause;
7029
- if (!(cause instanceof ScopeApiError) || cause.status !== 412)
7030
- throw new HostError(
7031
- `HEAD publication unconfirmed: ${message(cause)}. Candidate ${candidate} remains retained; inspect HEAD before retry.`,
7032
- 1,
7033
- "HEAD_UNCONFIRMED",
7034
- "publication",
7035
- );
7036
- continue;
7037
- }
7038
- try {
7039
- await swarmHeader(context, options.swarm, true);
7040
- } catch (cause) {
7041
- 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) =>
7042
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.`,
7043
- 1,
7044
- "PIN_STALE",
7045
- "publication",
7046
- );
7047
- }
7048
- return candidate;
7049
- }
7050
- 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;
7051
8274
  }