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

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 (120) hide show
  1. package/README.md +70 -30
  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/bundled-skills.d.ts +14 -0
  11. package/dist/bundled-skills.d.ts.map +1 -0
  12. package/dist/bundled-skills.js +34 -0
  13. package/dist/bundled-skills.js.map +1 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +309 -157
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +1 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +9 -4
  20. package/dist/config.js.map +1 -1
  21. package/dist/context.d.ts +4 -0
  22. package/dist/context.d.ts.map +1 -1
  23. package/dist/context.js +11 -2
  24. package/dist/context.js.map +1 -1
  25. package/dist/daemon.d.ts +4 -0
  26. package/dist/daemon.d.ts.map +1 -0
  27. package/dist/daemon.js +200 -0
  28. package/dist/daemon.js.map +1 -0
  29. package/dist/doctor.d.ts +2 -0
  30. package/dist/doctor.d.ts.map +1 -1
  31. package/dist/doctor.js +18 -4
  32. package/dist/doctor.js.map +1 -1
  33. package/dist/errors.d.ts +1 -8
  34. package/dist/errors.d.ts.map +1 -1
  35. package/dist/errors.js +1 -20
  36. package/dist/errors.js.map +1 -1
  37. package/dist/host-error.d.ts +9 -0
  38. package/dist/host-error.d.ts.map +1 -0
  39. package/dist/host-error.js +21 -0
  40. package/dist/host-error.js.map +1 -0
  41. package/dist/ipc.d.ts.map +1 -1
  42. package/dist/ipc.js +17 -0
  43. package/dist/ipc.js.map +1 -1
  44. package/dist/kubo-install.js +1 -1
  45. package/dist/kubo-install.js.map +1 -1
  46. package/dist/kubo-peers.d.ts.map +1 -1
  47. package/dist/kubo-peers.js +2 -1
  48. package/dist/kubo-peers.js.map +1 -1
  49. package/dist/kubo-topology.d.ts +19 -0
  50. package/dist/kubo-topology.d.ts.map +1 -0
  51. package/dist/kubo-topology.js +105 -0
  52. package/dist/kubo-topology.js.map +1 -0
  53. package/dist/kubo.d.ts +10 -0
  54. package/dist/kubo.d.ts.map +1 -1
  55. package/dist/kubo.js +96 -15
  56. package/dist/kubo.js.map +1 -1
  57. package/dist/skill-source.d.ts +4 -0
  58. package/dist/skill-source.d.ts.map +1 -1
  59. package/dist/skill-source.js +14 -2
  60. package/dist/skill-source.js.map +1 -1
  61. package/dist/skills.d.ts +18 -1
  62. package/dist/skills.d.ts.map +1 -1
  63. package/dist/skills.js +137 -39
  64. package/dist/skills.js.map +1 -1
  65. package/dist/space-path.d.ts +3 -0
  66. package/dist/space-path.d.ts.map +1 -0
  67. package/dist/space-path.js +17 -0
  68. package/dist/space-path.js.map +1 -0
  69. package/dist/space.d.ts +1 -2
  70. package/dist/space.d.ts.map +1 -1
  71. package/dist/space.js +2 -15
  72. package/dist/space.js.map +1 -1
  73. package/dist/state-storage.js +1 -1
  74. package/dist/state-storage.js.map +1 -1
  75. package/dist/state.d.ts +2 -0
  76. package/dist/state.d.ts.map +1 -1
  77. package/dist/state.js +31 -12
  78. package/dist/state.js.map +1 -1
  79. package/dist/swarm-files.d.ts +1 -1
  80. package/dist/swarm-files.d.ts.map +1 -1
  81. package/dist/swarm-files.js +10 -4
  82. package/dist/swarm-files.js.map +1 -1
  83. package/dist/swarm-meta.d.ts +1 -4
  84. package/dist/swarm-meta.d.ts.map +1 -1
  85. package/dist/swarm-meta.js +3 -34
  86. package/dist/swarm-meta.js.map +1 -1
  87. package/dist/swarm-observations.d.ts +40 -0
  88. package/dist/swarm-observations.d.ts.map +1 -0
  89. package/dist/swarm-observations.js +262 -0
  90. package/dist/swarm-observations.js.map +1 -0
  91. package/dist/swarm.d.ts +121 -6
  92. package/dist/swarm.d.ts.map +1 -1
  93. package/dist/swarm.js +672 -81
  94. package/dist/swarm.js.map +1 -1
  95. package/package.json +4 -4
  96. package/src/app-authoring.ts +12 -53
  97. package/src/app-prebuild.ts +61 -0
  98. package/src/bundled-skills.ts +60 -0
  99. package/src/cli.ts +398 -195
  100. package/src/config.ts +12 -4
  101. package/src/context.ts +15 -2
  102. package/src/daemon.ts +237 -0
  103. package/src/doctor.ts +42 -5
  104. package/src/errors.ts +1 -25
  105. package/src/host-error.ts +26 -0
  106. package/src/ipc.ts +19 -0
  107. package/src/kubo-install.ts +1 -1
  108. package/src/kubo-peers.ts +2 -3
  109. package/src/kubo-topology.ts +135 -0
  110. package/src/kubo.ts +134 -25
  111. package/src/skill-source.ts +16 -2
  112. package/src/skills.ts +195 -53
  113. package/src/space-path.ts +30 -0
  114. package/src/space.ts +2 -28
  115. package/src/state-storage.ts +1 -1
  116. package/src/state.ts +37 -12
  117. package/src/swarm-files.ts +8 -3
  118. package/src/swarm-meta.ts +15 -34
  119. package/src/swarm-observations.ts +374 -0
  120. package/src/swarm.ts +953 -92
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;
@@ -168,6 +186,8 @@ export interface MembershipRequest {
168
186
  signature: string;
169
187
  }
