@ipab/cli 0.1.0-rc.7 → 0.1.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +24 -1
  2. package/dist/app-authoring.d.ts.map +1 -1
  3. package/dist/app-authoring.js +2 -44
  4. package/dist/app-authoring.js.map +1 -1
  5. package/dist/app-prebuild.d.ts +18 -0
  6. package/dist/app-prebuild.d.ts.map +1 -1
  7. package/dist/app-prebuild.js +46 -0
  8. package/dist/app-prebuild.js.map +1 -1
  9. package/dist/builtins/skill.ipab.car +0 -0
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +290 -152
  12. package/dist/cli.js.map +1 -1
  13. package/dist/config.d.ts +1 -1
  14. package/dist/config.d.ts.map +1 -1
  15. package/dist/config.js +9 -4
  16. package/dist/config.js.map +1 -1
  17. package/dist/context.d.ts +4 -0
  18. package/dist/context.d.ts.map +1 -1
  19. package/dist/context.js +11 -2
  20. package/dist/context.js.map +1 -1
  21. package/dist/errors.d.ts +1 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +1 -20
  24. package/dist/errors.js.map +1 -1
  25. package/dist/host-error.d.ts +9 -0
  26. package/dist/host-error.d.ts.map +1 -0
  27. package/dist/host-error.js +21 -0
  28. package/dist/host-error.js.map +1 -0
  29. package/dist/ipc.d.ts.map +1 -1
  30. package/dist/ipc.js +17 -0
  31. package/dist/ipc.js.map +1 -1
  32. package/dist/kubo-install.js +1 -1
  33. package/dist/kubo-install.js.map +1 -1
  34. package/dist/kubo-peers.d.ts.map +1 -1
  35. package/dist/kubo-peers.js +2 -1
  36. package/dist/kubo-peers.js.map +1 -1
  37. package/dist/kubo-topology.d.ts +19 -0
  38. package/dist/kubo-topology.d.ts.map +1 -0
  39. package/dist/kubo-topology.js +105 -0
  40. package/dist/kubo-topology.js.map +1 -0
  41. package/dist/kubo.d.ts +10 -0
  42. package/dist/kubo.d.ts.map +1 -1
  43. package/dist/kubo.js +96 -15
  44. package/dist/kubo.js.map +1 -1
  45. package/dist/space-path.d.ts +3 -0
  46. package/dist/space-path.d.ts.map +1 -0
  47. package/dist/space-path.js +17 -0
  48. package/dist/space-path.js.map +1 -0
  49. package/dist/space.d.ts +1 -2
  50. package/dist/space.d.ts.map +1 -1
  51. package/dist/space.js +2 -15
  52. package/dist/space.js.map +1 -1
  53. package/dist/state-storage.js +1 -1
  54. package/dist/state-storage.js.map +1 -1
  55. package/dist/state.d.ts +2 -0
  56. package/dist/state.d.ts.map +1 -1
  57. package/dist/state.js +31 -12
  58. package/dist/state.js.map +1 -1
  59. package/dist/swarm-files.d.ts +1 -1
  60. package/dist/swarm-files.d.ts.map +1 -1
  61. package/dist/swarm-files.js +2 -2
  62. package/dist/swarm-files.js.map +1 -1
  63. package/dist/swarm-meta.d.ts +1 -4
  64. package/dist/swarm-meta.d.ts.map +1 -1
  65. package/dist/swarm-meta.js +3 -34
  66. package/dist/swarm-meta.js.map +1 -1
  67. package/dist/swarm-observations.d.ts +40 -0
  68. package/dist/swarm-observations.d.ts.map +1 -0
  69. package/dist/swarm-observations.js +262 -0
  70. package/dist/swarm-observations.js.map +1 -0
  71. package/dist/swarm.d.ts +119 -6
  72. package/dist/swarm.d.ts.map +1 -1
  73. package/dist/swarm.js +662 -80
  74. package/dist/swarm.js.map +1 -1
  75. package/package.json +4 -4
  76. package/src/app-authoring.ts +12 -53
  77. package/src/app-prebuild.ts +61 -0
  78. package/src/cli.ts +370 -190
  79. package/src/config.ts +12 -4
  80. package/src/context.ts +15 -2
  81. package/src/errors.ts +1 -25
  82. package/src/host-error.ts +26 -0
  83. package/src/ipc.ts +19 -0
  84. package/src/kubo-install.ts +1 -1
  85. package/src/kubo-peers.ts +2 -3
  86. package/src/kubo-topology.ts +135 -0
  87. package/src/kubo.ts +134 -25
  88. package/src/space-path.ts +30 -0
  89. package/src/space.ts +2 -28
  90. package/src/state-storage.ts +1 -1
  91. package/src/state.ts +37 -12
  92. package/src/swarm-files.ts +2 -1
  93. package/src/swarm-meta.ts +15 -34
  94. package/src/swarm-observations.ts +374 -0
  95. package/src/swarm.ts +942 -91
package/src/swarm.ts CHANGED
@@ -2,6 +2,7 @@ import { createReadStream } from "node:fs";
2
2
  import { lstat, mkdir, open } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
5
6
  import { createHash, randomBytes } from "node:crypto";
6
7
  import { stringify } from "yaml";
7
8
  import { CarBlockIterator } from "@ipld/car/iterator";
@@ -92,11 +93,24 @@ import {
92
93
  peerProof,
93
94
  prepareNode,
94
95
  startNode,
96
+ stopNode,
97
+ probePeer,
98
+ nodeConnections,
95
99
  validateAddress,
96
100
  type KuboNode,
97
101
  type ListenMode,
98
102
  } from "./kubo.js";
99
103
  import { memberPeers } from "./kubo-peering.js";
104
+ import { PivotCandidates } from "./kubo-topology.js";
105
+ import {
106
+ networkingBinding,
107
+ pivotLocalStatus,
108
+ readNetworkingSnapshot,
109
+ writeNetworkingSnapshot,
110
+ networkingAccount,
111
+ type LocalObservations,
112
+ type NetworkingSnapshot,
113
+ } from "./swarm-observations.js";
100
114
  import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
101
115
  import { inspectTemplate, templatePublicationSource } from "./templates.js";
102
116
  import { seedSkillSource } from "./skill-source.js";
