@ipab/cli 0.1.0-rc.4 → 0.1.0-rc.6

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 (128) hide show
  1. package/README.md +88 -16
  2. package/dist/app-templates.js +1 -1
  3. package/dist/app-templates.js.map +1 -1
  4. package/dist/builtins/skill.ipab.car +0 -0
  5. package/dist/builtins/template.node.car +0 -0
  6. package/dist/builtins/template.web-app.car +0 -0
  7. package/dist/cli.d.ts +6 -2
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +656 -278
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config-secret.d.ts +1 -1
  12. package/dist/config-secret.d.ts.map +1 -1
  13. package/dist/config-secret.js +2 -73
  14. package/dist/config-secret.js.map +1 -1
  15. package/dist/config.d.ts +1 -0
  16. package/dist/config.d.ts.map +1 -1
  17. package/dist/config.js +12 -1
  18. package/dist/config.js.map +1 -1
  19. package/dist/content-provider.d.ts +1 -1
  20. package/dist/content-provider.d.ts.map +1 -1
  21. package/dist/content-provider.js +4 -3
  22. package/dist/content-provider.js.map +1 -1
  23. package/dist/context-types.d.ts +12 -0
  24. package/dist/context-types.d.ts.map +1 -0
  25. package/dist/context-types.js +2 -0
  26. package/dist/context-types.js.map +1 -0
  27. package/dist/context.d.ts +6 -1
  28. package/dist/context.d.ts.map +1 -1
  29. package/dist/context.js +24 -9
  30. package/dist/context.js.map +1 -1
  31. package/dist/doctor.d.ts +29 -0
  32. package/dist/doctor.d.ts.map +1 -0
  33. package/dist/doctor.js +576 -0
  34. package/dist/doctor.js.map +1 -0
  35. package/dist/identity.d.ts +1 -1
  36. package/dist/identity.d.ts.map +1 -1
  37. package/dist/identity.js +9 -9
  38. package/dist/identity.js.map +1 -1
  39. package/dist/ipc.d.ts +3 -2
  40. package/dist/ipc.d.ts.map +1 -1
  41. package/dist/ipc.js +33 -9
  42. package/dist/ipc.js.map +1 -1
  43. package/dist/kubo-install.d.ts +26 -0
  44. package/dist/kubo-install.d.ts.map +1 -0
  45. package/dist/kubo-install.js +724 -0
  46. package/dist/kubo-install.js.map +1 -0
  47. package/dist/kubo-peering.d.ts +11 -0
  48. package/dist/kubo-peering.d.ts.map +1 -0
  49. package/dist/kubo-peering.js +93 -0
  50. package/dist/kubo-peering.js.map +1 -0
  51. package/dist/kubo-peers.d.ts +12 -0
  52. package/dist/kubo-peers.d.ts.map +1 -0
  53. package/dist/kubo-peers.js +118 -0
  54. package/dist/kubo-peers.js.map +1 -0
  55. package/dist/kubo-release.d.ts +22 -0
  56. package/dist/kubo-release.d.ts.map +1 -0
  57. package/dist/kubo-release.js +176 -0
  58. package/dist/kubo-release.js.map +1 -0
  59. package/dist/kubo.d.ts +12 -4
  60. package/dist/kubo.d.ts.map +1 -1
  61. package/dist/kubo.js +218 -259
  62. package/dist/kubo.js.map +1 -1
  63. package/dist/pins.d.ts +15 -17
  64. package/dist/pins.d.ts.map +1 -1
  65. package/dist/pins.js +144 -106
  66. package/dist/pins.js.map +1 -1
  67. package/dist/publish-source.d.ts +3 -0
  68. package/dist/publish-source.d.ts.map +1 -0
  69. package/dist/publish-source.js +85 -0
  70. package/dist/publish-source.js.map +1 -0
  71. package/dist/runtime.d.ts +2 -0
  72. package/dist/runtime.d.ts.map +1 -1
  73. package/dist/runtime.js +4 -2
  74. package/dist/runtime.js.map +1 -1
  75. package/dist/state-storage-windows.d.ts +2 -0
  76. package/dist/state-storage-windows.d.ts.map +1 -0
  77. package/dist/state-storage-windows.js +114 -0
  78. package/dist/state-storage-windows.js.map +1 -0
  79. package/dist/state-storage.d.ts +5 -0
  80. package/dist/state-storage.d.ts.map +1 -0
  81. package/dist/state-storage.js +330 -0
  82. package/dist/state-storage.js.map +1 -0
  83. package/dist/state.d.ts +42 -8
  84. package/dist/state.d.ts.map +1 -1
  85. package/dist/state.js +254 -98
  86. package/dist/state.js.map +1 -1
  87. package/dist/swarm-envelope.d.ts +1 -0
  88. package/dist/swarm-envelope.d.ts.map +1 -1
  89. package/dist/swarm-envelope.js +12 -0
  90. package/dist/swarm-envelope.js.map +1 -1
  91. package/dist/swarm-files.d.ts +1 -1
  92. package/dist/swarm-files.d.ts.map +1 -1
  93. package/dist/swarm-files.js +4 -1
  94. package/dist/swarm-files.js.map +1 -1
  95. package/dist/swarm.d.ts +70 -11
  96. package/dist/swarm.d.ts.map +1 -1
  97. package/dist/swarm.js +1033 -167
  98. package/dist/swarm.js.map +1 -1
  99. package/package.json +4 -4
  100. package/src/app-templates.ts +1 -1
  101. package/src/cli.ts +827 -356
  102. package/src/config-secret.ts +2 -84
  103. package/src/config.ts +14 -1
  104. package/src/content-provider.ts +4 -2
  105. package/src/context-types.ts +11 -0
  106. package/src/context.ts +39 -9
  107. package/src/doctor.ts +902 -0
  108. package/src/identity.ts +10 -10
  109. package/src/ipc.ts +49 -8
  110. package/src/kubo-install.ts +936 -0
  111. package/src/kubo-peering.ts +126 -0
  112. package/src/kubo-peers.ts +145 -0
  113. package/src/kubo-release.ts +230 -0
  114. package/src/kubo.ts +302 -336
  115. package/src/pins.ts +188 -126
  116. package/src/publish-source.ts +103 -0
  117. package/src/runtime.ts +10 -2
  118. package/src/state-storage-windows.ts +134 -0
  119. package/src/state-storage.ts +375 -0
  120. package/src/state.ts +410 -118
  121. package/src/swarm-envelope.ts +14 -0
  122. package/src/swarm-files.ts +4 -0
  123. package/src/swarm.ts +1482 -207
  124. package/dist/setup.d.ts +0 -7
  125. package/dist/setup.d.ts.map +0 -1
  126. package/dist/setup.js +0 -22
  127. package/dist/setup.js.map +0 -1
  128. package/src/setup.ts +0 -21
package/dist/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  import { readFile } from "node:fs/promises";
3
- import { IpfsStore } from "@ipab/ipfs-store";
3
+ import { ContentError, IpfsStore } from "@ipab/ipfs-store";
4
+ import { ContentBundleError } from "@ipab/bundle";
4
5
  import { randomUUID } from "node:crypto";
5
6
  import { CID } from "multiformats/cid";
6
7
  import stringWidth from "string-width";
@@ -9,43 +10,58 @@ import { HostError, message, object, syntax } from "./errors.js";
9
10
  import { filters, listHistory, selectedIds, Ownership, recoverInactive, removeHistory, } from "./history.js";
10
11
  import { execute } from "./runtime.js";
11
12
  import { validatedBundle } from "./space.js";
12
- import { exactCid, pinName, State } from "./state.js";
13
+ import { createAssociation, exactCid, State, } from "./state.js";
13
14
  import { buildBundle, inspectBundle, importBundle } from "./authoring.js";
14
15
  import { initApp } from "./app-authoring.js";
15
16
  import { assembleBundle } from "./assembly.js";
16
17
  import { getBundle } from "./get.js";
17
- import { setupDevice } from "./setup.js";
18
+ import { doctorDevice, doctorText } from "./doctor.js";
18
19
  import { keyId } from "@ipab/bundle/pointer/crypto";
19
- import { createSwarm, requestMembership, approveMembership, exportRequest, removeMember, resumeRemoval, updateProfile, verifiedRequest, membershipRequestSummary, swarmHeader, sharedSwarmStatus, addSwarm, updateSwarm, searchNames, resolveReference, publish, } from "./swarm.js";
20
+ import { createSwarm, requestMembership, approveMembership, exportRequest, removeMember, resumeRemoval, updateProfile, accountProfile, updateAccountProfile, swarmMembers, verifiedRequest, verifiedRequestStream, membershipRequestSummary, swarmHeader, sharedSwarmStatus, addSwarm, updateSwarm, searchNames, formatNameReference, resolveReference, parseNameReference, formalName, publish, pinNameSubscription, pinReference, swarmRegistrations, swarmAssociation, setSwarmAssociation, removeSwarmAssociation, } from "./swarm.js";
20
21
  import { schemaAlias } from "./app-definition.js";
21
- import { addPin, deletePin, pinDetails, renamePin } from "./pins.js";
22
+ import { unpin, pinDetails } from "./pins.js";
23
+ import { publicationSource } from "./publish-source.js";
22
24
  import { logFiles } from "./logs.js";
23
25
  import { builtinContent } from "./builtins.js";
24
26
  import { readSecretStream } from "./config-secret.js";