170
188
  export interface SwarmContext {
189
+ ensureDaemon?: () => Promise<void>;
190
+ daemonReady?: () => Promise<() => Promise<void>>;
171
191
  store: IpfsStore;
172
192
  env: NodeJS.ProcessEnv;
173
193
  stateDir: string;
@@ -183,6 +203,7 @@ export interface SwarmContext {
183
203
  finishRead?: () => Promise<void>;
184
204
  identity?: Identity;
185
205
  listen?: ListenMode;
206
+ pivot?: boolean;
186
207
  }
187
208
  async function contextIdentity(
188
209
  context: SwarmContext,
@@ -360,6 +381,10 @@ function client(
360
381
  }
361
382
  function parseOrganization(value: unknown, configUrl: string): Organization {
362
383
  const data = object(value, "organization configuration");
384
+ if (data.kind === "ipab-config-reservation")
385
+ throw new HostError(
386
+ "Swarm creation is initializing; the Owner must resume the saved creation operation.",
387
+ );
363
388
  const { scopeId } = coordinates(configUrl);
364
389
  if (
365
390
  Object.keys(data).sort().join() !==
@@ -455,10 +480,13 @@ function parseOrganization(value: unknown, configUrl: string): Organization {
455
480
  function parseProfile(value: unknown, expectedPeer: string): Profile {
456
481
  const data = object(value, "member profile");
457
482
  if (
458
- ![
459
- "addresses,name,updatedAt",
460
- "addresses,description,name,updatedAt",
461
- ].includes(Object.keys(data).sort().join()) ||
483
+ Object.keys(data).some(
484
+ (key) =>
485
+ !["addresses", "name", "description", "updatedAt", "pivot"].includes(
486
+ key,
487
+ ),
488
+ ) ||
489
+ (data.pivot !== undefined && typeof data.pivot !== "boolean") ||
462
490
  typeof data.name !== "string" ||
463
491
  data.name.length > 256 ||
464
492
  (data.description !== undefined &&
@@ -483,11 +511,15 @@ function parseProfile(value: unknown, expectedPeer: string): Profile {
483
511
  ? { description: data.description }
484
512
  : {}),
485
513
  addresses,
514
+ ...(typeof data.pivot === "boolean" ? { pivot: data.pivot } : {}),
486
515
  updatedAt: data.updatedAt,
487
516
  };
488
517
  }
489
- export async function swarmMembers(context: SwarmContext, url: string) {
490
- const { config } = await fetchConfig(context, canonicalSwarmUrl(url));
518
+ async function memberDirectory(
519
+ context: SwarmContext,
520
+ url: string,
521
+ config: Organization,
522
+ ) {
491
523
  const c = coordinates(url),
492
524
  api = client(context, c.service);
493
525
  const members = await boundedMap(config.members, async (member) => {
@@ -495,14 +527,354 @@ export async function swarmMembers(context: SwarmContext, url: string) {
495
527
  (await api.read(c.scopeId, member.profileId)).value,
496
528
  member.peerId,
497
529
  );
530
+ return { member, profile };
531
+ });
532
+ return members;
533
+ }
534
+ async function localObservations(
535
+ context: SwarmContext,
536
+ url: string,
537
+ config: Organization,
538
+ ) {
539
+ try {
540
+ const account =
541
+ context.identity?.publicKey ??
542
+ (await networkingAccount(context.stateDir, url));
543
+ const self = config.members.find((member) => member.publicKey === account);
544
+ if (!self || !account)
545
+ throw new HostError(
546
+ "No bound local daemon observations; run ipab daemon after normal membership activation.",
547
+ );
548
+ const c = coordinates(url);
549
+ const local = await readNetworkingSnapshot(
550
+ context.stateDir,
551
+ url,
552
+ networkingBinding(url, account, config),
553
+ nodeScope(c.service, config.scopeId),
554
+ config.epoch,
555
+ self.peerId,
556
+ );
498
557
  return {
499
- publicKey: member.publicKey,
500
- role: member.publicKey === config.owner ? "owner" : "member",
501
- name: profile.name,
502
- description: profile.description ?? "",
558
+ account:
559
+ context.identity?.publicKey ?? (local.snapshot ? account : undefined),
560
+ local,
503
561
  };
562
+ } catch (cause) {
563
+ return {
564
+ account: context.identity?.publicKey,
565
+ local: {
566
+ status: "unavailable",
567
+ updatedAt: null,
568
+ verifiedAt: null,
569
+ error: message(cause),
570
+ snapshot: null,
571
+ } satisfies LocalObservations,
572
+ };
573
+ }
574
+ }
575
+ function observationSummary(local: LocalObservations) {
576
+ return {
577
+ status: local.status,
578
+ updatedAt: local.updatedAt,
579
+ verifiedAt: local.verifiedAt,
580
+ error: local.error,
581
+ };
582
+ }
583
+ interface InspectionSnapshot {
584
+ v: 1;
585
+ configUrl: string;
586
+ updatedAt: number;
587
+ config: Organization;
588
+ directory: Awaited<ReturnType<typeof memberDirectory>>;
589
+ head: { root: string; cid: string };
590
+ }
591
+ function parseInspection(input: unknown, url: string): InspectionSnapshot {
592
+ const data = object(input, "Swarm inspection cache");
593
+ if (
594
+ Object.keys(data).sort().join() !==
595
+ "config,configUrl,directory,head,updatedAt,v" ||
596
+ data.v !== 1 ||
597
+ data.configUrl !== url ||
598
+ typeof data.updatedAt !== "number" ||
599
+ !Number.isSafeInteger(data.updatedAt) ||
600
+ data.updatedAt < 0 ||
601
+ data.updatedAt > 8_640_000_000_000_000 ||
602
+ !Array.isArray(data.directory) ||
603
+ data.directory.length > 256
604
+ )
605
+ throw new HostError(
606
+ "Invalid Swarm inspection cache; retry with --refresh.",
607
+ );
608
+ const config = parseOrganization(data.config, url);
609
+ if (
610
+ config.members.some(
611
+ (member) => !/^[A-Za-z0-9]{32,128}$/.test(member.peerId),
612
+ )
613
+ )
614
+ throw new HostError("Invalid cached member PeerID; use --refresh.");
615
+ if (data.directory.length !== config.members.length)
616
+ throw new HostError(
617
+ "Incomplete Swarm inspection directory; use --refresh.",
618
+ );
619
+ const directory = data.directory.map((input: unknown, index) => {
620
+ const entry = object(input, "cached directory entry");
621
+ const member = config.members[index]!;
622
+ if (
623
+ Object.keys(entry).sort().join() !== "member,profile" ||
624
+ JSON.stringify(entry.member) !== JSON.stringify(member)
625
+ )
626
+ throw new HostError("Cached member binding mismatch; use --refresh.");
627
+ return { member, profile: parseProfile(entry.profile, member.peerId) };
504
628
  });
505
- return { configUrl: url, members };
629
+ const head = object(data.head, "cached HEAD");
630
+ if (
631
+ Object.keys(head).sort().join() !== "cid,root" ||
632
+ typeof head.root !== "string" ||
633
+ typeof head.cid !== "string" ||
634
+ exactCid(head.root) !== head.root ||
635
+ exactCid(head.cid) !== head.cid
636
+ )
637
+ throw new HostError("Invalid cached HEAD; use --refresh.");
638
+ return {
639
+ v: 1,
640
+ configUrl: url,
641
+ updatedAt: data.updatedAt,
642
+ config,
643
+ directory,
644
+ head: { root: head.root, cid: head.cid },
645
+ };
646
+ }
647
+ async function inspection(context: SwarmContext, url: string, refresh = false) {
648
+ canonicalSwarmUrl(url);
649
+ const parent = join(context.stateDir, "swarm-inspections");
650
+ const name = `${createHash("sha256").update(url).digest("hex")}.json`;
651
+ const saved = refresh
652
+ ? undefined
653
+ : await readPrivate<unknown>(parent, name, [
654
+ { path: parent, directory: true },
655
+ ]);
656
+ let snapshot: InspectionSnapshot;
657
+ if (saved === undefined) {
658
+ snapshot = await withPrivateLock(
659
+ await privateDirectory(context.stateDir, "swarm-inspections"),
660
+ async () => {
661
+ const { config, variable } = await fetchConfig(context, url);
662
+ const directory = await memberDirectory(context, url, config);
663
+ const c = coordinates(url);
664
+ const head = headValue(
665
+ await client(context, c.service).read(c.scopeId, config.headId),
666
+ );
667
+ const confirmed = await fetchConfig(context, url);
668
+ if (
669
+ variable.cid !== confirmed.variable.cid ||
670
+ JSON.stringify(config) !== JSON.stringify(confirmed.config)
671
+ )
672
+ throw new HostError(
673
+ "Swarm configuration changed during inspection; retry --refresh.",
674
+ );
675
+ // Inspection persists only public declarations, never approval envelopes.
676
+ const publicConfig = {
677
+ ...config,
678
+ members: config.members.map((member) => ({
679
+ ...member,
680
+ approval: null,
681
+ })),
682
+ };
683
+ const fresh = parseInspection(
684
+ {
685
+ v: 1,
686
+ configUrl: url,
687
+ updatedAt: Date.now(),
688
+ config: publicConfig,
689
+ directory: directory.map(({ profile }, index) => ({
690
+ member: publicConfig.members[index],
691
+ profile,
692
+ })),
693
+ head: { root: head.root, cid: head.cid },
694
+ },
695
+ url,
696
+ );
697
+ if (Buffer.byteLength(JSON.stringify(fresh)) > 2 * 1024 * 1024)
698
+ throw new HostError("Swarm inspection snapshot is oversized.");
699
+ await writePrivate(parent, name, fresh);
700
+ return fresh;
701
+ },
702
+ );
703
+ } else {
704
+ snapshot = parseInspection(saved, url);
705
+ }
706
+ const age = Date.now() - snapshot.updatedAt;
707
+ return {
708
+ ...snapshot,
709
+ cache: {
710
+ source: saved === undefined ? ("network" as const) : ("cache" as const),
711
+ updatedAt: new Date(snapshot.updatedAt).toISOString(),
712
+ freshness:
713
+ age >= 0 && age < (context.cacheTtl ?? 300) * 1000
714
+ ? ("current" as const)
715
+ : ("stale" as const),
716
+ },
717
+ };
718
+ }
719
+ export async function swarmMembers(
720
+ context: SwarmContext,
721
+ url: string,
722
+ refresh = false,
723
+ ) {
724
+ const { config, directory, cache } = await inspection(context, url, refresh);
725
+ const observations = await localObservations(context, url, config);
726
+ const members = directory.map(({ member, profile }) => ({
727
+ publicKey: member.publicKey,
728
+ role: member.publicKey === config.owner ? "owner" : "member",
729
+ name: profile.name,
730
+ description: profile.description ?? "",
731
+ pivot: profile.pivot === true,
732
+ localStatus: pivotLocalStatus(
733
+ profile.pivot === true,
734
+ member.publicKey === observations.account,
735
+ profile.addresses,
736
+ member.peerId,
737
+ observations.local,
738
+ ),
739
+ peerId: member.peerId,
740
+ updatedAt: profile.updatedAt,
741
+ }));
742
+ return {
743
+ configUrl: url,
744
+ members,
745
+ cache,
746
+ local: observationSummary(observations.local),
747
+ };
748
+ }
749
+
750
+ export async function swarmNetworking(
751
+ context: SwarmContext,
752
+ url: string,
753
+ config: Organization,
754
+ directory?: Awaited<ReturnType<typeof memberDirectory>>,
755
+ ) {
756
+ directory ??= (await inspection(context, url)).directory;
757
+ const { account, local } = await localObservations(context, url, config);
758
+ const saved = local.snapshot?.connections;
759
+ const observedAt =
760
+ saved?.observedAt == null ? null : new Date(saved.observedAt).toISOString();
761
+ const connectionError =
762
+ local.status !== "current"
763
+ ? (local.error ?? "Daemon observations are not current.")
764
+ : saved === undefined || saved.observedAt === null
765
+ ? "No daemon connection snapshot; run ipab daemon."
766
+ : saved.error;
767
+ const connections = saved?.peers ?? [];
768
+ const freshness =
769
+ connectionError || !saved?.observedAt
770
+ ? observedAt
771
+ ? ("stale" as const)
772
+ : ("unavailable" as const)
773
+ : Date.now() - saved.observedAt > 90_000
774
+ ? ("stale" as const)
775
+ : ("current" as const);
776
+ const currentConnections = freshness === "current";
777
+ return {
778
+ daemon: observationSummary(local),
779
+ connections: {
780
+ observedAt,
781
+ error: connectionError,
782
+ peers: connections,
783
+ freshness,
784
+ },
785
+ pivots: directory
786
+ .filter(({ profile }) => profile.pivot === true)
787
+ .map(({ member, profile }) => {
788
+ const localStatus = pivotLocalStatus(
789
+ true,
790
+ member.publicKey === account,
791
+ profile.addresses,
792
+ member.peerId,
793
+ local,
794
+ );
795
+ const observation = local.snapshot?.pivots.find(
796
+ (entry) => entry.peerId === member.peerId,
797
+ );
798
+ const matching =
799
+ observation &&
800
+ JSON.stringify(observation.addresses) ===
801
+ JSON.stringify([...new Set(profile.addresses)].sort());
802
+ const current = local.status === "current" && matching;
803
+ const actual = connections.filter(
804
+ (entry) => entry.peerId === member.peerId,
805
+ );
806
+ const probeFreshness: LocalObservations["status"] =
807
+ matching && observation.probedAt !== null
808
+ ? current && Date.now() - observation.probedAt <= 90_000
809
+ ? "current"
810
+ : "stale"
811
+ : "unavailable";
812
+ const connectionStatus:
813
+ "self" | "unknown" | "direct" | "relay" | "disconnected" =
814
+ member.publicKey === account
815
+ ? "self"
816
+ : !currentConnections
817
+ ? "unknown"
818
+ : actual.some((entry) => entry.transport === "direct")
819
+ ? "direct"
820
+ : actual.length
821
+ ? "relay"
822
+ : "disconnected";
823
+ return {
824
+ publicKey: member.publicKey,
825
+ name: profile.name,
826
+ peerId: member.peerId,
827
+ pivot: true as const,
828
+ addresses: profile.addresses,
829
+ localStatus,
830
+ selected:
831
+ localStatus === "unknown" ? null : localStatus === "selected",
832
+ failures: matching ? observation.failures : null,
833
+ retryAt:
834
+ matching && observation.retryAt > 0
835
+ ? new Date(observation.retryAt).toISOString()
836
+ : null,
837
+ probe: {
838
+ result: matching ? observation.probe : ("unknown" as const),
839
+ at:
840
+ matching && observation.probedAt !== null
841
+ ? new Date(observation.probedAt).toISOString()
842
+ : null,
843
+ error: matching ? observation.error : null,
844
+ freshness: probeFreshness,
845
+ },
846
+ connection: {
847
+ status: connectionStatus,
848
+ observedAt,
849
+ error: connectionError,
850
+ freshness,
851
+ addresses: actual.map((entry) => entry.address),
852
+ },
853
+ };
854
+ }),
855
+ };
856
+ }
857
+ export async function inspectSwarmStatus(
858
+ context: SwarmContext,
859
+ url: string,
860
+ refresh = false,
861
+ ) {
862
+ const { config, directory, head, cache } = await inspection(
863
+ context,
864
+ url,
865
+ refresh,
866
+ );
867
+ return {
868
+ config,
869
+ head,
870
+ cache,
871
+ state: {
872
+ status: "unavailable" as const,
873
+ error:
874
+ "State content is not fetched or verified by inspection; use get ipab:/// to obtain the State Bundle.",
875
+ },
876
+ networking: await swarmNetworking(context, url, config, directory),
877
+ };
506
878
  }
507
879
 
508
880
  function accountProfileLocation(context: SwarmContext, publicKey: string) {
@@ -880,6 +1252,7 @@ async function privateSource(
880
1252
  context: SwarmContext,
881
1253
  record: LocalMembership,
882
1254
  signal?: AbortSignal,
1255
+ candidates?: PivotCandidates,
883
1256
  ) {
884
1257
  const config = record.config!,
885
1258
  secret = record.secret!;
@@ -912,17 +1285,38 @@ async function privateSource(
912
1285
  }
913
1286
  const personal = await storedAccountProfile(context);
914
1287
  const addresses = new Map<string, readonly string[]>();
1288
+ const observationErrors: string[] = [];
915
1289
  const api = client(context, c.service);
916
1290
  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
- );
1291
+ const profiles = await boundedMap(config.members, async (member) => {
1292
+ try {
1293
+ return await api.read(
1294
+ c.scopeId,
1295
+ member.profileId,
1296
+ signal ? { signal } : {},
1297
+ );
1298
+ } catch (cause) {
1299
+ signal?.throwIfAborted();
1300
+ if (!candidates) throw cause;
1301
+ observationErrors.push(`Profile ${member.peerId}: ${message(cause)}`);
1302
+ context.diagnostic?.(
1303
+ `Pivot profile refresh ${member.peerId} failed; retaining last-known approved candidate: ${message(cause)}`,
1304
+ );
1305
+ return undefined;
1306
+ }
1307
+ });
920
1308
  for (const [index, member] of config.members.entries()) {
921
- const profile = profiles[index]!;
1309
+ const profile = profiles[index];
1310
+ if (!profile) {
1311
+ const known = candidates?.known(member.peerId);
1312
+ if (known) addresses.set(member.peerId, known);
1313
+ continue;
1314
+ }
922
1315
  const value = parseProfile(profile.value, member.peerId);
923
1316
  if (member.publicKey === identity.publicKey)
924
1317
  selfProfile = { profile: value, cid: profile.cid };
925
- addresses.set(member.peerId, value.addresses);
1318
+ if (value.pivot === true && member.peerId !== self.peerId)
1319
+ addresses.set(member.peerId, value.addresses);
926
1320
  }
927
1321
  if (personal && selfProfile) {
928
1322
  selfProfile.profile = await syncAccountProfile(
@@ -933,7 +1327,34 @@ async function privateSource(
933
1327
  );
934
1328
  selfProfile.cid = await valueCid(selfProfile.profile);
935
1329
  }
936
- const desired = memberPeers(self.peerId, addresses, config.bootstrap);
1330
+ candidates?.reconcile(addresses);
1331
+ const active = candidates?.active() ?? addresses;
1332
+ if (!candidates) {
1333
+ try {
1334
+ const observed = await readNetworkingSnapshot(
1335
+ context.stateDir,
1336
+ record.configUrl,
1337
+ networkingBinding(record.configUrl, identity.publicKey, config),
1338
+ nodeScope(c.service, config.scopeId),
1339
+ config.epoch,
1340
+ self.peerId,
1341
+ );
1342
+ if (observed.status === "current")
1343
+ for (const pivot of observed.snapshot!.pivots)
1344
+ if (
1345
+ pivot.retryAt > Date.now() &&
1346
+ JSON.stringify(
1347
+ [...new Set(active.get(pivot.peerId) ?? [])].sort(),
1348
+ ) === JSON.stringify(pivot.addresses)
1349
+ )
1350
+ active.delete(pivot.peerId);
1351
+ } catch (cause) {
1352
+ context.diagnostic?.(
1353
+ `Local daemon observations could not be read: ${message(cause)}`,
1354
+ );
1355
+ }
1356
+ }
1357
+ const desired = memberPeers(self.peerId, active, []);
937
1358
  signal?.throwIfAborted();
938
1359
  const node = await startNode(
939
1360
  context.stateDir,
@@ -941,7 +1362,12 @@ async function privateSource(
941
1362
  secret.swarmKey,
942
1363
  config.epoch,
943
1364
  context.listen,
944
- { self: self.peerId, peers: desired, ...(signal ? { signal } : {}) },
1365
+ {
1366
+ self: self.peerId,
1367
+ peers: desired,
1368
+ pivot: context.pivot ?? false,
1369
+ ...(signal ? { signal } : {}),
1370
+ },
945
1371
  );
946
1372
  if (node.peerId !== self.peerId)
947
1373
  throw new HostError(
@@ -951,15 +1377,48 @@ async function privateSource(
951
1377
  Addrs.map((addr) => `${addr}/p2p/${ID}`),
952
1378
  );
953
1379
  signal?.throwIfAborted();
954
- if (!node.addresses.length && !selfProfile?.profile.addresses.length)
1380
+ if (
1381
+ context.pivot &&
1382
+ !node.addresses.length &&
1383
+ !selfProfile?.profile.addresses.length
1384
+ )
955
1385
  context.diagnostic?.(
956
- "No private LAN/VPN IPv4 address to advertise. Connect a routed interface or set your own address with swarm profile --address.",
1386
+ "Pivot has no IPv4 candidates. Connect an interface or set manual candidates with swarm profile --address.",
957
1387
  );
958
- if (
959
- node.addresses.length &&
960
- selfProfile &&
961
- selfProfile.profile.addresses.length === 0
962
- ) {
1388
+ if (selfProfile) {
1389
+ const dir = await directory(context);
1390
+ const preference = `pivot-${localName(record.configUrl)}`;
1391
+ const saved = await readPrivate<{ manual: string[] }>(dir, preference);
1392
+ const manual = saved?.manual ?? selfProfile.profile.addresses;
1393
+ for (const address of manual) validateAddress(address, self.peerId);
1394
+ if (!saved && context.pivot)
1395
+ await writePrivate(dir, preference, { manual });
1396
+ const published = context.pivot
1397
+ ? [...new Set([...manual, ...node.addresses])].slice(0, 16).sort()
1398
+ : manual;
1399
+ if (context.pivot && new Set([...manual, ...node.addresses]).size > 16)
1400
+ context.diagnostic?.(
1401
+ "Pivot profile is capped at 16 candidates; manual hints take priority over interface snapshots.",
1402
+ );
1403
+ const pivot = context.pivot ?? false;
1404
+ if (
1405
+ selfProfile.profile.pivot === pivot &&
1406
+ JSON.stringify([...selfProfile.profile.addresses].sort()) ===
1407
+ JSON.stringify(published)
1408
+ )
1409
+ return {
1410
+ node,
1411
+ peers,
1412
+ observationError: observationErrors.length
1413
+ ? observationErrors.join("; ")
1414
+ : null,
1415
+ source: kuboSource(
1416
+ node,
1417
+ peers,
1418
+ context.diagnostic,
1419
+ context.env.IPAB_SWARM_DIAL_DEBUG === "1",
1420
+ ),
1421
+ };
963
1422
  const writer = client(
964
1423
  context,
965
1424
  c.service,
@@ -968,7 +1427,8 @@ async function privateSource(
968
1427
  );
969
1428
  const profile = {
970
1429
  ...selfProfile.profile,
971
- addresses: node.addresses,
1430
+ pivot,
1431
+ addresses: published,
972
1432
  updatedAt: new Date().toISOString(),
973
1433
  };
974
1434
  await writer.write(
@@ -983,6 +1443,9 @@ async function privateSource(
983
1443
  return {
984
1444
  node,
985
1445
  peers,
1446
+ observationError: observationErrors.length
1447
+ ? observationErrors.join("; ")
1448
+ : null,
986
1449
  source: kuboSource(
987
1450
  node,
988
1451
  peers,
@@ -991,6 +1454,281 @@ async function privateSource(
991
1454
  ),
992
1455
  };
993
1456
  }
1457
+ export async function swarmDaemon(
1458
+ context: SwarmContext,
1459
+ selected: string | undefined,
1460
+ signal: AbortSignal,
1461
+ ): Promise<void> {
1462
+ const lock = await privateDirectory(context.stateDir, "swarm-daemon");
1463
+ await withPrivateLock(
1464
+ lock,
1465
+ async () => {
1466
+ const closeReadiness = await context.daemonReady?.();
1467
+ const sessions = new Map<
1468
+ string,
1469
+ {
1470
+ context: SwarmContext;
1471
+ candidates: PivotCandidates;
1472
+ nextDiscovery: number;
1473
+ healthy: number;
1474
+ record?: LocalMembership;
1475
+ node?: KuboNode;
1476
+ selected: Set<string>;
1477
+ verifiedAt: number | null;
1478
+ error: string | null;
1479
+ connections?: NetworkingSnapshot["connections"];
1480
+ }
1481
+ >();
1482
+ context.diagnostic?.(
1483
+ "IPAB daemon running in foreground; Ctrl-C stops management and leaves Kubo running.",
1484
+ );
1485
+ const persist = async (
1486
+ url: string,
1487
+ session: NonNullable<ReturnType<typeof sessions.get>>,
1488
+ running: boolean,
1489
+ ) => {
1490
+ const record = session.record;
1491
+ if (!record?.config) return;
1492
+ const redact = (error: string | null) => {
1493
+ if (error === null) return null;
1494
+ for (const secret of [
1495
+ record.secret?.swarmKey,
1496
+ session.node?.auth,
1497
+ session.context.identity?.privateKey,
1498
+ ])
1499
+ if (secret) error = error.split(secret).join("[redacted]");
1500
+ return error.slice(0, 2048);
1501
+ };
1502
+ const snapshot: NetworkingSnapshot = {
1503
+ v: 1,
1504
+ binding: networkingBinding(url, record.account, record.config),
1505
+ pid: process.pid,
1506
+ running,
1507
+ updatedAt: Date.now(),
1508
+ verifiedAt: session.verifiedAt,
1509
+ error: redact(session.error),
1510
+ topology: session.node?.topology ?? null,
1511
+ pivots: [...session.candidates.observations()].map(
1512
+ ([peerId, value]) => ({
1513
+ ...value,
1514
+ peerId,
1515
+ selected: session.selected.has(peerId),
1516
+ error: redact(value.error),
1517
+ }),
1518
+ ),
1519
+ account: record.account,
1520
+ connections: session.connections
1521
+ ? {
1522
+ ...session.connections,
1523
+ error: redact(session.connections.error),
1524
+ }
1525
+ : {
1526
+ observedAt: null,
1527
+ error: "No connection snapshot collected.",
1528
+ peers: [],
1529
+ },
1530
+ };
1531
+ await writeNetworkingSnapshot(context.stateDir, url, snapshot);
1532
+ };
1533
+ try {
1534
+ while (!signal.aborted) {
1535
+ const registrations = withState(context, (state) =>
1536
+ state.swarms(),
1537
+ ).filter((entry) => selected === undefined || entry.cid === selected);
1538
+ if (selected && !registrations.length)
1539
+ throw new HostError(
1540
+ "Selected Swarm is not registered; run ipab swarm add first.",
1541
+ );
1542
+ const urls = new Set(registrations.map((entry) => entry.cid));
1543
+ for (const url of sessions.keys())
1544
+ if (!urls.has(url)) {
1545
+ await persist(url, sessions.get(url)!, false);
1546
+ sessions.delete(url);
1547
+ }
1548
+ await boundedMap(registrations, async ({ cid: url }) => {
1549
+ let session = sessions.get(url);
1550
+ if (!session) {
1551
+ session = {
1552
+ context: { ...context },
1553
+ candidates: new PivotCandidates(),
1554
+ nextDiscovery: 0,
1555
+ healthy: 0,
1556
+ selected: new Set(),
1557
+ verifiedAt: null,
1558
+ error: null,
1559
+ };
1560
+ sessions.set(url, session);
1561
+ }
1562
+ try {
1563
+ if (Date.now() >= session.nextDiscovery || session.healthy < 1) {
1564
+ const record = await approvedMembership(
1565
+ session.context,
1566
+ url,
1567
+ signal,
1568
+ );
1569
+ const c = coordinates(url);
1570
+ const scope = nodeScope(c.service, record.config!.scopeId);
1571
+ const existing = await readPrivate<unknown>(
1572
+ join(context.stateDir, "swarm-nodes", scope),
1573
+ "node.json",
1574
+ );
1575
+ if (!existing)
1576
+ throw new HostError(
1577
+ "No existing managed node; activate this membership before running daemon.",
1578
+ );
1579
+ await saveLocal(session.context, record);
1580
+ if (
1581
+ !session.record?.config ||
1582
+ networkingBinding(url, record.account, record.config!) !==
1583
+ networkingBinding(
1584
+ url,
1585
+ session.record.account,
1586
+ session.record.config,
1587
+ )
1588
+ ) {
1589
+ session.candidates.reconcile(new Map());
1590
+ session.selected.clear();
1591
+ session.verifiedAt = null;
1592
+ delete session.connections;
1593
+ delete session.node;
1594
+ }
1595
+ session.record = record;
1596
+ const result = await privateSource(
1597
+ session.context,
1598
+ record,
1599
+ signal,
1600
+ session.candidates,
1601
+ );
1602
+ session.node = result.node;
1603
+ session.selected = new Set(
1604
+ result.peers.map((address) => address.split("/").at(-1)!),
1605
+ );
1606
+ session.error = result.observationError;
1607
+ if (!session.error) session.verifiedAt = Date.now();
1608
+ session.context.node = result.node;
1609
+ session.nextDiscovery = Date.now() + 120_000;
1610
+ await persist(url, session, true);
1611
+ }
1612
+ if (!session.node) return;
1613
+ let healthy = 0;
1614
+ await boundedMap(
1615
+ [...session.candidates.active()],
1616
+ async ([id, addresses]) => {
1617
+ let success = false;
1618
+ let error: string | null = null;
1619
+ try {
1620
+ success = await probePeer(
1621
+ session.node!,
1622
+ id,
1623
+ addresses,
1624
+ signal,
1625
+ );
1626
+ } catch (cause) {
1627
+ signal.throwIfAborted();
1628
+ error = message(cause);
1629
+ context.diagnostic?.(
1630
+ `[${url}] Pivot probe ${id}: ${message(cause)}`,
1631
+ );
1632
+ }
1633
+ session.candidates.result(
1634
+ id,
1635
+ success,
1636
+ Date.now(),
1637
+ Math.random(),
1638
+ success ? null : (error ?? "Pivot dial failed."),
1639
+ );
1640
+ if (success) healthy++;
1641
+ else {
1642
+ session.nextDiscovery = 0;
1643
+ context.diagnostic?.(
1644
+ `[${url}] Pivot ${id} dial failed; refreshing profile, with cooldown after repeated failure.`,
1645
+ );
1646
+ }
1647
+ },
1648
+ );
1649
+ session.healthy = healthy;
1650
+ // Startup-captured relay/bootstrap options must be removed immediately
1651
+ // when a candidate enters cooldown, not merely changed through config RPC.
1652
+ const record = session.record!;
1653
+ const self = record.config!.members.find(
1654
+ (member) => member.publicKey === record.account,
1655
+ )!;
1656
+ const desired = memberPeers(
1657
+ self.peerId,
1658
+ session.candidates.active(),
1659
+ [],
1660
+ );
1661
+ session.node = await startNode(
1662
+ context.stateDir,
1663
+ nodeScope(coordinates(url).service, record.config!.scopeId),
1664
+ record.secret!.swarmKey,
1665
+ record.config!.epoch,
1666
+ context.listen,
1667
+ {
1668
+ self: self.peerId,
1669
+ pivot: context.pivot ?? false,
1670
+ peers: desired,
1671
+ signal,
1672
+ },
1673
+ );
1674
+ session.selected = new Set(desired.map(({ ID }) => ID));
1675
+ try {
1676
+ const peers = await nodeConnections(session.node, signal);
1677
+ session.connections = {
1678
+ observedAt: Date.now(),
1679
+ error: null,
1680
+ peers,
1681
+ };
1682
+ } catch (cause) {
1683
+ signal.throwIfAborted();
1684
+ session.connections = {
1685
+ observedAt: session.connections?.observedAt ?? null,
1686
+ error: message(cause).slice(0, 2048),
1687
+ peers: session.connections?.peers ?? [],
1688
+ };
1689
+ }
1690
+ } catch (cause) {
1691
+ if (signal.aborted) return;
1692
+ session.error = message(cause);
1693
+ session.nextDiscovery = 0;
1694
+ context.diagnostic?.(
1695
+ `[${url}] Daemon refresh failed (last-known local candidates retained): ${message(cause)}`,
1696
+ );
1697
+ if (
1698
+ cause instanceof HostError &&
1699
+ /membership removed|identity was removed|epoch rollback|Pinned Owner changed/.test(
1700
+ cause.message,
1701
+ )
1702
+ ) {
1703
+ if (session.node) await stopNode(session.node);
1704
+ session.candidates.reconcile(new Map());
1705
+ delete session.node;
1706
+ session.selected.clear();
1707
+ await persist(url, session, false);
1708
+ delete session.record;
1709
+ }
1710
+ }
1711
+ await persist(url, session, true);
1712
+ });
1713
+ try {
1714
+ await delay(30_000 + Math.random() * 15_000, undefined, { signal });
1715
+ } catch {
1716
+ signal.throwIfAborted();
1717
+ }
1718
+ }
1719
+ } finally {
1720
+ try {
1721
+ for (const [url, session] of sessions)
1722
+ await persist(url, session, false);
1723
+ } finally {
1724
+ await closeReadiness?.();
1725
+ }
1726
+ }
1727
+ },
1728
+ signal,
1729
+ 1,
1730
+ );
1731
+ }
994
1732
  async function activate(context: SwarmContext, record: LocalMembership) {
995
1733
  const { node, peers, source } = await privateSource(context, record);
996
1734
  if (
@@ -1004,6 +1742,7 @@ async function activate(context: SwarmContext, record: LocalMembership) {
1004
1742
  context.sourcePeers = peers;
1005
1743
  }
1006
1744
  context.node = node;
1745
+ await context.ensureDaemon?.();
1007
1746
  }
1008
1747
  async function localForRead(
1009
1748
  context: SwarmContext,
@@ -1246,6 +1985,7 @@ async function writeStateBundle(
1246
1985
  store: IpfsStore,
1247
1986
  configuration: SwarmMeta,
1248
1987
  targets: Record<string, CID>,
1988
+ configUrl?: string,
1249
1989
  ): Promise<string> {
1250
1990
  const meta = parseSwarmMeta(configuration);
1251
1991
  const names = Object.fromEntries(
@@ -1254,20 +1994,37 @@ async function writeStateBundle(
1254
1994
  cid.toString(),
1255
1995
  ]),
1256
1996
  );
1997
+ const value = parseSwarmState({
1998
+ v: configUrl === undefined ? 5 : 6,
1999
+ ...(configUrl === undefined ? {} : { configUrl }),
2000
+ ...meta,
2001
+ names,
2002
+ });
1257
2003
  return jsonBundle(
1258
2004
  store,
1259
- meta.skillPath === undefined ? legacySwarmStateType : swarmStateType,
1260
- { v: 5, ...meta, names },
2005
+ configUrl !== undefined
2006
+ ? swarmStateType
2007
+ : meta.skillPath === undefined
2008
+ ? legacySwarmStateType
2009
+ : previousSwarmStateType,
2010
+ value,
1261
2011
  );
1262
2012
  }
1263
2013
  export async function writeSnapshot(
1264
2014
  store: IpfsStore,
1265
2015
  snapshot: Snapshot,
2016
+ configUrl?: string,
1266
2017
  ): Promise<string> {
1267
2018
  if (snapshot.stateBundle) {
1268
2019
  if (Object.keys(snapshot.registrations ?? {}).length)
1269
2020
  throw new HostError("State Bundles cannot contain legacy registrations.");
1270
- return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names);
2021
+ checkStateOrigin(snapshot, configUrl);
2022
+ return writeStateBundle(
2023
+ store,
2024
+ snapshot.stateBundle.meta,
2025
+ snapshot.names,
2026
+ snapshot.stateBundle.configUrl,
2027
+ );
1271
2028
  }
1272
2029
  const put = async (value: unknown) => {
1273
2030
  const encoded = dagCbor.encode(value);
@@ -1290,23 +2047,14 @@ async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1290
2047
  const type =
1291
2048
  bundle.schemaKey === legacySwarmStateSchema.cid.toString()
1292
2049
  ? 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.");
2050
+ : bundle.schemaKey === previousSwarmStateSchema.cid.toString()
2051
+ ? previousSwarmStateType
2052
+ : swarmStateType;
2053
+ const value = parseSwarmState(await typedJson(store, cid.toString(), type));
1306
2054
  const meta = parseSwarmMeta({
1307
2055
  templatePath: value.templatePath,
1308
2056
  registryPath: value.registryPath,
1309
- ...(type === legacySwarmStateType ? {} : { skillPath: value.skillPath }),
2057
+ ...(value.skillPath === undefined ? {} : { skillPath: value.skillPath }),
1310
2058
  });
1311
2059
  const names = Object.fromEntries(
1312
2060
  Object.entries(object(value.names, "Names")).map(([name, target]) => {
@@ -1316,7 +2064,17 @@ async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1316
2064
  return [name, CID.parse(target)];
1317
2065
  }),
1318
2066
  );
1319
- return { v: 2, names, stateBundle: { meta, cid: cid.toString() } };
2067
+ return {
2068
+ v: 2,
2069
+ names,
2070
+ stateBundle: {
2071
+ meta,
2072
+ cid: cid.toString(),
2073
+ ...(value.configUrl === undefined
2074
+ ? {}
2075
+ : { configUrl: value.configUrl }),
2076
+ },
2077
+ };
1320
2078
  }
1321
2079
  const data = await store.block.get(cid.toString());
1322
2080
  const root = object(dagCbor.decode(data), "State");
@@ -1406,14 +2164,33 @@ function decodeSnapshot(data: Uint8Array): Snapshot {
1406
2164
  export async function readSnapshot(
1407
2165
  store: IpfsStore,
1408
2166
  root: string,
2167
+ configUrl?: string,
1409
2168
  ): Promise<Snapshot> {
1410
2169
  const publication = await readPublication(store, root);
1411
- return readState(store, publication.state);
2170
+ const snapshot = await readState(store, publication.state);
2171
+ checkStateOrigin(snapshot, configUrl);
2172
+ return snapshot;
2173
+ }
2174
+ function checkStateOrigin(snapshot: Snapshot, configUrl?: string): void {
2175
+ if (
2176
+ configUrl !== undefined &&
2177
+ snapshot.stateBundle?.configUrl !== undefined &&
2178
+ snapshot.stateBundle.configUrl !== configUrl
2179
+ )
2180
+ throw new HostError(
2181
+ "State Bundle Config URL does not match the selected Swarm.",
2182
+ );
1412
2183
  }
1413
- async function readHeaderSnapshot(store: IpfsStore, root: string) {
2184
+ async function readHeaderSnapshot(
2185
+ store: IpfsStore,
2186
+ root: string,
2187
+ configUrl: string,
2188
+ ) {
1414
2189
  const publication = await readPublication(store, root);
2190
+ const snapshot = await readState(store, publication.state);
2191
+ checkStateOrigin(snapshot, configUrl);
1415
2192
  return {
1416
- snapshot: await readState(store, publication.state),
2193
+ snapshot,
1417
2194
  stateCid: publication.state.toString(),
1418
2195
  };
1419
2196
  }
@@ -1488,7 +2265,7 @@ export async function sharedSwarmStatus(
1488
2265
  );
1489
2266
  let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
1490
2267
  try {
1491
- content = await readHeaderSnapshot(context.store, head.root);
2268
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
1492
2269
  } catch (cause) {
1493
2270
  if (!missingContent(cause)) throw cause;
1494
2271
  const registered = withState(context, (state) =>
@@ -1576,12 +2353,12 @@ async function readSwarmHeader(
1576
2353
  : await (await boundPointer(context, configUrl, record)).read();
1577
2354
  let content: Awaited<ReturnType<typeof readHeaderSnapshot>>;
1578
2355
  try {
1579
- content = await readHeaderSnapshot(context.store, head.root);
2356
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
1580
2357
  } catch (cause) {
1581
2358
  if (mode === "local-first") throw cause;
1582
2359
  record = await refresh(context, configUrl);
1583
2360
  head = await (await boundPointer(context, configUrl, record)).read();
1584
- content = await readHeaderSnapshot(context.store, head.root);
2361
+ content = await readHeaderSnapshot(context.store, head.root, configUrl);
1585
2362
  }
1586
2363
  const current = await local(context, configUrl),
1587
2364
  verifiedAt = Date.now();
@@ -1643,13 +2420,29 @@ async function cachedHeader(
1643
2420
  if (stateBundle !== undefined) {
1644
2421
  const data = object(stateBundle, "cached State Bundle");
1645
2422
  if (
1646
- Object.keys(data).sort().join() !== "cid,meta" ||
2423
+ !["cid,meta", "cid,configUrl,meta"].includes(
2424
+ Object.keys(data).sort().join(),
2425
+ ) ||
1647
2426
  typeof data.cid !== "string" ||
1648
2427
  exactCid(data.cid) !== data.cid ||
1649
2428
  (cached.stateCid !== undefined && data.cid !== cached.stateCid)
1650
2429
  )
1651
2430
  throw new HostError("Invalid cached State Bundle.");
1652
- snapshot.stateBundle = { meta: parseSwarmMeta(data.meta), cid: data.cid };
2431
+ const meta = parseSwarmMeta(data.meta);
2432
+ const parsed = parseSwarmState({
2433
+ v: data.configUrl === undefined ? 5 : 6,
2434
+ ...meta,
2435
+ ...(data.configUrl === undefined ? {} : { configUrl: data.configUrl }),
2436
+ names: {},
2437
+ });
2438
+ snapshot.stateBundle = {
2439
+ meta,
2440
+ cid: data.cid,
2441
+ ...(parsed.configUrl === undefined
2442
+ ? {}
2443
+ : { configUrl: parsed.configUrl }),
2444
+ };
2445
+ checkStateOrigin(snapshot, record.configUrl);
1653
2446
  }
1654
2447
  let stateCid = cached.stateCid;
1655
2448
  if (!stateCid) {
@@ -1778,9 +2571,11 @@ async function lazyPrivateSource(
1778
2571
  record.config!.headId !== basis.headId
1779
2572
  )
1780
2573
  throw new HostError(
1781
- "Swarm membership changed since this cached HEAD; retry with --force.",
2574
+ "Swarm membership changed since this cached HEAD; retry with --refresh.",
1782
2575
  );
1783
- return (await privateSource(scoped, record, signal)).source;
2576
+ const { source } = await privateSource(scoped, record, signal);
2577
+ await context.ensureDaemon?.();
2578
+ return source;
1784
2579
  };
1785
2580
  // Same lock order as Owner rotation: credentials first, then the node.
1786
2581
  return withPrivateLock(await directory(scoped), authorize, signal);
@@ -1807,16 +2602,10 @@ async function lazyPrivateSource(
1807
2602
  await pending?.catch(() => {});
1808
2603
  };
1809
2604
  }
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
2605
  interface Creation {
2606
+ stateVersion?: 6;
2607
+ configReservationCid?: string;
2608
+ configPublished?: boolean;
1820
2609
  owner: string;
1821
2610
  service: string;
1822
2611
  encryption: EncryptionIdentity;
@@ -1879,6 +2668,7 @@ export async function createSwarm(
1879
2668
  if (!record) {
1880
2669
  if (options.resume) throw new HostError("Unknown creation operation.");
1881
2670
  record = {
2671
+ stateVersion: 6,
1882
2672
  owner: identity.publicKey,
1883
2673
  service,
1884
2674
  encryption: encryptionIdentity(),
@@ -1895,6 +2685,28 @@ export async function createSwarm(
1895
2685
  const save = () => writePrivate(dir, `creation-${op}.json`, record);
1896
2686
  const api = client(context, service, identity);
1897
2687
  try {
2688
+ if (record.stateVersion === 6) {
2689
+ if (!record.scopeId) {
2690
+ record.scopeId = (await api.createScope(`${op}.scope`)).id;
2691
+ await save();
2692
+ }
2693
+ if (!record.configId) {
2694
+ // Reserve the Config address, not a Config or a temporary HEAD.
2695
+ const reservation = await api.create(
2696
+ record.scopeId,
2697
+ {
2698
+ v: 1,
2699
+ kind: "ipab-config-reservation",
2700
+ owner: record.owner,
2701
+ operation: op,
2702
+ },
2703
+ `${op}.config-reserve`,
2704
+ );
2705
+ record.configId = reservation.id;
2706
+ record.configReservationCid = reservation.cid;
2707
+ await save();
2708
+ }
2709
+ }
1898
2710
  if (!record.seed) {
1899
2711
  if (record.headId)
1900
2712
  throw new HostError(
@@ -1905,7 +2717,7 @@ export async function createSwarm(
1905
2717
  const template = await seedTemplateSource(selector);
1906
2718
  for (const [cid, data] of template.blocks)
1907
2719
  await context.store.put(CID.parse(cid), data);
1908
- names[`ipab/template/${selector}`] = CID.parse(template.cid);
2720
+ names[`ipab/templates/${selector}`] = CID.parse(template.cid);
1909
2721
  }
1910
2722
  const skill = await seedSkillSource();
1911
2723
  for (const [cid, data] of skill.blocks)
@@ -1916,11 +2728,14 @@ export async function createSwarm(
1916
2728
  await writeStateBundle(
1917
2729
  context.store,
1918
2730
  {
1919
- templatePath: "ipab/template",
2731
+ templatePath: "ipab/templates",
1920
2732
  registryPath: "ipab/registry",
1921
2733
  skillPath: "ipab/skills",
1922
2734
  },
1923
2735
  names,
2736
+ record.stateVersion === 6
2737
+ ? `${service}/v1/${record.scopeId!}/${record.configId!}`
2738
+ : undefined,
1924
2739
  ),
1925
2740
  );
1926
2741
  const roots = await frozenPublicationClosure(context.store, root);
@@ -1960,12 +2775,13 @@ export async function createSwarm(
1960
2775
  }
1961
2776
  if (!record.profileId) {
1962
2777
  if (!record.profile) {
1963
- const addresses = options.addresses ?? node.addresses;
2778
+ const addresses = options.addresses ?? [];
1964
2779
  for (const address of addresses)
1965
2780
  validateAddress(address, node.peerId);
1966
2781
  record.profile = {
1967
2782
  ...(record.personal ?? { name: record.name }),
1968
2783
  addresses,
2784
+ pivot: context.pivot ?? false,
1969
2785
  updatedAt: record.createdAt,
1970
2786
  };
1971
2787
  await save();
@@ -1997,7 +2813,7 @@ export async function createSwarm(
1997
2813
  description: record.description,
1998
2814
  headId: record.headId,
1999
2815
  epoch: 1,
2000
- bootstrap: options.addresses ?? node.addresses,
2816
+ bootstrap: [],
2001
2817
  members: [member],
2002
2818
  };
2003
2819
  await save();
@@ -2012,6 +2828,29 @@ export async function createSwarm(
2012
2828
  ).id;
2013
2829
  await save();
2014
2830
  }
2831
+ if (record.stateVersion === 6 && !record.configPublished) {
2832
+ if (!record.configReservationCid)
2833
+ throw new HostError(
2834
+ "Creation Config reservation checkpoint is missing.",
2835
+ );
2836
+ const value = configValue(record.config);
2837
+ const current = await api.read(record.scopeId, record.configId);
2838
+ if (current.cid !== (await valueCid(value))) {
2839
+ if (current.cid !== record.configReservationCid)
2840
+ throw new HostError(
2841
+ "Creation Config reservation was changed; refusing to overwrite it.",
2842
+ );
2843
+ await api.write(
2844
+ record.scopeId,
2845
+ record.configId,
2846
+ value,
2847
+ record.configReservationCid,
2848
+ `${op}.config`,
2849
+ );
2850
+ }
2851
+ record.configPublished = true;
2852
+ await save();
2853
+ }
2015
2854
  const configUrl = `${service}/v1/${record.scopeId}/${record.configId}`;
2016
2855
  const cert = await issueScopeCertificate(
2017
2856
  {
@@ -2075,7 +2914,6 @@ export async function requestMembership(
2075
2914
  context: SwarmContext,
2076
2915
  url: string,
2077
2916
  options: {
2078
- alias?: string;
2079
2917
  output?: string;
2080
2918
  },
2081
2919
  ): Promise<{
@@ -2094,10 +2932,6 @@ export async function requestMembership(
2094
2932
  const personal = await ensureAccountProfile(context);
2095
2933
  const dir = await directory(context);
2096
2934
  await withPrivateLock(dir, async () => {
2097
- if (options.alias !== undefined)
2098
- withState(context, (state) => {
2099
- state.checkSwarmAlias(options.alias!, url);
2100
- });
2101
2935
  const existing = await readPrivate<LocalMembership>(dir, localName(url));
2102
2936
  if (existing) {
2103
2937
  if (
@@ -2109,7 +2943,6 @@ export async function requestMembership(
2109
2943
  );
2110
2944
  if (!existing.request)
2111
2945
  throw new HostError("This identity is already the Owner.");
2112
- withState(context, (state) => state.registerSwarm(url, options.alias));
2113
2946
  return;
2114
2947
  }
2115
2948
  const node = await prepareNode(
@@ -2149,7 +2982,6 @@ export async function requestMembership(
2149
2982
  encryption,
2150
2983
  request,
2151
2984
  });
2152
- withState(context, (state) => state.registerSwarm(url, options.alias));
2153
2985
  });
2154
2986
  const file =
2155
2987
  options.output === undefined ? undefined : resolve(options.output);
@@ -2549,6 +3381,13 @@ export async function updateProfile(
2549
3381
  existing.cid,
2550
3382
  uniqueId(),
2551
3383
  );
3384
+ await writePrivate(await directory(context), `pivot-${localName(url)}`, {
3385
+ manual: changes.addresses,
3386
+ });
3387
+ if (!context.pivot)
3388
+ context.diagnostic?.(
3389
+ "Manual addresses saved; they are discovery candidates only when swarm.pivot=true. Ordinary nodes do not provide relay service.",
3390
+ );
2552
3391
  return profile;
2553
3392
  }
2554
3393
  interface Removal {
@@ -2629,6 +3468,11 @@ export async function resumeRemoval(
2629
3468
  membershipBeforeSwitch.config = record.oldConfig;
2630
3469
  membershipBeforeSwitch.secret!.swarmKey = record.oldKey;
2631
3470
  await activate(context, membershipBeforeSwitch);
3471
+ await readSnapshot(
3472
+ context.store,
3473
+ headValue(record.finalHead).root,
3474
+ url,
3475
+ );
2632
3476
  if (!record.finalClosureRoots) {
2633
3477
  record.finalClosureRoots = await frozenPublicationClosure(
2634
3478
  context.store,
@@ -2874,7 +3718,7 @@ export function parseNameReference(
2874
3718
  try {
2875
3719
  return {
2876
3720
  ...(authority ? { swarm: authority } : {}),
2877
- name: formalName(segments.join("/")),
3721
+ name: match[2] === "" ? "" : formalName(segments.join("/")),
2878
3722
  };
2879
3723
  } catch (error) {
2880
3724
  if (!(error instanceof HostError)) throw error;
@@ -2915,14 +3759,16 @@ export async function resolveReference(
2915
3759
  const warm =
2916
3760
  mode === "local-first" ? await localHeader(context, selected) : undefined;
2917
3761
  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;
3762
+ const target = () =>
3763
+ shared.name === ""
3764
+ ? header.stateCid
3765
+ : Object.hasOwn(header.snapshot.names, shared.name)
3766
+ ? header.snapshot.names[shared.name]?.toString()
3767
+ : undefined;
3768
+ let link = target();
2921
3769
  if (!link && header.source === "cache") {
2922
3770
  header = await swarmHeader(context, selected, true);
2923
- link = Object.hasOwn(header.snapshot.names, shared.name)
2924
- ? header.snapshot.names[shared.name]
2925
- : undefined;
3771
+ link = target();
2926
3772
  }
2927
3773
  if (!link)
2928
3774
  throw new HostError(
@@ -2930,7 +3776,7 @@ export async function resolveReference(
2930
3776
  );
2931
3777
  if (warm && header === warm.header && !header.localSourceReady)
2932
3778
  await lazyPrivateSource(context, selected, warm.account, header.config);
2933
- targetCid = link.toString();
3779
+ targetCid = link;
2934
3780
  } else {
2935
3781
  if (swarm) await readyMembership(context, swarm);
2936
3782
  targetCid = local(reference);
@@ -2991,7 +3837,7 @@ export async function pinNameSubscription(
2991
3837
  const canonical = withState(context, (state) =>
2992
3838
  pinReference(state, reference, selected),
2993
3839
  );
2994
- if (!canonical.swarm || !canonical.name) {
3840
+ if (!canonical.swarm || canonical.name === undefined) {
2995
3841
  let roots: string[];
2996
3842
  try {
2997
3843
  roots = [
@@ -3043,7 +3889,7 @@ async function withStateAsync<T>(
3043
3889
  export async function refreshNamePins(
3044
3890
  context: SwarmContext,
3045
3891
  url: string,
3046
- header: Pick<SwarmHeader, "snapshot">,
3892
+ header: Pick<SwarmHeader, "snapshot" | "stateCid">,
3047
3893
  ): Promise<void> {
3048
3894
  const pins = withState(context, (state) =>
3049
3895
  state
@@ -3052,9 +3898,12 @@ export async function refreshNamePins(
3052
3898
  );
3053
3899
  const failures: string[] = [];
3054
3900
  for (const saved of pins) {
3055
- const target = Object.hasOwn(header.snapshot.names, saved.name!)
3056
- ? header.snapshot.names[saved.name!]!.toString()
3057
- : undefined;
3901
+ const target =
3902
+ saved.name === ""
3903
+ ? header.stateCid
3904
+ : Object.hasOwn(header.snapshot.names, saved.name!)
3905
+ ? header.snapshot.names[saved.name!]!.toString()
3906
+ : undefined;
3058
3907
  if (!target) {
3059
3908
  withState(context, (state) => {
3060
3909
  failedPin(
@@ -3492,7 +4341,11 @@ export async function removeSwarmTemplate(
3492
4341
  let basis: string | undefined;
3493
4342
  for (let attempt = 0; attempt < 8; attempt++) {
3494
4343
  const currentHead = await head.read();
3495
- const current = await readSnapshot(context.store, currentHead.root);
4344
+ const current = await readSnapshot(
4345
+ context.store,
4346
+ currentHead.root,
4347
+ configUrl,
4348
+ );
3496
4349
  const meta = await swarmMeta(context, { snapshot: current });
3497
4350
  const name = formalName(`${meta.templatePath}/${selector}`);
3498
4351
  if (basis !== undefined && basis !== name)
@@ -3628,7 +4481,7 @@ async function prepareNamesPublication(
3628
4481
  ) {
3629
4482
  const next = await publication(
3630
4483
  context.store,
3631
- await writeSnapshot(context.store, { ...current, names }),
4484
+ await writeSnapshot(context.store, { ...current, names }, configUrl),
3632
4485
  previousRoot,
3633
4486
  );
3634
4487
  const closure = await publicationClosure(context.store, next, false);
@@ -3667,7 +4520,11 @@ async function editSwarmAssociation(
3667
4520
  : new Set<string>();
3668
4521
  for (let attempt = 0; attempt < 8; attempt++) {
3669
4522
  const currentHead = await head.read();
3670
- const current = await readSnapshot(context.store, currentHead.root);
4523
+ const current = await readSnapshot(
4524
+ context.store,
4525
+ currentHead.root,
4526
+ configUrl,
4527
+ );
3671
4528
  assertNamesRegistry(current);
3672
4529
  const meta = await swarmMeta(context, { snapshot: current });
3673
4530
  const name = formalName(`${meta.registryPath}/${schemaCid}`);
@@ -3886,7 +4743,11 @@ async function publishContent(
3886
4743
  roots.add(root);
3887
4744
  for (let attempt = 0; attempt < 8; attempt++) {
3888
4745
  const currentHead = await head.read(),
3889
- current = await readSnapshot(context.store, currentHead.root);
4746
+ current = await readSnapshot(
4747
+ context.store,
4748
+ currentHead.root,
4749
+ options.swarm,
4750
+ );
3890
4751
  if (nameForSnapshot) {
3891
4752
  name = await nameForSnapshot(current);
3892
4753
  if (resolvedName !== undefined && resolvedName !== name)