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

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 (285) hide show
  1. package/README.md +226 -9
  2. package/dist/app-authoring.d.ts +15 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +144 -58
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-definition.d.ts +52 -57
  7. package/dist/app-definition.d.ts.map +1 -1
  8. package/dist/app-definition.js +33 -38
  9. package/dist/app-definition.js.map +1 -1
  10. package/dist/app-prebuild.d.ts +18 -0
  11. package/dist/app-prebuild.d.ts.map +1 -1
  12. package/dist/app-prebuild.js +46 -0
  13. package/dist/app-prebuild.js.map +1 -1
  14. package/dist/app-templates.d.ts +0 -1
  15. package/dist/app-templates.d.ts.map +1 -1
  16. package/dist/app-templates.js +8 -46
  17. package/dist/app-templates.js.map +1 -1
  18. package/dist/assembly.d.ts +7 -0
  19. package/dist/assembly.d.ts.map +1 -0
  20. package/dist/assembly.js +130 -0
  21. package/dist/assembly.js.map +1 -0
  22. package/dist/authoring.d.ts +4 -8
  23. package/dist/authoring.d.ts.map +1 -1
  24. package/dist/authoring.js +25 -15
  25. package/dist/authoring.js.map +1 -1
  26. package/dist/builtins/skill.ipab.car +0 -0
  27. package/dist/builtins/template.bundle-viewer.car +0 -0
  28. package/dist/builtins/template.check.car +0 -0
  29. package/dist/builtins/template.node.car +0 -0
  30. package/dist/builtins/template.web-app.car +0 -0
  31. package/dist/builtins.d.ts.map +1 -1
  32. package/dist/builtins.js +1 -23
  33. package/dist/builtins.js.map +1 -1
  34. package/dist/bundled-skills.d.ts +14 -0
  35. package/dist/bundled-skills.d.ts.map +1 -0
  36. package/dist/bundled-skills.js +34 -0
  37. package/dist/bundled-skills.js.map +1 -0
  38. package/dist/cli.d.ts +8 -2
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +1919 -256
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config-secret.d.ts +3 -0
  43. package/dist/config-secret.d.ts.map +1 -0
  44. package/dist/config-secret.js +12 -0
  45. package/dist/config-secret.js.map +1 -0
  46. package/dist/config.d.ts +7 -2
  47. package/dist/config.d.ts.map +1 -1
  48. package/dist/config.js +151 -8
  49. package/dist/config.js.map +1 -1
  50. package/dist/content-provider.d.ts +32 -0
  51. package/dist/content-provider.d.ts.map +1 -0
  52. package/dist/content-provider.js +222 -0
  53. package/dist/content-provider.js.map +1 -0
  54. package/dist/context-types.d.ts +12 -0
  55. package/dist/context-types.d.ts.map +1 -0
  56. package/dist/context-types.js +2 -0
  57. package/dist/context-types.js.map +1 -0
  58. package/dist/context.d.ts +26 -1
  59. package/dist/context.d.ts.map +1 -1
  60. package/dist/context.js +54 -10
  61. package/dist/context.js.map +1 -1
  62. package/dist/daemon-ui.d.ts +93 -0
  63. package/dist/daemon-ui.d.ts.map +1 -0
  64. package/dist/daemon-ui.js +713 -0
  65. package/dist/daemon-ui.js.map +1 -0
  66. package/dist/daemon.d.ts +21 -0
  67. package/dist/daemon.d.ts.map +1 -0
  68. package/dist/daemon.js +317 -0
  69. package/dist/daemon.js.map +1 -0
  70. package/dist/doctor.d.ts +32 -0
  71. package/dist/doctor.d.ts.map +1 -0
  72. package/dist/doctor.js +684 -0
  73. package/dist/doctor.js.map +1 -0
  74. package/dist/errors.d.ts +1 -8
  75. package/dist/errors.d.ts.map +1 -1
  76. package/dist/errors.js +1 -20
  77. package/dist/errors.js.map +1 -1
  78. package/dist/get.d.ts +3 -0
  79. package/dist/get.d.ts.map +1 -0
  80. package/dist/get.js +80 -0
  81. package/dist/get.js.map +1 -0
  82. package/dist/history.d.ts.map +1 -1
  83. package/dist/history.js +6 -14
  84. package/dist/history.js.map +1 -1
  85. package/dist/host-error.d.ts +9 -0
  86. package/dist/host-error.d.ts.map +1 -0
  87. package/dist/host-error.js +21 -0
  88. package/dist/host-error.js.map +1 -0
  89. package/dist/identity.d.ts +16 -0
  90. package/dist/identity.d.ts.map +1 -0
  91. package/dist/identity.js +119 -0
  92. package/dist/identity.js.map +1 -0
  93. package/dist/ipc.d.ts +5 -2
  94. package/dist/ipc.d.ts.map +1 -1
  95. package/dist/ipc.js +124 -12
  96. package/dist/ipc.js.map +1 -1
  97. package/dist/kubo-install.d.ts +26 -0
  98. package/dist/kubo-install.d.ts.map +1 -0
  99. package/dist/kubo-install.js +724 -0
  100. package/dist/kubo-install.js.map +1 -0
  101. package/dist/kubo-peering.d.ts +11 -0
  102. package/dist/kubo-peering.d.ts.map +1 -0
  103. package/dist/kubo-peering.js +93 -0
  104. package/dist/kubo-peering.js.map +1 -0
  105. package/dist/kubo-peers.d.ts +12 -0
  106. package/dist/kubo-peers.d.ts.map +1 -0
  107. package/dist/kubo-peers.js +119 -0
  108. package/dist/kubo-peers.js.map +1 -0
  109. package/dist/kubo-release.d.ts +22 -0
  110. package/dist/kubo-release.d.ts.map +1 -0
  111. package/dist/kubo-release.js +176 -0
  112. package/dist/kubo-release.js.map +1 -0
  113. package/dist/kubo-topology.d.ts +19 -0
  114. package/dist/kubo-topology.d.ts.map +1 -0
  115. package/dist/kubo-topology.js +113 -0
  116. package/dist/kubo-topology.js.map +1 -0
  117. package/dist/kubo.d.ts +85 -0
  118. package/dist/kubo.d.ts.map +1 -0
  119. package/dist/kubo.js +755 -0
  120. package/dist/kubo.js.map +1 -0
  121. package/dist/pins.d.ts +16 -18
  122. package/dist/pins.d.ts.map +1 -1
  123. package/dist/pins.js +144 -106
  124. package/dist/pins.js.map +1 -1
  125. package/dist/pivot-rpc.d.ts +62 -0
  126. package/dist/pivot-rpc.d.ts.map +1 -0
  127. package/dist/pivot-rpc.js +407 -0
  128. package/dist/pivot-rpc.js.map +1 -0
  129. package/dist/pivot-service.d.ts +16 -0
  130. package/dist/pivot-service.d.ts.map +1 -0
  131. package/dist/pivot-service.js +50 -0
  132. package/dist/pivot-service.js.map +1 -0
  133. package/dist/publish-source.d.ts +3 -0
  134. package/dist/publish-source.d.ts.map +1 -0
  135. package/dist/publish-source.js +85 -0
  136. package/dist/publish-source.js.map +1 -0
  137. package/dist/runtime.d.ts +2 -0
  138. package/dist/runtime.d.ts.map +1 -1
  139. package/dist/runtime.js +9 -4
  140. package/dist/runtime.js.map +1 -1
  141. package/dist/search-index.d.ts +64 -0
  142. package/dist/search-index.d.ts.map +1 -0
  143. package/dist/search-index.js +409 -0
  144. package/dist/search-index.js.map +1 -0
  145. package/dist/search-service.d.ts +23 -0
  146. package/dist/search-service.d.ts.map +1 -0
  147. package/dist/search-service.js +116 -0
  148. package/dist/search-service.js.map +1 -0
  149. package/dist/skill-definition.d.ts +6 -0
  150. package/dist/skill-definition.d.ts.map +1 -0
  151. package/dist/skill-definition.js +38 -0
  152. package/dist/skill-definition.js.map +1 -0
  153. package/dist/skill-source.d.ts +9 -0
  154. package/dist/skill-source.d.ts.map +1 -0
  155. package/dist/skill-source.js +24 -0
  156. package/dist/skill-source.js.map +1 -0
  157. package/dist/skills.d.ts +104 -0
  158. package/dist/skills.d.ts.map +1 -0
  159. package/dist/skills.js +894 -0
  160. package/dist/skills.js.map +1 -0
  161. package/dist/source-bundle.d.ts +3 -8
  162. package/dist/source-bundle.d.ts.map +1 -1
  163. package/dist/source-bundle.js +17 -12
  164. package/dist/source-bundle.js.map +1 -1
  165. package/dist/space-path.d.ts +3 -0
  166. package/dist/space-path.d.ts.map +1 -0
  167. package/dist/space-path.js +17 -0
  168. package/dist/space-path.js.map +1 -0
  169. package/dist/space.d.ts +16 -4
  170. package/dist/space.d.ts.map +1 -1
  171. package/dist/space.js +170 -24
  172. package/dist/space.js.map +1 -1
  173. package/dist/state-storage-windows.d.ts +2 -0
  174. package/dist/state-storage-windows.d.ts.map +1 -0
  175. package/dist/state-storage-windows.js +114 -0
  176. package/dist/state-storage-windows.js.map +1 -0
  177. package/dist/state-storage.d.ts +5 -0
  178. package/dist/state-storage.d.ts.map +1 -0
  179. package/dist/state-storage.js +333 -0
  180. package/dist/state-storage.js.map +1 -0
  181. package/dist/state.d.ts +115 -13
  182. package/dist/state.d.ts.map +1 -1
  183. package/dist/state.js +492 -91
  184. package/dist/state.js.map +1 -1
  185. package/dist/swarm-envelope.d.ts +57 -0
  186. package/dist/swarm-envelope.d.ts.map +1 -0
  187. package/dist/swarm-envelope.js +299 -0
  188. package/dist/swarm-envelope.js.map +1 -0
  189. package/dist/swarm-files.d.ts +6 -0
  190. package/dist/swarm-files.d.ts.map +1 -0
  191. package/dist/swarm-files.js +116 -0
  192. package/dist/swarm-files.js.map +1 -0
  193. package/dist/swarm-meta.d.ts +15 -0
  194. package/dist/swarm-meta.d.ts.map +1 -0
  195. package/dist/swarm-meta.js +68 -0
  196. package/dist/swarm-meta.js.map +1 -0
  197. package/dist/swarm-observations.d.ts +40 -0
  198. package/dist/swarm-observations.d.ts.map +1 -0
  199. package/dist/swarm-observations.js +271 -0
  200. package/dist/swarm-observations.js.map +1 -0
  201. package/dist/swarm.d.ts +469 -0
  202. package/dist/swarm.d.ts.map +1 -0
  203. package/dist/swarm.js +4708 -0
  204. package/dist/swarm.js.map +1 -0
  205. package/dist/template-definition.d.ts +47 -52
  206. package/dist/template-definition.d.ts.map +1 -1
  207. package/dist/template-definition.js +36 -41
  208. package/dist/template-definition.js.map +1 -1
  209. package/dist/template-paths.d.ts +7 -0
  210. package/dist/template-paths.d.ts.map +1 -0
  211. package/dist/template-paths.js +23 -0
  212. package/dist/template-paths.js.map +1 -0
  213. package/dist/template-presentation.d.ts +20 -0
  214. package/dist/template-presentation.d.ts.map +1 -0
  215. package/dist/template-presentation.js +133 -0
  216. package/dist/template-presentation.js.map +1 -0
  217. package/dist/template-source.d.ts +4 -1
  218. package/dist/template-source.d.ts.map +1 -1
  219. package/dist/template-source.js +11 -4
  220. package/dist/template-source.js.map +1 -1
  221. package/dist/templates.d.ts +11 -0
  222. package/dist/templates.d.ts.map +1 -0
  223. package/dist/templates.js +53 -0
  224. package/dist/templates.js.map +1 -0
  225. package/dist/unixfs-tree.d.ts +67 -0
  226. package/dist/unixfs-tree.d.ts.map +1 -0
  227. package/dist/unixfs-tree.js +329 -0
  228. package/dist/unixfs-tree.js.map +1 -0
  229. package/package.json +14 -7
  230. package/src/app-authoring.ts +240 -76
  231. package/src/app-definition.ts +33 -39
  232. package/src/app-prebuild.ts +61 -0
  233. package/src/app-templates.ts +17 -73
  234. package/src/assembly.ts +185 -0
  235. package/src/authoring.ts +41 -17
  236. package/src/builtins.ts +2 -27
  237. package/src/bundled-skills.ts +60 -0
  238. package/src/cli.ts +2399 -320
  239. package/src/config-secret.ts +14 -0
  240. package/src/config.ts +196 -8
  241. package/src/content-provider.ts +299 -0
  242. package/src/context-types.ts +11 -0
  243. package/src/context.ts +98 -10
  244. package/src/daemon-ui.ts +812 -0
  245. package/src/daemon.ts +386 -0
  246. package/src/doctor.ts +1082 -0
  247. package/src/errors.ts +1 -25
  248. package/src/get.ts +90 -0
  249. package/src/history.ts +5 -15
  250. package/src/host-error.ts +26 -0
  251. package/src/identity.ts +175 -0
  252. package/src/ipc.ts +160 -11
  253. package/src/kubo-install.ts +936 -0
  254. package/src/kubo-peering.ts +126 -0
  255. package/src/kubo-peers.ts +144 -0
  256. package/src/kubo-release.ts +230 -0
  257. package/src/kubo-topology.ts +148 -0
  258. package/src/kubo.ts +1088 -0
  259. package/src/pins.ts +188 -126
  260. package/src/pivot-rpc.ts +601 -0
  261. package/src/pivot-service.ts +87 -0
  262. package/src/publish-source.ts +103 -0
  263. package/src/runtime.ts +16 -4
  264. package/src/search-index.ts +560 -0
  265. package/src/search-service.ts +152 -0
  266. package/src/skill-definition.ts +53 -0
  267. package/src/skill-source.ts +29 -0
  268. package/src/skills.ts +1236 -0
  269. package/src/source-bundle.ts +26 -13
  270. package/src/space-path.ts +30 -0
  271. package/src/space.ts +230 -42
  272. package/src/state-storage-windows.ts +134 -0
  273. package/src/state-storage.ts +378 -0
  274. package/src/state.ts +759 -107
  275. package/src/swarm-envelope.ts +461 -0
  276. package/src/swarm-files.ts +126 -0
  277. package/src/swarm-meta.ts +98 -0
  278. package/src/swarm-observations.ts +393 -0
  279. package/src/swarm.ts +7051 -0
  280. package/src/template-definition.ts +36 -41
  281. package/src/template-paths.ts +43 -0
  282. package/src/template-presentation.ts +151 -0
  283. package/src/template-source.ts +19 -5
  284. package/src/templates.ts +77 -0
  285. package/src/unixfs-tree.ts +401 -0