27
+ let progressLine = false;
25
28
  export const processIO = {
26
29
  out(text) {
27
30
  process.stdout.write(`${text}\n`);
28
31
  },
29
- err(text) {
30
- process.stderr.write(`${text}\n`);
32
+ err(text, progress = false) {
33
+ if (progress && process.stderr.isTTY) {
34
+ const width = (process.stderr.columns > 1 ? process.stderr.columns : 80) - 1;
35
+ process.stderr.write(`\r\x1b[2K${text.slice(0, width)}`);
36
+ progressLine = true;
37
+ }
38
+ else {
39
+ process.stderr.write(`${progressLine ? "\n" : ""}${text}\n`);
40
+ progressLine = false;
41
+ }
31
42
  },
32
43
  tty: Boolean(process.stdin.isTTY && process.stderr.isTTY),
33
44
  columns() {
34
45
  return process.stdout.columns;
35
46
  },
47
+ requestInput() {
48
+ if (process.stdin.isTTY)
49
+ syntax("Pipe Request JSON into swarm approve - --yes, or pass a Request file.");
50
+ return process.stdin;
51
+ },
36
52
  async readSecret() {
37
53
  if (process.stdin.isTTY)
38
54
  syntax("Pipe the API key through stdin; interactive echo is not permitted.");
39
55
  process.stdin.setEncoding("utf8");
40
56
  return readSecretStream(process.stdin);
41
57
  },
42
- async confirm(text) {
58
+ async confirm(text, signal) {
43
59
  const reader = createInterface({
44
60
  input: process.stdin,
45
61
  output: process.stderr,
46
62
  });
47
63
  try {
48
- return /^(y|yes)$/i.test((await reader.question(`${text} [y/N] `)).trim());
64
+ return /^(y|yes)$/i.test((await reader.question(`${text} [y/N] `, signal ? { signal } : {})).trim());
49
65
  }
50
66
  finally {
51
67
  reader.close();
@@ -53,23 +69,25 @@ export const processIO = {
53
69
  },
54
70
  };
55
71
  const commands = {
56
- setup: "setup [--yes]",
72
+ doctor: "doctor [--fix [--yes]]",
73
+ profile: "profile [--name NAME] [--description TEXT]",
57
74
  "swarm create": "swarm create [--service URL] [--resume OPERATION]",
58
- "swarm request": "swarm request CONFIG_URL --owner-fingerprint FINGERPRINT [--output FILE] [--alias ALIAS]",
59
- "swarm export": "swarm export URL_OR_ALIAS --output FILE",
75
+ "swarm request": "swarm request CONFIG_URL [--output FILE] [--alias ALIAS]",
76
+ "swarm export": "swarm export --output FILE",
60
77
  "swarm approve": "swarm approve REQUEST_FILE [--again] --yes",
61
- "swarm exclude": "swarm exclude MEMBER_PUBLIC_KEY [--swarm URL_OR_ALIAS] --yes",
62
- "swarm resume": "swarm resume [URL_OR_ALIAS]",
63
- "swarm profile": "swarm profile [URL_OR_ALIAS] [--name NAME] [--address MULTIADDR]",
64
- "swarm status": "swarm status [URL_OR_ALIAS]",
78
+ "swarm exclude": "swarm exclude MEMBER_PUBLIC_KEY --yes",
79
+ "swarm resume": "swarm resume",
80
+ "swarm profile": "swarm profile --address MULTIADDR",
81
+ "swarm status": "swarm status [--local]",
82
+ "swarm members": "swarm members",
65
83
  "swarm list": "swarm list",
66
84
  "swarm add": "swarm add CONFIG_URL [--alias ALIAS]",
67
85
  "swarm use": "swarm use URL_OR_ALIAS",
68
86
  "swarm remove": "swarm remove URL_OR_ALIAS",
69
- "swarm update": "swarm update [URL_OR_ALIAS] [--name TEXT] [--description TEXT]",
70
- publish: "publish CID_OR_CAR [--name NAME [--expect OLD_NODE_CID | --snapshot]]",
87
+ "swarm update": "swarm update [--name TEXT] [--description TEXT]",
88
+ publish: "publish NAME SOURCE [--expect OLD_ARTIFACT_CID | --snapshot]",
71
89
  get: "get REF [--raw] [--force | --no-force] [-o DIRECTORY]",
72
- search: "search QUERY [--current] [--force | --no-force]",
90
+ search: "search QUERY [--all | --current] [--force | --no-force]",
73
91
  init: "init NAME [DIR] [OPTIONS]",
74
92
  build: "build [SOURCE] [OPTIONS]",
75
93
  "bundle build": "bundle build SOURCE [OPTIONS]",
@@ -77,14 +95,13 @@ const commands = {
77
95
  "bundle import": "bundle import FILE.car",
78
96
  exec: "exec [--log] [--force | --no-force] APP [APP_ARGS...]",
79
97
  open: "open [--log] [--raw] [--force | --no-force] CONTENT",
80
- "pin add": "pin add NAME CID",
81
- "pin delete": "pin delete NAME",
82
- "pin list": "pin list [--type TYPE]",
83
- "pin show": "pin show NAME",
84
- "pin rename": "pin rename OLD_NAME NEW_NAME",
85
- "register list": "register list",
86
- "register set": "register set SCHEMA APP [--replace] [-- TEMPLATE...]",
87
- "register remove": "register remove SCHEMA",
98
+ pin: "pin REF",
99
+ unpin: "unpin REF",
100
+ "pin list": "pin list",
101
+ "pin show": "pin show REF",
102
+ "register list": "register list [--swarm URL_OR_ALIAS]...",
103
+ "register set": "register set SCHEMA APP [--swarm URL_OR_ALIAS]... [--replace] [-- TEMPLATE...]",
104
+ "register remove": "register remove SCHEMA [--swarm URL_OR_ALIAS]...",
88
105
  "config get": "config get [KEY]",
89
106
  "config set": "config set KEY VALUE\n ipab config set pointers.apiKey - < protected-key-file",
90
107
  "config reset": "config reset KEY",
@@ -97,21 +114,48 @@ const commands = {
97
114
  const groups = {
98
115
  swarm: "Create, authorize, select and manage personal swarms",
99
116
  bundle: "Create, inspect and import content bundles",
100
- pin: "Retain content and manage short names",
117
+ pin: "Retain an exact CID or follow a shared Swarm Name",
101
118
  register: "Associate content types with Apps",
102
119
  config: "Manage local configuration",
103
120
  store: "Query local storage and collect unreferenced blocks",
104
121
  history: "View and remove execution history",
105
122
  };
106
123
  const commandHelp = {
107
- setup: {
108
- summary: "Verify/install Kubo and prepare the protected HOME account identity",
109
- examples: ["ipab setup --yes", "ipab setup"],
124
+ profile: {
125
+ summary: "Read or update your account-wide public name and description",
126
+ examples: [
127
+ "ipab profile",
128
+ 'ipab profile --name Wei --description "Developer"',
129
+ 'ipab profile --description ""',
130
+ ],
110
131
  options: [
111
- "--yes Confirm installation and identity initialization outside a TTY.",
132
+ "--name NAME Replace only your personal name.",
133
+ "--description TEXT Replace only your description; empty text clears it.",
112
134
  ],
113
135
  notes: [
114
- "Idempotent: reuse the same verified program and existing identity.",
136
+ "Independent of Swarm selection. Reading never creates an identity, persists a profile or activates a node.",
137
+ "An explicit update prepares a missing account identity without starting Kubo.",
138
+ "Updates persist locally first, then synchronize all registered memberships without changing network addresses. Partial failure exits nonzero and reports every result.",
139
+ "Retry the same profile update, or normally activate a failed membership to synchronize the saved profile.",
140
+ "First use preserves unanimous legacy values; conflicting fields require an explicit choice. New memberships adopt this same profile.",
141
+ ],
142
+ },
143
+ doctor: {
144
+ summary: "Inspect device readiness without writes; explicitly authorize safe repairs",
145
+ examples: [
146
+ "ipab doctor",
147
+ "ipab doctor --fix",
148
+ "ipab --json doctor --fix --yes",
149
+ ],
150
+ options: [
151
+ "--fix Repair missing components, cache official archives to verify existing Kubo without reinstall, and authorize healthy compatible upgrades within ^0.43.2.",
152
+ "--yes Authorize planned repairs without prompting; requires --fix.",
153
+ ],
154
+ notes: [
155
+ "Always checks local state/configuration, managed Kubo, HOME identity, local Swarm registry and compatible updates.",
156
+ "Inspection never creates state, locks, credentials or caches. Official release metadata may be queried; unavailable updates are not claimed current.",
157
+ "Healthy current components are reused without download or confirmation. Fixed protected archive cache is automatic.",
158
+ "Unverified existing Kubo: --fix may download/cache its exact-version official archive for byte comparison only; never execute it to authenticate itself or overwrite a mismatch.",
115
159
  "Does not create Swarm repos, start or contact any daemon, deploy services or install login startup.",
116
160
  ],
117
161
  },
@@ -138,16 +182,21 @@ const commandHelp = {
138
182
  "swarm request": {
139
183
  summary: "Save and export a signed self-contained membership Request",
140
184
  examples: [
141
- "ipab swarm request CONFIG_URL --owner-fingerprint TRUSTED_FINGERPRINT --output request.json --alias work",
185
+ "ipab swarm request CONFIG_URL --alias work",
186
+ "ipab swarm request CONFIG_URL --output request.json --alias work",
142
187
  ],
143
188
  options: [
144
- "--owner-fingerprint VALUE Verify Owner through a trusted independent channel.",
145
- "--name NAME Initial public display name.",
146
189
  "--alias ALIAS Pre-register the target for lazy onboarding.",
147
- "--output FILE Export the saved exact Request; no expiry or new PeerID on retry.",
190
+ "--output FILE Export to a new file instead of stdout; never overwrites.",
148
191
  ],
149
192
  notes: [
193
+ "Verify the printed Owner fingerprint through an independent trusted channel before manually sending the Request file to the Owner.",
194
+ "Without --output, stdout is the signed Request JSON, including in --json mode.",
195
+ "With --output, reports the file on stderr; --json returns file, requestId and ownerFingerprint.",
196
+ "Retries export the exact saved Request without expiry or a new PeerID.",
150
197
  "No Invite, Response file, password or Join. Next normal use fetches and decrypts the approved package.",
198
+ "Set your account-wide personal name with ipab profile --name NAME before requesting membership.",
199
+ "If the alias is taken, choose another to keep both Swarms. If you mean to replace only the local registration, run ipab swarm remove ALIAS and retry.",
151
200
  ],
152
201
  },
153
202
  "swarm approve": {
@@ -156,14 +205,18 @@ const commandHelp = {
156
205
  "--yes Explicit approval; required outside a TTY.",
157
206
  "--again Explicit fresh approval of an old Request; history is advisory.",
158
207
  ],
159
- examples: ["ipab swarm approve request.json --yes"],
208
+ examples: [
209
+ "ipab swarm approve request.json --yes",
210
+ "ipab swarm approve - --yes < request.json",
211
+ ],
160
212
  notes: [
213
+ "Use '-' to read Request JSON from stdin (maximum 16 KiB); --yes is required and no confirmation prompt reads stdin.",
161
214
  "Creates a public profile and publishes an Owner-signed X25519/AES-GCM package. Exact-ID certificates have no expiry.",
162
215
  ],
163
216
  },
164
217
  "swarm export": {
165
218
  summary: "Re-export the same persisted Request",
166
- examples: ["ipab swarm export work --output request.json"],
219
+ examples: ["ipab --swarm work swarm export --output request.json"],
167
220
  },
168
221
  "swarm exclude": {
169
222
  summary: "Owner removes a member with irreversible HEAD/key rotation",
@@ -174,13 +227,22 @@ const commandHelp = {
174
227
  },
175
228
  "swarm resume": {
176
229
  summary: "Owner resumes an interrupted organization switch",
177
- examples: ["ipab swarm resume work"],
230
+ examples: ["ipab --swarm work swarm resume"],
178
231
  },
179
232
  "swarm profile": {
180
- summary: "Update your public display name and LAN/VPN IPv4 TCP address",
233
+ summary: "Configure only your selected Swarm's LAN/VPN IPv4 TCP address",
181
234
  examples: [
182
- "ipab swarm profile work --name Wei",
183
- "ipab swarm profile work --address /ip4/192.168.1.12/tcp/4001/p2p/PEER_ID",
235
+ "ipab --swarm work swarm profile --address /ip4/192.168.1.12/tcp/4001/p2p/PEER_ID",
236
+ ],
237
+ notes: [
238
+ "Personal name/description are managed only by ipab profile, not this network configuration command.",
239
+ ],
240
+ },
241
+ "swarm members": {
242
+ summary: "List every public member, including the Owner",
243
+ examples: ["ipab --swarm work swarm members", "ipab --json swarm members"],
244
+ notes: [
245
+ "Public HTTP reads only; no local membership, identity creation or node activation. Failed reads fail the command, never omit members.",
184
246
  ],
185
247
  },
186
248
  "swarm status": {
@@ -190,8 +252,8 @@ const commandHelp = {
190
252
  ],
191
253
  examples: [
192
254
  "ipab swarm status",
193
- "ipab swarm status work",
194
- "ipab swarm status work --local",
255
+ "ipab --swarm work swarm status",
256
+ "ipab --swarm work swarm status --local",
195
257
  ],
196
258
  notes: [
197
259
  "Always read public configuration, Scope and HEAD, and verify the State. Local content needs no HOME identity or node activation.",
@@ -227,13 +289,12 @@ const commandHelp = {
227
289
  },
228
290
  "swarm update": {
229
291
  summary: "Owner updates public organization information",
230
- arguments: ["URL_OR_ALIAS Defaults to the effective current swarm."],
231
292
  options: [
232
293
  "--name TEXT Replace the shared display name; empty text clears it.",
233
294
  "--description TEXT Replace the shared description; empty text clears it.",
234
295
  ],
235
296
  examples: [
236
- 'ipab swarm update work --name "Team" --description "Shared workspace"',
297
+ 'ipab --swarm work swarm update --name "Team" --description "Shared workspace"',
237
298
  'ipab swarm update --description ""',
238
299
  ],
239
300
  notes: [
@@ -243,36 +304,44 @@ const commandHelp = {
243
304
  ],
244
305
  },
245
306
  search: {
246
- summary: "Search formal Names across registered swarms",
307
+ summary: "Search formal Names in the current swarm",
247
308
  arguments: [
248
309
  "QUERY Case-insensitive literal name substring, 1..256 characters.",
249
310
  ],
250
311
  options: [
251
- "--current Search only the effective current swarm; conflicts with --swarm.",
312
+ "--all Search all registered swarms; conflicts with --current and --swarm.",
313
+ "--current Explicitly select the default search scope; conflicts with --swarm.",
252
314
  "--force Refresh HEAD for every swarm in the search scope.",
253
315
  "--no-force Override swarm.forceRefresh and use valid cached headers.",
254
316
  ],
255
- examples: ["ipab search hello", "ipab --swarm work search hello --force"],
317
+ examples: [
318
+ "ipab search hello",
319
+ "ipab search hello --all",
320
+ "ipab --swarm work search hello --force",
321
+ ],
256
322
  notes: [
257
- "Searches all registered swarms unless --current or --swarm selects one.",
258
- "Valid caches use local Names only; absent/expired caches refresh. No payload downloads.",
323
+ "Searches only --swarm or the saved current swarm by default. Use --all to search every registration.",
324
+ "Valid caches use local Names; absent/expired caches refresh. Active Name pins may synchronize content.",
325
+ "Refresh reads public configuration and HEAD; private networking is activated only for missing content.",
259
326
  "No matches is success, not a reason to refresh valid caches. Any failed swarm fails the whole search.",
327
+ "Text uses local alias URIs when available; JSON references use full configuration URLs for cross-device sharing.",
260
328
  ],
261
329
  },
262
330
  publish: {
263
- summary: "Provide built content and explicitly publish a Name",
331
+ summary: "Protect content locally and publish a shared Swarm Name",
264
332
  options: [
265
- "--name NAME New formal Name; occupied Names fail.",
266
333
  "--expect CID Exact old Artifact node, required for iteration.",
267
334
  "--snapshot Name ordinary content without an Artifact; initial only.",
268
335
  ],
269
336
  examples: [
270
- "ipab publish app.car --name apps/hello",
271
- "ipab publish APP_CID --name apps/hello --expect OLD_NODE_CID",
272
- "ipab publish CONTENT_CID",
337
+ "ipab --swarm work publish apps/hello app.car",
338
+ "ipab publish apps/hello APP_CID --expect OLD_ARTIFACT_CID",
339
+ "ipab publish notes/readme ./README.md",
273
340
  ],
274
341
  notes: [
275
- "No build, edit, install or execution. CID-only stdout.",
342
+ "SOURCE is an exact Bundle CID, CAR, regular file or directory. No compiler, hooks, install or App execution.",
343
+ "Directories require .bundle.yaml/type, or a package.json source snapshot. Standalone .json/.yaml/.yml/.md/.txt entries get a standard Bundle; other file types require explicit metadata.",
344
+ "Occupied Names require --expect EXACT_OLD_ARTIFACT_CID. Published payloads are local CID pins; unpin CID releases that current protection, not legitimate history holders.",
276
345
  "Different-name CAS contention is rebased; same-name edits conflict (exit 3).",
277
346
  "Kubo pin confirmation precedes HEAD; it does not prove a remote device is online.",
278
347
  ],
@@ -295,6 +364,7 @@ const commandHelp = {
295
364
  "Stdout contains only the absolute directory path; --json also returns content and original target CIDs.",
296
365
  "Temporary exports remain after exit; copy before cleanup, not symlink. Use --output for a persistent destination.",
297
366
  "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
367
+ "Copy the reference from ipab search, or percent-encode the entire configuration URL and each Name path segment separately.",
298
368
  "Does not install, build, edit, or automatically retrieve associated source.",
299
369
  ],
300
370
  },
@@ -371,7 +441,9 @@ const commandHelp = {
371
441
  },
372
442
  "bundle inspect": {
373
443
  summary: "Inspect a Bundle or type definition",
374
- arguments: ["SOURCE Directory, definition file, CAR, CID or named pin."],
444
+ arguments: [
445
+ "SOURCE Directory, definition file, CAR, CID or packaged builtin reference.",
446
+ ],
375
447
  examples: ["ipab bundle inspect note\\dist\\bundle.car"],
376
448
  notes: ["Does not execute Apps, import content or create pins."],
377
449
  },
@@ -381,11 +453,11 @@ const commandHelp = {
381
453
  examples: ["ipab bundle import hello\\dist\\app.car"],
382
454
  notes: [
383
455
  "Repeated imports are safe; no App execution or daemon startup.",
384
- "Does not pin or retain content. Use pin add for persistent retention.",
456
+ "Does not pin or retain content. Use pin CID for persistent retention.",
385
457
  ],
386
458
  },
387
459
  exec: {
388
- summary: "Run an App by CID, named pin or IPAB URI",
460
+ summary: "Run an App by exact CID or Swarm IPAB URI",
389
461
  arguments: [
390
462
  "APP_ARGS Everything after APP is passed verbatim, including --help.",
391
463
  ],
@@ -409,7 +481,9 @@ const commandHelp = {
409
481
  },
410
482
  open: {
411
483
  summary: "Open content with its registered App",
412
- arguments: ["CONTENT Bundle CID, named pin or IPAB URI."],
484
+ arguments: [
485
+ "CONTENT Bundle CID, packaged builtin reference or Swarm IPAB URI.",
486
+ ],
413
487
  options: [
414
488
  "--log Record stdout/stderr; requires history enabled.",
415
489
  "--raw Open the Artifact node rather than its value.",
@@ -423,86 +497,107 @@ const commandHelp = {
423
497
  ],
424
498
  notes: [
425
499
  "Requires a saved registration and App support for the exact content type.",
500
+ "Uses only the content URI's Swarm, otherwise --swarm, otherwise swarm.default. A selected Swarm is required.",
501
+ "A registered App's retrieval, compatibility or execution failure never triggers fallback.",
502
+ "Legacy User registrations are inactive and preserved in the state database's legacy_user_registrations table; review them before explicit Swarm registration.",
426
503
  "ipab://ALIAS_OR_ENCODED_CONFIG_URL/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
427
504
  "Apps are NOT sandboxed; run only Apps you trust.",
428
505
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
429
506
  "--json is not supported; App stdio is passed through.",
430
507
  ],
431
508
  },
432
- "pin add": {
433
- summary: "Verify, retain and name a Bundle",
509
+ pin: {
510
+ summary: "Retain an immutable CID or follow a shared Swarm Name",
434
511
  arguments: [
435
- "NAME Unused short name.",
436
- "CID Exact Bundle CID, not another pin name or a standalone type block.",
512
+ "REF Exact Bundle CID or ipab://SWARM/NAME; no local content aliases.",
513
+ ],
514
+ examples: [
515
+ "ipab pin APP_CID",
516
+ "ipab pin ipab://work/apps/reader",
517
+ "ipab pin list",
437
518
  ],
438
- examples: ["ipab pin add reader APP_CID"],
439
519
  notes: [
440
520
  "Validates a complete Bundle and retains its full DAG in the configured Store.",
441
- "Does not execute or trust Apps, install dependencies or start a daemon.",
521
+ "A CID stays fixed. A shared Name saves its canonical configuration URL and exact Name, refreshing on related Swarm HEAD reads/sync, not continuously.",
522
+ "New content is verified and retained before the previous subscription version is released. Failures keep the last good version marked stale; deleted Names keep it marked missing.",
523
+ "Does not execute Apps or install dependencies. Shared Names connect to their Swarm content source only as needed.",
442
524
  "The builtin namespace is read-only.",
443
525
  ],
444
526
  },
445
- "pin delete": {
446
- summary: "Remove a user pin and release its retention",
447
- examples: ["ipab pin delete reader"],
527
+ unpin: {
528
+ summary: "Release a CID pin or stop following a shared Name",
529
+ examples: ["ipab unpin APP_CID", "ipab unpin ipab://work/apps/reader"],
448
530
  notes: [
449
531
  "Releases only this pin's ownership on its original backend; no block deletion or GC.",
450
- "Does not change registrations or history. Built-in pins are read-only.",
532
+ "Never re-resolves a shared Name to release content. Uses only saved actual roots. Missing pins are success.",
533
+ "Exact CID also releases archived legacy named-pin holders for that CID. Does not change shared Names, registrations or history. Built-ins are read-only.",
534
+ "Publication/history owners are independent; --snapshot payloads remain recursively retained by publication history after ordinary unpin.",
451
535
  ],
452
536
  },
453
537
  "pin list": {
454
- summary: "List user and built-in pins",
455
- options: [
456
- "--type TYPE Exact type CID or the name of a Bundle pin of that type.",
457
- ],
458
- examples: ["ipab pin list", "ipab pin list --type reader"],
538
+ summary: "List local retention, following Names and packaged built-ins",
539
+ examples: ["ipab pin list"],
459
540
  notes: [
460
- "Unfinished operations and legacy non-Bundle pins are reported separately.",
461
- "Legacy retention is preserved; use pin delete to explicitly release it.",
541
+ "Includes pending/stale/missing records and inactive archived local pin names.",
542
+ "Legacy retention is preserved; use unpin EXACT_CID to explicitly release its archived holders.",
462
543
  "Reads local registrations and packaged built-ins, not live node status.",
463
544
  ],
464
545
  },
465
546
  "pin show": {
466
- summary: "Show a pin's CID and type metadata",
467
- examples: ["ipab pin show reader", "ipab pin show builtin:template.node"],
547
+ summary: "Show saved retention and following status",
548
+ examples: ["ipab pin show APP_CID", "ipab pin show builtin:template.node"],
468
549
  notes: [
469
550
  "Reads local metadata; built-in pins do not claim user Store retention.",
470
551
  ],
471
552
  },
472
- "pin rename": {
473
- summary: "Rename a user pin without changing its content",
474
- examples: ["ipab pin rename reader my-reader"],
475
- notes: [
476
- "NEW_NAME must be unused. Built-in pins are read-only.",
477
- "CID, ownership, registrations and history are unchanged.",
478
- ],
479
- },
480
553
  "register list": {
481
554
  summary: "List saved content-type associations",
482
- examples: ["ipab register list"],
555
+ options: [
556
+ "--swarm URL_OR_ALIAS Read this Swarm registry; repeat for multiple Swarms.",
557
+ ],
558
+ examples: ["ipab register list", "ipab register list --swarm work"],
559
+ notes: [
560
+ "Without explicit --swarm, reads the saved default Swarm. Select one with --swarm or ipab swarm use.",
561
+ "Legacy User registrations are inactive and preserved in legacy_user_registrations; no automatic upload or deletion.",
562
+ ],
483
563
  },
484
564
  "register set": {
485
565
  summary: "Associate a content type with an App",
486
566
  arguments: [
487
567
  "SCHEMA Exact type CID or builtin:node-app.v1.",
488
- "APP App CID or named pin; the exact CID is saved.",
568
+ "APP App CID or Swarm IPAB URI; the exact CID is saved.",
489
569
  "TEMPLATE App argv after --; must contain a whole argument % (default: %).",
490
570
  ],
491
- options: ["--replace Allow changing an existing association."],
571
+ options: [
572
+ "--replace Allow changing an existing association.",
573
+ "--swarm URL_OR_ALIAS Write this Swarm registry; repeat for multiple Swarms.",
574
+ ],
492
575
  examples: [
493
576
  "ipab register set SCHEMA_CID reader",
494
577
  "ipab register set SCHEMA_CID reader '--' '--cid' '%'",
578
+ "ipab register set SCHEMA_CID ipab:///apps/reader --swarm work --swarm team",
495
579
  ],
496
580
  notes: [
497
581
  "Replaces only the whole % argument with the content CID; no shell expansion.",
498
582
  "Does not verify App type support; open checks it before execution.",
583
+ "Without explicit --swarm, writes the saved default Swarm. Swarm writes require HEAD write access.",
584
+ "Multiple Swarms commit sequentially, not atomically; failures report completed targets.",
499
585
  ],
500
586
  },
501
587
  "register remove": {
502
588
  summary: "Remove a saved content-type association",
503
589
  arguments: ["SCHEMA Exact type CID or builtin:node-app.v1."],
504
- examples: ["ipab register remove SCHEMA_CID"],
505
- notes: ["Does not remove Apps, pins or content."],
590
+ options: [
591
+ "--swarm URL_OR_ALIAS Remove from this Swarm registry; repeat for multiple Swarms.",
592
+ ],
593
+ examples: [
594
+ "ipab register remove SCHEMA_CID",
595
+ "ipab register remove SCHEMA_CID --swarm work",
596
+ ],
597
+ notes: [
598
+ "Without explicit --swarm, removes from the saved default Swarm. Multiple Swarm edits are not atomic.",
599
+ "Does not remove Apps, pins or content.",
600
+ ],
506
601
  },
507
602
  "config get": {
508
603
  summary: "Show effective configuration",
@@ -520,7 +615,7 @@ const commandHelp = {
520
615
  "store.gateway is a read-only HTTP gateway; blocks, pins and GC remain local.",
521
616
  "pointers.service is a canonical HTTPS origin (HTTP loopback allowed).",
522
617
  "pointers.apiKey is accepted only through stdin using VALUE '-'; queries and confirmations redact it.",
523
- "Saving pointers.apiKey protects state SQLite files with account-only Unix modes or Windows ACLs.",
618
+ "SQLite state is account-only even without a key. Reading or saving a nonempty key rechecks Unix modes or Windows ACLs.",
524
619
  ],
525
620
  },
526
621
  "config reset": {
@@ -530,7 +625,7 @@ const commandHelp = {
530
625
  "history list": {
531
626
  summary: "List execution history",
532
627
  options: [
533
- "--app APP Filter by App CID or named pin.",
628
+ "--app APP Filter by exact App CID.",
534
629
  "--status STATUS succeeded, failed or cancelled.",
535
630
  "--since TIME Include runs ended at or after TIME.",
536
631
  "--until TIME Include runs ended before TIME.",
@@ -553,7 +648,7 @@ const commandHelp = {
553
648
  "history remove": {
554
649
  summary: "Remove execution records and their logs",
555
650
  options: [
556
- "--app APP Filter by App CID or named pin.",
651
+ "--app APP Filter by exact App CID.",
557
652
  "--status STATUS succeeded, failed or cancelled.",
558
653
  "--since TIME Include runs ended at or after TIME.",
559
654
  "--until TIME Include runs ended before TIME.",
@@ -573,7 +668,7 @@ const commandHelp = {
573
668
  export function help(path = "") {
574
669
  const globalOptions = `Global options (before COMMAND):
575
670
  --swarm URL|ALIAS Select shared swarm (otherwise swarm.default; URI swarm takes precedence)
576
- --state-dir PATH Set the local state directory
671
+ --state-dir PATH Set a dedicated, account-private local state directory
577
672
  --store-gateway URL Use a read-only upstream HTTP gateway
578
673
  --json Output management/development metadata, not App stdio`;
579
674
  const footer = "Full reference: https://github.com/silvermoon-work/ipab/blob/main/docs/reference.md";
@@ -592,12 +687,14 @@ Create:
592
687
  bundle ${groups.bundle}
593
688
 
594
689
  Manage:
595
- setup ${commandHelp.setup.summary}
690
+ doctor ${commandHelp.doctor.summary}
691
+ profile ${commandHelp.profile.summary}
596
692
  swarm ${groups.swarm}
597
- search Search formal Names across registered swarms
693
+ search Search formal Names in the current swarm
598
694
  publish ${commandHelp.publish.summary}
599
695
  get ${commandHelp.get.summary}
600
696
  pin ${groups.pin}
697
+ unpin ${commandHelp.unpin.summary}
601
698
  register ${groups.register}
602
699
  config ${groups.config}
603
700
  store ${groups.store}
@@ -619,7 +716,25 @@ ${footer}`;
619
716
  ...(topic.arguments ? [section("Arguments", topic.arguments)] : []),
620
717
  ...(topic.options ? [section("Options", topic.options)] : []),
621
718
  section("Examples", topic.examples),
622
- ...(topic.notes ? [section("Notes", topic.notes)] : []),
719
+ ...([
720
+ "swarm status",
721
+ "swarm members",
722
+ "swarm update",
723
+ "swarm resume",
724
+ "swarm profile",
725
+ "swarm export",
726
+ "swarm approve",
727
+ "swarm exclude",
728
+ ].includes(path)
729
+ ? [
730
+ section("Notes", [
731
+ ...(topic.notes ?? []),
732
+ "Select only with global --swarm URL_OR_ALIAS (before the command), or the saved swarm.default. Neither means an error.",
733
+ ]),
734
+ ]
735
+ : topic.notes
736
+ ? [section("Notes", topic.notes)]
737
+ : []),
623
738
  `\n\n-h, --help shows this help. Global options: see 'ipab --help'.\n${footer}`,
624
739
  ].join("");
625
740
  }
@@ -644,6 +759,13 @@ function printable(text) {
644
759
  : char)
645
760
  .join("");
646
761
  }
762
+ export function formatSearchResults(matches) {
763
+ return matches.length
764
+ ? matches
765
+ .map((match) => `${printable(match.alias ?? match.swarm)} ${printable(match.name)} ${match.targetCid}\n ipab get ${formatNameReference(match.alias ?? match.swarm, match.name)}`)
766
+ .join("\n")
767
+ : "No matching Names.";
768
+ }
647
769
  function runTime(value, field) {
648
770
  const date = new Date(value);
649
771
  if (!Number.isFinite(date.getTime()))
@@ -736,6 +858,7 @@ async function closeStore(store, appExitCode) {
736
858
  export function parse(argv) {
737
859
  const tokens = [...argv];
738
860
  const flags = { json: false };
861
+ const swarms = [];
739
862
  while (tokens[0]?.startsWith("-")) {
740
863
  const flag = tokens.shift();
741
864
  if (flag === "-h" || flag === "--help")
@@ -771,8 +894,10 @@ export function parse(argv) {
771
894
  syntax(`${flag} needs a value.`);
772
895
  if (flag === "--state-dir")
773
896
  flags.stateDir = value;
774
- else if (flag === "--swarm")
897
+ else if (flag === "--swarm") {
775
898
  flags.swarm = value;
899
+ swarms.push(value);
900
+ }
776
901
  else {
777
902
  flags.storeGateway = publicUrl(value);
778
903
  }
@@ -788,6 +913,7 @@ export function parse(argv) {
788
913
  options: {},
789
914
  help: !group,
790
915
  version: false,
916
+ ...(group === "register" ? { registrySwarms: swarms } : {}),
791
917
  };
792
918
  if (!group)
793
919
  return result;
@@ -811,7 +937,17 @@ export function parse(argv) {
811
937
  result.positional = tokens;
812
938
  return result;
813
939
  }
814
- if (!["open", "init", "build", "publish", "get", "search", "setup"].includes(group)) {
940
+ if (![
941
+ "open",
942
+ "init",
943
+ "build",
944
+ "publish",
945
+ "get",
946
+ "search",
947
+ "doctor",
948
+ "profile",
949
+ "unpin",
950
+ ].includes(group)) {
815
951
  if (![
816
952
  "bundle",
817
953
  "pin",
@@ -821,12 +957,19 @@ export function parse(argv) {
821
957
  "store",
822
958
  "swarm",
823
959
  ].includes(group))
824
- syntax(`Unknown command "${group}".`);
825
- if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
960
+ syntax(`Unknown command "${group}".${group === "setup" ? " Run ipab doctor to inspect, or ipab doctor --fix to prepare this device." : " Run ipab --help."}`);
961
+ if (group === "pin" && !["list", "show"].includes(tokens[0] ?? "")) {
962
+ if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
963
+ result.help = true;
964
+ return result;
965
+ }
966
+ }
967
+ else if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
826
968
  result.help = true;
827
969
  return result;
828
970
  }
829
- result.path = `${group} ${tokens.shift()}`;
971
+ else
972
+ result.path = `${group} ${tokens.shift()}`;
830
973
  }
831
974
  else if (group === "open" && flags.json)
832
975
  syntax("--json is not supported for exec/open.");
@@ -845,8 +988,8 @@ export function parse(argv) {
845
988
  tokens.includes("pointers.apiKey") &&
846
989
  !(tokens.length === 2 && tokens[1] === "-"))
847
990
  syntax("API key must be provided through '-' and piped stdin; never pass it in command arguments.");
848
- const booleans = result.path === "setup"
849
- ? ["yes"]
991
+ const booleans = result.path === "doctor"
992
+ ? ["fix", "yes"]
850
993
  : result.path === "bundle build"
851
994
  ? ["replace", "schema-only", "no-import"]
852
995
  : result.path === "build"
@@ -856,7 +999,7 @@ export function parse(argv) {
856
999
  : result.path === "get"
857
1000
  ? ["raw", "force", "no-force"]
858
1001
  : result.path === "search"
859
- ? ["current", "force", "no-force"]
1002
+ ? ["all", "current", "force", "no-force"]
860
1003
  : result.path === "swarm approve"
861
1004
  ? ["yes", "again"]
862
1005
  : result.path === "swarm status"
@@ -875,17 +1018,17 @@ export function parse(argv) {
875
1018
  : result.path === "swarm add"
876
1019
  ? ["alias"]
877
1020
  : result.path === "swarm request"
878
- ? ["owner-fingerprint", "name", "alias", "output"]
1021
+ ? ["alias", "output"]
879
1022
  : result.path === "swarm export"
880
1023
  ? ["output"]
881
1024
  : result.path === "swarm profile"
882
- ? ["name", "address"]
883
- : result.path === "swarm update"
1025
+ ? ["address"]
1026
+ : result.path === "swarm update" || result.path === "profile"
884
1027
  ? ["name", "description"]
885
1028
  : result.path === "swarm approve"
886
1029
  ? []
887
1030
  : result.path === "publish"
888
- ? ["name", "expect"]
1031
+ ? ["expect"]
889
1032
  : result.path === "get"
890
1033
  ? ["output"]
891
1034
  : result.path === "init"
@@ -904,9 +1047,7 @@ export function parse(argv) {
904
1047
  ]
905
1048
  : result.path === "history remove"
906
1049
  ? ["app", "status", "since", "until"]
907
- : result.path === "pin list"
908
- ? ["type"]
909
- : [];
1050
+ : [];
910
1051
  while (tokens.length) {
911
1052
  const value = tokens.shift();
912
1053
  if (result.path === "swarm exclude" &&
@@ -915,6 +1056,14 @@ export function parse(argv) {
915
1056
  }
916
1057
  else if (value.startsWith("--") || value === "-o") {
917
1058
  const option = value === "-o" ? "output" : value.slice(2);
1059
+ if (result.path.startsWith("register ") && option === "swarm") {
1060
+ const input = tokens.shift();
1061
+ if (!input || input.startsWith("-"))
1062
+ syntax("--swarm needs a value.");
1063
+ result.registrySwarms.push(input);
1064
+ flags.swarm = input;
1065
+ continue;
1066
+ }
918
1067
  if (result.path === "init" && option === "param") {
919
1068
  const input = tokens.shift();
920
1069
  if (!input || input.startsWith("--") || input.indexOf("=") < 1)
@@ -930,12 +1079,14 @@ export function parse(argv) {
930
1079
  const input = tokens.shift();
931
1080
  if (input === undefined ||
932
1081
  (input.startsWith("--") &&
933
- !(["resume", "owner-fingerprint"].includes(option) &&
934
- /^[A-Za-z0-9_-]{43}$/.test(input))) ||
935
- (input === "" && result.path !== "swarm update"))
1082
+ !(option === "resume" && /^[A-Za-z0-9_-]{43}$/.test(input))) ||
1083
+ (input === "" && !["swarm update", "profile"].includes(result.path)))
936
1084
  syntax(`${value} needs a value.`);
937
1085
  result.options[option] = input;
938
1086
  }
1087
+ else if (option === "name" &&
1088
+ ["swarm profile", "swarm request"].includes(result.path))
1089
+ syntax(`Personal names are account-wide. Use ipab profile --name NAME instead.${result.path === "swarm profile" ? " For network configuration, use ipab --swarm URL_OR_ALIAS swarm profile --address MULTIADDR." : ""}`);
939
1090
  else
940
1091
  syntax(`Unknown option "${value}".`);
941
1092
  }
@@ -948,22 +1099,28 @@ export function parse(argv) {
948
1099
  result.options.current &&
949
1100
  flags.swarm !== undefined)
950
1101
  syntax("--current and --swarm are mutually exclusive.");
1102
+ if (result.path === "search" &&
1103
+ result.options.all &&
1104
+ (result.options.current || flags.swarm !== undefined))
1105
+ syntax("--all is mutually exclusive with --current and --swarm.");
951
1106
  const counts = {
952
- setup: [0, 0],
1107
+ doctor: [0, 0],
1108
+ profile: [0, 0],
953
1109
  "swarm create": [0, 0],
954
1110
  "swarm request": [1, 1],
955
1111
  "swarm approve": [1, 1],
956
- "swarm export": [1, 1],
1112
+ "swarm export": [0, 0],
957
1113
  "swarm exclude": [1, 1],
958
- "swarm resume": [0, 1],
959
- "swarm profile": [0, 1],
960
- "swarm status": [0, 1],
1114
+ "swarm resume": [0, 0],
1115
+ "swarm profile": [0, 0],
1116
+ "swarm status": [0, 0],
1117
+ "swarm members": [0, 0],
961
1118
  "swarm list": [0, 0],
962
1119
  "swarm add": [1, 1],
963
1120
  "swarm use": [1, 1],
964
1121
  "swarm remove": [1, 1],
965
- "swarm update": [0, 1],
966
- publish: [1, 1],
1122
+ "swarm update": [0, 0],
1123
+ publish: [2, 2],
967
1124
  get: [1, 1],
968
1125
  search: [1, 1],
969
1126
  init: [1, 2],
@@ -972,11 +1129,10 @@ export function parse(argv) {
972
1129
  "bundle inspect": [1, 1],
973
1130
  "bundle import": [1, 1],
974
1131
  open: [1, 1],
975
- "pin add": [2, 2],
976
- "pin delete": [1, 1],
1132
+ pin: [1, 1],
1133
+ unpin: [1, 1],
977
1134
  "pin list": [0, 0],
978
1135
  "pin show": [1, 1],
979
- "pin rename": [2, 2],
980
1136
  "register list": [0, 0],
981
1137
  "register set": [2, 2],
982
1138
  "register remove": [1, 1],
@@ -992,6 +1148,18 @@ export function parse(argv) {
992
1148
  if (result.options["with-source"] && result.options["without-source"])
993
1149
  syntax("--with-source and --without-source are mutually exclusive.");
994
1150
  const [minimum, maximum] = counts[result.path];
1151
+ if (result.path === "profile" && flags.swarm !== undefined)
1152
+ syntax("Personal profile is account-wide; do not pass --swarm.");
1153
+ if (result.positional.length &&
1154
+ [
1155
+ "swarm status",
1156
+ "swarm update",
1157
+ "swarm resume",
1158
+ "swarm profile",
1159
+ "swarm export",
1160
+ "swarm members",
1161
+ ].includes(result.path))
1162
+ syntax(`Swarm target positionals are no longer supported. Use ipab --swarm URL_OR_ALIAS ${result.path} instead.`);
995
1163
  if (result.positional.length < minimum || result.positional.length > maximum)
996
1164
  syntax(`Invalid arguments.\n${help(result.path)}`);
997
1165
  if (result.template &&
@@ -1004,12 +1172,20 @@ export function parse(argv) {
1004
1172
  syntax("history remove requires explicit IDs OR filters, not both.");
1005
1173
  }
1006
1174
  // Validate syntactic values before state access, let alone a backend connection.
1007
- if (result.path.startsWith("pin ") && result.path !== "pin list") {
1008
- pinName(result.positional[0], result.path === "pin show");
1009
- if (result.path === "pin add")
1010
- exactCid(result.positional[1]);
1011
- if (result.path === "pin rename")
1012
- pinName(result.positional[1]);
1175
+ if (["pin", "unpin", "pin show"].includes(result.path)) {
1176
+ const reference = result.positional[0];
1177
+ if (reference.startsWith("builtin:") && result.path !== "pin show")
1178
+ syntax("Packaged builtin references are read-only; they cannot be pinned or unpinned.");
1179
+ if (!(result.path === "pin show" && reference.startsWith("builtin:")) &&
1180
+ !parseNameReference(reference))
1181
+ exactCid(reference);
1182
+ }
1183
+ if (result.path === "publish") {
1184
+ formalName(result.positional[0]);
1185
+ if (typeof result.options.expect === "string")
1186
+ exactCid(result.options.expect);
1187
+ if (result.options.expect && result.options.snapshot)
1188
+ syntax("--snapshot is initial-only and cannot be combined with --expect.");
1013
1189
  }
1014
1190
  if (result.path.startsWith("config ") && result.positional[0]) {
1015
1191
  if (!(result.path === "config get" && result.positional[0] === "state-dir") &&
@@ -1028,12 +1204,15 @@ export function parse(argv) {
1028
1204
  parseValue("history.limit", result.options.limit, true);
1029
1205
  if (result.options.output === "-")
1030
1206
  syntax("CAR output requires a file path; binary stdout is not supported.");
1207
+ if (result.path === "doctor" && result.options.yes && !result.options.fix)
1208
+ syntax("doctor --yes requires --fix.");
1031
1209
  return result;
1032
1210
  }
1033
1211
  async function performCli(argv, io, env) {
1034
1212
  let state;
1035
1213
  let store;
1036
1214
  let appExitCode;
1215
+ let readContext;
1037
1216
  try {
1038
1217
  const parsed = parse(argv);
1039
1218
  if (parsed.help) {
@@ -1049,19 +1228,37 @@ async function performCli(argv, io, env) {
1049
1228
  }
1050
1229
  if (parsed.path === "history remove" && !parsed.options.yes && !io.tty)
1051
1230
  syntax("Non-interactive history remove requires --yes.");
1052
- if (parsed.path === "setup") {
1053
- if (!parsed.options.yes &&
1054
- (!io.tty ||
1055
- !(await io.confirm("Install checksum-verified Kubo and initialize/reuse the protected HOME identity? No daemon will be contacted or started."))))
1056
- throw new HostError("Setup requires explicit --yes or interactive confirmation.");
1057
- const result = await setupDevice(stateLocation(parsed.flags, env).path, env);
1058
- io.out(parsed.flags.json
1059
- ? JSON.stringify(result)
1060
- : `Kubo ${result.kuboVersion}: ${result.binary}\nAccount fingerprint: ${result.fingerprint}\nReady. Nodes start only when a Swarm is used.`);
1061
- return 0;
1231
+ if (parsed.path === "doctor") {
1232
+ const controller = new AbortController();
1233
+ const interrupt = () => {
1234
+ controller.abort(new HostError("Doctor interrupted.", 130, "ABORTED"));
1235
+ };
1236
+ const terminate = () => {
1237
+ controller.abort(new HostError("Doctor terminated.", 143, "ABORTED"));
1238
+ };
1239
+ process.once("SIGINT", interrupt);
1240
+ process.once("SIGTERM", terminate);
1241
+ try {
1242
+ const result = await doctorDevice(stateLocation(parsed.flags, env).path, env, {
1243
+ diagnostic: (text, progress) => {
1244
+ io.err(text, progress);
1245
+ },
1246
+ signal: controller.signal,
1247
+ fix: Boolean(parsed.options.fix),
1248
+ yes: Boolean(parsed.options.yes),
1249
+ tty: io.tty,
1250
+ confirm: (text, signal) => io.confirm(text, signal),
1251
+ });
1252
+ io.out(parsed.flags.json ? JSON.stringify(result) : doctorText(result));
1253
+ return result.ready ? 0 : 1;
1254
+ }
1255
+ finally {
1256
+ process.removeListener("SIGINT", interrupt);
1257
+ process.removeListener("SIGTERM", terminate);
1258
+ }
1062
1259
  }
1063
1260
  const builtins = await builtinContent();
1064
- state = new State(stateLocation(parsed.flags, env).path, builtins.pins);
1261
+ state = new State(stateLocation(parsed.flags, env).path, builtins.pins, env);
1065
1262
  if (parsed.path === "config reset" &&
1066
1263
  parsed.positional[0] === "store.rpc") {
1067
1264
  state.resetConfig("store.rpc");
@@ -1071,7 +1268,8 @@ async function performCli(argv, io, env) {
1071
1268
  return 0;
1072
1269
  }
1073
1270
  const items = effectiveConfig(state.config({
1074
- includeSecrets: parsed.path !== "swarm status" || Boolean(parsed.options.local),
1271
+ includeSecrets: !["swarm members", "profile", "swarm status"].includes(parsed.path) ||
1272
+ Boolean(parsed.options.local),
1075
1273
  }), parsed.flags, env, (reference) => state.resolveSwarm(reference));
1076
1274
  const value = (key) => items.find((item) => item.key === key).value;
1077
1275
  const emit = (result, human) => {
@@ -1081,6 +1279,11 @@ async function performCli(argv, io, env) {
1081
1279
  const selectedSwarm = value("swarm.default") === null
1082
1280
  ? undefined
1083
1281
  : String(value("swarm.default"));
1282
+ const requireSwarm = () => {
1283
+ if (!selectedSwarm)
1284
+ syntax("Select a Swarm with ipab --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS.");
1285
+ return selectedSwarm;
1286
+ };
1084
1287
  const swarmContext = () => ({
1085
1288
  get store() {
1086
1289
  return store;
@@ -1112,14 +1315,111 @@ async function performCli(argv, io, env) {
1112
1315
  ? filters(state, parsed.options)
1113
1316
  : {};
1114
1317
  const selection = () => {
1115
- const current = effectiveConfig(state.config(), parsed.flags, env, (reference) => state.resolveSwarm(reference)).find((item) => item.key === "swarm.default");
1318
+ const saved = state.config({ includeSecrets: false });
1319
+ const current = effectiveConfig(saved, parsed.flags, env, (reference) => state.resolveSwarm(reference)).find((item) => item.key === "swarm.default");
1116
1320
  return {
1117
- savedCurrent: state.config()["swarm.default"] ?? null,
1321
+ savedCurrent: saved["swarm.default"] ?? null,
1118
1322
  effectiveCurrent: current.value,
1119
1323
  source: current.source,
1120
1324
  };
1121
1325
  };
1326
+ if (parsed.path === "open" || parsed.path.startsWith("register ")) {
1327
+ if (state.legacyRegistrationCount)
1328
+ io.err(`Legacy User registrations are inactive. ${state.legacyRegistrationCount} entries are preserved in legacy_user_registrations in the state database under ${state.directory}; nothing was uploaded or deleted. Review the archived values and explicitly run ipab register set TYPE_CID APP_CID --swarm URL_OR_ALIAS [-- TEMPLATE...] to publish only intended associations.`);
1329
+ }
1330
+ if (state.legacyPinCount)
1331
+ io.err(`Legacy local pin names are inactive: ${state.legacyPinCount} records are preserved in legacy_named_pins under ${state.directory}. Retention and original Store owners are unchanged; inspect ipab pin list and release intended archived holders with ipab unpin EXACT_CID.`);
1332
+ if (parsed.path.startsWith("register ")) {
1333
+ const references = parsed.registrySwarms?.length
1334
+ ? parsed.registrySwarms
1335
+ : selectedSwarm
1336
+ ? [selectedSwarm]
1337
+ : [];
1338
+ if (!references.length)
1339
+ throw new HostError("Register requires a selected Swarm. Pass --swarm URL_OR_ALIAS (repeat for multiple Swarms), or save a default with ipab swarm use URL_OR_ALIAS.");
1340
+ const targets = [
1341
+ ...new Set(references.map((reference) => state.resolveSwarm(reference))),
1342
+ ];
1343
+ const schema = first
1344
+ ? state.resolve(schemaAlias(first), true)
1345
+ : undefined;
1346
+ const results = [];
1347
+ const completed = [];
1348
+ const human = [];
1349
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1350
+ for (const configUrl of targets) {
1351
+ const context = swarmContext();
1352
+ try {
1353
+ if (parsed.path === "register list") {
1354
+ const items = await swarmRegistrations(context, configUrl);
1355
+ results.push({ items });
1356
+ human.push(`${configUrl}\n${table(["SCHEMA CID", "APP CID", "ARGV"], items.map((item) => [
1357
+ item.schemaCid,
1358
+ item.appCid,
1359
+ JSON.stringify(item.argv),
1360
+ ]), "No associations.")}`);
1361
+ }
1362
+ else if (parsed.path === "register set") {
1363
+ const appCid = parseNameReference(second)
1364
+ ? (await resolveReference(context, second, configUrl, (reference) => state.resolve(reference))).cid
1365
+ : state.resolve(second);
1366
+ const association = await setSwarmAssociation(context, configUrl, createAssociation(schema, appCid, parsed.template ?? ["%"]), Boolean(parsed.options.replace));
1367
+ results.push({ association });
1368
+ human.push(`${configUrl}: ${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`);
1369
+ }
1370
+ else {
1371
+ const removed = await removeSwarmAssociation(context, configUrl, schema);
1372
+ results.push({ removed: [removed] });
1373
+ human.push(`${configUrl}: removed association for ${removed}.`);
1374
+ }
1375
+ completed.push(configUrl);
1376
+ }
1377
+ catch (cause) {
1378
+ throw new HostError(`Registry operation failed for ${configUrl}: ${message(cause)}. Completed Swarms: ${completed.length ? completed.join(", ") : "(none)"}. Multiple Swarm edits are not atomic.`, cause instanceof HostError ? cause.exitCode : 1, cause instanceof HostError ? cause.code : "REGISTRY_FAILED", "publication");
1379
+ }
1380
+ finally {
1381
+ await context.finishRead?.();
1382
+ }
1383
+ }
1384
+ emit({
1385
+ swarms: results.map((result, index) => ({
1386
+ configUrl: targets[index],
1387
+ ...result,
1388
+ })),
1389
+ }, human.join("\n\n"));
1390
+ return 0;
1391
+ }
1122
1392
  switch (parsed.path) {
1393
+ case "profile": {
1394
+ const context = swarmContext();
1395
+ readContext = context;
1396
+ const changes = {
1397
+ ...(typeof parsed.options.name === "string"
1398
+ ? { name: parsed.options.name }
1399
+ : {}),
1400
+ ...(typeof parsed.options.description === "string"
1401
+ ? { description: parsed.options.description }
1402
+ : {}),
1403
+ };
1404
+ if (!Object.keys(changes).length) {
1405
+ const profile = await accountProfile(context);
1406
+ emit({ profile, localPersisted: profile.updatedAt !== null }, `Name: ${printable(profile.name)}\nDescription: ${printable(profile.description)}\nPublic key: ${profile.publicKey}`);
1407
+ }
1408
+ else {
1409
+ const result = await updateAccountProfile(context, changes);
1410
+ emit(result, [
1411
+ `Name: ${printable(result.profile.name)}`,
1412
+ `Description: ${printable(result.profile.description)}`,
1413
+ "Personal profile saved locally.",
1414
+ ...result.swarms.map((entry) => `${entry.configUrl}: ${entry.synchronized ? "synchronized" : `FAILED: ${entry.error}`}`),
1415
+ ].join("\n"));
1416
+ if (result.swarms.some((entry) => !entry.synchronized)) {
1417
+ io.err("Profile saved locally, but some Swarms failed. Retry the profile update or normally activate each failed membership to synchronize it.");
1418
+ return 1;
1419
+ }
1420
+ }
1421
+ break;
1422
+ }
1123
1423
  case "swarm list": {
1124
1424
  const result = { swarms: state.swarms(), ...selection() };
1125
1425
  emit({
@@ -1152,7 +1452,10 @@ async function performCli(argv, io, env) {
1152
1452
  }
1153
1453
  case "swarm remove": {
1154
1454
  const removed = state.removeSwarm(first);
1155
- emit({ removed, savedCurrent: state.config()["swarm.default"] ?? null }, `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`);
1455
+ emit({
1456
+ removed,
1457
+ savedCurrent: state.config({ includeSecrets: false })["swarm.default"] ?? null,
1458
+ }, `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`);
1156
1459
  break;
1157
1460
  }
1158
1461
  case "swarm add":
@@ -1165,24 +1468,38 @@ async function performCli(argv, io, env) {
1165
1468
  case "swarm exclude":
1166
1469
  case "swarm resume":
1167
1470
  case "swarm profile":
1471
+ case "swarm members":
1168
1472
  case "swarm status":
1169
1473
  case "publish":
1474
+ case "pin":
1170
1475
  case "get": {
1171
1476
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1172
1477
  const context = swarmContext();
1478
+ readContext = context;
1479
+ if (parsed.path === "pin") {
1480
+ io.err("Fetching, verifying and retaining content...");
1481
+ const result = await pinNameSubscription(context, first, selectedSwarm);
1482
+ store = context.store;
1483
+ emit(result, `${result.reference} → ${result.cid}\nStatus: ${result.freshness}`);
1484
+ break;
1485
+ }
1486
+ if (parsed.path === "swarm members") {
1487
+ const result = await swarmMembers(context, requireSwarm());
1488
+ emit(result, table(["NAME", "DESCRIPTION", "ROLE", "PUBLIC KEY"], result.members.map((member) => [
1489
+ member.name,
1490
+ member.description,
1491
+ member.role,
1492
+ member.publicKey,
1493
+ ]), "No members."));
1494
+ break;
1495
+ }
1173
1496
  if (parsed.path === "swarm export") {
1174
- const id = await exportRequest(context, state.resolveSwarm(first), String(parsed.options.output ?? ""));
1497
+ const id = await exportRequest(context, requireSwarm(), String(parsed.options.output ?? ""));
1175
1498
  emit({ id }, id);
1176
1499
  break;
1177
1500
  }
1178
1501
  if (["swarm exclude", "swarm resume", "swarm profile"].includes(parsed.path)) {
1179
- const url = parsed.path === "swarm exclude"
1180
- ? selectedSwarm
1181
- : first
1182
- ? state.resolveSwarm(first)
1183
- : selectedSwarm;
1184
- if (!url)
1185
- syntax("Select a Swarm configuration URL or alias.");
1502
+ const url = requireSwarm();
1186
1503
  if (parsed.path === "swarm exclude") {
1187
1504
  if (!parsed.options.yes)
1188
1505
  syntax("Member removal is irreversible; --yes required.");
@@ -1192,9 +1509,6 @@ async function performCli(argv, io, env) {
1192
1509
  await resumeRemoval(context, url);
1193
1510
  else {
1194
1511
  const profile = await updateProfile(context, url, {
1195
- ...(typeof parsed.options.name === "string"
1196
- ? { name: parsed.options.name }
1197
- : {}),
1198
1512
  ...(typeof parsed.options.address === "string"
1199
1513
  ? { addresses: [parsed.options.address] }
1200
1514
  : {}),
@@ -1208,9 +1522,7 @@ async function performCli(argv, io, env) {
1208
1522
  break;
1209
1523
  }
1210
1524
  if (parsed.path === "swarm update") {
1211
- const cid = first ? state.resolveSwarm(first) : selectedSwarm;
1212
- if (!cid)
1213
- syntax("swarm update requires a registered alias, configuration URL or current swarm.");
1525
+ const cid = requireSwarm();
1214
1526
  const result = await updateSwarm(context, cid, {
1215
1527
  ...(typeof parsed.options.name === "string"
1216
1528
  ? { name: parsed.options.name }
@@ -1231,37 +1543,28 @@ async function performCli(argv, io, env) {
1231
1543
  emit({
1232
1544
  configUrl: entry.cid,
1233
1545
  alias: entry.alias,
1234
- savedCurrent: state.config()["swarm.default"] ?? null,
1546
+ savedCurrent: state.config({ includeSecrets: false })["swarm.default"] ??
1547
+ null,
1235
1548
  }, `Registered swarm ${entry.alias ?? cid} (${cid}).`);
1236
1549
  break;
1237
1550
  }
1238
1551
  if (parsed.path === "search") {
1239
- const source = items.find((item) => item.key === "swarm.default").source;
1240
- const limited = parsed.options.current || source === "flag";
1241
- if (limited && !selectedSwarm)
1242
- syntax("Search of the current swarm requires --swarm or swarm.default.");
1243
1552
  const registrations = state.swarms();
1244
- const scope = limited
1245
- ? [
1553
+ const scope = parsed.options.all
1554
+ ? registrations
1555
+ : [
1246
1556
  {
1247
- cid: selectedSwarm,
1557
+ cid: requireSwarm(),
1248
1558
  alias: registrations.find((entry) => entry.cid === selectedSwarm)
1249
1559
  ?.alias ?? null,
1250
1560
  },
1251
- ]
1252
- : registrations;
1561
+ ];
1253
1562
  const result = await searchNames(context, first, scope);
1254
- emit(result, result.matches.length
1255
- ? result.matches
1256
- .map((match) => `${printable(match.alias ?? match.swarm)} ${printable(match.name)} ${match.targetCid}\n ipab get ${printable(match.reference)}`)
1257
- .join("\n")
1258
- : "No matching Names.");
1563
+ emit(result, formatSearchResults(result.matches));
1259
1564
  break;
1260
1565
  }
1261
1566
  if (parsed.path === "swarm status") {
1262
- const cid = first ? state.resolveSwarm(first) : selectedSwarm;
1263
- if (!cid)
1264
- syntax("swarm status requires a configuration URL or swarm.default.");
1567
+ const cid = requireSwarm();
1265
1568
  const local = Boolean(parsed.options.local);
1266
1569
  const { head, config } = local
1267
1570
  ? await swarmHeader(context, cid, true)
@@ -1314,13 +1617,13 @@ async function performCli(argv, io, env) {
1314
1617
  break;
1315
1618
  }
1316
1619
  if (parsed.path === "get") {
1317
- const localCid = first.startsWith("ipab://")
1620
+ const localCid = /^(ipab|name):/i.test(first)
1318
1621
  ? undefined
1319
1622
  : state.resolve(first);
1320
1623
  const builtin = builtins.pins.find((pin) => pin.cid === localCid);
1321
1624
  const selected = builtin
1322
1625
  ? { cid: builtin.cid, targetCid: builtin.cid }
1323
- : await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw));
1626
+ : await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw), "local-first");
1324
1627
  const contentStore = context.store;
1325
1628
  const source = IpfsStore.fromClient({
1326
1629
  block: {
@@ -1342,6 +1645,12 @@ async function performCli(argv, io, env) {
1342
1645
  finally {
1343
1646
  await source.close();
1344
1647
  }
1648
+ try {
1649
+ await context.finishRead?.();
1650
+ }
1651
+ finally {
1652
+ readContext = undefined;
1653
+ }
1345
1654
  const closing = store;
1346
1655
  store = undefined;
1347
1656
  await closeStore(closing, undefined);
@@ -1351,6 +1660,7 @@ async function performCli(argv, io, env) {
1351
1660
  break;
1352
1661
  }
1353
1662
  let cid;
1663
+ let contentCid;
1354
1664
  if (parsed.path === "swarm create") {
1355
1665
  cid = await createSwarm(context, {
1356
1666
  ...(typeof parsed.options.service === "string"
@@ -1368,12 +1678,8 @@ async function performCli(argv, io, env) {
1368
1678
  : {}),
1369
1679
  });
1370
1680
  }
1371
- else if (parsed.path === "swarm request")
1372
- cid = await requestMembership(context, first, {
1373
- ownerFingerprint: String(parsed.options["owner-fingerprint"] ?? ""),
1374
- ...(typeof parsed.options.name === "string"
1375
- ? { name: parsed.options.name }
1376
- : {}),
1681
+ else if (parsed.path === "swarm request") {
1682
+ const result = await requestMembership(context, first, {
1377
1683
  ...(typeof parsed.options.alias === "string"
1378
1684
  ? { alias: parsed.options.alias }
1379
1685
  : {}),
@@ -1381,8 +1687,30 @@ async function performCli(argv, io, env) {
1381
1687
  ? { output: parsed.options.output }
1382
1688
  : {}),
1383
1689
  });
1690
+ store = context.store;
1691
+ io.err(`Owner fingerprint: ${result.ownerFingerprint}\nVerify this fingerprint through an independent trusted channel before manually sending the Request file to the Owner.`);
1692
+ if (result.file === undefined)
1693
+ io.out(JSON.stringify(result.request, null, 2));
1694
+ else {
1695
+ io.err(`Request saved to: ${result.file}`);
1696
+ if (parsed.flags.json)
1697
+ emit({
1698
+ file: result.file,
1699
+ requestId: result.requestId,
1700
+ ownerFingerprint: result.ownerFingerprint,
1701
+ }, "");
1702
+ }
1703
+ break;
1704
+ }
1384
1705
  else if (parsed.path === "swarm approve") {
1385
- const request = await verifiedRequest(first);
1706
+ const selected = requireSwarm();
1707
+ if (first === "-" && !parsed.options.yes)
1708
+ syntax("Reading a Request from stdin requires explicit --yes; no interactive confirmation is available.");
1709
+ const request = first === "-"
1710
+ ? await verifiedRequestStream((io.requestInput ?? processIO.requestInput)())
1711
+ : await verifiedRequest(first);
1712
+ if (request.configUrl !== selected)
1713
+ syntax(`Request belongs to ${request.configUrl}, not the selected Swarm. Use ipab --swarm ${request.configUrl} swarm approve REQUEST_FILE --yes.`);
1386
1714
  io.err(await membershipRequestSummary(request));
1387
1715
  if (!parsed.options.yes &&
1388
1716
  (!io.tty ||
@@ -1393,16 +1721,11 @@ async function performCli(argv, io, env) {
1393
1721
  });
1394
1722
  }
1395
1723
  else {
1396
- let content;
1397
- if (first.toLowerCase().endsWith(".car"))
1398
- content = (await importBundle(first, () => Promise.resolve(store))).cid;
1399
- else
1400
- content = exactCid(first);
1724
+ const content = await publicationSource(second, store);
1725
+ contentCid = content;
1401
1726
  cid = await publish(context, content, {
1402
1727
  ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
1403
- ...(typeof parsed.options.name === "string"
1404
- ? { name: parsed.options.name }
1405
- : {}),
1728
+ name: first,
1406
1729
  ...(typeof parsed.options.expect === "string"
1407
1730
  ? { expect: parsed.options.expect }
1408
1731
  : {}),
@@ -1411,12 +1734,12 @@ async function performCli(argv, io, env) {
1411
1734
  }
1412
1735
  store = context.store;
1413
1736
  if (parsed.path === "swarm create")
1414
- io.err(`Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config()["swarm.default"] ?? "(none)"}.`);
1415
- emit(parsed.path === "swarm request"
1416
- ? { requestId: cid }
1417
- : parsed.path === "swarm create" || parsed.path === "swarm approve"
1418
- ? { configUrl: cid }
1419
- : { cid }, cid);
1737
+ io.err(`Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config({ includeSecrets: false })["swarm.default"] ?? "(none)"}.`);
1738
+ if (contentCid)
1739
+ io.err(`Locally protected payload: ${contentCid}. Use ipab unpin ${contentCid} to release this CID pin only; Name subscriptions and publication/history owners remain. --snapshot links payloads directly into retained publication history, so unpin cannot release that protection.`);
1740
+ emit(parsed.path === "swarm create" || parsed.path === "swarm approve"
1741
+ ? { configUrl: cid }
1742
+ : { cid, ...(contentCid ? { contentCid } : {}) }, cid);
1420
1743
  break;
1421
1744
  }
1422
1745
  case "store usage":
@@ -1544,7 +1867,7 @@ async function performCli(argv, io, env) {
1544
1867
  if (result.files.includes("package.json") &&
1545
1868
  (result.files.includes("ipab.yaml") ||
1546
1869
  result.files.includes("ipab.json")))
1547
- io.err(`Next: install declared dependencies and explicitly link the candidate @ipab/cli as a project dependency in ${JSON.stringify(result.directory)}; run pnpm build to prepare and package the App. Root ipab build does not compile.`);
1870
+ io.err(`Next: install declared dependencies in ${JSON.stringify(result.directory)}; if your template does not declare @ipab/cli, add or link it as a development dependency. Run pnpm build to prepare and package the App. Root ipab build does not compile.`);
1548
1871
  else if (result.files.includes(".bundle.yaml"))
1549
1872
  io.err(`Next: ipab bundle build ${JSON.stringify(result.directory)}`);
1550
1873
  }
@@ -1563,80 +1886,62 @@ async function performCli(argv, io, env) {
1563
1886
  break;
1564
1887
  }
1565
1888
  case "pin list": {
1566
- const type = typeof parsed.options.type === "string"
1567
- ? state.resolve(parsed.options.type, true)
1568
- : undefined;
1569
- const pins = state.pins();
1570
- const listed = pins
1571
- .filter((pin) => pin.status === "ready" && pin.metadata?.kind === "bundle")
1572
- .map(pinDetails)
1573
- .filter((pin) => type === undefined || pin.schemaCid === type);
1574
- const invalid = pins
1575
- .filter((pin) => pin.status === "ready" && pin.metadata?.kind !== "bundle")
1576
- .map(({ name, cid, metadata }) => ({
1577
- name,
1578
- cid,
1579
- kind: metadata?.kind,
1580
- reason: "Not a Bundle pin; retention is preserved. Use pin delete to release it.",
1581
- }));
1582
- const pending = pins
1583
- .filter((pin) => pin.status !== "ready")
1584
- .map(({ name, cid, status }) => ({ name, cid, status }));
1585
- if (pending.length)
1586
- io.err(`Unfinished pin operations (not usable pins): ${JSON.stringify(pending)}. Retry pin add/delete.`);
1587
- if (invalid.length)
1588
- io.err(`Legacy non-Bundle pins (not usable pins): ${JSON.stringify(invalid)}. Retention is unchanged; delete explicitly and wrap content in a Bundle before pinning again.`);
1589
- emit({ items: listed, pending, invalid }, table(["NAME", "CID", "KIND", "TITLE", "TYPE CID", "SOURCE"], listed.map((pin) => [
1590
- pin.name,
1591
- pin.cid,
1592
- pin.kind,
1593
- pin.title,
1594
- pin.schemaCid,
1595
- pin.builtin ? "built-in (read-only)" : "user",
1596
- ]), "No named pins."));
1597
- break;
1598
- }
1599
- case "pin add": {
1600
- io.err("Fetching, verifying and retaining content in Store...");
1601
- const result = await addPin(state, first, second, await storeConfiguration(value("store.gateway")));
1602
- emit(result, `${result.name} → ${result.cid}\nTitle: ${printable(result.title)}\nType CID: ${result.schemaCid}`);
1889
+ const listed = state.contentPins();
1890
+ const archived = state.archivedPins();
1891
+ const builtins = state.pins().map(pinDetails);
1892
+ emit({ items: listed, builtins, archived }, table(["REFERENCE", "CID", "STATUS", "SOURCE"], [
1893
+ ...listed.map((pin) => [
1894
+ pin.reference,
1895
+ pin.cid ?? "(none)",
1896
+ `${pin.status}/${pin.freshness}${pin.error ? `: ${pin.error}` : ""}`,
1897
+ pin.swarm ? "following shared Name" : "fixed CID",
1898
+ ]),
1899
+ ...builtins.map((pin) => [
1900
+ pin.name,
1901
+ pin.cid,
1902
+ "read-only",
1903
+ "built-in",
1904
+ ]),
1905
+ ...archived.map((pin) => [
1906
+ pin.cid,
1907
+ pin.cid,
1908
+ pin.status,
1909
+ `inactive archive (${pin.name}); unpin exact CID`,
1910
+ ]),
1911
+ ], "No pins."));
1603
1912
  break;
1604
1913
  }
1605
- case "pin delete": {
1606
- const result = await deletePin(state, first);
1607
- emit(result, `Deleted ${first}; released only its retention responsibility. No blocks deleted or GC requested.`);
1914
+ case "unpin": {
1915
+ const canonical = pinReference(state, first, selectedSwarm);
1916
+ const result = await unpin(state, canonical.reference);
1917
+ emit(result, `Unpinned ${canonical.reference}; released only its saved retention responsibility. No blocks deleted or GC requested.`);
1608
1918
  break;
1609
1919
  }
1610
1920
  case "pin show": {
1611
- const pin = state.pin(first);
1612
- if (!pin)
1921
+ const builtin = first.startsWith("builtin:")
1922
+ ? state.pin(first)
1923
+ : undefined;
1924
+ const canonical = builtin
1925
+ ? undefined
1926
+ : pinReference(state, first, selectedSwarm);
1927
+ const pin = canonical
1928
+ ? state.contentPin(canonical.reference)
1929
+ : undefined;
1930
+ const archived = canonical
1931
+ ? state
1932
+ .archivedPins()
1933
+ .filter((pin) => pin.cid === canonical.reference)
1934
+ : [];
1935
+ if (!pin && !builtin && !archived.length)
1613
1936
  throw new HostError(`Pin "${first}" does not exist. Run ipab pin list.`);
1614
- const result = pinDetails(pin);
1615
- emit(result, `Name: ${printable(result.name)}\nCID: ${result.cid}\nTitle: ${printable(result.title)}\nType CID: ${result.schemaCid}\nSource: ${result.builtin ? "built-in (read-only; content bundled with IPAB)" : "local registration (not live node verification)"}`);
1616
- break;
1617
- }
1618
- case "pin rename": {
1619
- const result = renamePin(state, first, second);
1620
- emit(result, `${first} → ${result.name} (${result.cid})`);
1621
- break;
1622
- }
1623
- case "register list": {
1624
- const associations = state.registrations();
1625
- emit({ items: associations }, table(["SCHEMA CID", "APP CID", "ARGV"], associations.map((association) => [
1626
- association.schemaCid,
1627
- association.appCid,
1628
- JSON.stringify(association.argv),
1629
- ]), "No associations."));
1630
- break;
1631
- }
1632
- case "register set": {
1633
- const association = state.setAssociation(schemaAlias(first), second, parsed.template ?? ["%"], Boolean(parsed.options.replace));
1634
- emit(association, `${association.schemaCid} → ${association.appCid} ${JSON.stringify(association.argv)}`);
1635
- break;
1636
- }
1637
- case "register remove": {
1638
- const removed = state.removeAssociation(schemaAlias(first));
1639
- emit({ removed: [removed] }, `Removed association for ${removed}.`);
1937
+ const result = builtin
1938
+ ? pinDetails(builtin)
1939
+ : {
1940
+ pin: pin ?? null,
1941
+ roots: pin ? state.hold(pin.owner)?.roots : [],
1942
+ archived,
1943
+ };
1944
+ emit(result, JSON.stringify(result, null, 2));
1640
1945
  break;
1641
1946
  }
1642
1947
  case "config get": {
@@ -1726,13 +2031,62 @@ async function performCli(argv, io, env) {
1726
2031
  }
1727
2032
  case "exec":
1728
2033
  case "open": {
2034
+ const named = parsed.path === "open" ? parseNameReference(first) : undefined;
2035
+ const registrySwarm = named?.swarm
2036
+ ? state.resolveSwarm(named.swarm)
2037
+ : selectedSwarm;
2038
+ if (parsed.path === "open" && !registrySwarm)
2039
+ throw new HostError("Open requires a selected Swarm. Use ipab://URL_OR_ALIAS/PATH, pass --swarm URL_OR_ALIAS, or save a default with ipab swarm use URL_OR_ALIAS. To select an App directly, use ipab exec.");
1729
2040
  if (parsed.options.log && !value("history.enabled"))
1730
2041
  throw new HostError("Execution logging requires history.enabled=true.");
1731
2042
  await recoverInactive(state);
1732
2043
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1733
2044
  const context = swarmContext();
1734
- const target = (await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw))).cid;
2045
+ readContext = context;
2046
+ const target = (await resolveReference(context, first, selectedSwarm, (reference) => state.resolve(reference), Boolean(parsed.options.raw), "local-first")).cid;
1735
2047
  store = context.store;
2048
+ const resolveBundleReference = async (reference, signal, preferredSwarm) => {
2049
+ signal.throwIfAborted();
2050
+ const lookup = {
2051
+ ...swarmContext(),
2052
+ store: new IpfsStore(await storeConfiguration(value("store.gateway"))),
2053
+ };
2054
+ try {
2055
+ const named = parseNameReference(reference);
2056
+ const swarm = named?.swarm
2057
+ ? state.resolveSwarm(named.swarm)
2058
+ : preferredSwarm
2059
+ ? state.resolveSwarm(preferredSwarm)
2060
+ : selectedSwarm;
2061
+ const resolve = (source) => resolveReference(lookup, reference, source, (input) => state.resolve(input), false, "local-first");
2062
+ let resolved;
2063
+ try {
2064
+ resolved = await resolve(named ? swarm : undefined);
2065
+ }
2066
+ catch (cause) {
2067
+ let failure = cause;
2068
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
2069
+ failure = failure.cause;
2070
+ if (named ||
2071
+ !swarm ||
2072
+ !(failure instanceof ContentError) ||
2073
+ failure.code !== "missing_block")
2074
+ throw cause;
2075
+ signal.throwIfAborted();
2076
+ resolved = await resolve(swarm);
2077
+ }
2078
+ signal.throwIfAborted();
2079
+ return { ...resolved, ...(swarm ? { swarm } : {}) };
2080
+ }
2081
+ finally {
2082
+ try {
2083
+ await lookup.finishRead?.();
2084
+ }
2085
+ finally {
2086
+ await lookup.store.close();
2087
+ }
2088
+ }
2089
+ };
1736
2090
  let appCid;
1737
2091
  let appArgv;
1738
2092
  if (parsed.path === "open") {
@@ -1741,14 +2095,32 @@ async function performCli(argv, io, env) {
1741
2095
  try {
1742
2096
  const content = await validatedBundle(root, store, owner);
1743
2097
  const schema = content.schemaKey;
1744
- const association = state.association(schema);
2098
+ let association;
2099
+ if (registrySwarm) {
2100
+ const lookup = {
2101
+ ...swarmContext(),
2102
+ store: new IpfsStore(await storeConfiguration(value("store.gateway"))),
2103
+ };
2104
+ try {
2105
+ association = await swarmAssociation(lookup, registrySwarm, schema, "local-first");
2106
+ }
2107
+ finally {
2108
+ try {
2109
+ await lookup.finishRead?.();
2110
+ }
2111
+ finally {
2112
+ await lookup.store.close();
2113
+ }
2114
+ }
2115
+ }
1745
2116
  if (!association)
1746
- throw new HostError(`No App registered for Schema ${schema}. Use ipab register set or ipab exec.`);
2117
+ throw new HostError(`No App registered for Schema ${schema} in Swarm ${registrySwarm}. Use ipab register set ${schema} APP_CID --swarm ${registrySwarm} or ipab exec.`);
1747
2118
  appCid = association.appCid;
1748
2119
  appArgv = association.argv.map((argument) => argument === "%" ? root : argument);
1749
2120
  // execute owns the App/input context before this validation owner's eventual release.
1750
2121
  const result = await execute(state, store, { origin: "open", appCid, argv: appArgv }, {
1751
2122
  inputSchema: schema,
2123
+ resolveBundleReference,
1752
2124
  history: Boolean(value("history.enabled")),
1753
2125
  retain: value("output.retention") === "history",
1754
2126
  log: Boolean(parsed.options.log),
@@ -1768,6 +2140,7 @@ async function performCli(argv, io, env) {
1768
2140
  appArgv = parsed.positional.slice(1);
1769
2141
  }
1770
2142
  appExitCode = (await execute(state, store, { origin: "exec", appCid, argv: appArgv }, {
2143
+ resolveBundleReference,
1771
2144
  history: Boolean(value("history.enabled")),
1772
2145
  retain: value("output.retention") === "history",
1773
2146
  log: Boolean(parsed.options.log),
@@ -1788,7 +2161,12 @@ async function performCli(argv, io, env) {
1788
2161
  }
1789
2162
  finally {
1790
2163
  try {
1791
- await closeStore(store, appExitCode);
2164
+ try {
2165
+ await readContext?.finishRead?.();
2166
+ }
2167
+ finally {
2168
+ await closeStore(store, appExitCode);
2169
+ }
1792
2170
  }
1793
2171
  finally {
1794
2172
  state?.close();