@@ -106,6 +120,9 @@ import {
106
120
  swarmMetaType,
107
121
  swarmMetaSchema,
108
122
  swarmStateType,
123
+ previousSwarmStateType,
124
+ previousSwarmStateSchema,
125
+ parseSwarmState,
109
126
  legacySwarmStateType,
110
127
  legacySwarmStateSchema,
111
128
  isSwarmStateSchema,
@@ -138,6 +155,7 @@ export interface Profile {
138
155
  name: string;
139
156
  description?: string;
140
157
  addresses: string[];
158
+ pivot?: boolean;
141
159
  updatedAt: string;
142
160
  }
143
161
  export interface AccountProfile {
@@ -150,7 +168,7 @@ export interface Snapshot {
150
168
  v: 2;
151
169
  names: Record<string, CID>;
152
170
  registrations?: Record<string, { appCid: CID; argv: string[] }>;
153
- stateBundle?: { meta: SwarmMeta; cid: string };
171
+ stateBundle?: { meta: SwarmMeta; cid: string; configUrl?: string };
154
172
  }
155
173
  export interface MembershipRequest {
156
174
  v: 1;
@@ -183,6 +201,7 @@ export interface SwarmContext {
183
201
  finishRead?: () => Promise<void>;
184
202
  identity?: Identity;
185
203
  listen?: ListenMode;
204
+ pivot?: boolean;
186
205
  }
187
206
  async function contextIdentity(
188
207
  context: SwarmContext,
@@ -360,6 +379,10 @@ function client(
360
379
  }
361
380
  function parseOrganization(value: unknown, configUrl: string): Organization {
362
381
  const data = object(value, "organization configuration");
382
+ if (data.kind === "ipab-config-reservation")
383
+ throw new HostError(
384
+ "Swarm creation is initializing; the Owner must resume the saved creation operation.",
385
+ );
363
386
  const { scopeId } = coordinates(configUrl);
364
387
  if (
365
388
  Object.keys(data).sort().join() !==
@@ -455,10 +478,13 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
455
478
  function parseProfile(value: unknown, expectedPeer: string): Profile {
456
479
  const data = object(value, "member profile");
457
480
  if (
458
- ![
459
- "addresses,name,updatedAt",
460
- "addresses,description,name,updatedAt",
461
- ].includes(Object.keys(data).sort().join()) ||
481
+ Object.keys(data).some(
482
+ (key) =>
483
+ !["addresses", "name", "description", "updatedAt", "pivot"].includes(
484
+ key,
485
+ ),
486
+ ) ||
487
+ (data.pivot !== undefined && typeof data.pivot !== "boolean") ||
462
488
  typeof data.name !== "string" ||
463
489
  data.name.length > 256 ||
464
490
  (data.description !== undefined &&
@@ -483,11 +509,15 @@ function parseProfile(value: unknown, expectedPeer: string): Profile {
483
509
  ? { description: data.description }
484
510
  : {}),
485
511
  addresses,
512
+ ...(typeof data.pivot === "boolean" ? { pivot: data.pivot } : {}),
486
513
  updatedAt: data.updatedAt,
487
514
  };
488
515
  }
489
- export async function swarmMembers(context: SwarmContext, url: string) {
490
- const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
516
+ async function memberDirectory(
517
+ context: SwarmContext,
518
+ url: string,
519
+ config: Organization,
520
+ ) {
491
521
  const c = coordinates(url),
492
522
  api = client(context, c.service);
493
523
  const members = await boundedMap(config.members, async (member) => {
@@ -495,14 +525,354 @@ export async function swarmMembers(context: SwarmContext, url: string) {
495
525
  (await api.read(c.scopeId, member.profileId)).value,
496
526
  member.peerId,
497
527
  );
528
+ return { member, profile };
529
+ });
530
+ return members;
531
+ }
532
+ async function localObservations(
533
+ context: SwarmContext,
534
+ url: string,
535
+ config: Organization,
536
+ ) {
537
+ try {
538
+ const account =
539
+ context.identity?.publicKey ??
540
+ (await networkingAccount(context.stateDir, url));
541
+ const self = config.members.find((member) => member.publicKey === account);
542
+ if (!self || !account)
543
+ throw new HostError(
544
+ "No bound local daemon observations; run ipab daemon after normal membership activation.",
545
+ );
546
+ const c = coordinates(url);
547
+ const local = await readNetworkingSnapshot(
548
+ context.stateDir,
549
+ url,
550
+ networkingBinding(url, account, config),
551
+ nodeScope(c.service, config.scopeId),
552
+ config.epoch,
553
+ self.peerId,
554
+ );
498
555
  return {
499
- publicKey: member.publicKey,
500
- role: member.publicKey === config.owner ? "owner" : "member",
501
- name: profile.name,
502
- description: profile.description ?? "",
556
+ account:
557
+ context.identity?.publicKey ?? (local.snapshot ? account : undefined),
558
+ local,
503
559
  };
560
+ } catch (cause) {
561
+ return {
562
+ account: context.identity?.publicKey,
563
+ local: {
564
+ status: "unavailable",
565
+ updatedAt: null,
566
+ verifiedAt: null,
567
+ error: message(cause),
568
+ snapshot: null,
569
+ } satisfies LocalObservations,
570
+ };
571
+ }
572
+ }
573
+ function observationSummary(local: LocalObservations) {
574
+ return {
575
+ status: local.status,
576
+ updatedAt: local.updatedAt,
577
+ verifiedAt: local.verifiedAt,
578
+ error: local.error,
579
+ };
580
+ }
581
+ interface InspectionSnapshot {
582
+ v: 1;
583
+ configUrl: string;
584
+ updatedAt: number;
585
+ config: Organization;
586
+ directory: Awaited<ReturnType<typeof memberDirectory>>;
587
+ head: { root: string; cid: string };
588
+ }
589
+ function parseInspection(input: unknown, url: string): InspectionSnapshot {
590
+ const data = object(input, "Swarm inspection cache");
591
+ if (
592
+ Object.keys(data).sort().join() !==
593
+ "config,configUrl,directory,head,updatedAt,v" ||
594
+ data.v !== 1 ||
595
+ data.configUrl !== url ||
596
+ typeof data.updatedAt !== "number" ||
597
+ !Number.isSafeInteger(data.updatedAt) ||
598
+ data.updatedAt < 0 ||
599
+ data.updatedAt > 8_640_000_000_000_000 ||
600
+ !Array.isArray(data.directory) ||
601
+ data.directory.length > 256
602
+ )
603
+ throw new HostError(
604
+ "Invalid Swarm inspection cache; retry with --refresh.",
605
+ );
606
+ const config = parseOrganization(data.config, url);
607
+ if (
608
+ config.members.some(
609
+ (member) => !/^[A-Za-z0-9]{32,128}$/.test(member.peerId),
610
+ )
611
+ )
612
+ throw new HostError("Invalid cached member PeerID; use --refresh.");
613
+ if (data.directory.length !== config.members.length)
614
+ throw new HostError(
615
+ "Incomplete Swarm inspection directory; use --refresh.",
616
+ );
617
+ const directory = data.directory.map((input: unknown, index) => {
618
+ const entry = object(input, "cached directory entry");
619
+ const member = config.members[index]!;
620
+ if (
621
+ Object.keys(entry).sort().join() !== "member,profile" ||
622
+ JSON.stringify(entry.member) !== JSON.stringify(member)
623
+ )
624
+ throw new HostError("Cached member binding mismatch; use --refresh.");
625
+ return { member, profile: parseProfile(entry.profile, member.peerId) };
504
626
  });
505
- return { configUrl: url, members };
627
+ const head = object(data.head, "cached HEAD");
628
+ if (
629
+ Object.keys(head).sort().join() !== "cid,root" ||
630
+ typeof head.root !== "string" ||
631
+ typeof head.cid !== "string" ||
632
+ exactCid(head.root) !== head.root ||
633
+ exactCid(head.cid) !== head.cid
634
+ )
635
+ throw new HostError("Invalid cached HEAD; use --refresh.");
636
+ return {
637
+ v: 1,
638
+ configUrl: url,
639
+ updatedAt: data.updatedAt,
640
+ config,
641
+ directory,
642
+ head: { root: head.root, cid: head.cid },
643
+ };
644
+ }
645
+ async function inspection(context: SwarmContext, url: string, refresh = false) {
646
+ canonicalSwarmUrl(url);
647
+ const parent = join(context.stateDir, "swarm-inspections");
648
+ const name = `${createHash("sha256").update(url).digest("hex")}.json`;
649
+ const saved = refresh
650
+ ? undefined
651
+ : await readPrivate<unknown>(parent, name, [
652
+ { path: parent, directory: true },
653
+ ]);
654
+ let snapshot: InspectionSnapshot;
655
+ if (saved === undefined) {
656
+ snapshot = await withPrivateLock(
657
+ await privateDirectory(context.stateDir, "swarm-inspections"),
658
+ async () => {
659
+ const { config, variable } = await fetchConfig(context, url);
660
+ const directory = await memberDirectory(context, url, config);
661
+ const c = coordinates(url);
662
+ const head = headValue(
663
+ await client(context, c.service).read(c.scopeId, config.headId),
664
+ );
665
+ const confirmed = await fetchConfig(context, url);
666
+ if (
667
+ variable.cid !== confirmed.variable.cid ||
668
+ JSON.stringify(config) !== JSON.stringify(confirmed.config)
669
+ )
670
+ throw new HostError(
671
+ "Swarm configuration changed during inspection; retry --refresh.",
672
+ );
673
+ // Inspection persists only public declarations, never approval envelopes.
674
+ const publicConfig = {
675
+ ...config,
676
+ members: config.members.map((member) => ({
677
+ ...member,
678
+ approval: null,
679
+ })),
680
+ };
681
+ const fresh = parseInspection(
682
+ {
683
+ v: 1,
684
+ configUrl: url,
685
+ updatedAt: Date.now(),
686
+ config: publicConfig,
687
+ directory: directory.map(({ profile }, index) => ({
688
+ member: publicConfig.members[index],
689
+ profile,
690
+ })),
691
+ head: { root: head.root, cid: head.cid },
692
+ },
693
+ url,
694
+ );
695
+ if (Buffer.byteLength(JSON.stringify(fresh)) > 2 * 1024 * 1024)
696
+ throw new HostError("Swarm inspection snapshot is oversized.");
697
+ await writePrivate(parent, name, fresh);
698
+ return fresh;
699
+ },
700
+ );
701
+ } else {
702
+ snapshot = parseInspection(saved, url);
703
+ }
704
+ const age = Date.now() - snapshot.updatedAt;
705
+ return {
706
+ ...snapshot,
707
+ cache: {
708
+ source: saved === undefined ? ("network" as const) : ("cache" as const),
709
+ updatedAt: new Date(snapshot.updatedAt).toISOString(),
710
+ freshness:
711
+ age >= 0 && age < (context.cacheTtl ?? 300) * 1000
712
+ ? ("current" as const)
713
+ : ("stale" as const),
714
+ },
715
+ };
716
+ }
717
+ export async function swarmMembers(
718
+ context: SwarmContext,
719
+ url: string,
720
+ refresh = false,
721
+ ) {
722
+ const { config, directory, cache } = await inspection(context, url, refresh);
723
+ const observations = await localObservations(context, url, config);
724
+ const members = directory.map(({ member, profile }) => ({
725
+ publicKey: member.publicKey,
726
+ role: member.publicKey === config.owner ? "owner" : "member",
727
+ name: profile.name,
728
+ description: profile.description ?? "",
729
+ pivot: profile.pivot === true,
730
+ localStatus: pivotLocalStatus(
731
+ profile.pivot === true,
732
+ member.publicKey === observations.account,
733
+ profile.addresses,
734
+ member.peerId,
735
+ observations.local,
736
+ ),
737
+ peerId: member.peerId,
738
+ updatedAt: profile.updatedAt,
739
+ }));
740
+ return {
741
+ configUrl: url,
742
+ members,
743
+ cache,
744
+ local: observationSummary(observations.local),
745
+ };
746
+ }
747
+
748
+ export async function swarmNetworking(
749
+ context: SwarmContext,
750
+ url: string,
751
+ config: Organization,
752
+ directory?: Awaited<ReturnType<typeof memberDirectory>>,
753
+ ) {
754
+ directory ??= (await inspection(context, url)).directory;
755
+ const { account, local } = await localObservations(context, url, config);
756
+ const saved = local.snapshot?.connections;
757
+ const observedAt =
758
+ saved?.observedAt == null ? null : new Date(saved.observedAt).toISOString();
759
+ const connectionError =
760
+ local.status !== "current"
761
+ ? (local.error ?? "Daemon observations are not current.")
762
+ : saved === undefined || saved.observedAt === null
763
+ ? "No daemon connection snapshot; run ipab daemon."
764
+ : saved.error;
765
+ const connections = saved?.peers ?? [];
766
+ const freshness =
767
+ connectionError || !saved?.observedAt
768
+ ? observedAt
769
+ ? ("stale" as const)
770
+ : ("unavailable" as const)
771
+ : Date.now() - saved.observedAt > 90_000
772
+ ? ("stale" as const)
773
+ : ("current" as const);
774
+ const currentConnections = freshness === "current";
775
+ return {
776
+ daemon: observationSummary(local),
777
+ connections: {
778
+ observedAt,
779
+ error: connectionError,
780
+ peers: connections,
781
+ freshness,
782
+ },
783
+ pivots: directory
784
+ .filter(({ profile }) => profile.pivot === true)
785
+ .map(({ member, profile }) => {
786
+ const localStatus = pivotLocalStatus(
787
+ true,
788
+ member.publicKey === account,
789
+ profile.addresses,
790
+ member.peerId,
791
+ local,
792
+ );
793
+ const observation = local.snapshot?.pivots.find(
794
+ (entry) => entry.peerId === member.peerId,
795
+ );
796
+ const matching =
797
+ observation &&
798
+ JSON.stringify(observation.addresses) ===
799
+ JSON.stringify([...new Set(profile.addresses)].sort());
800
+ const current = local.status === "current" && matching;
801
+ const actual = connections.filter(
802
+ (entry) => entry.peerId === member.peerId,
803
+ );
804
+ const probeFreshness: LocalObservations["status"] =
805
+ matching && observation.probedAt !== null
806
+ ? current && Date.now() - observation.probedAt <= 90_000
807
+ ? "current"
808
+ : "stale"
809
+ : "unavailable";
810
+ const connectionStatus:
811
+ "self" | "unknown" | "direct" | "relay" | "disconnected" =
812
+ member.publicKey === account
813
+ ? "self"
814
+ : !currentConnections
815
+ ? "unknown"
816
+ : actual.some((entry) => entry.transport === "direct")
817
+ ? "direct"
818
+ : actual.length
819
+ ? "relay"
820
+ : "disconnected";
821
+ return {
822
+ publicKey: member.publicKey,
823
+ name: profile.name,
824
+ peerId: member.peerId,
825
+ pivot: true as const,
826
+ addresses: profile.addresses,
827
+ localStatus,
828
+ selected:
829
+ localStatus === "unknown" ? null : localStatus === "selected",
830
+ failures: matching ? observation.failures : null,
831
+ retryAt:
832
+ matching && observation.retryAt > 0
833
+ ? new Date(observation.retryAt).toISOString()
834
+ : null,
835
+ probe: {
836
+ result: matching ? observation.probe : ("unknown" as const),
837
+ at:
838
+ matching && observation.probedAt !== null
839
+ ? new Date(observation.probedAt).toISOString()
840
+ : null,
841
+ error: matching ? observation.error : null,
842
+ freshness: probeFreshness,
843
+ },
844
+ connection: {
845
+ status: connectionStatus,
846
+ observedAt,
847
+ error: connectionError,
848
+ freshness,
849
+ addresses: actual.map((entry) => entry.address),
850
+ },
851
+ };
852
+ }),
853
+ };
854
+ }
855
+ export async function inspectSwarmStatus(
856
+ context: SwarmContext,
857
+ url: string,
858
+ refresh = false,
859
+ ) {
860
+ const { config, directory, head, cache } = await inspection(
861
+ context,
862
+ url,
863
+ refresh,
864
+ );
865
+ return {
866
+ config,
867
+ head,
868
+ cache,
869
+ state: {
870
+ status: "unavailable" as const,
871
+ error:
872
+ "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
873
+ },
874
+ networking: await swarmNetworking(context, url, config, directory),
875
+ };
506
876
  }
507
877
 
508
878
  function accountProfileLocation(context: SwarmContext, publicKey: string) {
@@ -880,6 +1250,7 @@ async function privateSource(
880
1250
  context: SwarmContext,
881
1251
  record: LocalMembership,
882
1252
  signal?: AbortSignal,
1253
+ candidates?: PivotCandidates,
883
1254
  ) {
884
1255
  const config = record.config!,
885
1256
  secret = record.secret!;
@@ -912,17 +1283,38 @@ async function privateSource(
912
1283
  }
913
1284
  const personal = await storedAccountProfile(context);
914
1285
  const addresses = new Map<string, readonly string[]>();
1286
+ const observationErrors: string[] = [];
915
1287
  const api = client(context, c.service);
916
1288
  let selfProfile: { profile: Profile; cid: string } | undefined;
917
- const profiles = await boundedMap(config.members, (member) =>
918
- api.read(c.scopeId, member.profileId, signal ? { signal } : {}),
919
- );
1289
+ const profiles = await boundedMap(config.members, async (member) => {
1290
+ try {
1291
+ return await api.read(
1292
+ c.scopeId,
1293
+ member.profileId,
1294
+ signal ? { signal } : {},
1295
+ );
1296
+ } catch (cause) {
1297
+ signal?.throwIfAborted();
1298
+ if (!candidates) throw cause;
1299
+ observationErrors.push(`Profile ${member.peerId}: ${message(cause)}`);
1300
+ context.diagnostic?.(
1301
+ `Pivot profile refresh ${member.peerId} failed; retaining last-known approved candidate: ${message(cause)}`,
1302
+ );
1303
+ return undefined;
1304
+ }
1305
+ });
920
1306
  for (const [index, member] of config.members.entries()) {
921
- const profile = profiles[index]!;
1307
+ const profile = profiles[index];
1308
+ if (!profile) {
1309
+ const known = candidates?.known(member.peerId);
1310
+ if (known) addresses.set(member.peerId, known);
1311
+ continue;
1312
+ }
922
1313
  const value = parseProfile(profile.value, member.peerId);
923
1314
  if (member.publicKey === identity.publicKey)
924
1315
  selfProfile = { profile: value, cid: profile.cid };
925
- addresses.set(member.peerId, value.addresses);
1316
+ if (value.pivot === true && member.peerId !== self.peerId)
1317
+ addresses.set(member.peerId, value.addresses);
926
1318
  }
927
1319
  if (personal && selfProfile) {
928
1320
  selfProfile.profile = await syncAccountProfile(
@@ -933,7 +1325,34 @@ async function privateSource(
933
1325
  );
934
1326
  selfProfile.cid = await valueCid(selfProfile.profile);
935
1327
  }
936
- const desired = memberPeers(self.peerId, addresses, config.bootstrap);
1328
+ candidates?.reconcile(addresses);
1329
+ const active = candidates?.active() ?? addresses;
1330
+ if (!candidates) {
1331
+ try {
1332
+ const observed = await readNetworkingSnapshot(
1333
+ context.stateDir,
1334
+ record.configUrl,
1335
+ networkingBinding(record.configUrl, identity.publicKey, config),
1336
+ nodeScope(c.service, config.scopeId),
1337
+ config.epoch,
1338
+ self.peerId,
1339
+ );
1340
+ if (observed.status === "current")
1341
+ for (const pivot of observed.snapshot!.pivots)
1342
+ if (
1343
+ pivot.retryAt > Date.now() &&
1344
+ JSON.stringify(
1345
+ [...new Set(active.get(pivot.peerId) ?? [])].sort(),
1346
+ ) === JSON.stringify(pivot.addresses)
1347
+ )
1348
+ active.delete(pivot.peerId);
1349
+ } catch (cause) {
1350
+ context.diagnostic?.(
1351
+ `Local daemon observations could not be read: ${message(cause)}`,
1352
+ );
1353
+ }
1354
+ }
1355
+ const desired = memberPeers(self.peerId, active, []);
937
1356
  signal?.throwIfAborted();
938
1357
  const node = await startNode(
939
1358
  context.stateDir,
@@ -941,7 +1360,12 @@ async function privateSource(
941
1360
  secret.swarmKey,
942
1361
  config.epoch,
943
1362
  context.listen,
944
- { self: self.peerId, peers: desired, ...(signal ? { signal } : {}) },
1363
+ {
1364
+ self: self.peerId,
1365
+ peers: desired,
1366
+ pivot: context.pivot ?? false,
1367
+ ...(signal ? { signal } : {}),
1368
+ },
945
1369
  );
946
1370
  if (node.peerId !== self.peerId)
947
1371
  throw new HostError(
@@ -951,15 +1375,48 @@ async function privateSource(
951
1375
  Addrs.map((addr) => `${addr}/p2p/${ID}`),
952
1376
  );
953
1377
  signal?.throwIfAborted();
954
- if (!node.addresses.length && !selfProfile?.profile.addresses.length)
1378
+ if (
1379
+ context.pivot &&
1380
+ !node.addresses.length &&
1381
+ !selfProfile?.profile.addresses.length
1382
+ )
955
1383
  context.diagnostic?.(
956
- "No private LAN/VPN IPv4 address to advertise. Connect a routed interface or set your own address with swarm profile --address.",
1384
+ "Pivot has no IPv4 candidates. Connect an interface or set manual candidates with swarm profile --address.",
957
1385
  );
958
- if (
959
- node.addresses.length &&
960
- selfProfile &&
961
- selfProfile.profile.addresses.length === 0
962
- ) {
1386
+ if (selfProfile) {
1387
+ const dir = await directory(context);
1388
+ const preference = `pivot-${localName(record.configUrl)}`;
1389
+ const saved = await readPrivate<{ manual: string[] }>(dir, preference);
1390
+ const manual = saved?.manual ?? selfProfile.profile.addresses;
1391
+ for (const address of manual) validateAddress(address, self.peerId);
1392
+ if (!saved && context.pivot)
1393
+ await writePrivate(dir, preference, { manual });
1394
+ const published = context.pivot
1395
+ ? [...new Set([...manual, ...node.addresses])].slice(0, 16).sort()
1396
+ : manual;
1397
+ if (context.pivot && new Set([...manual, ...node.addresses]).size > 16)
1398
+ context.diagnostic?.(
1399
+ "Pivot profile is capped at 16 candidates; manual hints take priority over interface snapshots.",
1400
+ );
1401
+ const pivot = context.pivot ?? false;
1402
+ if (
1403
+ selfProfile.profile.pivot === pivot &&
1404
+ JSON.stringify([...selfProfile.profile.addresses].sort()) ===
1405
+ JSON.stringify(published)
1406
+ )
1407
+ return {
1408
+ node,
1409
+ peers,
1410
+ observationError: observationErrors.length
1411
+ ? observationErrors.join("; ")
1412
+ : null,
1413
+ source: kuboSource(
1414
+ node,
1415
+ peers,
1416
+ context.diagnostic,
1417
+ context.env.IPAB_SWARM_DIAL_DEBUG === "1",
1418
+ ),
1419
+ };
963
1420
  const writer = client(
964
1421
  context,
965
1422
  c.service,
@@ -968,7 +1425,8 @@ async function privateSource(
968
1425
  );
969
1426
  const profile = {
970
1427
  ...selfProfile.profile,
971
- addresses: node.addresses,
1428
+ pivot,
1429
+ addresses: published,
972
1430
  updatedAt: new Date().toISOString(),
973
1431
  };
974
1432
  await writer.write(
@@ -983,6 +1441,9 @@ async function privateSource(
983
1441
  return {
984
1442
  node,
985
1443
  peers,
1444
+ observationError: observationErrors.length
1445
+ ? observationErrors.join("; ")
1446
+ : null,
986
1447
  source: kuboSource(
987
1448
  node,
988
1449
  peers,
@@ -991,6 +1452,276 @@ async function privateSource(
991
1452
  ),
992
1453
  };
993
1454
  }
1455
+ export async function swarmDaemon(
1456
+ context: SwarmContext,
1457
+ selected: string | undefined,
1458
+ signal: AbortSignal,
1459
+ ): Promise<void> {
1460
+ const lock = await privateDirectory(context.stateDir, "swarm-daemon");
1461
+ await withPrivateLock(
1462
+ lock,
1463
+ async () => {
1464
+ const sessions = new Map<
1465
+ string,
1466
+ {
1467
+ context: SwarmContext;
1468
+ candidates: PivotCandidates;
1469
+ nextDiscovery: number;
1470
+ healthy: number;
1471
+ record?: LocalMembership;
1472
+ node?: KuboNode;
1473
+ selected: Set<string>;
1474
+ verifiedAt: number | null;
1475
+ error: string | null;
1476
+ connections?: NetworkingSnapshot["connections"];
1477
+ }
1478
+ >();
1479
+ context.diagnostic?.(
1480
+ "IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.",
1481
+ );
1482
+ const persist = async (
1483
+ url: string,
1484
+ session: NonNullable<ReturnType<typeof sessions.get>>,
1485
+ running: boolean,
1486
+ ) => {
1487
+ const record = session.record;
1488
+ if (!record?.config) return;
1489
+ const redact = (error: string | null) => {
1490
+ if (error === null) return null;
1491
+ for (const secret of [
1492
+ record.secret?.swarmKey,
1493
+ session.node?.auth,
1494
+ session.context.identity?.privateKey,
1495
+ ])
1496
+ if (secret) error = error.split(secret).join("[redacted]");
1497
+ return error.slice(0, 2048);
1498
+ };
1499
+ const snapshot: NetworkingSnapshot = {
1500
+ v: 1,
1501
+ binding: networkingBinding(url, record.account, record.config),
1502
+ pid: process.pid,
1503
+ running,
1504
+ updatedAt: Date.now(),
1505
+ verifiedAt: session.verifiedAt,
1506
+ error: redact(session.error),
1507
+ topology: session.node?.topology ?? null,
1508
+ pivots: [...session.candidates.observations()].map(
1509
+ ([peerId, value]) => ({
1510
+ ...value,
1511
+ peerId,
1512
+ selected: session.selected.has(peerId),
1513
+ error: redact(value.error),
1514
+ }),
1515
+ ),
1516
+ account: record.account,
1517
+ connections: session.connections
1518
+ ? {
1519
+ ...session.connections,
1520
+ error: redact(session.connections.error),
1521
+ }
1522
+ : {
1523
+ observedAt: null,
1524
+ error: "No connection snapshot collected.",
1525
+ peers: [],
1526
+ },
1527
+ };
1528
+ await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1529
+ };
1530
+ try {
1531
+ while (!signal.aborted) {
1532
+ const registrations = withState(context, (state) =>
1533
+ state.swarms(),
1534
+ ).filter((entry) => selected === undefined || entry.cid === selected);
1535
+ if (selected && !registrations.length)
1536
+ throw new HostError(
1537
+ "Selected Swarm is not registered; run ipab swarm add first.",
1538
+ );
1539
+ const urls = new Set(registrations.map((entry) => entry.cid));
1540
+ for (const url of sessions.keys())
1541
+ if (!urls.has(url)) {
1542
+ await persist(url, sessions.get(url)!, false);
1543
+ sessions.delete(url);
1544
+ }
1545
+ await boundedMap(registrations, async ({ cid: url }) => {
1546
+ let session = sessions.get(url);
1547
+ if (!session) {
1548
+ session = {
1549
+ context: { ...context },
1550
+ candidates: new PivotCandidates(),
1551
+ nextDiscovery: 0,
1552
+ healthy: 0,
1553
+ selected: new Set(),
1554
+ verifiedAt: null,
1555
+ error: null,
1556
+ };
1557
+ sessions.set(url, session);
1558
+ }
1559
+ try {
1560
+ if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
1561
+ const record = await approvedMembership(
1562
+ session.context,
1563
+ url,
1564
+ signal,
1565
+ );
1566
+ const c = coordinates(url);
1567
+ const scope = nodeScope(c.service, record.config!.scopeId);
1568
+ const existing = await readPrivate<unknown>(
1569
+ join(context.stateDir, "swarm-nodes", scope),
1570
+ "node.json",
1571
+ );
1572
+ if (!existing)
1573
+ throw new HostError(
1574
+ "No existing managed node; activate this membership before running daemon.",
1575
+ );
1576
+ await saveLocal(session.context, record);
1577
+ if (
1578
+ !session.record?.config ||
1579
+ networkingBinding(url, record.account, record.config!) !==
1580
+ networkingBinding(
1581
+ url,
1582
+ session.record.account,
1583
+ session.record.config,
1584
+ )
1585
+ ) {
1586
+ session.candidates.reconcile(new Map());
1587
+ session.selected.clear();
1588
+ session.verifiedAt = null;
1589
+ delete session.connections;
1590
+ delete session.node;
1591
+ }
1592
+ session.record = record;
1593
+ const result = await privateSource(
1594
+ session.context,
1595
+ record,
1596
+ signal,
1597
+ session.candidates,
1598
+ );
1599
+ session.node = result.node;
1600
+ session.selected = new Set(
1601
+ result.peers.map((address) => address.split("/").at(-1)!),
1602
+ );
1603
+ session.error = result.observationError;
1604
+ if (!session.error) session.verifiedAt = Date.now();
1605
+ session.context.node = result.node;
1606
+ session.nextDiscovery = Date.now() + 120_000;
1607
+ await persist(url, session, true);
1608
+ }
1609
+ if (!session.node) return;
1610
+ let healthy = 0;
1611
+ await boundedMap(
1612
+ [...session.candidates.active()],
1613
+ async ([id, addresses]) => {
1614
+ let success = false;
1615
+ let error: string | null = null;
1616
+ try {
1617
+ success = await probePeer(
1618
+ session.node!,
1619
+ id,
1620
+ addresses,
1621
+ signal,
1622
+ );
1623
+ } catch (cause) {
1624
+ signal.throwIfAborted();
1625
+ error = message(cause);
1626
+ context.diagnostic?.(
1627
+ `[${url}] Pivot probe ${id}: ${message(cause)}`,
1628
+ );
1629
+ }
1630
+ session.candidates.result(
1631
+ id,
1632
+ success,
1633
+ Date.now(),
1634
+ Math.random(),
1635
+ success ? null : (error ?? "Pivot dial failed."),
1636
+ );
1637
+ if (success) healthy++;
1638
+ else {
1639
+ session.nextDiscovery = 0;
1640
+ context.diagnostic?.(
1641
+ `[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`,
1642
+ );
1643
+ }
1644
+ },
1645
+ );
1646
+ session.healthy = healthy;
1647
+ // Startup-captured relay/bootstrap options must be removed immediately
1648
+ // when a candidate enters cooldown, not merely changed through config RPC.
1649
+ const record = session.record!;
1650
+ const self = record.config!.members.find(
1651
+ (member) => member.publicKey === record.account,
1652
+ )!;
1653
+ const desired = memberPeers(
1654
+ self.peerId,
1655
+ session.candidates.active(),
1656
+ [],
1657
+ );
1658
+ session.node = await startNode(
1659
+ context.stateDir,
1660
+ nodeScope(coordinates(url).service, record.config!.scopeId),
1661
+ record.secret!.swarmKey,
1662
+ record.config!.epoch,
1663
+ context.listen,
1664
+ {
1665
+ self: self.peerId,
1666
+ pivot: context.pivot ?? false,
1667
+ peers: desired,
1668
+ signal,
1669
+ },
1670
+ );
1671
+ session.selected = new Set(desired.map(({ ID }) => ID));
1672
+ try {
1673
+ const peers = await nodeConnections(session.node, signal);
1674
+ session.connections = {
1675
+ observedAt: Date.now(),
1676
+ error: null,
1677
+ peers,
1678
+ };
1679
+ } catch (cause) {
1680
+ signal.throwIfAborted();
1681
+ session.connections = {
1682
+ observedAt: session.connections?.observedAt ?? null,
1683
+ error: message(cause).slice(0, 2048),
1684
+ peers: session.connections?.peers ?? [],
1685
+ };
1686
+ }
1687
+ } catch (cause) {
1688
+ if (signal.aborted) return;
1689
+ session.error = message(cause);
1690
+ session.nextDiscovery = 0;
1691
+ context.diagnostic?.(
1692
+ `[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`,
1693
+ );
1694
+ if (
1695
+ cause instanceof HostError &&
1696
+ /membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(
1697
+ cause.message,
1698
+ )
1699
+ ) {
1700
+ if (session.node) await stopNode(session.node);
1701
+ session.candidates.reconcile(new Map());
1702
+ delete session.node;
1703
+ session.selected.clear();
1704
+ await persist(url, session, false);
1705
+ delete session.record;
1706
+ }
1707
+ }
1708
+ await persist(url, session, true);
1709
+ });
1710
+ try {
1711
+ await delay(30_000 + Math.random() * 15_000, undefined, { signal });
1712
+ } catch {
1713
+ signal.throwIfAborted();
1714
+ }
1715
+ }
1716
+ } finally {
1717
+ for (const [url, session] of sessions)
1718
+ await persist(url, session, false);
1719
+ }
1720
+ },
1721
+ signal,
1722
+ 1,
1723
+ );
1724
+ }
994
1725
  async function activate(context: SwarmContext, record: LocalMembership) {
995
1726
  const { node, peers, source } = await privateSource(context, record);
996
1727
  if (
@@ -1246,6 +1977,7 @@ async function writeStateBundle(
1246
1977
  store: IpfsStore,
1247
1978
  configuration: SwarmMeta,
1248
1979
  targets: Record<string, CID>,
1980
+ configUrl?: string,
1249
1981
  ): Promise<string> {
1250
1982
  const meta = parseSwarmMeta(configuration);
1251
1983
  const names = Object.fromEntries(
@@ -1254,20 +1986,37 @@ async function writeStateBundle(
1254
1986
  cid.toString(),
1255
1987
  ]),
1256
1988
  );
1989
+ const value = parseSwarmState({
1990
+ v: configUrl === undefined ? 5 : 6,
1991
+ ...(configUrl === undefined ? {} : { configUrl }),
1992
+ ...meta,
1993
+ names,
1994
+ });
1257
1995
  return jsonBundle(
1258
1996
  store,
1259
- meta.skillPath === undefined ? legacySwarmStateType : swarmStateType,
1260
- { v: 5, ...meta, names },
1997
+ configUrl !== undefined
1998
+ ? swarmStateType
1999
+ : meta.skillPath === undefined
2000
+ ? legacySwarmStateType
2001
+ : previousSwarmStateType,
2002
+ value,
1261
2003
  );
1262
2004
  }
1263
2005
  export async function writeSnapshot(
1264
2006
  store: IpfsStore,
1265
2007
  snapshot: Snapshot,
2008
+ configUrl?: string,
1266
2009
  ): Promise<string> {
1267
2010
  if (snapshot.stateBundle) {
1268
2011
  if (Object.keys(snapshot.registrations ?? {}).length)
1269
2012
  throw new HostError("State Bundles cannot contain legacy registrations.");
1270
- return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names);
2013
+ checkStateOrigin(snapshot, configUrl);
2014
+ return writeStateBundle(
2015
+ store,
2016
+ snapshot.stateBundle.meta,
2017
+ snapshot.names,
2018
+ snapshot.stateBundle.configUrl,
2019
+ );
1271
2020
  }
1272
2021
  const put = async (value: unknown) => {
1273
2022
  const encoded = dagCbor.encode(value);
@@ -1290,23 +2039,14 @@ async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1290
2039
  const type =
1291
2040
  bundle.schemaKey === legacySwarmStateSchema.cid.toString()
1292
2041
  ? legacySwarmStateType
1293
- : swarmStateType;
1294
- const value = object(
1295
- await typedJson(store, cid.toString(), type),
1296
- "State Bundle",
1297
- );
1298
- if (
1299
- value.v !== 5 ||
1300
- Object.keys(value).sort().join() !==
1301
- (type === legacySwarmStateType
1302
- ? "names,registryPath,templatePath,v"
1303
- : "names,registryPath,skillPath,templatePath,v")
1304
- )
1305
- throw new HostError("Invalid State Bundle entry.");
2042
+ : bundle.schemaKey === previousSwarmStateSchema.cid.toString()
2043
+ ? previousSwarmStateType
2044
+ : swarmStateType;
2045
+ const value = parseSwarmState(await typedJson(store, cid.toString(), type));
1306
2046
  const meta = parseSwarmMeta({
1307
2047
  templatePath: value.templatePath,
1308
2048
  registryPath: value.registryPath,
1309
- ...(type === legacySwarmStateType ? {} : { skillPath: value.skillPath }),
2049
+ ...(value.skillPath === undefined ? {} : { skillPath: value.skillPath }),
1310
2050
  });
1311
2051
  const names = Object.fromEntries(
1312
2052
  Object.entries(object(value.names, "Names")).map(([name, target]) => {
@@ -1316,7 +2056,17 @@ async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1316
2056
  return [name, CID.parse(target)];
1317
2057
  }),
1318
2058
  );
1319
- return { v: 2, names, stateBundle: { meta, cid: cid.toString() } };
2059
+ return {
2060
+ v: 2,
2061
+ names,
2062
+ stateBundle: {
2063
+ meta,
2064
+ cid: cid.toString(),
2065
+ ...(value.configUrl === undefined
2066
+ ? {}
2067
+ : { configUrl: value.configUrl }),
2068
+ },
2069
+ };
1320
2070
  }
1321
2071
  const data = await store.block.get(cid.toString());
1322
2072
  const root = object(dagCbor.decode(data), "State");
@@ -1406,14 +2156,33 @@ function decodeSnapshot(data: Uint8Array): Snapshot {
1406
2156
  export async function readSnapshot(
1407
2157
  store: IpfsStore,
1408
2158
  root: string,
2159
+ configUrl?: string,
1409
2160
  ): Promise<Snapshot> {
1410
2161
  const publication = await readPublication(store, root);
1411
- return readState(store, publication.state);
2162
+ const snapshot = await readState(store, publication.state);
2163
+ checkStateOrigin(snapshot, configUrl);
2164
+ return snapshot;
2165
+ }
2166
+ function checkStateOrigin(snapshot: Snapshot, configUrl?: string): void {
2167
+ if (
2168
+ configUrl !== undefined &&
2169
+ snapshot.stateBundle?.configUrl !== undefined &&
2170
+ snapshot.stateBundle.configUrl !== configUrl
2171
+ )
2172
+ throw new HostError(
2173
+ "State Bundle Config URL does not match the selected Swarm.",
2174
+ );
1412
2175
  }
1413
- async function readHeaderSnapshot(store: IpfsStore, root: string) {
2176
+ async function readHeaderSnapshot(
2177
+ store: IpfsStore,
2178
+ root: string,
2179
+ configUrl: string,
2180
+ ) {
1414
2181
  const publication = await readPublication(store, root);
2182
+ const snapshot = await readState(store, publication.state);
2183
+ checkStateOrigin(snapshot, configUrl);
1415
2184
  return {
1416
- snapshot: await readState(store, publication.state),
2185
+ snapshot,
1417
2186
  stateCid: publication.state.toString(),
1418
2187
  };
1419
2188
  }
@@ -1488,7 +2257,7 @@ export async function sharedSwarmStatus(
1488
2257
  );
1489
2258
  let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
1490
2259
  try {
1491
- content = await readHeaderSnapshot(context.store, head.root);
2260
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
1492
2261
  } catch (cause) {
1493
2262
  if (!missingContent(cause)) throw cause;
1494
2263
  const registered = withState(context, (state) =>
@@ -1576,12 +2345,12 @@ async function readSwarmHeader(
1576
2345
  : await (await boundPointer(context, configUrl, record)).read();
1577
2346
  let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
1578
2347
  try {
1579
- content = await readHeaderSnapshot(context.store, head.root);
2348
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
1580
2349
  } catch (cause) {
1581
2350
  if (mode === "local-first") throw cause;
1582
2351
  record = await refresh(context, configUrl);
1583
2352
  head = await (await boundPointer(context, configUrl, record)).read();
1584
- content = await readHeaderSnapshot(context.store, head.root);
2353
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
1585
2354
  }
1586
2355
  const current = await local(context, configUrl),
1587
2356
  verifiedAt = Date.now();
@@ -1643,13 +2412,29 @@ async function cachedHeader(
1643
2412
  if (stateBundle !== undefined) {
1644
2413
  const data = object(stateBundle, "cached State Bundle");
1645
2414
  if (
1646
- Object.keys(data).sort().join() !== "cid,meta" ||
2415
+ !["cid,meta", "cid,configUrl,meta"].includes(
2416
+ Object.keys(data).sort().join(),
2417
+ ) ||
1647
2418
  typeof data.cid !== "string" ||
1648
2419
  exactCid(data.cid) !== data.cid ||
1649
2420
  (cached.stateCid !== undefined && data.cid !== cached.stateCid)
1650
2421
  )
1651
2422
  throw new HostError("Invalid cached State Bundle.");
1652
- snapshot.stateBundle = { meta: parseSwarmMeta(data.meta), cid: data.cid };
2423
+ const meta = parseSwarmMeta(data.meta);
2424
+ const parsed = parseSwarmState({
2425
+ v: data.configUrl === undefined ? 5 : 6,
2426
+ ...meta,
2427
+ ...(data.configUrl === undefined ? {} : { configUrl: data.configUrl }),
2428
+ names: {},
2429
+ });
2430
+ snapshot.stateBundle = {
2431
+ meta,
2432
+ cid: data.cid,
2433
+ ...(parsed.configUrl === undefined
2434
+ ? {}
2435
+ : { configUrl: parsed.configUrl }),
2436
+ };
2437
+ checkStateOrigin(snapshot, record.configUrl);
1653
2438
  }
1654
2439
  let stateCid = cached.stateCid;
1655
2440
  if (!stateCid) {
@@ -1778,7 +2563,7 @@ async function lazyPrivateSource(
1778
2563
  record.config!.headId !== basis.headId
1779
2564
  )
1780
2565
  throw new HostError(
1781
- "Swarm membership changed since this cached HEAD; retry with --force.",
2566
+ "Swarm membership changed since this cached HEAD; retry with --refresh.",
1782
2567
  );
1783
2568
  return (await privateSource(scoped, record, signal)).source;
1784
2569
  };
@@ -1807,16 +2592,10 @@ async function lazyPrivateSource(
1807
2592
  await pending?.catch(() => {});
1808
2593
  };
1809
2594
  }
1810
- export async function addSwarm(
1811
- context: SwarmContext,
1812
- url: string,
1813
- alias?: string,
1814
- ): Promise<void> {
1815
- canonicalSwarmUrl(url);
1816
- await readyMembership(context, url);
1817
- withState(context, (state) => state.registerSwarm(url, alias));
1818
- }
1819
2595
  interface Creation {
2596
+ stateVersion?: 6;
2597
+ configReservationCid?: string;
2598
+ configPublished?: boolean;
1820
2599
  owner: string;
1821
2600
  service: string;
1822
2601
  encryption: EncryptionIdentity;
@@ -1879,6 +2658,7 @@ export async function createSwarm(
1879
2658
  if (!record) {
1880
2659
  if (options.resume) throw new HostError("Unknown creation operation.");
1881
2660
  record = {
2661
+ stateVersion: 6,
1882
2662
  owner: identity.publicKey,
1883
2663
  service,
1884
2664
  encryption: encryptionIdentity(),
@@ -1895,6 +2675,28 @@ export async function createSwarm(
1895
2675
  const save = () => writePrivate(dir, `creation-${op}.json`, record);
1896
2676
  const api = client(context, service, identity);
1897
2677
  try {
2678
+ if (record.stateVersion === 6) {
2679
+ if (!record.scopeId) {
2680
+ record.scopeId = (await api.createScope(`${op}.scope`)).id;
2681
+ await save();
2682
+ }
2683
+ if (!record.configId) {
2684
+ // Reserve the Config address, not a Config or a temporary HEAD.
2685
+ const reservation = await api.create(
2686
+ record.scopeId,
2687
+ {
2688
+ v: 1,
2689
+ kind: "ipab-config-reservation",
2690
+ owner: record.owner,
2691
+ operation: op,
2692
+ },
2693
+ `${op}.config-reserve`,
2694
+ );
2695
+ record.configId = reservation.id;
2696
+ record.configReservationCid = reservation.cid;
2697
+ await save();
2698
+ }
2699
+ }
1898
2700
  if (!record.seed) {
1899
2701
  if (record.headId)
1900
2702
  throw new HostError(
@@ -1905,7 +2707,7 @@ export async function createSwarm(
1905
2707
  const template = await seedTemplateSource(selector);
1906
2708
  for (const [cid, data] of template.blocks)
1907
2709
  await context.store.put(CID.parse(cid), data);
1908
- names[`ipab/template/${selector}`] = CID.parse(template.cid);
2710
+ names[`ipab/templates/${selector}`] = CID.parse(template.cid);
1909
2711
  }
1910
2712
  const skill = await seedSkillSource();
1911
2713
  for (const [cid, data] of skill.blocks)
@@ -1916,11 +2718,14 @@ export async function createSwarm(
1916
2718
  await writeStateBundle(
1917
2719
  context.store,
1918
2720
  {
1919
- templatePath: "ipab/template",
2721
+ templatePath: "ipab/templates",
1920
2722
  registryPath: "ipab/registry",
1921
2723
  skillPath: "ipab/skills",
1922
2724
  },
1923
2725
  names,
2726
+ record.stateVersion === 6
2727
+ ? `${service}/v1/${record.scopeId!}/${record.configId!}`
2728
+ : undefined,
1924
2729
  ),
1925
2730
  );
1926
2731
  const roots = await frozenPublicationClosure(context.store, root);
@@ -1960,12 +2765,13 @@ export async function createSwarm(
1960
2765
  }
1961
2766
  if (!record.profileId) {
1962
2767
  if (!record.profile) {
1963
- const addresses = options.addresses ?? node.addresses;
2768
+ const addresses = options.addresses ?? [];
1964
2769
  for (const address of addresses)
1965
2770
  validateAddress(address, node.peerId);
1966
2771
  record.profile = {
1967
2772
  ...(record.personal ?? { name: record.name }),
1968
2773
  addresses,
2774
+ pivot: context.pivot ?? false,
1969
2775
  updatedAt: record.createdAt,
1970
2776
  };
1971
2777
  await save();
@@ -1997,7 +2803,7 @@ export async function createSwarm(
1997
2803
  description: record.description,
1998
2804
  headId: record.headId,
1999
2805
  epoch: 1,
2000
- bootstrap: options.addresses ?? node.addresses,
2806
+ bootstrap: [],
2001
2807
  members: [member],
2002
2808
  };
2003
2809
  await save();
@@ -2012,6 +2818,29 @@ export async function createSwarm(
2012
2818
  ).id;
2013
2819
  await save();
2014
2820
  }
2821
+ if (record.stateVersion === 6 && !record.configPublished) {
2822
+ if (!record.configReservationCid)
2823
+ throw new HostError(
2824
+ "Creation Config reservation checkpoint is missing.",
2825
+ );
2826
+ const value = configValue(record.config);
2827
+ const current = await api.read(record.scopeId, record.configId);
2828
+ if (current.cid !== (await valueCid(value))) {
2829
+ if (current.cid !== record.configReservationCid)
2830
+ throw new HostError(
2831
+ "Creation Config reservation was changed; refusing to overwrite it.",
2832
+ );
2833
+ await api.write(
2834
+ record.scopeId,
2835
+ record.configId,
2836
+ value,
2837
+ record.configReservationCid,
2838
+ `${op}.config`,
2839
+ );
2840
+ }
2841
+ record.configPublished = true;
2842
+ await save();
2843
+ }
2015
2844
  const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
2016
2845
  const cert = await issueScopeCertificate(
2017
2846
  {
@@ -2075,7 +2904,6 @@ export async function requestMembership(
2075
2904
  context: SwarmContext,
2076
2905
  url: string,
2077
2906
  options: {
2078
- alias?: string;
2079
2907
  output?: string;
2080
2908
  },
2081
2909
  ): Promise<{
@@ -2094,10 +2922,6 @@ export async function requestMembership(
2094
2922
  const personal = await ensureAccountProfile(context);
2095
2923
  const dir = await directory(context);
2096
2924
  await withPrivateLock(dir, async () => {
2097
- if (options.alias !== undefined)
2098
- withState(context, (state) => {
2099
- state.checkSwarmAlias(options.alias!, url);
2100
- });
2101
2925
  const existing = await readPrivate<LocalMembership>(dir, localName(url));
2102
2926
  if (existing) {
2103
2927
  if (
@@ -2109,7 +2933,6 @@ export async function requestMembership(
2109
2933
  );
2110
2934
  if (!existing.request)
2111
2935
  throw new HostError("This identity is already the Owner.");
2112
- withState(context, (state) => state.registerSwarm(url, options.alias));
2113
2936
  return;
2114
2937
  }
2115
2938
  const node = await prepareNode(
@@ -2149,7 +2972,6 @@ export async function requestMembership(
2149
2972
  encryption,
2150
2973
  request,
2151
2974
  });
2152
- withState(context, (state) => state.registerSwarm(url, options.alias));
2153
2975
  });
2154
2976
  const file =
2155
2977
  options.output === undefined ? undefined : resolve(options.output);
@@ -2549,6 +3371,13 @@ export async function updateProfile(
2549
3371
  existing.cid,
2550
3372
  uniqueId(),
2551
3373
  );
3374
+ await writePrivate(await directory(context), `pivot-${localName(url)}`, {
3375
+ manual: changes.addresses,
3376
+ });
3377
+ if (!context.pivot)
3378
+ context.diagnostic?.(
3379
+ "Manual addresses saved; they are discovery candidates only when swarm.pivot=true. Ordinary nodes do not provide relay service.",
3380
+ );
2552
3381
  return profile;
2553
3382
  }
2554
3383
  interface Removal {
@@ -2629,6 +3458,11 @@ export async function resumeRemoval(
2629
3458
  membershipBeforeSwitch.config = record.oldConfig;
2630
3459
  membershipBeforeSwitch.secret!.swarmKey = record.oldKey;
2631
3460
  await activate(context, membershipBeforeSwitch);
3461
+ await readSnapshot(
3462
+ context.store,
3463
+ headValue(record.finalHead).root,
3464
+ url,
3465
+ );
2632
3466
  if (!record.finalClosureRoots) {
2633
3467
  record.finalClosureRoots = await frozenPublicationClosure(
2634
3468
  context.store,
@@ -2874,7 +3708,7 @@ export function parseNameReference(
2874
3708
  try {
2875
3709
  return {
2876
3710
  ...(authority ? { swarm: authority } : {}),
2877
- name: formalName(segments.join("/")),
3711
+ name: match[2] === "" ? "" : formalName(segments.join("/")),
2878
3712
  };
2879
3713
  } catch (error) {
2880
3714
  if (!(error instanceof HostError)) throw error;
@@ -2915,14 +3749,16 @@ export async function resolveReference(
2915
3749
  const warm =
2916
3750
  mode === "local-first" ? await localHeader(context, selected) : undefined;
2917
3751
  let header = warm?.header ?? (await swarmHeader(context, selected));
2918
- let link = Object.hasOwn(header.snapshot.names, shared.name)
2919
- ? header.snapshot.names[shared.name]
2920
- : undefined;
3752
+ const target = () =>
3753
+ shared.name === ""
3754
+ ? header.stateCid
3755
+ : Object.hasOwn(header.snapshot.names, shared.name)
3756
+ ? header.snapshot.names[shared.name]?.toString()
3757
+ : undefined;
3758
+ let link = target();
2921
3759
  if (!link && header.source === "cache") {
2922
3760
  header = await swarmHeader(context, selected, true);
2923
- link = Object.hasOwn(header.snapshot.names, shared.name)
2924
- ? header.snapshot.names[shared.name]
2925
- : undefined;
3761
+ link = target();
2926
3762
  }
2927
3763
  if (!link)
2928
3764
  throw new HostError(
@@ -2930,7 +3766,7 @@ export async function resolveReference(
2930
3766
  );
2931
3767
  if (warm && header === warm.header && !header.localSourceReady)
2932
3768
  await lazyPrivateSource(context, selected, warm.account, header.config);
2933
- targetCid = link.toString();
3769
+ targetCid = link;
2934
3770
  } else {
2935
3771
  if (swarm) await readyMembership(context, swarm);
2936
3772
  targetCid = local(reference);
@@ -2991,7 +3827,7 @@ export async function pinNameSubscription(
2991
3827
  const canonical = withState(context, (state) =>
2992
3828
  pinReference(state, reference, selected),
2993
3829
  );
2994
- if (!canonical.swarm || !canonical.name) {
3830
+ if (!canonical.swarm || canonical.name === undefined) {
2995
3831
  let roots: string[];
2996
3832
  try {
2997
3833
  roots = [
@@ -3043,7 +3879,7 @@ async function withStateAsync<T>(
3043
3879
  export async function refreshNamePins(
3044
3880
  context: SwarmContext,
3045
3881
  url: string,
3046
- header: Pick<SwarmHeader, "snapshot">,
3882
+ header: Pick<SwarmHeader, "snapshot" | "stateCid">,
3047
3883
  ): Promise<void> {
3048
3884
  const pins = withState(context, (state) =>
3049
3885
  state
@@ -3052,9 +3888,12 @@ export async function refreshNamePins(
3052
3888
  );
3053
3889
  const failures: string[] = [];
3054
3890
  for (const saved of pins) {
3055
- const target = Object.hasOwn(header.snapshot.names, saved.name!)
3056
- ? header.snapshot.names[saved.name!]!.toString()
3057
- : undefined;
3891
+ const target =
3892
+ saved.name === ""
3893
+ ? header.stateCid
3894
+ : Object.hasOwn(header.snapshot.names, saved.name!)
3895
+ ? header.snapshot.names[saved.name!]!.toString()
3896
+ : undefined;
3058
3897
  if (!target) {
3059
3898
  withState(context, (state) => {
3060
3899
  failedPin(
@@ -3492,7 +4331,11 @@ export async function removeSwarmTemplate(
3492
4331
  let basis: string | undefined;
3493
4332
  for (let attempt = 0; attempt < 8; attempt++) {
3494
4333
  const currentHead = await head.read();
3495
- const current = await readSnapshot(context.store, currentHead.root);
4334
+ const current = await readSnapshot(
4335
+ context.store,
4336
+ currentHead.root,
4337
+ configUrl,
4338
+ );
3496
4339
  const meta = await swarmMeta(context, { snapshot: current });
3497
4340
  const name = formalName(`${meta.templatePath}/${selector}`);
3498
4341
  if (basis !== undefined && basis !== name)
@@ -3628,7 +4471,7 @@ async function prepareNamesPublication(
3628
4471
  ) {
3629
4472
  const next = await publication(
3630
4473
  context.store,
3631
- await writeSnapshot(context.store, { ...current, names }),
4474
+ await writeSnapshot(context.store, { ...current, names }, configUrl),
3632
4475
  previousRoot,
3633
4476
  );
3634
4477
  const closure = await publicationClosure(context.store, next, false);
@@ -3667,7 +4510,11 @@ async function editSwarmAssociation(
3667
4510
  : new Set<string>();
3668
4511
  for (let attempt = 0; attempt < 8; attempt++) {
3669
4512
  const currentHead = await head.read();
3670
- const current = await readSnapshot(context.store, currentHead.root);
4513
+ const current = await readSnapshot(
4514
+ context.store,
4515
+ currentHead.root,
4516
+ configUrl,
4517
+ );
3671
4518
  assertNamesRegistry(current);
3672
4519
  const meta = await swarmMeta(context, { snapshot: current });
3673
4520
  const name = formalName(`${meta.registryPath}/${schemaCid}`);
@@ -3886,7 +4733,11 @@ async function publishContent(
3886
4733
  roots.add(root);
3887
4734
  for (let attempt = 0; attempt < 8; attempt++) {
3888
4735
  const currentHead = await head.read(),
3889
- current = await readSnapshot(context.store, currentHead.root);
4736
+ current = await readSnapshot(
4737
+ context.store,
4738
+ currentHead.root,
4739
+ options.swarm,
4740
+ );
3890
4741
  if (nameForSnapshot) {
3891
4742
  name = await nameForSnapshot(current);
3892
4743
  if (resolvedName !== undefined && resolvedName !== name)