package/dist/doctor.js ADDED
@@ -0,0 +1,684 @@
1
+ import { lstat, mkdtemp, readdir, readFile, rm, writeFile, } from "node:fs/promises";
2
+ import { createHash } from "node:crypto";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { DatabaseSync } from "node:sqlite";
6
+ import { requireAccountOnlyMany } from "@ipab/bundle/pointer/protected-files";
7
+ import { RESOURCE_ID_PATTERN, ScopeClient } from "@ipab/bundle/pointer/scope";
8
+ import { nodeError } from "./authoring.js";
9
+ import { accountIdentity, protectedPath, secureNew } from "./identity.js";
10
+ import { effectiveConfig, swarmUrl, validateUserConfig, } from "./config.js";
11
+ import { swarmAlias } from "./state.js";
12
+ import { prepareStateStorage, verifyStateLocation, verifyStateStorage, } from "./state-storage.js";
13
+ import { inspectKubo, inspectKuboCache, kuboBinary, verifyExistingKuboArchive, recoverableInstallation, runningManagedNodes, } from "./kubo-install.js";
14
+ import { KUBO_RANGE, compareKuboVersions, latestKuboRelease, sameVersionKuboArchive, } from "./kubo-release.js";
15
+ import { HostError, message } from "./errors.js";
16
+ import { inspectBundledSkills, installBundledSkills, } from "./bundled-skills.js";
17
+ import { inspectLocalMembership } from "./swarm.js";
18
+ import { nodeRecord } from "./kubo.js";
19
+ import { readPrivate } from "./swarm-files.js";
20
+ import { KUBO_REPO_VERSION } from "./kubo-release.js";
21
+ async function authorize(options, actions) {
22
+ const text = `${actions.join("\n")}\nApply these safe repairs? Existing credentials/repos will not be replaced or migrated.`;
23
+ const signal = options.signal;
24
+ if (!signal)
25
+ return options.confirm(text);
26
+ signal.throwIfAborted();
27
+ let abort = () => { };
28
+ const cancelled = new Promise((_resolve, reject) => {
29
+ abort = () => {
30
+ reject(signal.reason instanceof Error
31
+ ? signal.reason
32
+ : new HostError("Doctor cancelled."));
33
+ };
34
+ signal.addEventListener("abort", abort, { once: true });
35
+ });
36
+ try {
37
+ return await Promise.race([options.confirm(text, signal), cancelled]);
38
+ }
39
+ finally {
40
+ signal.removeEventListener("abort", abort);
41
+ }
42
+ }
43
+ async function present(path) {
44
+ try {
45
+ await lstat(path);
46
+ return true;
47
+ }
48
+ catch (cause) {
49
+ if (nodeError(cause, "ENOENT"))
50
+ return false;
51
+ throw cause;
52
+ }
53
+ }
54
+ async function inspectRegistryResources(stateDir, account) {
55
+ const credentials = join(stateDir, "swarm-credentials");
56
+ const peers = new Map();
57
+ if (await present(credentials)) {
58
+ await protectedPath(credentials, true);
59
+ await requireAccountOnlyMany([credentials]);
60
+ for (const name of await readdir(credentials)) {
61
+ const file = join(credentials, name);
62
+ const publicationLock = /^state-pin-[a-f0-9]{64}$/.test(name);
63
+ await protectedPath(file, publicationLock);
64
+ await requireAccountOnlyMany([file]);
65
+ if (!/^[a-f0-9]{64}\.json$/.test(name))
66
+ continue;
67
+ const membership = await inspectLocalMembership(await readPrivate(credentials, name), account);
68
+ if (`${createHash("sha256").update(membership.configUrl).digest("hex")}.json` !==
69
+ name)
70
+ throw new Error("Membership filename mismatch.");
71
+ if (membership.peer) {
72
+ const previous = peers.get(membership.scope);
73
+ if (previous && previous !== membership.peer)
74
+ throw new Error("Conflicting node identity bindings.");
75
+ peers.set(membership.scope, membership.peer);
76
+ }
77
+ }
78
+ }
79
+ const nodes = join(stateDir, "swarm-nodes");
80
+ if (!(await present(nodes)))
81
+ return;
82
+ await protectedPath(nodes, true);
83
+ await requireAccountOnlyMany([nodes]);
84
+ for (const scope of await readdir(nodes)) {
85
+ if (!/^[a-f0-9]{64}$/.test(scope))
86
+ throw new Error("Invalid managed node scope.");
87
+ const directory = join(nodes, scope), repo = join(directory, "repo");
88
+ await protectedPath(directory, true);
89
+ await protectedPath(repo, true);
90
+ await requireAccountOnlyMany([
91
+ directory,
92
+ repo,
93
+ join(directory, "node.json"),
94
+ join(repo, "config"),
95
+ join(repo, "version"),
96
+ ]);
97
+ const node = nodeRecord(await readPrivate(directory, "node.json"), scope);
98
+ const config = await readPrivate(repo, "config");
99
+ if (config?.Identity?.PeerID !== node.peerId ||
100
+ (peers.has(scope) && peers.get(scope) !== node.peerId) ||
101
+ (await readFile(join(repo, "version"), "utf8")).trim() !==
102
+ KUBO_REPO_VERSION)
103
+ throw new Error("Managed node identity/repo mismatch.");
104
+ const key = join(repo, "swarm.key");
105
+ if (await present(key)) {
106
+ await requireAccountOnlyMany([key]);
107
+ if ((await lstat(key)).size > 128 ||
108
+ !/^\/key\/swarm\/psk\/1\.0\.0\/\n\/base16\/\n[a-f0-9]{64}\n$/.test(await readFile(key, "utf8")))
109
+ throw new Error("Invalid managed swarm key.");
110
+ }
111
+ else if (node.epoch !== undefined)
112
+ throw new Error("Managed node key is missing.");
113
+ }
114
+ }
115
+ function check(id, status, message, repairable = false, guidance = "") {
116
+ return {
117
+ id,
118
+ capability: id === "state" || id === "ipab-skill" ? "base" : "swarm",
119
+ required: id === "state",
120
+ status,
121
+ message,
122
+ repairable,
123
+ guidance,
124
+ };
125
+ }
126
+ function ready(report) {
127
+ return (!report.checks.some((item) => item.status === "invalid" ||
128
+ (item.status === "blocked" && item.id !== "kubo-update") ||
129
+ (item.required && item.status !== "ok")) && !report.repairs.some((item) => item.status === "failed"));
130
+ }
131
+ function publicObject(value) {
132
+ if (!value || typeof value !== "object" || Array.isArray(value))
133
+ throw new Error("Invalid public declaration.");
134
+ return value;
135
+ }
136
+ async function declaredPivot(configUrl, fetcher, signal) {
137
+ const url = new URL(configUrl);
138
+ const [, , scopeId, configId] = url.pathname.split("/");
139
+ const api = new ScopeClient({ service: url.origin, fetch: fetcher });
140
+ const options = { signal };
141
+ const config = publicObject((await api.read(scopeId, configId, options)).value);
142
+ const scope = await api.send("GET", scopeId, "", undefined, options);
143
+ if (typeof config.owner !== "string" ||
144
+ config.owner !== scope.owner ||
145
+ (config.v !== 1 && config.v !== 2 && config.v !== 3) ||
146
+ !Array.isArray(config.members) ||
147
+ config.members.length < 1 ||
148
+ config.members.length > 256)
149
+ throw new Error("Invalid public member directory.");
150
+ for (const entry of config.members) {
151
+ let member = publicObject(entry);
152
+ if (config.v === 3) {
153
+ const isOwner = member.publicKey === config.owner;
154
+ if (Object.keys(member).sort().join() !==
155
+ "approvalId,profileId,publicKey,role" ||
156
+ typeof member.publicKey !== "string" ||
157
+ (member.role !== "ordinary" && member.role !== "pivot") ||
158
+ typeof member.profileId !== "string" ||
159
+ !RESOURCE_ID_PATTERN.test(member.profileId) ||
160
+ (isOwner
161
+ ? member.approvalId !== null
162
+ : typeof member.approvalId !== "string" ||
163
+ !RESOURCE_ID_PATTERN.test(member.approvalId)))
164
+ throw new Error("Invalid public member binding.");
165
+ }
166
+ else if (config.v === 2) {
167
+ if (typeof member.memberId !== "string" ||
168
+ !RESOURCE_ID_PATTERN.test(member.memberId) ||
169
+ typeof member.publicKey !== "string")
170
+ throw new Error("Invalid public member binding.");
171
+ const record = publicObject((await api.read(scopeId, member.memberId, options)).value);
172
+ if (record.publicKey !== member.publicKey)
173
+ throw new Error("Public member identity mismatch.");
174
+ member = record;
175
+ }
176
+ if (typeof member.profileId !== "string" ||
177
+ !RESOURCE_ID_PATTERN.test(member.profileId))
178
+ throw new Error("Invalid public profile binding.");
179
+ const profile = publicObject((await api.read(scopeId, member.profileId, options)).value);
180
+ if (profile.pivot !== undefined && typeof profile.pivot !== "boolean")
181
+ throw new Error("Invalid Pivot declaration.");
182
+ if (config.v === 3
183
+ ? member.role === "pivot" && profile.pivot !== false
184
+ : profile.pivot === true)
185
+ return true;
186
+ }
187
+ return false;
188
+ }
189
+ async function inspectPivotMembers(swarms, options) {
190
+ if (!swarms.length)
191
+ return [];
192
+ const deadline = AbortSignal.timeout(5_000);
193
+ const signal = options.signal
194
+ ? AbortSignal.any([options.signal, deadline])
195
+ : deadline;
196
+ const checks = [];
197
+ for (const { url, name } of swarms) {
198
+ try {
199
+ const pivot = await declaredPivot(url, options.fetch ?? fetch, signal);
200
+ checks.push(check(`swarm-pivots:${url}`, pivot ? "ok" : "warning", pivot
201
+ ? `Swarm ${url} has an approved member declaring Pivot mode for durable published-content replication; availability was not checked.`
202
+ : `Swarm ${url} has no approved Pivot member. Published content may become unavailable when ordinary members are offline.`, false, pivot
203
+ ? ""
204
+ : `On an approved member intended to retain published Swarm content, explicitly declare Pivot mode with ipab --swarm ${name} swarm profile --pivot true, then run ipab daemon. Doctor does not enable Pivot mode or start a daemon.`));
205
+ }
206
+ catch {
207
+ options.signal?.throwIfAborted();
208
+ checks.push(check(`swarm-pivots:${url}`, "not-checked", `Pivot declarations for Swarm ${url} could not be checked; public lookup failed or exceeded the diagnostic budget. This does not mean there are no approved Pivot members or nodes.`, false, "Retry when the public Swarm configuration and member profiles are reachable. No local resources were initialized."));
209
+ }
210
+ }
211
+ return checks;
212
+ }
213
+ async function stateSnapshot(file, signal) {
214
+ const read = async () => {
215
+ if ((await present(`${file}-journal`)) &&
216
+ (await lstat(`${file}-journal`)).size > 0)
217
+ throw new HostError("A rollback transaction appeared during snapshot capture; preserve its journal and retry.", 1, "STATE_SNAPSHOT_BUSY");
218
+ for (const path of [file, `${file}-wal`]) {
219
+ if (!(await present(path)))
220
+ continue;
221
+ if ((await lstat(path)).size > 256 * 1024 * 1024)
222
+ throw new HostError("State exceeds the 256 MiB per-file diagnostic snapshot budget.", 1, "STATE_SNAPSHOT_BUSY");
223
+ }
224
+ const main = await readFile(file, { signal });
225
+ const wal = (await present(`${file}-wal`))
226
+ ? await readFile(`${file}-wal`, { signal })
227
+ : undefined;
228
+ return { main, wal };
229
+ };
230
+ for (let attempt = 0; attempt < 3; attempt++) {
231
+ signal?.throwIfAborted();
232
+ let first, second;
233
+ try {
234
+ first = await read();
235
+ second = await read();
236
+ }
237
+ catch (cause) {
238
+ if (nodeError(cause, "ENOENT"))
239
+ continue;
240
+ throw cause;
241
+ }
242
+ if (!first.main.equals(second.main) ||
243
+ (first.wal === undefined
244
+ ? second.wal !== undefined
245
+ : second.wal === undefined || !first.wal.equals(second.wal)))
246
+ continue;
247
+ const directory = await mkdtemp(join(tmpdir(), "ipab-doctor-state-"));
248
+ let db;
249
+ try {
250
+ await secureNew(directory, true);
251
+ const copy = join(directory, "state.sqlite");
252
+ await writeFile(copy, first.main, { mode: 0o600 });
253
+ if (first.wal)
254
+ await writeFile(`${copy}-wal`, first.wal, { mode: 0o600 });
255
+ // Only the disposable copy may create SHM or checkpoint committed WAL.
256
+ db = new DatabaseSync(copy);
257
+ if (db.prepare("PRAGMA quick_check").get()?.quick_check !== "ok")
258
+ throw new Error("Invalid database snapshot.");
259
+ const tables = db
260
+ .prepare("SELECT name FROM sqlite_master WHERE type='table'")
261
+ .all();
262
+ if (!tables.some((row) => row.name === "config") ||
263
+ !tables.some((row) => row.name === "swarms"))
264
+ throw new Error("Invalid state schema.");
265
+ return {
266
+ config: db.prepare("SELECT key,value FROM config").all(),
267
+ swarms: db.prepare("SELECT cid,alias FROM swarms").all(),
268
+ };
269
+ }
270
+ finally {
271
+ try {
272
+ db?.close();
273
+ }
274
+ finally {
275
+ await rm(directory, { recursive: true, force: true });
276
+ }
277
+ }
278
+ }
279
+ throw new HostError("State changed during snapshot capture; retry when writes have settled.", 1, "STATE_SNAPSHOT_BUSY");
280
+ }
281
+ async function inspect(stateDir, env, options, verificationFact) {
282
+ const checks = [];
283
+ const report = { ready: false, checks, repairs: [] };
284
+ let registry;
285
+ let user = {};
286
+ try {
287
+ verifyStateLocation(stateDir, env);
288
+ if (!(await present(stateDir))) {
289
+ checks.push(check("state", "missing", "Local state directory is missing.", true, "Run ipab doctor --fix."));
290
+ }
291
+ else {
292
+ verifyStateStorage(stateDir, env);
293
+ const file = join(stateDir, "state.sqlite");
294
+ // An active rollback transaction cannot be safely recovered from a copy.
295
+ if ((await present(`${file}-journal`)) &&
296
+ (await lstat(`${file}-journal`)).size > 0) {
297
+ checks.push(check("state", "blocked", "State has a nonempty rollback journal; its transaction state cannot be safely verified.", false, "A journal alone does not prove another process is running. Preserve the sidecars and recover the database through normal SQLite operations before retrying."));
298
+ }
299
+ else {
300
+ if ((await lstat(file)).size > 0) {
301
+ const snapshot = await stateSnapshot(file, options.signal);
302
+ registry = snapshot.swarms;
303
+ const raw = Object.fromEntries(snapshot.config.map((row) => {
304
+ if (typeof row.key !== "string" || typeof row.value !== "string")
305
+ throw new Error("Invalid configuration.");
306
+ return [row.key, JSON.parse(row.value)];
307
+ }));
308
+ user = validateUserConfig(raw);
309
+ }
310
+ effectiveConfig(user, { json: false, stateDir }, env);
311
+ checks.push(check("state", "ok", "Local state and configuration are valid."));
312
+ }
313
+ }
314
+ }
315
+ catch (cause) {
316
+ options.signal?.throwIfAborted();
317
+ checks.push(check("state", cause instanceof HostError && cause.code === "STATE_SNAPSHOT_BUSY"
318
+ ? "blocked"
319
+ : "invalid", cause instanceof HostError && cause.code === "STATE_SNAPSHOT_BUSY"
320
+ ? cause.message
321
+ : "Local state or configuration is invalid or unprotected.", false, "Back up and inspect the existing state/configuration; no permissions or data were changed."));
322
+ }
323
+ let release;
324
+ if (!options.release)
325
+ options.diagnostic?.("Checking official compatible Kubo release metadata...");
326
+ try {
327
+ release = options.release ?? (await latestKuboRelease(options.signal));
328
+ }
329
+ catch {
330
+ options.signal?.throwIfAborted();
331
+ options.diagnostic?.("Could not check Kubo updates; no claim about the latest compatible release.");
332
+ }
333
+ let installed;
334
+ let verification;
335
+ let cacheInvalid = false;
336
+ try {
337
+ installed = await inspectKubo(stateDir, release, options.signal);
338
+ if (installed?.provenance === false) {
339
+ try {
340
+ verification =
341
+ verificationFact?.version === installed.version
342
+ ? verificationFact
343
+ : await sameVersionKuboArchive(installed.version, release, options.signal);
344
+ }
345
+ catch {
346
+ options.signal?.throwIfAborted();
347
+ options.diagnostic?.("Trusted same-version archive metadata is unavailable; no verification archive was downloaded.");
348
+ }
349
+ if (verification && (await inspectKuboCache(stateDir, verification)))
350
+ installed = await inspectKubo(stateDir, release, options.signal, verification);
351
+ }
352
+ checks.push(installed
353
+ ? installed.provenance === false
354
+ ? check("kubo", "not-checked", `Managed Kubo ${installed.version} matches its protected receipt, but official archive provenance is unverified.`, Boolean(verification), verification
355
+ ? `Run ipab doctor --fix to download/cache the official ${installed.version} archive for verification only, without reinstall or node stopping.`
356
+ : "Trusted same-version official metadata/digest is unavailable; verification and dependent repairs remain blocked. No archive was downloaded.")
357
+ : check("kubo", "ok", `Managed Kubo ${installed.version} is verified.`)
358
+ : check("kubo", "missing", "Managed Kubo is missing (optional Swarm component).", true, "Run ipab doctor --fix."));
359
+ }
360
+ catch (cause) {
361
+ verification = undefined;
362
+ let recoverable = false;
363
+ try {
364
+ recoverable = await recoverableInstallation(stateDir);
365
+ }
366
+ catch {
367
+ /* Unsafe or unrecognized journals remain manual-only. */
368
+ }
369
+ checks.push(recoverable
370
+ ? check("kubo", "blocked", "Managed Kubo has a verified recoverable installation journal.", true, "Run ipab doctor --fix to recover only the journaled installation.")
371
+ : cause instanceof HostError && cause.code === "KUBO_CACHE_INVALID"
372
+ ? check("kubo", "invalid", cause.message, false, "Restore the vetted protected archive cache; it was not overwritten or redownloaded.")
373
+ : check("kubo", "invalid", "Existing managed Kubo is invalid, unprotected or interrupted.", false, "Inspect the protected installation and journal manually; damaged installations are never replaced."));
374
+ }
375
+ if (release &&
376
+ (!installed ||
377
+ compareKuboVersions(release.version, installed.version) > 0) &&
378
+ checks[0]?.status === "ok") {
379
+ try {
380
+ await inspectKuboCache(stateDir, release);
381
+ }
382
+ catch {
383
+ cacheInvalid = true;
384
+ if (!installed &&
385
+ checks.find((item) => item.id === "kubo")?.status === "missing") {
386
+ const item = checks.find((item) => item.id === "kubo");
387
+ item.status = "blocked";
388
+ item.repairable = false;
389
+ item.message =
390
+ "Managed Kubo is unavailable and the target official archive cache is invalid or unprotected.";
391
+ item.guidance =
392
+ "Inspect the archive cache manually. It was not deleted, adopted or redownloaded.";
393
+ }
394
+ }
395
+ }
396
+ const home = resolve(env.HOME ?? env.USERPROFILE ?? homedir());
397
+ const parent = join(home, ".ipab"), identity = join(parent, "identity");
398
+ let account;
399
+ try {
400
+ if (!(await present(identity))) {
401
+ if (await present(parent)) {
402
+ await protectedPath(parent, true);
403
+ await requireAccountOnlyMany([parent]);
404
+ }
405
+ if (!(await present(home)))
406
+ throw new Error("HOME missing.");
407
+ await protectedPath(home, true);
408
+ checks.push(check("identity", "missing", "HOME account identity is missing (optional Swarm component).", true, "Run ipab doctor --fix."));
409
+ }
410
+ else {
411
+ account = (await accountIdentity(env, false, true)).publicKey;
412
+ checks.push(check("identity", "ok", "HOME identity is consistent and protected."));
413
+ }
414
+ }
415
+ catch {
416
+ checks.push(check("identity", "invalid", "Existing HOME identity or its parent path is invalid or unprotected.", false, "Restore the existing protected key file; do not create a replacement."));
417
+ }
418
+ let pivotSwarms;
419
+ try {
420
+ const urls = new Set(), aliases = new Set();
421
+ if (registry) {
422
+ for (const row of registry) {
423
+ if (typeof row.cid !== "string" ||
424
+ (row.alias !== null && typeof row.alias !== "string"))
425
+ throw new Error("Invalid registry.");
426
+ const url = swarmUrl(row.cid);
427
+ if (url !== row.cid || urls.has(url))
428
+ throw new Error("Invalid registry.");
429
+ urls.add(url);
430
+ if (row.alias !== null) {
431
+ swarmAlias(row.alias);
432
+ if (aliases.has(row.alias))
433
+ throw new Error("Duplicate alias.");
434
+ aliases.add(row.alias);
435
+ }
436
+ }
437
+ if (typeof user["swarm.default"] === "string" &&
438
+ !urls.has(user["swarm.default"]))
439
+ throw new Error("Unregistered default.");
440
+ if (checks[0]?.status === "ok")
441
+ pivotSwarms = registry.map((row) => ({
442
+ url: row.cid,
443
+ name: (row.alias ?? row.cid),
444
+ }));
445
+ }
446
+ if (checks[0]?.status === "ok")
447
+ await inspectRegistryResources(stateDir, account);
448
+ if (registry) {
449
+ checks.push(check("swarm-registry", urls.size ? "ok" : "missing", urls.size
450
+ ? "Local Swarm registry is consistent."
451
+ : "No Swarms are registered (optional).", false, urls.size
452
+ ? ""
453
+ : "Use ipab swarm create or ipab swarm request to prepare sharing."));
454
+ }
455
+ else
456
+ checks.push(check("swarm-registry", checks[0]?.status === "missing" || checks[0]?.status === "ok"
457
+ ? "missing"
458
+ : "not-checked", "Local Swarm registry is absent or cannot be checked.", false, "Resolve local state issues first; no registry was created."));
459
+ }
460
+ catch {
461
+ checks.push(check("swarm-registry", "invalid", "Existing local Swarm registry is inconsistent.", false, "Inspect the saved URLs, aliases and default; no registrations were removed."));
462
+ }
463
+ if (pivotSwarms)
464
+ checks.push(...(await inspectPivotMembers(pivotSwarms, options)));
465
+ if (!release)
466
+ checks.push(check("kubo-update", "not-checked", `Compatible Kubo updates (${KUBO_RANGE}) were not checked.`, false, "Retry when official release metadata is available."));
467
+ else if (installed &&
468
+ compareKuboVersions(release.version, installed.version) > 0) {
469
+ try {
470
+ if (installed.provenance === false && !verification)
471
+ checks.push(check("kubo-update", "blocked", "A compatible Kubo update exists, but the existing installation's official provenance is unverified.", false, "Restore a vetted official archive cache before authorizing an upgrade; the existing installation was retained."));
472
+ else if (cacheInvalid)
473
+ checks.push(check("kubo-update", "blocked", "The target official Kubo archive cache is invalid or unprotected; upgrade is blocked.", false, "Inspect the cache manually; it was not deleted or redownloaded."));
474
+ else if (await runningManagedNodes(stateDir))
475
+ checks.push(check("kubo-update", "blocked", `Kubo ${installed.version} → ${release.version} is blocked by running or uncertain managed nodes.`, false, "Stop your managed nodes explicitly before upgrading; doctor never stops or contacts daemons."));
476
+ else
477
+ checks.push(check("kubo-update", "update-available", `Managed Kubo ${installed.version}; latest compatible stable ${release.version} (${KUBO_RANGE})${installed.provenance === false ? "; upgrade depends on successful same-version archive verification" : ""}.`, true, "Run ipab doctor --fix to authorize the upgrade."));
478
+ }
479
+ catch {
480
+ checks.push(check("kubo-update", "blocked", "Managed node state cannot be verified for a safe upgrade.", false, "Inspect local managed node records; no daemon was contacted."));
481
+ }
482
+ }
483
+ else if (installed?.provenance === false)
484
+ checks.push(check("kubo-update", "not-checked", `Latest verified compatible stable Kubo is ${release.version} (${KUBO_RANGE}); installed receipt version ${installed.version} has unverified provenance, so its update state is unconfirmed.`, false, "Restore vetted archive provenance before confirming the installed version or authorizing an upgrade."));
485
+ else
486
+ checks.push(check("kubo-update", "ok", `Latest verified compatible stable Kubo is ${release.version} (${KUBO_RANGE}); installed ${installed?.version ?? "none"}.`));
487
+ try {
488
+ const skill = await inspectBundledSkills(options.skillsPort);
489
+ checks.push(check("ipab-skill", skill.status, skill.message, skill.repairable, skill.guidance));
490
+ }
491
+ catch (cause) {
492
+ options.signal?.throwIfAborted();
493
+ checks.push(check("ipab-skill", "invalid", `Could not inspect bundled IPAB Skill: ${message(cause)}`, false, "Inspect Agent directories and the protected Skills ledger; no Skill files were changed."));
494
+ }
495
+ report.ready = ready(report);
496
+ options.signal?.throwIfAborted();
497
+ return {
498
+ report,
499
+ ...(release ? { release } : {}),
500
+ ...(verification ? { verification } : {}),
501
+ };
502
+ }
503
+ export async function doctorDevice(stateDir, env, options) {
504
+ options.signal?.throwIfAborted();
505
+ const initial = await inspect(stateDir, env, options);
506
+ let report = initial.report;
507
+ const release = initial.release;
508
+ const verification = initial.verification;
509
+ if (!options.fix)
510
+ return report;
511
+ const state = report.checks.find((item) => item.id === "state");
512
+ const kubo = report.checks.find((item) => item.id === "kubo");
513
+ const unverifiedInstall = kubo.repairable && !verification && !release;
514
+ if (unverifiedInstall) {
515
+ options.diagnostic?.("Kubo repair is blocked: no verified latest compatible target. Retry doctor when official metadata is available.");
516
+ kubo.status = "blocked";
517
+ kubo.repairable = false;
518
+ kubo.message =
519
+ "Managed Kubo repair is blocked because the latest compatible official target is unverified.";
520
+ kubo.guidance =
521
+ "Retry when official release metadata is available; no installation was attempted.";
522
+ }
523
+ const blockedRepairs = [];
524
+ const update = report.checks.find((item) => item.id === "kubo-update");
525
+ if (update.status === "blocked") {
526
+ blockedRepairs.push({
527
+ id: "kubo-update",
528
+ action: `Upgrade managed Kubo blocked: ${update.message}`,
529
+ status: "skipped",
530
+ });
531
+ options.diagnostic?.(`Repair blocked: ${update.message}`);
532
+ }
533
+ const identity = report.checks.find((item) => item.id === "identity");
534
+ const blockedIdentity = identity.status === "missing" &&
535
+ kubo.status === "not-checked" &&
536
+ !verification;
537
+ if (blockedIdentity) {
538
+ identity.status = "blocked";
539
+ identity.repairable = false;
540
+ identity.message =
541
+ "Missing HOME identity repair is blocked by unverified managed Kubo provenance.";
542
+ identity.guidance =
543
+ "Restore verified Kubo provenance before creating the dependent identity; no identity was created.";
544
+ blockedRepairs.push({
545
+ id: "identity",
546
+ action: identity.message,
547
+ status: "skipped",
548
+ });
549
+ options.diagnostic?.(`Repair blocked: ${identity.message}`);
550
+ }
551
+ const actions = report.checks
552
+ .filter((item) => item.repairable)
553
+ .filter((item) => (item.id === "state" || state.status === "ok" || state.repairable) &&
554
+ (item.id !== "kubo" || verification || release) &&
555
+ (item.id !== "identity" ||
556
+ kubo.status === "ok" ||
557
+ (kubo.repairable && (verification || release))))
558
+ .map((item) => ({
559
+ id: item.id,
560
+ action: item.id === "kubo-update"
561
+ ? `Upgrade managed Kubo to ${release.version}`
562
+ : item.id === "kubo"
563
+ ? kubo.status === "not-checked" && verification
564
+ ? `Download/cache the official Kubo ${verification.version} archive to verify the existing executable (no reinstall or node stopping)`
565
+ : `${kubo.status === "blocked" ? "Recover journaled installation using verified managed Kubo" : "Install verified managed Kubo"} ${release.version}`
566
+ : item.id === "identity"
567
+ ? "Create missing protected HOME account identity"
568
+ : item.id === "ipab-skill"
569
+ ? `Install/update bundled IPAB Skill: ${item.message}`
570
+ : "Create missing protected local state",
571
+ }));
572
+ if (!actions.length) {
573
+ report.repairs = blockedRepairs;
574
+ if (unverifiedInstall || blockedRepairs.length)
575
+ report.ready = false;
576
+ return report;
577
+ }
578
+ for (const item of actions)
579
+ options.diagnostic?.(`Planned repair: ${item.action}.`);
580
+ if (!options.yes &&
581
+ (!options.tty ||
582
+ !(await authorize(options, actions.map((item) => item.action))))) {
583
+ options.diagnostic?.("Repairs were not authorized; use ipab doctor --fix --yes outside an interactive terminal.");
584
+ report.repairs = [
585
+ ...blockedRepairs,
586
+ ...actions.map((item) => ({ ...item, status: "skipped" })),
587
+ ];
588
+ report.ready = false;
589
+ return report;
590
+ }
591
+ const repairs = [];
592
+ let installationFailed = false;
593
+ for (const action of actions) {
594
+ options.signal?.throwIfAborted();
595
+ if ((action.id === "identity" || action.id === "kubo-update") &&
596
+ installationFailed) {
597
+ repairs.push({ ...action, status: "skipped" });
598
+ continue;
599
+ }
600
+ try {
601
+ // Inspect again immediately before each action; concurrent actors may
602
+ // have filled a missing resource or made its path unsafe.
603
+ const current = await inspect(stateDir, env, {
604
+ ...options,
605
+ ...(release ? { release } : {}),
606
+ }, verification);
607
+ const item = current.report.checks.find((item) => item.id === action.id);
608
+ if (item.status === "ok") {
609
+ repairs.push({ ...action, status: "skipped" });
610
+ continue;
611
+ }
612
+ if (!item.repairable)
613
+ throw new Error("Repair is no longer safe.");
614
+ if (action.id !== "state" &&
615
+ current.report.checks.find((item) => item.id === "state")?.status !==
616
+ "ok")
617
+ throw new Error("State dependency is invalid.");
618
+ if (action.id === "state")
619
+ prepareStateStorage(stateDir, env);
620
+ else if (action.id === "identity") {
621
+ if (current.report.checks.find((item) => item.id === "kubo")?.status !==
622
+ "ok")
623
+ throw new Error("Kubo dependency is unavailable.");
624
+ await accountIdentity(env, true, true);
625
+ }
626
+ else if (action.id === "ipab-skill") {
627
+ await installBundledSkills(env, (text) => options.diagnostic?.(text), options.skillsPort);
628
+ }
629
+ else if (action.id === "kubo" && verification)
630
+ await verifyExistingKuboArchive(stateDir, verification, {
631
+ ...options,
632
+ ...(release ? { release } : {}),
633
+ });
634
+ else
635
+ await kuboBinary(stateDir, {
636
+ ...options,
637
+ ...(release ? { release } : {}),
638
+ upgrade: action.id === "kubo-update",
639
+ });
640
+ repairs.push({ ...action, status: "completed" });
641
+ }
642
+ catch (cause) {
643
+ options.signal?.throwIfAborted();
644
+ options.diagnostic?.(`Repair failed: ${action.action}. ${message(cause)} Existing resources were not replaced; inspect the protected installation/cache and retry.`);
645
+ repairs.push({ ...action, status: "failed" });
646
+ if (action.id === "kubo" || action.id === "kubo-update")
647
+ installationFailed = true;
648
+ }
649
+ }
650
+ ({ report } = await inspect(stateDir, env, {
651
+ ...options,
652
+ ...(release ? { release } : {}),
653
+ }, verification));
654
+ report.repairs = [...blockedRepairs, ...repairs];
655
+ if (unverifiedInstall) {
656
+ const item = report.checks.find((item) => item.id === "kubo");
657
+ item.status = kubo.status;
658
+ item.repairable = false;
659
+ item.message = kubo.message;
660
+ item.guidance = kubo.guidance;
661
+ }
662
+ if (blockedIdentity) {
663
+ const item = report.checks.find((item) => item.id === "identity");
664
+ if (item.status === "missing")
665
+ Object.assign(item, identity);
666
+ }
667
+ report.ready =
668
+ ready(report) &&
669
+ !unverifiedInstall &&
670
+ blockedRepairs.length === 0 &&
671
+ !report.checks.some((item) => item.id === "kubo-update" && item.status === "blocked");
672
+ options.signal?.throwIfAborted();
673
+ return report;
674
+ }
675
+ export function doctorText(report) {
676
+ return [
677
+ ...report.checks.map((item) => `${item.status.toUpperCase().padEnd(17)} ${item.message}${item.guidance ? `\n ${item.guidance}` : ""}`),
678
+ ...report.repairs.map((item) => `${item.status.toUpperCase()} ${item.action}`),
679
+ report.ready
680
+ ? "Local operations are ready. Optional Swarm readiness is shown above."
681
+ : "Not ready; resolve the reported issues.",
682
+ ].join("\n");
683
+ }
684
+ //# sourceMappingURL=doctor.js.map